ParaMonte Fortran 2.0.0
Parallel Monte Carlo and Machine Learning Library
See the latest version documentation.
pm_mathGammaNR Module Reference

This module contains procedures and generic interfaces for the Lower and Upper Incomplete Gamma functions. More...

Data Types

interface  getGammaIncLowNR
 Generate and return the regularized Lower Incomplete Gamma function for the specified shape parameter ( \(\kappa\)) and upper limit of the integral x. More...
 
interface  getGammaIncUppNR
 Generate and return the regularized Upper Incomplete Gamma function for the specified shape parameter ( \(\kappa\)) and lower limit of the integral x. More...
 
interface  setGammaIncLowNR
 Return the regularized Lower Incomplete Gamma function for the specified shape parameter ( \(\kappa\)) and upper limit of the integral x. More...
 
interface  setGammaIncLowSeriesNR
 Return the regularized Lower Incomplete Gamma function for the specified upper limit x and shape parameter, evaluated by the series representation of the Incomplete Gamma function. More...
 
interface  setGammaIncUppContFracNR
 Return the regularized Upper Incomplete Gamma function for the specified lower limit x and shape parameter, evaluated by the Legendre continued fraction representation of the Incomplete Gamma function. More...
 
interface  setGammaIncUppNR
 Return the regularized Upper Incomplete Gamma function for the specified shape parameter ( \(\kappa\)) and lower limit of the integral x. More...
 

Variables

character(*, SK), parameter MODULE_NAME = "@pm_mathGammaNR"
 

Detailed Description

This module contains procedures and generic interfaces for the Lower and Upper Incomplete Gamma functions.

This module provides multiple function and subroutine procedures for computing the Lower and Upper Incomplete Gamma functions. These routines mostly differ only in terms of performance and usage convenience.

  1. If performance is important, use the subroutine interface setGammaIncLowNR and setGammaIncUppNR to compute the Lower and Upper Incomplete Gamma function.
  2. If ease of use matters more than performance, use the function interfaces getGammaIncLowNR and getGammaIncUppNR to compute the Lower and Upper Incomplete Gamma function.
  3. setGammaIncLowSeriesNR and setGammaIncUppContFracNR are not meant to be used directly to compute directly the incomplete Gamma functions since their performance depends on the values of the input parameters.
    Rather they are low-level implementations to be called only by the above higher-level interfaces.
    See below for the relevant benchmark.
Warning
Although all generic interfaces of this module are available for all processor real kinds, the accuracy and performance of the implemented algorithms are optimized for IEEE double precision.
In particular, the algorithms may not accurately compute the lower incomplete gamma function in extended precision (e.g., 128 bits) mode corresponding to RKH kind type parameter.
Note
The computations of this module are an implementation of the algorithm proposed approach by:
Numerical Recipes in Fortran 77: The Art of Scientific Computing 2nd Edition William H. Press (Author), Brian P. Flannery (Author), Saul A. Teukolsky (Author), William T. Vetterling (Author)
Benchmarks:


Benchmark :: The runtime performance of setGammaIncLowSeries vs. setGammaIncUppContFracNR

1! Test the performance of `setGammaIncLowSeriesNR()` vs. `setGammaIncUppContFracNR()`.
2program benchmark
3
4 use iso_fortran_env, only: error_unit
5 use pm_kind, only: IK, LK, RKG => RK, RK, SK
7 use pm_bench, only: bench_type
8
9 implicit none
10
11 integer(IK) :: i
12 integer(IK) :: ipnt
13 integer(IK) :: fileUnit
14 integer(IK) , parameter :: NPNT = 20_IK
15 integer(IK) , parameter :: NBENCH = 2_IK
16 real(RKG) , parameter :: kappa = 1._RKG
17 real(RKG) , parameter :: logGammaKappa = log_gamma(kappa)
18 !real(RKG) , parameter :: TOL = 1000 * epsilon(0._RKG) !< The tolerance.
19 real(RKG) :: Point(NPNT)
20 real(RKG) :: dummy = 0._RKG
21 real(RKG) :: gammaInc
22 integer(IK) :: info
23 type(bench_type) :: bench(NBENCH)
24
25 bench(1) = bench_type(name = SK_"setGammaIncLowSeriesNR", exec = setGammaIncLowSeriesNR, overhead = setOverhead)
26 bench(2) = bench_type(name = SK_"setGammaIncUppContFracNR", exec = setGammaIncUppContFracNR, overhead = setOverhead)
27
28 call setLogSpace(Point, logx1 = log(0.04_RKG), logx2 = log(100._RKG))
29
30
31 write(*,"(*(g0,:,' '))")
32 write(*,"(*(g0,:,' vs. '))") (bench(i)%name, i = 1, NBENCH)
33 write(*,"(*(g0,:,' '))")
34
35 open(newunit = fileUnit, file = "main.out", status = "replace")
36
37 write(fileUnit, "(*(g0,:,','))") "x / (kappa + 1)", (bench(i)%name, i = 1, NBENCH)
38
39 loopOverPoint: do ipnt = 1, NPNT
40
41 write(*,"(*(g0,:,' '))") "Benchmarking with point", Point(ipnt)
42
43 do i = 1, NBENCH
44 bench(i)%timing = bench(i)%getTiming(minsec = 0.05_RK)
45 end do
46
47 write(fileUnit,"(*(g0,:,','))") Point(ipnt) / (kappa + 1), (bench(i)%timing%mean, i = 1, NBENCH)
48
49 end do loopOverPoint
50
51 write(*,"(*(g0,:,' '))") dummy
52 write(*,"(*(g0,:,' '))")
53
54 close(fileUnit)
55
56contains
57
58 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
59 ! procedure wrappers.
60 !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
61
62 subroutine setOverhead()
63 call finalize()
64 end subroutine
65
66 subroutine finalize()
67 if (info < 0_IK) error stop
68 dummy = dummy + gammaInc
69 end subroutine
70
71 subroutine setGammaIncLowSeriesNR()
72 block
74 call setGammaIncLowSeriesNR( gammaIncLow = gammaInc &
75 , x = Point(ipnt) &
76 , logGammaKappa = logGammaKappa &
77 , kappa = kappa &
78 , info = info &
79 !, tol = TOL &
80 )
81 call finalize()
82 end block
83 end subroutine
84
85 subroutine setGammaIncUppContFracNR()
86 block
88 call setGammaIncUppContFracNR( gammaIncUpp = gammaInc &
89 , x = Point(ipnt) &
90 , logGammaKappa = logGammaKappa &
91 , kappa = kappa &
92 , info = info &
93 !, tol = TOL &
94 )
95 call finalize()
96 end block
97 end subroutine
98
99end program benchmark
Return the logSpace output argument with size(logSpace) elements of logarithmically-evenly-spaced val...
Generate and return an object of type timing_type containing the benchmark timing information and sta...
Definition: pm_bench.F90:574
Return the regularized Lower Incomplete Gamma function for the specified upper limit x and shape para...
Return the regularized Upper Incomplete Gamma function for the specified lower limit x and shape para...
This module contains procedures and generic interfaces for generating arrays with linear or logarithm...
This module contains abstract interfaces and types that facilitate benchmarking of different procedur...
Definition: pm_bench.F90:41
This module defines the relevant Fortran kind type-parameters frequently used in the ParaMonte librar...
Definition: pm_kind.F90:268
integer, parameter RK
The default real kind in the ParaMonte library: real64 in Fortran, c_double in C-Fortran Interoperati...
Definition: pm_kind.F90:543
integer, parameter LK
The default logical kind in the ParaMonte library: kind(.true.) in Fortran, kind(....
Definition: pm_kind.F90:541
integer, parameter IK
The default integer kind in the ParaMonte library: int32 in Fortran, c_int32_t in C-Fortran Interoper...
Definition: pm_kind.F90:540
integer, parameter SK
The default character kind in the ParaMonte library: kind("a") in Fortran, c_char in C-Fortran Intero...
Definition: pm_kind.F90:539
This module contains procedures and generic interfaces for the Lower and Upper Incomplete Gamma funct...
This is the class for creating benchmark and performance-profiling objects.
Definition: pm_bench.F90:386

Example Unix compile command via Intel ifort compiler
1#!/usr/bin/env sh
2rm main.exe
3ifort -fpp -standard-semantics -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Example Windows Batch compile command via Intel ifort compiler
1del main.exe
2set PATH=..\..\..\lib;%PATH%
3ifort /fpp /standard-semantics /O3 /I:..\..\..\include main.F90 ..\..\..\lib\libparamonte*.lib /exe:main.exe
4main.exe

Example Unix / MinGW compile command via GNU gfortran compiler
1#!/usr/bin/env sh
2rm main.exe
3gfortran -cpp -ffree-line-length-none -O3 -Wl,-rpath,../../../lib -I../../../inc main.F90 ../../../lib/libparamonte* -o main.exe
4./main.exe

Postprocessing of the benchmark output
1#!/usr/bin/env python
2
3import matplotlib.pyplot as plt
4import pandas as pd
5import numpy as np
6
7import os
8dirname = os.path.basename(os.getcwd())
9
10fontsize = 14
11
12df = pd.read_csv("main.out", delimiter = ",")
13colnames = list(df.columns.values)
14
15
18
19ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
20ax = plt.subplot()
21
22for colname in colnames[1:]:
23 plt.plot( df[colnames[0]].values
24 , df[colname].values
25 , linewidth = 2
26 )
27
28plt.xticks(fontsize = fontsize)
29plt.yticks(fontsize = fontsize)
30ax.set_xlabel(colnames[0], fontsize = fontsize)
31ax.set_ylabel("Runtime [ seconds ]", fontsize = fontsize)
32ax.set_title(" vs. ".join(colnames[1:])+"\nLower is better.", fontsize = fontsize)
33ax.set_xscale("log")
34ax.set_yscale("log")
35plt.minorticks_on()
36plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
37ax.tick_params(axis = "y", which = "minor")
38ax.tick_params(axis = "x", which = "minor")
39ax.legend ( colnames[1:]
40 #, loc='center left'
41 #, bbox_to_anchor=(1, 0.5)
42 , fontsize = fontsize
43 )
44
45plt.tight_layout()
46plt.savefig("benchmark." + dirname + ".runtime.png")
47
48
51
52ax = plt.figure(figsize = 1.25 * np.array([6.4,4.6]), dpi = 200)
53ax = plt.subplot()
54
55plt.plot( df[colnames[0]].values
56 , np.ones(len(df[colnames[0]].values))
57 , linestyle = "--"
58 #, color = "black"
59 , linewidth = 2
60 )
61for colname in colnames[2:]:
62 plt.plot( df[colnames[0]].values
63 , df[colname].values / df[colnames[1]].values
64 , linewidth = 2
65 )
66
67plt.xticks(fontsize = fontsize)
68plt.yticks(fontsize = fontsize)
69ax.set_xlabel(colnames[0], fontsize = fontsize)
70ax.set_ylabel("Runtime compared to {}".format(colnames[1]), fontsize = fontsize)
71ax.set_title("Runtime Ratio Comparison. Lower means faster.\nLower than 1 means faster than {}().".format(colnames[1]), fontsize = fontsize)
72ax.set_xscale("log")
73ax.set_yscale("log")
74plt.minorticks_on()
75plt.grid(visible = True, which = "both", axis = "both", color = "0.85", linestyle = "-")
76ax.tick_params(axis = "y", which = "minor")
77ax.tick_params(axis = "x", which = "minor")
78ax.legend ( colnames[1:]
79 #, bbox_to_anchor = (1, 0.5)
80 #, loc = "center left"
81 , fontsize = fontsize
82 )
83
84plt.tight_layout()
85plt.savefig("benchmark." + dirname + ".runtime.ratio.png")

Visualization of the benchmark output

Benchmark moral
  1. The procedures under the generic interface setGammaIncLowSeriesNR compute the Lower Incomplete Gamma function suing the series representation of the Incomplete Gamma function while the procedures under the generic interface setGammaIncUppContFracNR use the Continued Fraction representation of the Gamma function.
    The Legendre continued fraction representation is known to converge faster at \(x > \kappa + 1\) whereas the series representation converges faster at \(x < \kappa + 1\).
    This performance difference dependence on the specific values of \(x\) and \(\kappa\) is well illustrated by this benchmark.
See also
pm_mathGammaNR for detailed description of the (Regularized Incomplete) Gamma Function.
Test:
test_pm_mathGammaNR
Todo:
Critical Priority: The implementation of the algorithms of this module must be properly changed to allow reliable extended-precision computations of the incomplete Gamma function.
This would require significant investment in making the original algorithms of Gil et al. kind-agnostic.


Final Remarks


If you believe this algorithm or its documentation can be improved, we appreciate your contribution and help to edit this page's documentation and source file on GitHub.
For details on the naming abbreviations, see this page.
For details on the naming conventions, see this page.
This software is distributed under the MIT license with additional terms outlined below.

  1. If you use any parts or concepts from this library to any extent, please acknowledge the usage by citing the relevant publications of the ParaMonte library.
  2. If you regenerate any parts/ideas from this library in a programming environment other than those currently supported by this ParaMonte library (i.e., other than C, C++, Fortran, MATLAB, Python, R), please also ask the end users to cite this original ParaMonte library.

This software is available to the public under a highly permissive license.
Help us justify its continued development and maintenance by acknowledging its benefit to society, distributing it, and contributing to it.

Author:
Amir Shahmoradi, July 22, 2024, 11:45 AM, NASA Goddard Space Flight Center, Washington, D.C.

Variable Documentation

◆ MODULE_NAME

character(*, SK), parameter pm_mathGammaNR::MODULE_NAME = "@pm_mathGammaNR"

Definition at line 92 of file pm_mathGammaNR.F90.