repo_name
stringlengths
7
81
path
stringlengths
4
224
copies
stringlengths
1
4
size
stringlengths
4
7
content
stringlengths
975
1.04M
license
stringclasses
15 values
nicamdc-dev/nicamdc
src/nhm/driver/prg_driver-dc.f90
1
11037
!------------------------------------------------------------------------------- ! !+ Program driver ! !------------------------------------------------------------------------------- program prg_driver !----------------------------------------------------------------------------- ! !++ Description: ! This program is a driver of non-hydrostatic model based on an ! icosahedral grid system. ! !++ Current Corresponding Author : H.Tomita ! !++ History: ! Version Date Comment ! ----------------------------------------------------------------------- ! 0.00 04-02-17 Imported from igdc-4.34 ! 0.03 04-05-31 Change by addtion of mod[onestep]. ! 05-12-01 M.Satoh add history_setup ! 05-12-19 S.Iga moved output_timeinfo after output_all ! 06-04-18 T.Mitsui add sfc_restart ! 06-04-21 H.Tomita: remove output_timeinfo due to ! computational efficeincy. ! Instead, this process is move to ! mod[mod_output]. ! 06-08-07 W.Yanase add history_vars ! 06-09-27 S.Iga add history_vars_cfmip ! 07-03-23 Y.Niwa add NDG_setup, ndg_do, FLAG_NUDGING ! 07-06-27 Y.Niwa add history_vars_setup ! 07-07-24 K.Suzuki: implementing SPRINTARS aerosol model ! 07-08-06 Y.Niwa: add history_obs, history_vars_obs ! 07-11-07 T.Mitsui: add option to omit output_all ! 08-03-10 T.Mitsui: add intermediate output of restart file ! 08-05-24 T.Mitsui: trivial fix ! 08-09-09 Y.Niwa : modfied for nudging ! 09-01-23 H.Tomita: a) abolish mod_output, mod_extdata ! mod_history_vars_cfmip, mod_o3var. ! b) introduce mod_extdata. ! 09-04-14 T.Mitsui: arrange initialization of aerosols ! 09-07-10 H.Tomita: Add the module [mod_embudget]. ! 09-08-05 S.Iga: remove latlon_setup (suggested by T.Mitsui) ! 09-08-05 T.Mitsui: add conditioning by ADM_myprc_is_run ! to keep out extra-processes from main routines. ! 09-08-18 T.Mitsui: change of 09-08-05 is not enough. ! 10-03-08 C.Kodama: Modify for overwrite_restart option ! 10-04-30 M.Satoh: move diagvar_setup ! 11-09-03 H.Yashiro : New I/O ! 11-11-28 Y.Yamada : merge Terai-san timer ! 12-06-07 T.Seiki : Application to Multi-job System ! 12-10-12 R.Yoshida : Modify for Dynamical Core test ! 12-10-22 R.Yoshida : add papi instructions ! ----------------------------------------------------------------------- ! !----------------------------------------------------------------------------- ! !++ Used modules ! use mod_precision use mod_debug use mod_adm, only: & ADM_MULTI_PRC, & ADM_LOG_FID, & ADM_prc_me, & ADM_prc_run_master, & ADM_proc_init, & ADM_proc_finish, & ADM_setup use mod_random, only: & RANDOM_setup use mod_cnst, only: & CNST_setup use mod_calendar, only: & calendar_setup use mod_fio, only: & FIO_setup use mod_comm, only: & COMM_setup use mod_grd, only: & GRD_setup use mod_gmtr, only: & GMTR_setup use mod_oprt, only: & OPRT_setup use mod_vmtr, only: & VMTR_setup use mod_time, only: & TIME_setup, & TIME_report, & TIME_advance, & TIME_LSTEP_MAX, & TIME_CSTEP, & TIME_CTIME, & TIME_DTL use mod_extdata, only: & extdata_setup use mod_runconf, only: & runconf_setup use mod_prgvar, only: & prgvar_setup, & restart_input_basename, & restart_output_basename, & restart_input, & restart_output use mod_dynamics, only: & dynamics_setup, & dynamics_step use mod_forcing_driver, only: & forcing_setup, & forcing_step use mod_history, only: & history_setup, & history_out, & HIST_output_step0 use mod_history_vars, only: & history_vars_setup, & history_vars use mod_embudget, only: & embudget_setup, & embudget_monitor !##### OpenACC (for data copy) ##### use mod_adm, only: & ADM_prc_tab, & ADM_rgn_vnum, & ADM_IopJop use mod_comm, only: & sendlist, sendlist_pl, & sendinfo, sendinfo_pl, & recvlist, recvlist_pl, & recvinfo, recvinfo_pl, & recvlist_r2r, sendlist_r2r, & recvlist_r2p, sendlist_r2p, & recvlist_p2r, sendlist_p2r, & recvlist_sgp, sendlist_sgp, & copyinfo_r2r, copyinfo_sgp, & copyinfo_r2p, copyinfo_p2r, & nsmax, nsmax_pl, & nrmax, nrmax_pl, & ncmax_r2r, ncmax_sgp, & ncmax_r2p, ncmax_p2r use mod_grd, only: & GRD_x, & GRD_xt, & GRD_zs, & GRD_rdgz, & GRD_rdgzh, & GRD_vz use mod_gmtr, only: & GMTR_P_var, & GMTR_T_var, & GMTR_A_var use mod_oprt, only: & cdiv, & cgrad, & clap, & cinterp_TN, & cinterp_HN, & cinterp_TRA, & cinterp_PRA use mod_vmtr, only: & VMTR_GAM2, & VMTR_GAM2H, & VMTR_GSGAM2, & VMTR_GSGAM2H, & VMTR_RGSQRTH, & VMTR_RGAM, & VMTR_RGAMH, & VMTR_RGSGAM2, & VMTR_RGSGAM2H, & VMTR_W2Cfact, & VMTR_C2Wfact, & VMTR_C2WfactGz, & VMTR_PHI use mod_runconf, only: & CVW use mod_prgvar, only: & PRG_var, & PRG_var1, & DIAG_var use mod_bsstate, only: & rho_bs, & pre_bs, & tem_bs use mod_numfilter, only: & Kh_coef, & Kh_coef_lap1, & divdamp_coef use mod_vi, only : & Mc, & Ml, & Mu use mod_history, only: & ksumstr, & cnvpre_klev, & cnvpre_fac1, & cnvpre_fac2 !##### OpenACC ##### implicit none character(len=14) :: cdate integer :: n !----------------------------------------------------------------------------- call ADM_proc_init(ADM_MULTI_PRC) !---< admin module setup >--- call ADM_setup('nhm_driver.cnf') call DEBUG_rapstart('Total') !############################################################################# call DEBUG_rapstart('Setup_ALL') write(ADM_LOG_FID,*) '##### start setup #####' if ( ADM_prc_me == ADM_prc_run_master ) then write(*,*) '##### start setup #####' endif !---< radom module setup >--- call RANDOM_setup !---< cnst module setup >--- call CNST_setup !---< calendar module setup >--- call calendar_setup !---< I/O module setup >--- call FIO_setup !---< comm module setup >--- call COMM_setup !---< grid module setup >--- call GRD_setup !---< geometrics module setup >--- call GMTR_setup !---< operator module setup >--- call OPRT_setup !---< vertical metrics module setup >--- call VMTR_setup !---< time module setup >--- call TIME_setup !---< external data module setup >--- call extdata_setup !---< nhm_runconf module setup >--- call runconf_setup !---< prognostic variable module setup >--- call prgvar_setup call restart_input( restart_input_basename ) !---< dynamics module setup >--- call dynamics_setup !---< forcing module setup >--- call forcing_setup !---< energy&mass budget module setup >--- call embudget_setup !---< history module setup >--- call history_setup !---< history variable module setup >--- call history_vars_setup write(ADM_LOG_FID,*) '##### finish setup #####' if ( ADM_prc_me == ADM_prc_run_master ) then write(*,*) '##### finish setup #####' endif call DEBUG_rapend('Setup_ALL') !############################################################################# call DEBUG_rapstart('Main_ALL') write(ADM_LOG_FID,*) '##### start main loop #####' if ( ADM_prc_me == ADM_prc_run_master ) then write(*,*) '##### start main loop #####' endif #ifdef _FIPP_ call fipp_start() #endif !$acc data & !$acc& pcopyin(ADM_prc_tab,ADM_rgn_vnum,ADM_IopJop) & !$acc& pcopyin(sendlist,sendlist_pl) & !$acc& pcopyin(sendinfo,sendinfo_pl) & !$acc& pcopyin(recvlist,recvlist_pl) & !$acc& pcopyin(recvinfo,recvinfo_pl) & !$acc& pcopyin(recvlist_r2r,sendlist_r2r) & !$acc& pcopyin(recvlist_sgp,sendlist_sgp) & !$acc& pcopyin(recvlist_r2p,sendlist_r2p) & !$acc& pcopyin(recvlist_p2r,sendlist_p2r) & !$acc& pcopyin(copyinfo_r2r,copyinfo_sgp,copyinfo_r2p,copyinfo_p2r) & !$acc& pcopyin(nsmax,nsmax_pl,nrmax,nrmax_pl) & !$acc& pcopyin(ncmax_r2r,ncmax_sgp,ncmax_r2p,ncmax_p2r) & !$acc& pcopyin(GRD_rdgz,GRD_rdgzh,GRD_x,GRD_xt,GRD_vz,GRD_zs) & !$acc& pcopyin(GMTR_P_var,GMTR_T_var,GMTR_A_var) & !$acc& pcopyin(cdiv,cgrad,clap,cinterp_TN,cinterp_HN,cinterp_TRA,cinterp_PRA) & !$acc& pcopyin(VMTR_GAM2,VMTR_GAM2H,VMTR_GSGAM2,VMTR_GSGAM2H) & !$acc& pcopyin(VMTR_RGSQRTH,VMTR_RGAM,VMTR_RGAMH,VMTR_RGSGAM2,VMTR_RGSGAM2H) & !$acc& pcopyin(VMTR_W2Cfact,VMTR_C2Wfact,VMTR_C2WfactGz,VMTR_PHI) & !$acc& pcopyin(CVW) & !$acc& pcopyin(rho_bs,pre_bs,tem_bs) & !$acc& pcopyin(divdamp_coef,Kh_coef,Kh_coef_lap1) & !$acc& pcopyin(Mc,Mu,Ml) & !$acc& pcopyin(ksumstr,cnvpre_klev,cnvpre_fac1,cnvpre_fac2) & !$acc& pcopy (PRG_var,PRG_var1,DIAG_var) !--- history output at initial time if ( HIST_output_step0 ) then TIME_CSTEP = TIME_CSTEP - 1 TIME_CTIME = TIME_CTIME - TIME_DTL call history_vars call TIME_advance call history_out else call TIME_report endif do n = 1, TIME_LSTEP_MAX call DEBUG_rapstart('_Atmos') call dynamics_step call forcing_step call DEBUG_rapend ('_Atmos') call DEBUG_rapstart('_History') call history_vars call TIME_advance !--- budget monitor call embudget_monitor call history_out if (n == TIME_LSTEP_MAX) then cdate = "" call restart_output( restart_output_basename ) endif call DEBUG_rapend ('_History') enddo !$acc end data #ifdef _FIPP_ call fipp_stop() #endif write(ADM_LOG_FID,*) '##### finish main loop #####' if ( ADM_prc_me == ADM_prc_run_master ) then write(*,*) '##### finish main loop #####' endif call DEBUG_rapend('Main_ALL') !############################################################################# call DEBUG_rapend('Total') call DEBUG_rapreport !--- finalize all process call ADM_proc_finish stop end program prg_driver !-------------------------------------------------------------------------------
bsd-2-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/reference/cgemvf.f
50
10127
SUBROUTINE CGEMVF ( TRANS, M, N, ALPHA, A, LDA, X, INCX, $ BETA, Y, INCY ) * .. Scalar Arguments .. COMPLEX ALPHA, BETA INTEGER INCX, INCY, LDA, M, N CHARACTER*1 TRANS * .. Array Arguments .. COMPLEX A( LDA, * ), X( * ), Y( * ) * .. * * Purpose * ======= * * CGEMV performs one of the matrix-vector operations * * y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y, or * * y := alpha*conjg( A' )*x + beta*y, * * where alpha and beta are scalars, x and y are vectors and A is an * m by n matrix. * * Parameters * ========== * * TRANS - CHARACTER*1. * On entry, TRANS specifies the operation to be performed as * follows: * * TRANS = 'N' or 'n' y := alpha*A*x + beta*y. * * TRANS = 'T' or 't' y := alpha*A'*x + beta*y. * * TRANS = 'C' or 'c' y := alpha*conjg( A' )*x + beta*y. * * Unchanged on exit. * * M - INTEGER. * On entry, M specifies the number of rows of the matrix A. * M must be at least zero. * Unchanged on exit. * * N - INTEGER. * On entry, N specifies the number of columns of the matrix A. * N must be at least zero. * Unchanged on exit. * * ALPHA - COMPLEX . * On entry, ALPHA specifies the scalar alpha. * Unchanged on exit. * * A - COMPLEX array of DIMENSION ( LDA, n ). * Before entry, the leading m by n part of the array A must * contain the matrix of coefficients. * Unchanged on exit. * * LDA - INTEGER. * On entry, LDA specifies the first dimension of A as declared * in the calling (sub) program. LDA must be at least * max( 1, m ). * Unchanged on exit. * * X - COMPLEX array of DIMENSION at least * ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' * and at least * ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. * Before entry, the incremented array X must contain the * vector x. * Unchanged on exit. * * INCX - INTEGER. * On entry, INCX specifies the increment for the elements of * X. INCX must not be zero. * Unchanged on exit. * * BETA - COMPLEX . * On entry, BETA specifies the scalar beta. When BETA is * supplied as zero then Y need not be set on input. * Unchanged on exit. * * Y - COMPLEX array of DIMENSION at least * ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' * and at least * ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. * Before entry with BETA non-zero, the incremented array Y * must contain the vector y. On exit, Y is overwritten by the * updated vector y. * * INCY - INTEGER. * On entry, INCY specifies the increment for the elements of * Y. INCY must not be zero. * Unchanged on exit. * * * Level 2 Blas routine. * * -- Written on 22-October-1986. * Jack Dongarra, Argonne National Lab. * Jeremy Du Croz, Nag Central Office. * Sven Hammarling, Nag Central Office. * Richard Hanson, Sandia National Labs. * * * .. Parameters .. COMPLEX ONE PARAMETER ( ONE = ( 1.0E+0, 0.0E+0 ) ) COMPLEX ZERO PARAMETER ( ZERO = ( 0.0E+0, 0.0E+0 ) ) * .. Local Scalars .. COMPLEX TEMP INTEGER I, INFO, IX, IY, J, JX, JY, KX, KY, LENX, LENY LOGICAL NOCONJ, NOTRANS, XCONJ * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. External Subroutines .. EXTERNAL XERBLA * .. Intrinsic Functions .. INTRINSIC CONJG, MAX * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 IF ( .NOT.LSAME( TRANS, 'N' ).AND. $ .NOT.LSAME( TRANS, 'T' ).AND. $ .NOT.LSAME( TRANS, 'R' ).AND. $ .NOT.LSAME( TRANS, 'C' ).AND. $ .NOT.LSAME( TRANS, 'O' ).AND. $ .NOT.LSAME( TRANS, 'U' ).AND. $ .NOT.LSAME( TRANS, 'S' ).AND. $ .NOT.LSAME( TRANS, 'D' ) )THEN INFO = 1 ELSE IF( M.LT.0 )THEN INFO = 2 ELSE IF( N.LT.0 )THEN INFO = 3 ELSE IF( LDA.LT.MAX( 1, M ) )THEN INFO = 6 ELSE IF( INCX.EQ.0 )THEN INFO = 8 ELSE IF( INCY.EQ.0 )THEN INFO = 11 END IF IF( INFO.NE.0 )THEN CALL XERBLA( 'CGEMV ', INFO ) RETURN END IF * * Quick return if possible. * IF( ( M.EQ.0 ).OR.( N.EQ.0 ).OR. $ ( ( ALPHA.EQ.ZERO ).AND.( BETA.EQ.ONE ) ) ) $ RETURN * NOCONJ = (LSAME( TRANS, 'N' ) .OR. LSAME( TRANS, 'T' ) $ .OR. LSAME( TRANS, 'O' ) .OR. LSAME( TRANS, 'U' )) NOTRANS = (LSAME( TRANS, 'N' ) .OR. LSAME( TRANS, 'R' ) $ .OR. LSAME( TRANS, 'O' ) .OR. LSAME( TRANS, 'S' )) XCONJ = (LSAME( TRANS, 'N' ) .OR. LSAME( TRANS, 'T' ) $ .OR. LSAME( TRANS, 'R' ) .OR. LSAME( TRANS, 'C' )) * * Set LENX and LENY, the lengths of the vectors x and y, and set * up the start points in X and Y. * IF(NOTRANS)THEN LENX = N LENY = M ELSE LENX = M LENY = N END IF IF( INCX.GT.0 )THEN KX = 1 ELSE KX = 1 - ( LENX - 1 )*INCX END IF IF( INCY.GT.0 )THEN KY = 1 ELSE KY = 1 - ( LENY - 1 )*INCY END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through A. * * First form y := beta*y. * IF( BETA.NE.ONE )THEN IF( INCY.EQ.1 )THEN IF( BETA.EQ.ZERO )THEN DO 10, I = 1, LENY Y( I ) = ZERO 10 CONTINUE ELSE DO 20, I = 1, LENY Y( I ) = BETA*Y( I ) 20 CONTINUE END IF ELSE IY = KY IF( BETA.EQ.ZERO )THEN DO 30, I = 1, LENY Y( IY ) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40, I = 1, LENY Y( IY ) = BETA*Y( IY ) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF( ALPHA.EQ.ZERO ) $ RETURN IF(NOTRANS)THEN * * Form y := alpha*A*x + y. * JX = KX IF( INCY.EQ.1 )THEN DO 60, J = 1, N IF( X( JX ).NE.ZERO )THEN IF (XCONJ) THEN TEMP = ALPHA*X( JX ) ELSE TEMP = ALPHA*CONJG(X( JX )) ENDIF IF (NOCONJ) THEN DO 50, I = 1, M Y( I ) = Y( I ) + TEMP*A( I, J ) 50 CONTINUE ELSE DO 55, I = 1, M Y( I ) = Y( I ) + TEMP*CONJG(A( I, J )) 55 CONTINUE ENDIF END IF JX = JX + INCX 60 CONTINUE ELSE DO 80, J = 1, N IF( X( JX ).NE.ZERO )THEN IF (XCONJ) THEN TEMP = ALPHA*X( JX ) ELSE TEMP = ALPHA*CONJG(X( JX )) ENDIF IY = KY IF (NOCONJ) THEN DO 70, I = 1, M Y( IY ) = Y( IY ) + TEMP*A( I, J ) IY = IY + INCY 70 CONTINUE ELSE DO 75, I = 1, M Y( IY ) = Y( IY ) + TEMP* CONJG(A( I, J )) IY = IY + INCY 75 CONTINUE ENDIF END IF JX = JX + INCX 80 CONTINUE END IF ELSE * * Form y := alpha*A'*x + y or y := alpha*conjg( A' )*x + y. * JY = KY IF( INCX.EQ.1 )THEN DO 110, J = 1, N TEMP = ZERO IF( NOCONJ )THEN DO 90, I = 1, M IF (XCONJ) THEN TEMP = TEMP + A( I, J )*X( I ) ELSE TEMP = TEMP + A( I, J )*CONJG(X( I )) ENDIF 90 CONTINUE ELSE DO 100, I = 1, M IF (XCONJ) THEN TEMP = TEMP + CONJG( A( I, J ) )*X( I ) ELSE TEMP = TEMP + CONJG( A( I, J ) )*CONJG(X( I )) ENDIF 100 CONTINUE END IF Y( JY ) = Y( JY ) + ALPHA*TEMP JY = JY + INCY 110 CONTINUE ELSE DO 140, J = 1, N TEMP = ZERO IX = KX IF( NOCONJ )THEN DO 120, I = 1, M IF (XCONJ) THEN TEMP = TEMP + A( I, J )*X( IX ) ELSE TEMP = TEMP + A( I, J )*CONJG(X( IX )) ENDIF IX = IX + INCX 120 CONTINUE ELSE DO 130, I = 1, M IF (XCONJ) THEN TEMP = TEMP + CONJG( A( I, J ) )*X( IX ) ELSE TEMP = TEMP + CONJG( A( I, J ) )*CONJG(X( IX )) ENDIF IX = IX + INCX 130 CONTINUE END IF Y( JY ) = Y( JY ) + ALPHA*TEMP JY = JY + INCY 140 CONTINUE END IF END IF * RETURN * * End of CGEMV . * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/cpbequ.f
29
6687
*> \brief \b CPBEQU * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download CPBEQU + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cpbequ.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cpbequ.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cpbequ.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE CPBEQU( UPLO, N, KD, AB, LDAB, S, SCOND, AMAX, INFO ) * * .. Scalar Arguments .. * CHARACTER UPLO * INTEGER INFO, KD, LDAB, N * REAL AMAX, SCOND * .. * .. Array Arguments .. * REAL S( * ) * COMPLEX AB( LDAB, * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CPBEQU computes row and column scalings intended to equilibrate a *> Hermitian positive definite band matrix A and reduce its condition *> number (with respect to the two-norm). S contains the scale factors, *> S(i) = 1/sqrt(A(i,i)), chosen so that the scaled matrix B with *> elements B(i,j) = S(i)*A(i,j)*S(j) has ones on the diagonal. This *> choice of S puts the condition number of B within a factor N of the *> smallest possible condition number over all possible diagonal *> scalings. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> = 'U': Upper triangular of A is stored; *> = 'L': Lower triangular of A is stored. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix A. N >= 0. *> \endverbatim *> *> \param[in] KD *> \verbatim *> KD is INTEGER *> The number of superdiagonals of the matrix A if UPLO = 'U', *> or the number of subdiagonals if UPLO = 'L'. KD >= 0. *> \endverbatim *> *> \param[in] AB *> \verbatim *> AB is COMPLEX array, dimension (LDAB,N) *> The upper or lower triangle of the Hermitian band matrix A, *> stored in the first KD+1 rows of the array. The j-th column *> of A is stored in the j-th column of the array AB as follows: *> if UPLO = 'U', AB(kd+1+i-j,j) = A(i,j) for max(1,j-kd)<=i<=j; *> if UPLO = 'L', AB(1+i-j,j) = A(i,j) for j<=i<=min(n,j+kd). *> \endverbatim *> *> \param[in] LDAB *> \verbatim *> LDAB is INTEGER *> The leading dimension of the array A. LDAB >= KD+1. *> \endverbatim *> *> \param[out] S *> \verbatim *> S is REAL array, dimension (N) *> If INFO = 0, S contains the scale factors for A. *> \endverbatim *> *> \param[out] SCOND *> \verbatim *> SCOND is REAL *> If INFO = 0, S contains the ratio of the smallest S(i) to *> the largest S(i). If SCOND >= 0.1 and AMAX is neither too *> large nor too small, it is not worth scaling by S. *> \endverbatim *> *> \param[out] AMAX *> \verbatim *> AMAX is REAL *> Absolute value of largest matrix element. If AMAX is very *> close to overflow or very close to underflow, the matrix *> should be scaled. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value. *> > 0: if INFO = i, the i-th diagonal element is nonpositive. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup complexOTHERcomputational * * ===================================================================== SUBROUTINE CPBEQU( UPLO, N, KD, AB, LDAB, S, SCOND, AMAX, INFO ) * * -- LAPACK computational routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER UPLO INTEGER INFO, KD, LDAB, N REAL AMAX, SCOND * .. * .. Array Arguments .. REAL S( * ) COMPLEX AB( LDAB, * ) * .. * * ===================================================================== * * .. Parameters .. REAL ZERO, ONE PARAMETER ( ZERO = 0.0E+0, ONE = 1.0E+0 ) * .. * .. Local Scalars .. LOGICAL UPPER INTEGER I, J REAL SMIN * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX, MIN, REAL, SQRT * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 UPPER = LSAME( UPLO, 'U' ) IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 ELSE IF( KD.LT.0 ) THEN INFO = -3 ELSE IF( LDAB.LT.KD+1 ) THEN INFO = -5 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'CPBEQU', -INFO ) RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) THEN SCOND = ONE AMAX = ZERO RETURN END IF * IF( UPPER ) THEN J = KD + 1 ELSE J = 1 END IF * * Initialize SMIN and AMAX. * S( 1 ) = REAL( AB( J, 1 ) ) SMIN = S( 1 ) AMAX = S( 1 ) * * Find the minimum and maximum diagonal elements. * DO 10 I = 2, N S( I ) = REAL( AB( J, I ) ) SMIN = MIN( SMIN, S( I ) ) AMAX = MAX( AMAX, S( I ) ) 10 CONTINUE * IF( SMIN.LE.ZERO ) THEN * * Find the first non-positive diagonal element and return. * DO 20 I = 1, N IF( S( I ).LE.ZERO ) THEN INFO = I RETURN END IF 20 CONTINUE ELSE * * Set the scale factors to the reciprocals * of the diagonal elements. * DO 30 I = 1, N S( I ) = ONE / SQRT( S( I ) ) 30 CONTINUE * * Compute SCOND = min(S(I)) / max(S(I)) * SCOND = SQRT( SMIN ) / SQRT( AMAX ) END IF RETURN * * End of CPBEQU * END
bsd-3-clause
astrofrog/fortranlib
templates/type_var2d_pdf2d_template.f90
1
7899
! ------------------------------------------------------------------------------ ! Copyright (c) 2009-13, Thomas P. Robitaille ! ! All rights reserved. ! ! Redistribution and use in source and binary forms, with or without ! modification, are permitted provided that the following conditions are met: ! ! * Redistributions of source code must retain the above copyright notice, this ! list of conditions and the following disclaimer. ! ! * Redistributions in binary form must reproduce the above copyright notice, ! this list of conditions and the following disclaimer in the documentation ! and/or other materials provided with the distribution. ! ! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ! DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ! FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ! SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ! OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ! ------------------------------------------------------------------------------ module type_var2d_pdf2d use lib_array, only : locate, interp2d use lib_random, only : random use type_pdf2d, only : pdf2d_sp, pdf2d_dp, sample_pdf2d, set_pdf2d, interpolate_pdf2d implicit none save private integer,parameter :: sp = selected_real_kind(p=6,r=37) integer,parameter :: dp = selected_real_kind(p=15,r=307) ! The purpose of this class is to implement a 2-d PDF that depends on two ! other variables that are provided when sampling. The four PDFs neighboring ! the value requested are then sampled with the same random number, and the ! resulting value is then interpolated using bilinear interpolation. !!@FOR real(sp):sp real(<T>):dp public :: var2d_pdf2d_<T> type var2d_pdf2d_<T> integer :: nw, nz real(<T>), allocatable :: w(:) real(<T>), allocatable :: z(:) type(pdf2d_<T>), allocatable :: p(:,:) end type var2d_pdf2d_<T> !!@END FOR public :: set_var2d_pdf2d interface set_var2d_pdf2d module procedure set_var2d_pdf2d_sp module procedure set_var2d_pdf2d_dp end interface set_var2d_pdf2d public :: sample_var2d_pdf2d interface sample_var2d_pdf2d module procedure sample_var2d_pdf2d_sp module procedure sample_var2d_pdf2d_dp end interface sample_var2d_pdf2d public :: interpolate_var2d_pdf2d interface interpolate_var2d_pdf2d module procedure interpolate_var2d_pdf2d_sp module procedure interpolate_var2d_pdf2d_dp end interface interpolate_var2d_pdf2d contains !!@FOR real(sp):sp real(<T>):dp type(var2d_pdf2d_<T>) function set_var2d_pdf2d_<T>(x, y, w, z, prob) result(v) ! Initialize a var2d_pdf2d_<T> object ! ! This version assumes that all the PDFs are defined on the same grid. ! We can easily create a version that has different x and y values for ! each PDF. ! ! Parameters ! ---------- ! x : 1-d array (size nx) ! x values in the PDFs ! y : 1-d array (size ny) ! y values in the PDFs ! w : 1-d array (size nw) ! First set of values that the PDFs are defined for ! z : 1-d array (size nz) ! Second set of values that the PDFs are defined for ! prob : 2-d array (size nx, ny, nw, nz) ! The probabilities for all the x, y, w, and z values implicit none real(<T>),intent(in) :: x(:), y(:), w(:), z(:), prob(:,:,:,:) integer :: iw,iz if(size(prob,1) /= size(x)) stop "incorrect dimensions for prob" if(size(prob,2) /= size(y)) stop "incorrect dimensions for prob" if(size(prob,3) /= size(w)) stop "incorrect dimensions for prob" if(size(prob,4) /= size(z)) stop "incorrect dimensions for prob" v%nw = size(w) v%nz = size(z) allocate(v%w(v%nw)) allocate(v%z(v%nz)) allocate(v%p(v%nw, v%nz)) v%w = w v%z = z do iw=1,v%nw do iz=1,v%nz v%p(iw,iz) = set_pdf2d(x, y, prob(:, :, iw, iz)) end do end do end function set_var2d_pdf2d_<T> subroutine sample_var2d_pdf2d_<T>(w, z, v, x, y) ! Sample a var2d_pdf2d_<T> object ! ! Parameters ! ---------- ! w, z : @T ! The w and z value to sample the PDFs for ! v : var2d_pdf2d_<T> ! The variable PDF to sample ! ! Returns ! ------- ! x, y : @T ! The sampled values real(<T>),intent(in) :: w, z type(var2d_pdf2d_<T>),intent(in) :: v real(<T>),intent(out) :: x, y real(<T>) :: x11,x12,x21,x22,y11,y12,y21,y22,xi(4) integer :: iw, iz integer :: i ! Find bin in w and z arrays iw = locate(v%w, w) iz = locate(v%z, z) ! Sample random values do i=1,4 call random(xi(i)) end do ! Sample neighboring PDFs call sample_pdf2d(v%p(iw, iz), x11, y11, xi_alt=xi) call sample_pdf2d(v%p(iw+1, iz), x21, y21, xi_alt=xi) call sample_pdf2d(v%p(iw, iz+1), x12, y12, xi_alt=xi) call sample_pdf2d(v%p(iw+1, iz+1), x22, y22, xi_alt=xi) ! Calculate result using bilinear interpolation x = (x11 * (v%w(iw + 1) - w) * (v%z(iz + 1) - z) & & + x21 * (w - v%w(iw)) * (v%z(iz + 1) - z) & & + x12 * (v%w(iw + 1) - w) * (z - v%z(iz)) & & + x22 * (w - v%w(iw)) * (z - v%z(iz))) & & / (v%w(iw+1) - v%w(iw)) / (v%z(iz+1) - v%z(iz)) y = (y11 * (v%w(iw + 1) - w) * (v%z(iz + 1) - z) & & + y21 * (w - v%w(iw)) * (v%z(iz + 1) - z) & & + y12 * (v%w(iw + 1) - w) * (z - v%z(iz)) & & + y22 * (w - v%w(iw)) * (z - v%z(iz))) & & / (v%w(iw+1) - v%w(iw)) / (v%z(iz+1) - v%z(iz)) end subroutine sample_var2d_pdf2d_<T> @T function interpolate_var2d_pdf2d_<T>(w, z, v, x, y, bounds_error, fill_value) result(prob) ! Interpolate a 2-d PDF ! ! Parameters ! ---------- ! w, z : @T ! The w and z value to sample the PDFs for ! v : var2d_pdf2d_<T> ! The variable PDF to interpolate ! x, y : @T ! Position at which to interpolate the 2-d PDF ! bounds_error : logical, optional ! Whether to raise an error if the interpolation is out of bounds ! fill_value : @T ! The value to use for out-of-bounds interpolation if bounds_error = .false. ! ! Returns ! ------- ! prob : @T ! The probability at the position requested implicit none real(<T>),intent(in) :: w, z type(var2d_pdf2d_<T>),intent(in) :: v @T,intent(in) :: x, y logical,intent(in),optional :: bounds_error real(<T>),intent(in),optional :: fill_value @T :: p11,p12,p21,p22 integer :: iw, iz ! Find bin in w and z arrays iw = locate(v%w, w) iz = locate(v%z, z) ! Interpolate neighboring PDFs p11 = interpolate_pdf2d(v%p(iw, iz), x, y, bounds_error, fill_value) p21 = interpolate_pdf2d(v%p(iw+1, iz), x, y, bounds_error, fill_value) p12 = interpolate_pdf2d(v%p(iw, iz+1), x, y, bounds_error, fill_value) p22 = interpolate_pdf2d(v%p(iw+1, iz+1), x, y, bounds_error, fill_value) ! Calculate result using bilinear interpolation prob = (p11 * (v%w(iw + 1) - w) * (v%z(iz + 1) - z) & & + p21 * (w - v%w(iw)) * (v%z(iz + 1) - z) & & + p12 * (v%w(iw + 1) - w) * (z - v%z(iz)) & & + p22 * (w - v%w(iw)) * (z - v%z(iz))) & & / (v%w(iw+1) - v%w(iw)) / (v%z(iz+1) - v%z(iz)) end function interpolate_var2d_pdf2d_<T> !!@END FOR end module type_var2d_pdf2d
bsd-2-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/zsysvxx.f
5
27072
*> \brief <b> ZSYSVXX computes the solution to system of linear equations A * X = B for SY matrices</b> * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download ZSYSVXX + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zsysvxx.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zsysvxx.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zsysvxx.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE ZSYSVXX( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, * EQUED, S, B, LDB, X, LDX, RCOND, RPVGRW, BERR, * N_ERR_BNDS, ERR_BNDS_NORM, ERR_BNDS_COMP, * NPARAMS, PARAMS, WORK, RWORK, INFO ) * * .. Scalar Arguments .. * CHARACTER EQUED, FACT, UPLO * INTEGER INFO, LDA, LDAF, LDB, LDX, N, NRHS, NPARAMS, * $ N_ERR_BNDS * DOUBLE PRECISION RCOND, RPVGRW * .. * .. Array Arguments .. * INTEGER IPIV( * ) * COMPLEX*16 A( LDA, * ), AF( LDAF, * ), B( LDB, * ), * $ X( LDX, * ), WORK( * ) * DOUBLE PRECISION S( * ), PARAMS( * ), BERR( * ), * $ ERR_BNDS_NORM( NRHS, * ), * $ ERR_BNDS_COMP( NRHS, * ), RWORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> ZSYSVXX uses the diagonal pivoting factorization to compute the *> solution to a complex*16 system of linear equations A * X = B, where *> A is an N-by-N symmetric matrix and X and B are N-by-NRHS *> matrices. *> *> If requested, both normwise and maximum componentwise error bounds *> are returned. ZSYSVXX will return a solution with a tiny *> guaranteed error (O(eps) where eps is the working machine *> precision) unless the matrix is very ill-conditioned, in which *> case a warning is returned. Relevant condition numbers also are *> calculated and returned. *> *> ZSYSVXX accepts user-provided factorizations and equilibration *> factors; see the definitions of the FACT and EQUED options. *> Solving with refinement and using a factorization from a previous *> ZSYSVXX call will also produce a solution with either O(eps) *> errors or warnings, but we cannot make that claim for general *> user-provided factorizations and equilibration factors if they *> differ from what ZSYSVXX would itself produce. *> \endverbatim * *> \par Description: * ================= *> *> \verbatim *> *> The following steps are performed: *> *> 1. If FACT = 'E', double precision scaling factors are computed to equilibrate *> the system: *> *> diag(S)*A*diag(S) *inv(diag(S))*X = diag(S)*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 diag(S)*A*diag(S) and B by diag(S)*B. *> *> 2. If FACT = 'N' or 'E', the LU decomposition is used to factor *> the matrix A (after equilibration if FACT = 'E') as *> *> A = U * D * U**T, if UPLO = 'U', or *> A = L * D * L**T, 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. *> *> 3. If some D(i,i)=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 (see *> argument RCOND). If the reciprocal of the condition number is *> less than machine precision, 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. By default (unless PARAMS(LA_LINRX_ITREF_I) is set to zero), *> the routine will use iterative refinement to try to get a small *> error and error bounds. Refinement calculates the residual to at *> least twice the working precision. *> *> 6. If equilibration was used, the matrix X is premultiplied by *> diag(R) so that it solves the original system before *> equilibration. *> \endverbatim * * Arguments: * ========== * *> \verbatim *> Some optional parameters are bundled in the PARAMS array. These *> settings determine how refinement is performed, but often the *> defaults are acceptable. If the defaults are acceptable, users *> can pass NPARAMS = 0 which prevents the source code from accessing *> the PARAMS argument. *> \endverbatim *> *> \param[in] FACT *> \verbatim *> FACT is CHARACTER*1 *> Specifies whether or not the factored form of the matrix A is *> supplied on entry, and if not, whether the matrix A should be *> equilibrated before it is factored. *> = 'F': On entry, AF and IPIV contain the factored form of A. *> If EQUED is not 'N', the matrix A has been *> equilibrated with scaling factors given by S. *> A, AF, and IPIV are not modified. *> = 'N': The matrix A will be copied to AF and factored. *> = 'E': The matrix A will be equilibrated if necessary, then *> copied to AF and factored. *> \endverbatim *> *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> = 'U': Upper triangle of A is stored; *> = 'L': Lower triangle of A is stored. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of linear equations, i.e., the order of the *> matrix A. N >= 0. *> \endverbatim *> *> \param[in] NRHS *> \verbatim *> NRHS is INTEGER *> The number of right hand sides, i.e., the number of columns *> of the matrices B and X. NRHS >= 0. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX*16 array, dimension (LDA,N) *> The 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 FACT = 'E' and EQUED = 'Y', A is overwritten by *> diag(S)*A*diag(S). *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,N). *> \endverbatim *> *> \param[in,out] AF *> \verbatim *> AF is COMPLEX*16 array, dimension (LDAF,N) *> If FACT = 'F', then AF is an input argument and on entry *> contains the block diagonal matrix D and the multipliers *> used to obtain the factor U or L from the factorization A = *> U*D*U**T or A = L*D*L**T as computed by DSYTRF. *> *> If FACT = 'N', then AF is an output argument and on exit *> returns the block diagonal matrix D and the multipliers *> used to obtain the factor U or L from the factorization A = *> U*D*U**T or A = L*D*L**T. *> \endverbatim *> *> \param[in] LDAF *> \verbatim *> LDAF is INTEGER *> The leading dimension of the array AF. LDAF >= max(1,N). *> \endverbatim *> *> \param[in,out] IPIV *> \verbatim *> IPIV is INTEGER array, dimension (N) *> If FACT = 'F', then IPIV is an input argument and on entry *> contains details of the interchanges and the block *> structure of D, as determined by DSYTRF. If IPIV(k) > 0, *> then rows and columns k and IPIV(k) were interchanged and *> D(k,k) 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. *> *> If FACT = 'N', then IPIV is an output argument and on exit *> contains details of the interchanges and the block *> structure of D, as determined by DSYTRF. *> \endverbatim *> *> \param[in,out] EQUED *> \verbatim *> EQUED is CHARACTER*1 *> Specifies the form of equilibration that was done. *> = 'N': No equilibration (always true if FACT = 'N'). *> = 'Y': Both row and column equilibration, i.e., A has been *> replaced by diag(S) * A * diag(S). *> EQUED is an input argument if FACT = 'F'; otherwise, it is an *> output argument. *> \endverbatim *> *> \param[in,out] S *> \verbatim *> S is DOUBLE PRECISION array, dimension (N) *> The scale factors for A. If EQUED = 'Y', A is multiplied on *> the left and right by diag(S). S is an input argument if FACT = *> 'F'; otherwise, S is an output argument. If FACT = 'F' and EQUED *> = 'Y', each element of S must be positive. If S is output, each *> element of S is a power of the radix. If S is input, each element *> of S should be a power of the radix to ensure a reliable solution *> and error estimates. Scaling by powers of the radix does not cause *> rounding errors unless the result underflows or overflows. *> Rounding errors during scaling lead to refining with a matrix that *> is not equivalent to the input matrix, producing error estimates *> that may not be reliable. *> \endverbatim *> *> \param[in,out] B *> \verbatim *> B is COMPLEX*16 array, dimension (LDB,NRHS) *> On entry, the N-by-NRHS right hand side matrix B. *> On exit, *> if EQUED = 'N', B is not modified; *> if EQUED = 'Y', B is overwritten by diag(S)*B; *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> The leading dimension of the array B. LDB >= max(1,N). *> \endverbatim *> *> \param[out] X *> \verbatim *> X is COMPLEX*16 array, dimension (LDX,NRHS) *> If INFO = 0, the N-by-NRHS solution matrix X to the original *> system of equations. Note that A and B are modified on exit if *> EQUED .ne. 'N', and the solution to the equilibrated system is *> inv(diag(S))*X. *> \endverbatim *> *> \param[in] LDX *> \verbatim *> LDX is INTEGER *> The leading dimension of the array X. LDX >= max(1,N). *> \endverbatim *> *> \param[out] RCOND *> \verbatim *> RCOND is DOUBLE PRECISION *> Reciprocal scaled condition number. This is an estimate of the *> reciprocal Skeel condition number of the matrix A after *> equilibration (if done). If this is less than the machine *> precision (in particular, if it is zero), the matrix is singular *> to working precision. Note that the error may still be small even *> if this number is very small and the matrix appears ill- *> conditioned. *> \endverbatim *> *> \param[out] RPVGRW *> \verbatim *> RPVGRW is DOUBLE PRECISION *> Reciprocal pivot growth. On exit, this contains the reciprocal *> pivot growth factor norm(A)/norm(U). The "max absolute element" *> norm is used. If this 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, estimated condition numbers, *> and error bounds could be unreliable. If factorization fails with *> 0<INFO<=N, then this contains the reciprocal pivot growth factor *> for the leading INFO columns of A. *> \endverbatim *> *> \param[out] BERR *> \verbatim *> BERR is DOUBLE PRECISION array, dimension (NRHS) *> Componentwise relative backward error. This is the *> componentwise 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). *> \endverbatim *> *> \param[in] N_ERR_BNDS *> \verbatim *> N_ERR_BNDS is INTEGER *> Number of error bounds to return for each right hand side *> and each type (normwise or componentwise). See ERR_BNDS_NORM and *> ERR_BNDS_COMP below. *> \endverbatim *> *> \param[out] ERR_BNDS_NORM *> \verbatim *> ERR_BNDS_NORM is DOUBLE PRECISION array, dimension (NRHS, N_ERR_BNDS) *> For each right-hand side, this array contains information about *> various error bounds and condition numbers corresponding to the *> normwise relative error, which is defined as follows: *> *> Normwise relative error in the ith solution vector: *> max_j (abs(XTRUE(j,i) - X(j,i))) *> ------------------------------ *> max_j abs(X(j,i)) *> *> The array is indexed by the type of error information as described *> below. There currently are up to three pieces of information *> returned. *> *> The first index in ERR_BNDS_NORM(i,:) corresponds to the ith *> right-hand side. *> *> The second index in ERR_BNDS_NORM(:,err) contains the following *> three fields: *> err = 1 "Trust/don't trust" boolean. Trust the answer if the *> reciprocal condition number is less than the threshold *> sqrt(n) * dlamch('Epsilon'). *> *> err = 2 "Guaranteed" error bound: The estimated forward error, *> almost certainly within a factor of 10 of the true error *> so long as the next entry is greater than the threshold *> sqrt(n) * dlamch('Epsilon'). This error bound should only *> be trusted if the previous boolean is true. *> *> err = 3 Reciprocal condition number: Estimated normwise *> reciprocal condition number. Compared with the threshold *> sqrt(n) * dlamch('Epsilon') to determine if the error *> estimate is "guaranteed". These reciprocal condition *> numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some *> appropriately scaled matrix Z. *> Let Z = S*A, where S scales each row by a power of the *> radix so all absolute row sums of Z are approximately 1. *> *> See Lapack Working Note 165 for further details and extra *> cautions. *> \endverbatim *> *> \param[out] ERR_BNDS_COMP *> \verbatim *> ERR_BNDS_COMP is DOUBLE PRECISION array, dimension (NRHS, N_ERR_BNDS) *> For each right-hand side, this array contains information about *> various error bounds and condition numbers corresponding to the *> componentwise relative error, which is defined as follows: *> *> Componentwise relative error in the ith solution vector: *> abs(XTRUE(j,i) - X(j,i)) *> max_j ---------------------- *> abs(X(j,i)) *> *> The array is indexed by the right-hand side i (on which the *> componentwise relative error depends), and the type of error *> information as described below. There currently are up to three *> pieces of information returned for each right-hand side. If *> componentwise accuracy is not requested (PARAMS(3) = 0.0), then *> ERR_BNDS_COMP is not accessed. If N_ERR_BNDS .LT. 3, then at most *> the first (:,N_ERR_BNDS) entries are returned. *> *> The first index in ERR_BNDS_COMP(i,:) corresponds to the ith *> right-hand side. *> *> The second index in ERR_BNDS_COMP(:,err) contains the following *> three fields: *> err = 1 "Trust/don't trust" boolean. Trust the answer if the *> reciprocal condition number is less than the threshold *> sqrt(n) * dlamch('Epsilon'). *> *> err = 2 "Guaranteed" error bound: The estimated forward error, *> almost certainly within a factor of 10 of the true error *> so long as the next entry is greater than the threshold *> sqrt(n) * dlamch('Epsilon'). This error bound should only *> be trusted if the previous boolean is true. *> *> err = 3 Reciprocal condition number: Estimated componentwise *> reciprocal condition number. Compared with the threshold *> sqrt(n) * dlamch('Epsilon') to determine if the error *> estimate is "guaranteed". These reciprocal condition *> numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some *> appropriately scaled matrix Z. *> Let Z = S*(A*diag(x)), where x is the solution for the *> current right-hand side and S scales each row of *> A*diag(x) by a power of the radix so all absolute row *> sums of Z are approximately 1. *> *> See Lapack Working Note 165 for further details and extra *> cautions. *> \endverbatim *> *> \param[in] NPARAMS *> \verbatim *> NPARAMS is INTEGER *> Specifies the number of parameters set in PARAMS. If .LE. 0, the *> PARAMS array is never referenced and default values are used. *> \endverbatim *> *> \param[in,out] PARAMS *> \verbatim *> PARAMS is DOUBLE PRECISION array, dimension NPARAMS *> Specifies algorithm parameters. If an entry is .LT. 0.0, then *> that entry will be filled with default value used for that *> parameter. Only positions up to NPARAMS are accessed; defaults *> are used for higher-numbered parameters. *> *> PARAMS(LA_LINRX_ITREF_I = 1) : Whether to perform iterative *> refinement or not. *> Default: 1.0D+0 *> = 0.0 : No refinement is performed, and no error bounds are *> computed. *> = 1.0 : Use the extra-precise refinement algorithm. *> (other values are reserved for future use) *> *> PARAMS(LA_LINRX_ITHRESH_I = 2) : Maximum number of residual *> computations allowed for refinement. *> Default: 10 *> Aggressive: Set to 100 to permit convergence using approximate *> factorizations or factorizations other than LU. If *> the factorization uses a technique other than *> Gaussian elimination, the guarantees in *> err_bnds_norm and err_bnds_comp may no longer be *> trustworthy. *> *> PARAMS(LA_LINRX_CWISE_I = 3) : Flag determining if the code *> will attempt to find a solution with small componentwise *> relative error in the double-precision algorithm. Positive *> is true, 0.0 is false. *> Default: 1.0 (attempt componentwise convergence) *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is COMPLEX*16 array, dimension (2*N) *> \endverbatim *> *> \param[out] RWORK *> \verbatim *> RWORK is DOUBLE PRECISION array, dimension (2*N) *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: Successful exit. The solution to every right-hand side is *> guaranteed. *> < 0: If INFO = -i, the i-th argument had an illegal value *> > 0 and <= N: U(INFO,INFO) 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 *> is returned. *> = N+J: The solution corresponding to the Jth right-hand side is *> not guaranteed. The solutions corresponding to other right- *> hand sides K with K > J may not be guaranteed as well, but *> only the first such right-hand side is reported. If a small *> componentwise error is not requested (PARAMS(3) = 0.0) then *> the Jth right-hand side is the first with a normwise error *> bound that is not guaranteed (the smallest J such *> that ERR_BNDS_NORM(J,1) = 0.0). By default (PARAMS(3) = 1.0) *> the Jth right-hand side is the first with either a normwise or *> componentwise error bound that is not guaranteed (the smallest *> J such that either ERR_BNDS_NORM(J,1) = 0.0 or *> ERR_BNDS_COMP(J,1) = 0.0). See the definition of *> ERR_BNDS_NORM(:,1) and ERR_BNDS_COMP(:,1). To get information *> about all of the right-hand sides check ERR_BNDS_NORM or *> ERR_BNDS_COMP. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date April 2012 * *> \ingroup complex16SYsolve * * ===================================================================== SUBROUTINE ZSYSVXX( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, $ EQUED, S, B, LDB, X, LDX, RCOND, RPVGRW, BERR, $ N_ERR_BNDS, ERR_BNDS_NORM, ERR_BNDS_COMP, $ NPARAMS, PARAMS, WORK, RWORK, INFO ) * * -- LAPACK driver routine (version 3.6.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * April 2012 * * .. Scalar Arguments .. CHARACTER EQUED, FACT, UPLO INTEGER INFO, LDA, LDAF, LDB, LDX, N, NRHS, NPARAMS, $ N_ERR_BNDS DOUBLE PRECISION RCOND, RPVGRW * .. * .. Array Arguments .. INTEGER IPIV( * ) COMPLEX*16 A( LDA, * ), AF( LDAF, * ), B( LDB, * ), $ X( LDX, * ), WORK( * ) DOUBLE PRECISION S( * ), PARAMS( * ), BERR( * ), $ ERR_BNDS_NORM( NRHS, * ), $ ERR_BNDS_COMP( NRHS, * ), RWORK( * ) * .. * * ================================================================== * * .. Parameters .. DOUBLE PRECISION ZERO, ONE PARAMETER ( ZERO = 0.0D+0, ONE = 1.0D+0 ) INTEGER FINAL_NRM_ERR_I, FINAL_CMP_ERR_I, BERR_I INTEGER RCOND_I, NRM_RCOND_I, NRM_ERR_I, CMP_RCOND_I INTEGER CMP_ERR_I, PIV_GROWTH_I PARAMETER ( FINAL_NRM_ERR_I = 1, FINAL_CMP_ERR_I = 2, $ BERR_I = 3 ) PARAMETER ( RCOND_I = 4, NRM_RCOND_I = 5, NRM_ERR_I = 6 ) PARAMETER ( CMP_RCOND_I = 7, CMP_ERR_I = 8, $ PIV_GROWTH_I = 9 ) * .. * .. Local Scalars .. LOGICAL EQUIL, NOFACT, RCEQU INTEGER INFEQU, J DOUBLE PRECISION AMAX, BIGNUM, SMIN, SMAX, SCOND, SMLNUM * .. * .. External Functions .. EXTERNAL LSAME, DLAMCH, ZLA_SYRPVGRW LOGICAL LSAME DOUBLE PRECISION DLAMCH, ZLA_SYRPVGRW * .. * .. External Subroutines .. EXTERNAL ZSYCON, ZSYEQUB, ZSYTRF, ZSYTRS, ZLACPY, $ ZLAQSY, XERBLA, ZLASCL2, ZSYRFSX * .. * .. Intrinsic Functions .. INTRINSIC MAX, MIN * .. * .. Executable Statements .. * INFO = 0 NOFACT = LSAME( FACT, 'N' ) EQUIL = LSAME( FACT, 'E' ) SMLNUM = DLAMCH( 'Safe minimum' ) BIGNUM = ONE / SMLNUM IF( NOFACT .OR. EQUIL ) THEN EQUED = 'N' RCEQU = .FALSE. ELSE RCEQU = LSAME( EQUED, 'Y' ) ENDIF * * Default is failure. If an input parameter is wrong or * factorization fails, make everything look horrible. Only the * pivot growth is set here, the rest is initialized in ZSYRFSX. * RPVGRW = ZERO * * Test the input parameters. PARAMS is not tested until ZSYRFSX. * IF( .NOT.NOFACT .AND. .NOT.EQUIL .AND. .NOT. $ LSAME( FACT, 'F' ) ) THEN INFO = -1 ELSE IF( .NOT.LSAME(UPLO, 'U') .AND. $ .NOT.LSAME(UPLO, 'L') ) THEN INFO = -2 ELSE IF( N.LT.0 ) THEN INFO = -3 ELSE IF( NRHS.LT.0 ) THEN INFO = -4 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -6 ELSE IF( LDAF.LT.MAX( 1, N ) ) THEN INFO = -8 ELSE IF( LSAME( FACT, 'F' ) .AND. .NOT. $ ( RCEQU .OR. LSAME( EQUED, 'N' ) ) ) THEN INFO = -10 ELSE IF ( RCEQU ) THEN SMIN = BIGNUM SMAX = ZERO DO 10 J = 1, N SMIN = MIN( SMIN, S( J ) ) SMAX = MAX( SMAX, S( J ) ) 10 CONTINUE IF( SMIN.LE.ZERO ) THEN INFO = -11 ELSE IF( N.GT.0 ) THEN SCOND = MAX( SMIN, SMLNUM ) / MIN( SMAX, BIGNUM ) ELSE SCOND = ONE END IF END IF IF( INFO.EQ.0 ) THEN IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -13 ELSE IF( LDX.LT.MAX( 1, N ) ) THEN INFO = -15 END IF END IF END IF * IF( INFO.NE.0 ) THEN CALL XERBLA( 'ZSYSVXX', -INFO ) RETURN END IF * IF( EQUIL ) THEN * * Compute row and column scalings to equilibrate the matrix A. * CALL ZSYEQUB( UPLO, N, A, LDA, S, SCOND, AMAX, WORK, INFEQU ) IF( INFEQU.EQ.0 ) THEN * * Equilibrate the matrix. * CALL ZLAQSY( UPLO, N, A, LDA, S, SCOND, AMAX, EQUED ) RCEQU = LSAME( EQUED, 'Y' ) END IF END IF * * Scale the right hand-side. * IF( RCEQU ) CALL ZLASCL2( N, NRHS, S, B, LDB ) * IF( NOFACT .OR. EQUIL ) THEN * * Compute the LDL^T or UDU^T factorization of A. * CALL ZLACPY( UPLO, N, N, A, LDA, AF, LDAF ) CALL ZSYTRF( UPLO, N, AF, LDAF, IPIV, WORK, 5*MAX(1,N), INFO ) * * Return if INFO is non-zero. * IF( INFO.GT.0 ) THEN * * Pivot in column INFO is exactly 0 * Compute the reciprocal pivot growth factor of the * leading rank-deficient INFO columns of A. * IF ( N.GT.0 ) $ RPVGRW = ZLA_SYRPVGRW( UPLO, N, INFO, A, LDA, AF, $ LDAF, IPIV, RWORK ) RETURN END IF END IF * * Compute the reciprocal pivot growth factor RPVGRW. * IF ( N.GT.0 ) $ RPVGRW = ZLA_SYRPVGRW( UPLO, N, INFO, A, LDA, AF, LDAF, $ IPIV, RWORK ) * * Compute the solution matrix X. * CALL ZLACPY( 'Full', N, NRHS, B, LDB, X, LDX ) CALL ZSYTRS( UPLO, N, NRHS, AF, LDAF, IPIV, X, LDX, INFO ) * * Use iterative refinement to improve the computed solution and * compute error bounds and backward error estimates for it. * CALL ZSYRFSX( UPLO, EQUED, N, NRHS, A, LDA, AF, LDAF, IPIV, $ S, B, LDB, X, LDX, RCOND, BERR, N_ERR_BNDS, ERR_BNDS_NORM, $ ERR_BNDS_COMP, NPARAMS, PARAMS, WORK, RWORK, INFO ) * * Scale solutions. * IF ( RCEQU ) THEN CALL ZLASCL2 (N, NRHS, S, X, LDX ) END IF * RETURN * * End of ZSYSVXX * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/dsytri_rook.f
22
13375
*> \brief \b DSYTRI_ROOK * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download DSYTRI_ROOK + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dsytri_rook.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dsytri_rook.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dsytri_rook.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE DSYTRI_ROOK( UPLO, N, A, LDA, IPIV, WORK, INFO ) * * .. Scalar Arguments .. * CHARACTER UPLO * INTEGER INFO, LDA, N * .. * .. Array Arguments .. * INTEGER IPIV( * ) * DOUBLE PRECISION A( LDA, * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DSYTRI_ROOK computes the inverse of a real symmetric *> matrix A using the factorization A = U*D*U**T or A = L*D*L**T *> computed by DSYTRF_ROOK. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> Specifies whether the details of the factorization are stored *> as an upper or lower triangular matrix. *> = 'U': Upper triangular, form is A = U*D*U**T; *> = 'L': Lower triangular, form is A = L*D*L**T. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix A. N >= 0. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is DOUBLE PRECISION array, dimension (LDA,N) *> On entry, the block diagonal matrix D and the multipliers *> used to obtain the factor U or L as computed by DSYTRF_ROOK. *> *> On exit, if INFO = 0, the (symmetric) inverse of the original *> matrix. If UPLO = 'U', the upper triangular part of the *> inverse is formed and the part of A below the diagonal is not *> referenced; if UPLO = 'L' the lower triangular part of the *> inverse is formed and the part of A above the diagonal is *> not referenced. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,N). *> \endverbatim *> *> \param[in] IPIV *> \verbatim *> IPIV is INTEGER array, dimension (N) *> Details of the interchanges and the block structure of D *> as determined by DSYTRF_ROOK. *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is DOUBLE PRECISION array, dimension (N) *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> > 0: if INFO = i, D(i,i) = 0; the matrix is singular and its *> inverse could not be computed. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date April 2012 * *> \ingroup doubleSYcomputational * *> \par Contributors: * ================== *> *> \verbatim *> *> April 2012, Igor Kozachenko, *> Computer Science Division, *> University of California, Berkeley *> *> September 2007, Sven Hammarling, Nicholas J. Higham, Craig Lucas, *> School of Mathematics, *> University of Manchester *> *> \endverbatim * * ===================================================================== SUBROUTINE DSYTRI_ROOK( UPLO, N, A, LDA, IPIV, WORK, INFO ) * * -- LAPACK computational routine (version 3.4.1) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * April 2012 * * .. Scalar Arguments .. CHARACTER UPLO INTEGER INFO, LDA, N * .. * .. Array Arguments .. INTEGER IPIV( * ) DOUBLE PRECISION A( LDA, * ), WORK( * ) * .. * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ONE, ZERO PARAMETER ( ONE = 1.0D+0, ZERO = 0.0D+0 ) * .. * .. Local Scalars .. LOGICAL UPPER INTEGER K, KP, KSTEP DOUBLE PRECISION AK, AKKP1, AKP1, D, T, TEMP * .. * .. External Functions .. LOGICAL LSAME DOUBLE PRECISION DDOT EXTERNAL LSAME, DDOT * .. * .. External Subroutines .. EXTERNAL DCOPY, DSWAP, DSYMV, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC ABS, MAX * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 UPPER = LSAME( UPLO, 'U' ) IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -4 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'DSYTRI_ROOK', -INFO ) RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * * Check that the diagonal matrix D is nonsingular. * IF( UPPER ) THEN * * Upper triangular storage: examine D from bottom to top * DO 10 INFO = N, 1, -1 IF( IPIV( INFO ).GT.0 .AND. A( INFO, INFO ).EQ.ZERO ) $ RETURN 10 CONTINUE ELSE * * Lower triangular storage: examine D from top to bottom. * DO 20 INFO = 1, N IF( IPIV( INFO ).GT.0 .AND. A( INFO, INFO ).EQ.ZERO ) $ RETURN 20 CONTINUE END IF INFO = 0 * IF( UPPER ) THEN * * Compute inv(A) from the factorization A = U*D*U**T. * * K is the main loop index, increasing from 1 to N in steps of * 1 or 2, depending on the size of the diagonal blocks. * K = 1 30 CONTINUE * * If K > N, exit from loop. * IF( K.GT.N ) $ GO TO 40 * IF( IPIV( K ).GT.0 ) THEN * * 1 x 1 diagonal block * * Invert the diagonal block. * A( K, K ) = ONE / A( K, K ) * * Compute column K of the inverse. * IF( K.GT.1 ) THEN CALL DCOPY( K-1, A( 1, K ), 1, WORK, 1 ) CALL DSYMV( UPLO, K-1, -ONE, A, LDA, WORK, 1, ZERO, $ A( 1, K ), 1 ) A( K, K ) = A( K, K ) - DDOT( K-1, WORK, 1, A( 1, K ), $ 1 ) END IF KSTEP = 1 ELSE * * 2 x 2 diagonal block * * Invert the diagonal block. * T = ABS( A( K, K+1 ) ) AK = A( K, K ) / T AKP1 = A( K+1, K+1 ) / T AKKP1 = A( K, K+1 ) / T D = T*( AK*AKP1-ONE ) A( K, K ) = AKP1 / D A( K+1, K+1 ) = AK / D A( K, K+1 ) = -AKKP1 / D * * Compute columns K and K+1 of the inverse. * IF( K.GT.1 ) THEN CALL DCOPY( K-1, A( 1, K ), 1, WORK, 1 ) CALL DSYMV( UPLO, K-1, -ONE, A, LDA, WORK, 1, ZERO, $ A( 1, K ), 1 ) A( K, K ) = A( K, K ) - DDOT( K-1, WORK, 1, A( 1, K ), $ 1 ) A( K, K+1 ) = A( K, K+1 ) - $ DDOT( K-1, A( 1, K ), 1, A( 1, K+1 ), 1 ) CALL DCOPY( K-1, A( 1, K+1 ), 1, WORK, 1 ) CALL DSYMV( UPLO, K-1, -ONE, A, LDA, WORK, 1, ZERO, $ A( 1, K+1 ), 1 ) A( K+1, K+1 ) = A( K+1, K+1 ) - $ DDOT( K-1, WORK, 1, A( 1, K+1 ), 1 ) END IF KSTEP = 2 END IF * IF( KSTEP.EQ.1 ) THEN * * Interchange rows and columns K and IPIV(K) in the leading * submatrix A(1:k+1,1:k+1) * KP = IPIV( K ) IF( KP.NE.K ) THEN IF( KP.GT.1 ) $ CALL DSWAP( KP-1, A( 1, K ), 1, A( 1, KP ), 1 ) CALL DSWAP( K-KP-1, A( KP+1, K ), 1, A( KP, KP+1 ), LDA ) TEMP = A( K, K ) A( K, K ) = A( KP, KP ) A( KP, KP ) = TEMP END IF ELSE * * Interchange rows and columns K and K+1 with -IPIV(K) and * -IPIV(K+1)in the leading submatrix A(1:k+1,1:k+1) * KP = -IPIV( K ) IF( KP.NE.K ) THEN IF( KP.GT.1 ) $ CALL DSWAP( KP-1, A( 1, K ), 1, A( 1, KP ), 1 ) CALL DSWAP( K-KP-1, A( KP+1, K ), 1, A( KP, KP+1 ), LDA ) * TEMP = A( K, K ) A( K, K ) = A( KP, KP ) A( KP, KP ) = TEMP TEMP = A( K, K+1 ) A( K, K+1 ) = A( KP, K+1 ) A( KP, K+1 ) = TEMP END IF * K = K + 1 KP = -IPIV( K ) IF( KP.NE.K ) THEN IF( KP.GT.1 ) $ CALL DSWAP( KP-1, A( 1, K ), 1, A( 1, KP ), 1 ) CALL DSWAP( K-KP-1, A( KP+1, K ), 1, A( KP, KP+1 ), LDA ) TEMP = A( K, K ) A( K, K ) = A( KP, KP ) A( KP, KP ) = TEMP END IF END IF * K = K + 1 GO TO 30 40 CONTINUE * ELSE * * Compute inv(A) from the factorization A = L*D*L**T. * * K is the main loop index, increasing from 1 to N in steps of * 1 or 2, depending on the size of the diagonal blocks. * K = N 50 CONTINUE * * If K < 1, exit from loop. * IF( K.LT.1 ) $ GO TO 60 * IF( IPIV( K ).GT.0 ) THEN * * 1 x 1 diagonal block * * Invert the diagonal block. * A( K, K ) = ONE / A( K, K ) * * Compute column K of the inverse. * IF( K.LT.N ) THEN CALL DCOPY( N-K, A( K+1, K ), 1, WORK, 1 ) CALL DSYMV( UPLO, N-K, -ONE, A( K+1, K+1 ), LDA, WORK, 1, $ ZERO, A( K+1, K ), 1 ) A( K, K ) = A( K, K ) - DDOT( N-K, WORK, 1, A( K+1, K ), $ 1 ) END IF KSTEP = 1 ELSE * * 2 x 2 diagonal block * * Invert the diagonal block. * T = ABS( A( K, K-1 ) ) AK = A( K-1, K-1 ) / T AKP1 = A( K, K ) / T AKKP1 = A( K, K-1 ) / T D = T*( AK*AKP1-ONE ) A( K-1, K-1 ) = AKP1 / D A( K, K ) = AK / D A( K, K-1 ) = -AKKP1 / D * * Compute columns K-1 and K of the inverse. * IF( K.LT.N ) THEN CALL DCOPY( N-K, A( K+1, K ), 1, WORK, 1 ) CALL DSYMV( UPLO, N-K, -ONE, A( K+1, K+1 ), LDA, WORK, 1, $ ZERO, A( K+1, K ), 1 ) A( K, K ) = A( K, K ) - DDOT( N-K, WORK, 1, A( K+1, K ), $ 1 ) A( K, K-1 ) = A( K, K-1 ) - $ DDOT( N-K, A( K+1, K ), 1, A( K+1, K-1 ), $ 1 ) CALL DCOPY( N-K, A( K+1, K-1 ), 1, WORK, 1 ) CALL DSYMV( UPLO, N-K, -ONE, A( K+1, K+1 ), LDA, WORK, 1, $ ZERO, A( K+1, K-1 ), 1 ) A( K-1, K-1 ) = A( K-1, K-1 ) - $ DDOT( N-K, WORK, 1, A( K+1, K-1 ), 1 ) END IF KSTEP = 2 END IF * IF( KSTEP.EQ.1 ) THEN * * Interchange rows and columns K and IPIV(K) in the trailing * submatrix A(k-1:n,k-1:n) * KP = IPIV( K ) IF( KP.NE.K ) THEN IF( KP.LT.N ) $ CALL DSWAP( N-KP, A( KP+1, K ), 1, A( KP+1, KP ), 1 ) CALL DSWAP( KP-K-1, A( K+1, K ), 1, A( KP, K+1 ), LDA ) TEMP = A( K, K ) A( K, K ) = A( KP, KP ) A( KP, KP ) = TEMP END IF ELSE * * Interchange rows and columns K and K-1 with -IPIV(K) and * -IPIV(K-1) in the trailing submatrix A(k-1:n,k-1:n) * KP = -IPIV( K ) IF( KP.NE.K ) THEN IF( KP.LT.N ) $ CALL DSWAP( N-KP, A( KP+1, K ), 1, A( KP+1, KP ), 1 ) CALL DSWAP( KP-K-1, A( K+1, K ), 1, A( KP, K+1 ), LDA ) * TEMP = A( K, K ) A( K, K ) = A( KP, KP ) A( KP, KP ) = TEMP TEMP = A( K, K-1 ) A( K, K-1 ) = A( KP, K-1 ) A( KP, K-1 ) = TEMP END IF * K = K - 1 KP = -IPIV( K ) IF( KP.NE.K ) THEN IF( KP.LT.N ) $ CALL DSWAP( N-KP, A( KP+1, K ), 1, A( KP+1, KP ), 1 ) CALL DSWAP( KP-K-1, A( K+1, K ), 1, A( KP, K+1 ), LDA ) TEMP = A( K, K ) A( K, K ) = A( KP, KP ) A( KP, KP ) = TEMP END IF END IF * K = K - 1 GO TO 50 60 CONTINUE END IF * RETURN * * End of DSYTRI_ROOK * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/TESTING/LIN/cerrsy.f
24
13750
*> \brief \b CERRSY * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE CERRSY( PATH, NUNIT ) * * .. Scalar Arguments .. * CHARACTER*3 PATH * INTEGER NUNIT * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CERRSY tests the error exits for the COMPLEX routines *> for symmetric indefinite matrices. *> \endverbatim * * Arguments: * ========== * *> \param[in] PATH *> \verbatim *> PATH is CHARACTER*3 *> The LAPACK path name for the routines to be tested. *> \endverbatim *> *> \param[in] NUNIT *> \verbatim *> NUNIT is INTEGER *> The unit number for output. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2013 * *> \ingroup complex_lin * * ===================================================================== SUBROUTINE CERRSY( PATH, NUNIT ) * * -- LAPACK test routine (version 3.5.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2013 * * .. Scalar Arguments .. CHARACTER*3 PATH INTEGER NUNIT * .. * * ===================================================================== * * .. Parameters .. INTEGER NMAX PARAMETER ( NMAX = 4 ) * .. * .. Local Scalars .. CHARACTER*2 C2 INTEGER I, INFO, J REAL ANRM, RCOND * .. * .. Local Arrays .. INTEGER IP( NMAX ) REAL R( NMAX ), R1( NMAX ), R2( NMAX ) COMPLEX A( NMAX, NMAX ), AF( NMAX, NMAX ), B( NMAX ), $ W( 2*NMAX ), X( NMAX ) * .. * .. External Functions .. LOGICAL LSAMEN EXTERNAL LSAMEN * .. * .. External Subroutines .. EXTERNAL ALAESM, CHKXER, CSPCON, CSPRFS, CSPTRF, CSPTRI, $ CSPTRS, CSYCON, CSYCON_ROOK, CSYRFS, CSYTF2, $ CSYTF2_ROOK, CSYTRF, CSYTRF_ROOK, CSYTRI, $ CSYTRI_ROOK, CSYTRI2, CSYTRS, CSYTRS_ROOK * .. * .. Scalars in Common .. LOGICAL LERR, OK CHARACTER*32 SRNAMT INTEGER INFOT, NOUT * .. * .. Common blocks .. COMMON / INFOC / INFOT, NOUT, OK, LERR COMMON / SRNAMC / SRNAMT * .. * .. Intrinsic Functions .. INTRINSIC CMPLX, REAL * .. * .. Executable Statements .. * NOUT = NUNIT WRITE( NOUT, FMT = * ) C2 = PATH( 2: 3 ) * * Set the variables to innocuous values. * DO 20 J = 1, NMAX DO 10 I = 1, NMAX A( I, J ) = CMPLX( 1. / REAL( I+J ), -1. / REAL( I+J ) ) AF( I, J ) = CMPLX( 1. / REAL( I+J ), -1. / REAL( I+J ) ) 10 CONTINUE B( J ) = 0. R1( J ) = 0. R2( J ) = 0. W( J ) = 0. X( J ) = 0. IP( J ) = J 20 CONTINUE ANRM = 1.0 OK = .TRUE. * * Test error exits of the routines that use factorization * of a symmetric indefinite matrix with patrial * (Bunch-Kaufman) diagonal pivoting method. * IF( LSAMEN( 2, C2, 'SY' ) ) THEN * * CSYTRF * SRNAMT = 'CSYTRF' INFOT = 1 CALL CSYTRF( '/', 0, A, 1, IP, W, 1, INFO ) CALL CHKXER( 'CSYTRF', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTRF( 'U', -1, A, 1, IP, W, 1, INFO ) CALL CHKXER( 'CSYTRF', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYTRF( 'U', 2, A, 1, IP, W, 4, INFO ) CALL CHKXER( 'CSYTRF', INFOT, NOUT, LERR, OK ) * * CSYTF2 * SRNAMT = 'CSYTF2' INFOT = 1 CALL CSYTF2( '/', 0, A, 1, IP, INFO ) CALL CHKXER( 'CSYTF2', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTF2( 'U', -1, A, 1, IP, INFO ) CALL CHKXER( 'CSYTF2', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYTF2( 'U', 2, A, 1, IP, INFO ) CALL CHKXER( 'CSYTF2', INFOT, NOUT, LERR, OK ) * * CSYTRI * SRNAMT = 'CSYTRI' INFOT = 1 CALL CSYTRI( '/', 0, A, 1, IP, W, INFO ) CALL CHKXER( 'CSYTRI', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTRI( 'U', -1, A, 1, IP, W, INFO ) CALL CHKXER( 'CSYTRI', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYTRI( 'U', 2, A, 1, IP, W, INFO ) CALL CHKXER( 'CSYTRI', INFOT, NOUT, LERR, OK ) * * CSYTRI2 * SRNAMT = 'CSYTRI2' INFOT = 1 CALL CSYTRI2( '/', 0, A, 1, IP, W, 1, INFO ) CALL CHKXER( 'CSYTRI2', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTRI2( 'U', -1, A, 1, IP, W, 1, INFO ) CALL CHKXER( 'CSYTRI2', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYTRI2( 'U', 2, A, 1, IP, W, 1, INFO ) CALL CHKXER( 'CSYTRI2', INFOT, NOUT, LERR, OK ) * * CSYTRS * SRNAMT = 'CSYTRS' INFOT = 1 CALL CSYTRS( '/', 0, 0, A, 1, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTRS( 'U', -1, 0, A, 1, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL CSYTRS( 'U', 0, -1, A, 1, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL CSYTRS( 'U', 2, 1, A, 1, IP, B, 2, INFO ) CALL CHKXER( 'CSYTRS', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL CSYTRS( 'U', 2, 1, A, 2, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS', INFOT, NOUT, LERR, OK ) * * CSYRFS * SRNAMT = 'CSYRFS' INFOT = 1 CALL CSYRFS( '/', 0, 0, A, 1, AF, 1, IP, B, 1, X, 1, R1, R2, W, $ R, INFO ) CALL CHKXER( 'CSYRFS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYRFS( 'U', -1, 0, A, 1, AF, 1, IP, B, 1, X, 1, R1, R2, $ W, R, INFO ) CALL CHKXER( 'CSYRFS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL CSYRFS( 'U', 0, -1, A, 1, AF, 1, IP, B, 1, X, 1, R1, R2, $ W, R, INFO ) CALL CHKXER( 'CSYRFS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL CSYRFS( 'U', 2, 1, A, 1, AF, 2, IP, B, 2, X, 2, R1, R2, W, $ R, INFO ) CALL CHKXER( 'CSYRFS', INFOT, NOUT, LERR, OK ) INFOT = 7 CALL CSYRFS( 'U', 2, 1, A, 2, AF, 1, IP, B, 2, X, 2, R1, R2, W, $ R, INFO ) CALL CHKXER( 'CSYRFS', INFOT, NOUT, LERR, OK ) INFOT = 10 CALL CSYRFS( 'U', 2, 1, A, 2, AF, 2, IP, B, 1, X, 2, R1, R2, W, $ R, INFO ) CALL CHKXER( 'CSYRFS', INFOT, NOUT, LERR, OK ) INFOT = 12 CALL CSYRFS( 'U', 2, 1, A, 2, AF, 2, IP, B, 2, X, 1, R1, R2, W, $ R, INFO ) CALL CHKXER( 'CSYRFS', INFOT, NOUT, LERR, OK ) * * CSYCON * SRNAMT = 'CSYCON' INFOT = 1 CALL CSYCON( '/', 0, A, 1, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYCON( 'U', -1, A, 1, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYCON( 'U', 2, A, 1, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON', INFOT, NOUT, LERR, OK ) INFOT = 6 CALL CSYCON( 'U', 1, A, 1, IP, -ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON', INFOT, NOUT, LERR, OK ) * * Test error exits of the routines that use factorization * of a symmetric indefinite matrix with "rook" * (bounded Bunch-Kaufman) diagonal pivoting method. * ELSE IF( LSAMEN( 2, C2, 'SR' ) ) THEN * * CSYTRF_ROOK * SRNAMT = 'CSYTRF_ROOK' INFOT = 1 CALL CSYTRF_ROOK( '/', 0, A, 1, IP, W, 1, INFO ) CALL CHKXER( 'CSYTRF_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTRF_ROOK( 'U', -1, A, 1, IP, W, 1, INFO ) CALL CHKXER( 'CSYTRF_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYTRF_ROOK( 'U', 2, A, 1, IP, W, 4, INFO ) CALL CHKXER( 'CSYTRF_ROOK', INFOT, NOUT, LERR, OK ) * * CSYTF2_ROOK * SRNAMT = 'CSYTF2_ROOK' INFOT = 1 CALL CSYTF2_ROOK( '/', 0, A, 1, IP, INFO ) CALL CHKXER( 'CSYTF2_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTF2_ROOK( 'U', -1, A, 1, IP, INFO ) CALL CHKXER( 'CSYTF2_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYTF2_ROOK( 'U', 2, A, 1, IP, INFO ) CALL CHKXER( 'CSYTF2_ROOK', INFOT, NOUT, LERR, OK ) * * CSYTRI_ROOK * SRNAMT = 'CSYTRI_ROOK' INFOT = 1 CALL CSYTRI_ROOK( '/', 0, A, 1, IP, W, INFO ) CALL CHKXER( 'CSYTRI_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTRI_ROOK( 'U', -1, A, 1, IP, W, INFO ) CALL CHKXER( 'CSYTRI_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYTRI_ROOK( 'U', 2, A, 1, IP, W, INFO ) CALL CHKXER( 'CSYTRI_ROOK', INFOT, NOUT, LERR, OK ) * * CSYTRS_ROOK * SRNAMT = 'CSYTRS_ROOK' INFOT = 1 CALL CSYTRS_ROOK( '/', 0, 0, A, 1, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYTRS_ROOK( 'U', -1, 0, A, 1, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL CSYTRS_ROOK( 'U', 0, -1, A, 1, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL CSYTRS_ROOK( 'U', 2, 1, A, 1, IP, B, 2, INFO ) CALL CHKXER( 'CSYTRS_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL CSYTRS_ROOK( 'U', 2, 1, A, 2, IP, B, 1, INFO ) CALL CHKXER( 'CSYTRS_ROOK', INFOT, NOUT, LERR, OK ) * * CSYCON_ROOK * SRNAMT = 'CSYCON_ROOK' INFOT = 1 CALL CSYCON_ROOK( '/', 0, A, 1, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSYCON_ROOK( 'U', -1, A, 1, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL CSYCON_ROOK( 'U', 2, A, 1, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON_ROOK', INFOT, NOUT, LERR, OK ) INFOT = 6 CALL CSYCON_ROOK( 'U', 1, A, 1, IP, -ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSYCON_ROOK', INFOT, NOUT, LERR, OK ) * * Test error exits of the routines that use factorization * of a symmetric indefinite packed matrix with patrial * (Bunch-Kaufman) diagonal pivoting method. * ELSE IF( LSAMEN( 2, C2, 'SP' ) ) THEN * * CSPTRF * SRNAMT = 'CSPTRF' INFOT = 1 CALL CSPTRF( '/', 0, A, IP, INFO ) CALL CHKXER( 'CSPTRF', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSPTRF( 'U', -1, A, IP, INFO ) CALL CHKXER( 'CSPTRF', INFOT, NOUT, LERR, OK ) * * CSPTRI * SRNAMT = 'CSPTRI' INFOT = 1 CALL CSPTRI( '/', 0, A, IP, W, INFO ) CALL CHKXER( 'CSPTRI', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSPTRI( 'U', -1, A, IP, W, INFO ) CALL CHKXER( 'CSPTRI', INFOT, NOUT, LERR, OK ) * * CSPTRS * SRNAMT = 'CSPTRS' INFOT = 1 CALL CSPTRS( '/', 0, 0, A, IP, B, 1, INFO ) CALL CHKXER( 'CSPTRS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSPTRS( 'U', -1, 0, A, IP, B, 1, INFO ) CALL CHKXER( 'CSPTRS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL CSPTRS( 'U', 0, -1, A, IP, B, 1, INFO ) CALL CHKXER( 'CSPTRS', INFOT, NOUT, LERR, OK ) INFOT = 7 CALL CSPTRS( 'U', 2, 1, A, IP, B, 1, INFO ) CALL CHKXER( 'CSPTRS', INFOT, NOUT, LERR, OK ) * * CSPRFS * SRNAMT = 'CSPRFS' INFOT = 1 CALL CSPRFS( '/', 0, 0, A, AF, IP, B, 1, X, 1, R1, R2, W, R, $ INFO ) CALL CHKXER( 'CSPRFS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSPRFS( 'U', -1, 0, A, AF, IP, B, 1, X, 1, R1, R2, W, R, $ INFO ) CALL CHKXER( 'CSPRFS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL CSPRFS( 'U', 0, -1, A, AF, IP, B, 1, X, 1, R1, R2, W, R, $ INFO ) CALL CHKXER( 'CSPRFS', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL CSPRFS( 'U', 2, 1, A, AF, IP, B, 1, X, 2, R1, R2, W, R, $ INFO ) CALL CHKXER( 'CSPRFS', INFOT, NOUT, LERR, OK ) INFOT = 10 CALL CSPRFS( 'U', 2, 1, A, AF, IP, B, 2, X, 1, R1, R2, W, R, $ INFO ) CALL CHKXER( 'CSPRFS', INFOT, NOUT, LERR, OK ) * * CSPCON * SRNAMT = 'CSPCON' INFOT = 1 CALL CSPCON( '/', 0, A, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSPCON', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL CSPCON( 'U', -1, A, IP, ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSPCON', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL CSPCON( 'U', 1, A, IP, -ANRM, RCOND, W, INFO ) CALL CHKXER( 'CSPCON', INFOT, NOUT, LERR, OK ) END IF * * Print a summary line. * CALL ALAESM( PATH, OK, NOUT ) * RETURN * * End of CERRSY * END
bsd-3-clause
nicjhan/MOM5
src/preprocessing/river_regrid/river_regrid.f90
7
88253
program river_regrid !----------------------------------------------------------------------- ! GNU General Public License ! ! This program is free software; you can redistribute it and/or modify it and ! are expected to follow 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. ! ! MOM 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. ! ! For the full text of the GNU General Public License, ! write to: Free Software Foundation, Inc., ! 675 Mass Ave, Cambridge, MA 02139, USA. ! or see: http://www.gnu.org/licenses/gpl.html !----------------------------------------------------------------------- ! !<CONTACT EMAIL="GFDL.Climate.Model.Info@noaa.gov"> Zhi Liang </CONTACT> !<CONTACT EMAIL="GFDL.Climate.Model.Info@noaa.gov"> Kirsten Findell </CONTACT> !<OVERVIEW> ! This program can remap river network data from spherical grid onto another ! spherical grid. !</OVERVIEW> !<DESCRIPTION> ! The program expects to read river network data from a netcdf file, which ! is specified by the namelist variable "river_input_file". This file should ! contains field 'cellarea', 'tocell', 'fromcell', 'basin', 'basincells', ! 'order', 'travel', 'subL', 'subA','disttomouth', 'disttoocean' and 'dx'. ! The program will remap the data in "river_input_file" onto the grid, which ! is specified by namelist grid_file. The grid file should contains the same ! grid as the land modle to be run. The output is stored in a netcdf file, which ! is specified by river_output_file. !</DESCRIPTION> use mpp_mod, only : mpp_error, FATAL, NOTE, mpp_init, mpp_pe, mpp_root_pe, mpp_npes use mpp_domains_mod, only : domain2D, mpp_define_layout, mpp_define_domains, mpp_get_compute_domain use mpp_domains_mod, only : mpp_global_field use mpp_io_mod, only : mpp_open, mpp_close, axistype, fieldtype, mpp_write, mpp_write_meta use mpp_io_mod, only : MPP_OVERWR, MPP_NETCDF, MPP_MULTI, MPP_RDONLY, MPP_ASCII, MPP_SINGLE use mpp_io_mod, only : mpp_get_atts, mpp_get_axes, mpp_get_axis_data, mpp_get_fields use mpp_io_mod, only : mpp_read, mpp_get_info, mpp_io_init use fms_mod, only : open_namelist_file, check_nml_error, stdout, stdlog, close_file use fms_mod, only : file_exist, write_version_number, error_mesg, read_data use fms_mod, only : fms_init, fms_end, field_exist, field_size use axis_utils_mod, only : get_axis_cart, get_axis_bounds use constants_mod, only : PI, radius, constants_init, DEG_TO_RAD use fms_io_mod, only : fms_io_exit use horiz_interp_mod, only : horiz_interp_init, horiz_interp_new, horiz_interp, horiz_interp_del, horiz_interp_type implicit none !--- namelist interface ---------------------------------------------- !<NAMELIST NAME="river_regrid_nml"> ! <DATA NAME="river_input_file" TYPE="character(len=128)" > ! river data source file. ! </DATA> ! <DATA NAME="grid_file" TYPE="character(len=128)" > ! the grid file that contains land and ocean grid information. ! </DATA> ! <DATA NAME="river_output_file" TYPE="character(len=128)" > ! The output river data file after coupled with land grid. ! </DATA> ! <DATA NAME="lon_start, lon_end" TYPE="real"> ! starting and ending longitude of the river network to be extended to. Default value is 0 and 360. ! </DATA> ! <DATA NAME="lat_start, lat_end" TYPE="real"> ! starting and ending latitude of the river network to be extended to. Default value is -90 and 90. ! </DATA> ! <DATA NAME="lat_end" TYPE="real"> ! The ending latitude. Default value is 90. Used to extend river network. ! </DATA> !</NAMELIST> character(len=128) :: river_input_file = 'river_input.nc' character(len=128) :: grid_file = 'grid_spec.nc' character(len=128) :: river_output_file = 'river_output.nc' ! character(len=128) :: edit_table = 'river_table' real :: lon_start = 0 real :: lon_end = 360 real :: lat_start = -90 real :: lat_end = 90 namelist /river_regrid_nml/ river_input_file, river_output_file, grid_file, & lon_start, lon_end, lat_start, lat_end real :: missing_value = -9999. !--- derived data type ------------------------------------------------ type river_regrid_type real, dimension(:), pointer :: lon => NULL() ! longitude (in degree) real, dimension(:), pointer :: lat => NULL() ! lattitude (in degree) real, dimension(:), pointer :: lonb => NULL() ! longitude edges (in degree) real, dimension(:), pointer :: latb => NULL() ! latitude edges (in degree) real, dimension(:,:), pointer :: slope => NULL() ! slope real, dimension(:,:), pointer :: cellarea => NULL() ! cell area real, dimension(:,:), pointer :: subL => NULL() ! subbasin length real, dimension(:,:), pointer :: subA => NULL() ! subbasin area real, dimension(:,:), pointer :: disttoocean => NULL() ! distant to ocean real, dimension(:,:), pointer :: celllength => NULL() ! cell size integer, dimension(:,:), pointer :: order => NULL() ! river order integer, dimension(:,:), pointer :: basinid => NULL() ! basin id integer, dimension(:,:), pointer :: tocell => NULL() ! tocell information integer, dimension(:,:), pointer :: fromcell => NULL() ! fromcell information integer, dimension(:,:), pointer :: basincells => NULL() ! basincells integer, dimension(:,:), pointer :: travel => NULL() ! number of travel to ocean real, dimension(:,:), pointer :: mask => NULL() ! land/sea mask(land=1) real, dimension(:,:,:), pointer :: dist => NULL() ! distance to neighbor cell integer, dimension(:,:), pointer :: neighbor => NULL() ! neighbor information integer, dimension(:,:), pointer :: land_order => NULL() ! land_order integer :: nlon, nlat ! grid size end type river_regrid_type !--- version information --------------------------------------------- character(len=128) :: version = '$ID$' character(len=128) :: tagname = '$Name: tikal $' !--- other variables type(river_regrid_type),save :: Source type(river_regrid_type),save :: River real, parameter :: lnd_thresh = 1.0e-6 ! some small number logical :: module_is_initialized = .FALSE. integer :: next_basinid = 0 real :: D2R integer :: nlon, nlat ! grid size of extended river grid real, dimension(:,:), allocatable :: mask_ocn, lon_ocn, lat_ocn !--- begin the program call fms_init call constants_init call river_regrid_init() write(stdout(),*)"complete river_regrid_init" call river_regrid_data(River) write(stdout(),*)"complete river_regrid_data" if(mpp_pe() == mpp_root_pe())call write_river_regrid_data(River) write(stdout(),*)"complete write_river_regrid_data" call river_regrid_end(River) write(stdout(),*)" ****** congradulation! You have successfully run river_regrid" call fms_end contains !--- initialization routine, reading namelist, read river source !--- data and land grid information. subroutine river_regrid_init integer :: unit, ierr, io_status !--- read namelist and write out namelist -------------------------- unit = open_namelist_file() read (unit, river_regrid_nml,iostat=io_status) write (stdout(),'(/)') write (stdout(), river_regrid_nml) write (stdlog(), river_regrid_nml) ierr = check_nml_error(io_status,'river_regrid_nml') call close_file (unit) D2R = PI/180.0 !--- write out version information --------------------------------- call write_version_number(version, tagname) !--- read the river data from river_input_file call read_river_src_data( ) return end subroutine river_regrid_init !##################################################################### !--- remap and define river routing network. subroutine river_regrid_data(River) type(river_regrid_type), intent(inout) :: River !--- define River to make land and river has the same range and initialize !--- the river data. call define_new_grid(River) !--- the following will be done only on root pe. if(mpp_pe() .NE. mpp_root_pe()) return !--- remove previously land point call trim_river(River) !--- define land order for new river grid call define_new_land_order(River) !--- define new land point data call define_new_land_data(River) !--- extend river with travel = 0 , tocell not zero, full land cell an extra points. call update_coast_land(River) !--- check river data to see if there is any bad value. call check_river_data(River) end subroutine river_regrid_data !#################################################################### subroutine update_coast_land(River) type(river_regrid_type), intent(inout) :: River integer :: nbasin, basin, cur_basin, num_nbrs integer :: i_array(8), j_array(8) integer :: i, j, ii, jj, i_nbr, j_nbr integer :: num_river_merged = 0 integer :: num_river_extended = 0 integer :: num_partial_land = 0 !--- first add one ocean point to the river network with the coast point is a full land cell. !--- ( point with travel=0, tocell > 0) nbasin = maxval(River%basinid) do basin = 1, nbasin LOOP: do j = 1, nlat do i = 1, nlon if(River%basinid(i,j) == basin .AND. River%travel(i,j) == 0) then if(River%tocell(i,j)>0 .AND. River%mask(i,j) ==1 ) then ! full land coast point, not inland point, add one more point. call get_nbr_index(River%tocell(i,j), i, j, i_array, j_array, num_nbrs) if(num_nbrs .ne. 1) call mpp_error(FATAL,'River will flow to one and only one direction') i_nbr = i_array(1) j_nbr = j_array(1) if(River%basinid(i_nbr,j_nbr) >0) then ! the ocean point is already extended. num_river_merged = num_river_merged + 1 cur_basin = River%basinid(i_nbr,j_nbr) if(River%fromcell(i_nbr,j_nbr) <0) then ! write(stdout(), *)"The river with basinid = ", basin, & ! " will be merged into river with basin =", cur_basin call mpp_error(FATAL,'crash') end if do jj = 1, nlat do ii = 1, nlon if(River%basinid(ii,jj) == basin) then River%basinid(ii,jj) = cur_basin River%travel(ii,jj) = River%travel(ii,jj) + 1 end if end do end do if(River%tocell(i,j) .lt. 16) then River%fromcell(i_nbr,j_nbr) = River%fromcell(i_nbr,j_nbr) + River%tocell(i,j)*16 else if(River%tocell(i,j) .ge. 16) then River%fromcell(i_nbr,j_nbr) = River%fromcell(i_nbr,j_nbr) + River%tocell(i,j)/16 endif else num_river_extended = num_river_extended + 1 ! write(stdout(), *) "The river with basinid = ", basin, " will be extended " do jj = 1, nlat do ii = 1, nlon if(River%basinid(ii,jj) == basin) then River%travel(ii,jj) = River%travel(ii,jj) + 1 end if end do end do River%basinid(i_nbr,j_nbr) = basin River%travel(i_nbr,j_nbr) = 0 River%tocell(i_nbr,j_nbr) = 0 if(River%tocell(i,j) .lt. 16) then River%fromcell(i_nbr,j_nbr) = River%tocell(i,j)*16 else if(River%tocell(i,j) .ge. 16) then River%fromcell(i_nbr,j_nbr) = River%tocell(i,j)/16 endif end if end if exit LOOP end if end do end do LOOP end do !--- set tocell of coast partial land to 0 num_partial_land = 0 do j = 1, nlat do i = 1, nlon if(River%travel(i,j) == 0 .AND. River%tocell(i,j) > 0) then ! coast point if(River%mask(i,j) < 1) then River%tocell(i,j) = 0 ! partial land coast point will flow into itself. num_partial_land = num_partial_land + 1 end if end if end do end do write(stdout(),*) "******* number of river extended is :", num_river_extended write(stdout(),*) "******* number of river merged is :", num_river_merged write(stdout(),*) "******* number of coast partial river point with tocell set to 0 is :", num_partial_land end subroutine update_coast_land !#################################################################### subroutine check_river_data(River) type(river_regrid_type), intent(in) :: River integer :: nbasin, basin, ncoast, i, j integer :: i_array(8), j_array(8), i_nbr, j_nbr, num_nbrs ! check that all the data should be missing value or greater than or equal to 0 do j = 1, nlat do i = 1, nlon if(River%basinid(i,j) < 0 .AND. River%basinid(i,j) .NE. missing_value) call mpp_error(FATAL, & "the basinid of some points is less than 0 and not equal to missing_value") if(River%cellarea(i,j) < 0 .AND. River%cellarea(i,j) .NE. missing_value) call mpp_error(FATAL, & "the cellarea of some points is less than 0 and not equal to missing_value") if(River%subL(i,j) < 0 .AND. River%subL(i,j) .NE. missing_value) call mpp_error(FATAL, & "the subL of some points is less than 0 and not equal to missing_value") if(River%subA(i,j) < 0 .AND. River%subA(i,j) .NE. missing_value) call mpp_error(FATAL, & "the subA of some points is less than 0 and not equal to missing_value") if(River%disttoocean(i,j) < 0 .AND. River%disttoocean(i,j) .NE. missing_value) call mpp_error(FATAL, & "the disttoocean of some points is less than 0 and not equal to missing_value") if(River%celllength(i,j) < 0 .AND. River%celllength(i,j) .NE. missing_value) call mpp_error(FATAL, & "the celllength of some points is less than 0 and not equal to missing_value") if(River%order(i,j) < 0 .AND. River%order(i,j) .NE. missing_value) call mpp_error(FATAL, & "the order of some points is less than 0 and not equal to missing_value") if(River%tocell(i,j) < 0 .AND. River%tocell(i,j) .NE. missing_value) call mpp_error(FATAL, & "the tocell of some points is less than 0 and not equal to missing_value") if(River%fromcell(i,j) < 0 .AND. River%fromcell(i,j) .NE. missing_value) call mpp_error(FATAL, & "the fromcell of some points is less than 0 and not equal to missing_value") if(River%basincells(i,j) < 0 .AND. River%basincells(i,j) .NE. missing_value) call mpp_error(FATAL, & "the basincells of some points is less than 0 and not equal to missing_value") if(River%travel(i,j) < 0 .AND. River%travel(i,j) .NE. missing_value) call mpp_error(FATAL, & "the basinid of some points is less than 0 and not equal to missing_value") end do end do ! check river travel to make sure there is one and only one point with travel = 0. nbasin = maxval(River%basinid) do basin = 1, nbasin ncoast = 0 do j = 1, nlat do i = 1, nlon if(River%basinid(i,j) == basin ) then if(River%travel(i,j) == 0 ) ncoast = ncoast + 1 end if end do end do if( ncoast < 0 ) then write(stdout(),*) ' river with basin = ', basin, ' has no point with traver = 0' call mpp_error(FATAL,"some river has no point with travel = 0") end if if( ncoast > 1 ) then write(stdout(),*) ' river with basin = ', basin, ' has more that 1 point with traver = 0' call mpp_error(FATAL,"some river has more than one point with travel = 0") end if end do !--- make sure when the mask is 1 ( land/river), basin is not missing value !--- and = missing_value when mask is 0 ( ocean ) do j = 1, nlat do i = 1, nlon if(River%mask(i,j) > lnd_thresh ) then ! river point if(River%basinid(i,j) == missing_value ) then write(stdout(),*) 'at (i,j) = (', i, ',',j, & '), mask = 1(river), but basinid equal to missing value' call mpp_error(FATAL,"some river point has basinid = missing value") end if else if(River%basinid(i,j) > 0) then if(River%travel(i,j) .NE. 0 .OR. River%tocell(i,j) .NE. 0 ) then write(stdout(),*) 'at (i,j) = (', i, ',',j, & '), mask = 0( ocean), basinid = ', River%basinid(i,j), & ', travel = ', River%travel(i,j), ', tocell = ', River%tocell(i,j) call mpp_error(FATAL,"some ocean point in the river network has nonzero travel or nonzero tocell") end if end if end do end do !--- check travel, tocell, fromcell and basinid do j = 1, nlat do i = 1, nlon if(River%tocell(i,j) >0 ) then ! river point call get_nbr_index(River%tocell(i,j), i, j, i_array, j_array, num_nbrs) if(num_nbrs .ne. 1) then write(stdout(),*) 'at (i,j) = (', i, ',',j, & ', there are ', num_nbrs, ' tocell and the neighbors are: i_nbr = ', & i_array(1:num_nbrs), ', j_nbr = ', j_array(1:num_nbrs) call mpp_error(FATAL,'River can only flow to one direction') end if i_nbr = i_array(1) j_nbr = j_array(1) if(River%basinid(i,j) .NE. River%basinid(i_nbr,j_nbr)) then write(stdout(),*) 'at (i,j) = (', i, ',',j, & '), basinid = ', River%basinid(i,j), ',tocell = (', i_nbr, ',', j_nbr, & ') with basinid = ', River%basinid(i_nbr, j_nbr), & River%travel(i,j), River%mask(i,j), River%travel(i_nbr,j_nbr), River%mask(i_nbr,j_nbr) call mpp_error(FATAL,"Every cell should have the same basinid as its tocell") end if call get_nbr_index(River%fromcell(i_nbr,j_nbr), i_nbr, j_nbr, i_array, j_array, num_nbrs) if(count(i_array(1:num_nbrs) == i .AND. j_array(1:num_nbrs) == j) .NE. 1) then write(stdout(),*) 'at (i,j) = (', i, ',',j, '), all the fromcell of its tocell does not contain itself' call mpp_error(FATAL,"all the fromcell of its tocell does not contain itself") end if if( River%travel(i,j) .NE. River%travel(i_nbr,j_nbr) + 1 ) then write(stdout(),*) 'at (i,j) = (', i, ',',j, '), The travel does not equal to the travel of tocell + 1' call mpp_error(FATAL,"The travel does not equal to the travel of tocell + 1") end if end if end do end do !--- make sure no river point with travel = 0 and tocell > 0 if(ANY(River%travel(1:nlon,1:nlat) == 0 .AND. River%tocell(1:nlon,1:nlat) > 0) ) call mpp_error(FATAL, & "some river point have zero travel and nonzero tocell") end subroutine check_river_data !##################################################################### !--- write out river routing data subroutine write_river_regrid_data(River) type(river_regrid_type), intent(in) :: River integer :: unit type(axistype) :: axis_x, axis_y, axis_x_ocn, axis_y_ocn type(fieldtype) :: fld_basin, fld_basincells, fld_cellarea type(fieldtype) :: fld_disttoocean, fld_fromcell, fld_order, fld_subA type(fieldtype) :: fld_subL, fld_tocell, fld_travel, fld_celllength, fld_mask type(fieldtype) :: fld_neighbor, fld_land_order, fld_ocn_mask, fld_slope type(fieldtype) :: fld_ocn_lon, fld_ocn_lat real, allocatable :: tmp(:,:) call mpp_open(unit,trim(river_output_file), MPP_OVERWR, MPP_NETCDF, threading = MPP_SINGLE) !--- write out axis meta data --------------------------------------------- call mpp_write_meta(unit, axis_x,'lon','degree_east','Nominal Longitude of T-cell center', & cartesian ='X', data = River%lon ) call mpp_write_meta(unit, axis_y,'lat','degree_north','Nominal Latitude of T-cell center', & cartesian ='Y', data = River%lat ) call mpp_write_meta(unit, axis_x_ocn,'grid_x_ocn','degree_east','Nominal Longitude of T-cell center of ocean grid', & cartesian ='X', data = lon_ocn(:,1) ) call mpp_write_meta(unit, axis_y_ocn,'grid_y_ocn','degree_north','Nominal Latitude of T-cell center of ocean grid', & cartesian ='Y', data = lat_ocn(1,:) ) !--- write out field meta data --------------------------------------------- call mpp_write_meta(unit, fld_basin, (/axis_x, axis_y/), 'basin', & 'none','river basin id', pack=1, missing=missing_value ) call mpp_write_meta(unit, fld_basincells, (/axis_x, axis_y/), 'basincells', & 'none','number of cells in subbasin', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_slope, (/axis_x, axis_y/), 'So', & 'none','slope', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_cellarea, (/axis_x, axis_y/), 'cellarea', & 'm2','cell area', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_disttoocean, (/axis_x, axis_y/), 'disttoocean', & 'm','distance to ocean', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_fromcell, (/axis_x, axis_y/), 'fromcell', & 'none','sum of directions from upstream cells', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_order, (/axis_x, axis_y/), 'order', & 'none','Strahler stream order', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_subA, (/axis_x, axis_y/), 'subA', & 'm2','subbasin area', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_subL, (/axis_x, axis_y/), 'subL', & 'm','subbasin length', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_tocell, (/axis_x, axis_y/), 'tocell', & 'none','direction to downstream cell', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_travel, (/axis_x, axis_y/), 'travel', & 'none','cells left to travel before reaching ocean', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_celllength, (/axis_x, axis_y/), 'celllength', & 'm','cell length', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_mask, (/axis_x, axis_y/), 'mask', & 'none','land/sea mask(land = 1)', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_neighbor, (/axis_x, axis_y/), 'neighbor', & 'none','neighbor point', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_land_order, (/axis_x, axis_y/), 'land_order', & 'none','neighbor point', pack=1, missing=missing_value) call mpp_write_meta(unit, fld_ocn_lon, (/axis_x_ocn, axis_y_ocn/), 'lon_ocean', & 'none','geographical longitude of ocean grid', pack=1) call mpp_write_meta(unit, fld_ocn_lat, (/axis_x_ocn, axis_y_ocn/), 'lat_ocean', & 'none','geographical latitude of ocean grid', pack=1) call mpp_write_meta(unit, fld_ocn_mask, (/axis_x_ocn, axis_y_ocn/), 'mask_ocean', & 'none','land/sea mask of ocean grid', pack=1) call mpp_write(unit, axis_x) call mpp_write(unit, axis_y) call mpp_write(unit, axis_x_ocn) call mpp_write(unit, axis_y_ocn) allocate(tmp(nlon, nlat) ) tmp = River%basinid(1:nlon,1:nlat) call mpp_write(unit, fld_basin, tmp) tmp = River%basincells(1:nlon,1:nlat) call mpp_write(unit, fld_basincells, tmp) call mpp_write(unit, fld_slope, River%slope(1:nlon,1:nlat)) call mpp_write(unit, fld_cellarea, River%cellarea(1:nlon,1:nlat)) call mpp_write(unit, fld_disttoocean, River%disttoocean(1:nlon,1:nlat)) tmp = River%fromcell(1:nlon,1:nlat) call mpp_write(unit, fld_fromcell, tmp) tmp = River%order(1:nlon,1:nlat) call mpp_write(unit, fld_order, tmp) call mpp_write(unit, fld_subA, River%subA(1:nlon,1:nlat)) call mpp_write(unit, fld_subL, River%subL(1:nlon,1:nlat)) tmp = River%tocell(1:nlon,1:nlat) call mpp_write(unit, fld_tocell, tmp) tmp = River%travel(1:nlon,1:nlat) call mpp_write(unit, fld_travel, tmp) call mpp_write(unit, fld_celllength, River%celllength(1:nlon,1:nlat)) call mpp_write(unit, fld_mask, River%mask(1:nlon,1:nlat)) tmp = River%neighbor(1:nlon,1:nlat) call mpp_write(unit, fld_neighbor, tmp) tmp = River%land_order(1:nlon,1:nlat) call mpp_write(unit, fld_land_order, tmp) call mpp_write(unit, fld_ocn_lon, lon_ocn ) call mpp_write(unit, fld_ocn_lat, lat_ocn ) call mpp_write(unit, fld_ocn_mask, mask_ocn ) call mpp_close(unit) deallocate(tmp) end subroutine write_river_regrid_data !##################################################################### ! release memory subroutine river_regrid_end(River) type(river_regrid_type), intent(inout) :: River module_is_initialized = .FALSE. deallocate(River%lonb, River%latb, River%cellarea, River%subL, River%subA ) deallocate(River%disttoocean, River%celllength, River%order ) deallocate(River%basinid, River%tocell, River%fromcell, River%basincells ) deallocate(River%travel, River%mask, River%neighbor, River%land_order ) deallocate(River%dist, River%lon, River%lat ) end subroutine river_regrid_end !##################################################################### !--- read river source data subroutine read_river_src_data type(axistype), dimension(:), allocatable :: axes, axes_bounds type(fieldtype), dimension(:), allocatable :: fields real, dimension(:,:), allocatable :: tmp real :: old_missing_value integer :: unit, n, m, ndim, nvar, natt, ntime, len_axes, nlon_src, nlat_src character(len=128) :: name character(len=1) :: cart logical :: found_cellarea, found_tocell, found_fromcell, found_basin, found_so logical :: found_basincells, found_order, found_travel, found_subL logical :: found_subA, found_disttoocean, found_dx write(stdout(),*) ' read river src data from file '//trim(river_input_file) if(.not. file_exist(trim(river_input_file))) & call mpp_error(FATAL, 'river_regrid: file '//trim(river_input_file)//' does not exist') !--- get the grid size and grids call mpp_open(unit,trim(river_input_file),action=MPP_RDONLY,form=MPP_NETCDF) call mpp_get_info(unit, ndim, nvar, natt, ntime) allocate(fields(nvar)) call mpp_get_fields(unit,fields) found_cellarea = .false. do n = 1, nvar call mpp_get_atts(fields(n),name=name) if(trim(name) == "cellarea") then found_cellarea = .true. ndim = 2 allocate(axes(ndim), axes_bounds(ndim)) call mpp_get_atts(fields(n),axes=axes) do m = 1, ndim cart = 'N' call get_axis_cart(axes(m), cart) call mpp_get_atts(axes(m),len=len_axes) if (cart == 'N') call mpp_error(FATAL,'river_routing_mod: couldnt recognize axis atts.') select case (cart) case ('X') nlon_src = len_axes allocate(Source%lonb(nlon_src+1), Source%lon(nlon_src)) call mpp_get_axis_data(axes(m), Source%lon) call get_axis_bounds(axes(m), axes_bounds(m), axes) call mpp_get_axis_data(axes_bounds(m), Source%lonb) case ('Y') nlat_src = len_axes allocate(Source%latb(nlat_src+1), Source%lat(nlat_src)) call mpp_get_axis_data(axes(m), Source%lat) call get_axis_bounds(axes(m), axes_bounds(m), axes) call mpp_get_axis_data(axes_bounds(m), Source%latb) end select enddo exit end if end do if(.not. found_cellarea) call mpp_error(FATAL,'river_routing_mod: cellarea is not in file '//trim(river_input_file) ) Source%nlon = nlon_src Source%nlat = nlat_src !--- read the field allocate(Source%cellarea (nlon_src,nlat_src), Source%tocell (nlon_src,nlat_src) ) allocate(Source%fromcell (nlon_src,nlat_src), Source%basinid (nlon_src,nlat_src) ) allocate(Source%basincells (nlon_src,nlat_src), Source%travel (nlon_src,nlat_src) ) allocate(Source%subL (nlon_src,nlat_src), Source%subA (nlon_src,nlat_src) ) allocate(Source%disttoocean(nlon_src,nlat_src) ) allocate(Source%celllength (nlon_src,nlat_src), Source%order (nlon_src,nlat_src) ) allocate(Source%slope (nlon_src,nlat_src), tmp (nlon_src,nlat_src) ) found_cellarea = .FALSE. ; found_tocell = .FALSE. found_fromcell = .FALSE. ; found_basin = .FALSE. found_basincells = .FALSE. ; found_order = .FALSE. found_travel = .FALSE. ; found_subL = .FALSE. found_subA = .FALSE. found_disttoocean = .FALSE. ; found_dx = .FALSE. do n = 1, nvar call mpp_get_atts(fields(n),name=name, missing = old_missing_value) select case (trim(name)) case ('So') found_so = .TRUE. call mpp_read(unit,fields(n), Source%slope ) where(Source%Slope == old_missing_value) Source%slope = missing_value case ('cellarea') found_cellarea = .TRUE. call mpp_read(unit,fields(n), Source%cellarea ) where(Source%cellarea == old_missing_value) Source%cellarea = missing_value case ('tocell') found_tocell = .TRUE. call mpp_read(unit,fields(n), tmp ) Source%tocell = tmp where(Source%tocell == old_missing_value) Source%tocell = missing_value case ('fromcell') found_fromcell = .TRUE. call mpp_read(unit,fields(n), tmp ) Source%fromcell = tmp where(Source%fromcell == old_missing_value) Source%fromcell = missing_value case ('basin') found_basin = .TRUE. call mpp_read(unit,fields(n), tmp ) Source%basinid = tmp where(Source%basinid == old_missing_value) Source%basinid = missing_value case ('basincells') found_basincells = .TRUE. call mpp_read(unit,fields(n), tmp) Source%basincells = tmp where(Source%basincells == old_missing_value) Source%basincells = missing_value case ('order') found_order = .TRUE. call mpp_read(unit,fields(n), tmp ) Source%order = tmp where(Source%order == old_missing_value) Source%order = missing_value case ('travel') found_travel = .TRUE. call mpp_read(unit,fields(n), tmp ) Source%travel = tmp where(Source%travel == old_missing_value) Source%travel = missing_value case ('subL') found_subL = .TRUE. call mpp_read(unit,fields(n), Source%subL ) where(Source%subL == old_missing_value) Source%subL = missing_value case ('subA') found_subA = .TRUE. call mpp_read(unit,fields(n), Source%subA ) where(Source%subA == old_missing_value) Source%subA = missing_value case ('disttoocean') found_disttoocean = .TRUE. call mpp_read(unit,fields(n), Source%disttoocean ) where(Source%disttoocean == old_missing_value) Source%disttoocean = missing_value case ('dx') found_dx = .TRUE. call mpp_read(unit,fields(n), Source%celllength ) where(Source%celllength == old_missing_value) Source%celllength = missing_value end select enddo deallocate(tmp, axes, axes_bounds, fields ) if(.not. found_so) call mpp_error(FATAL,'river_routing_mod: So is not in file '//trim(river_input_file) ) if(.not. found_cellarea) call mpp_error(FATAL,'river_routing_mod: cellarea is not in file '//trim(river_input_file) ) if(.not. found_tocell) call mpp_error(FATAL,'river_routing_mod: tocell is not in file '//trim(river_input_file) ) if(.not. found_fromcell) call mpp_error(FATAL,'river_routing_mod: fromcell is not in file '//trim(river_input_file) ) if(.not. found_basin) call mpp_error(FATAL,'river_routing_mod: basin is not in file '//trim(river_input_file) ) if(.not. found_basincells) call mpp_error(FATAL,'river_routing_mod: basincells is not in file '//trim(river_input_file) ) if(.not. found_order) call mpp_error(FATAL,'river_routing_mod: order is not in file '//trim(river_input_file) ) if(.not. found_travel) call mpp_error(FATAL,'river_routing_mod: travel is not in file '//trim(river_input_file) ) if(.not. found_subL) call mpp_error(FATAL,'river_routing_mod: subL is not in file '//trim(river_input_file) ) if(.not. found_subA) call mpp_error(FATAL,'river_routing_mod: subA is not in file '//trim(river_input_file) ) if(.not. found_disttoocean) call mpp_error(FATAL,'river_routing_mod: disttoocean is not in file '//trim(river_input_file) ) if(.not. found_dx) call mpp_error(FATAL,'river_routing_mod: dx is not in file '//trim(river_input_file) ) call mpp_close(unit) end subroutine read_river_src_data !##################################################################### !--- extend river grid to match land grid !--- define land/sea mask for each grid. subroutine define_new_grid(River) type(river_regrid_type), intent(out) :: River integer :: num_lon_begin, num_lon_end, num_lat_begin, num_lat_end, nlon_src, nlat_src integer :: i, j, i_trans, j_trans, im1, ip1, jm1, jp1 real :: dx, dy write(stdout(),*) 'define new grid After coupled with ocean grid' !--- We assume river source grid always is uniform dx = Source%lonb(2) - Source%lonb(1) dy = Source%latb(2) - Source%latb(1) nlon_src = Source%nlon; nlat_src = Source%nlat !--- The river grid should be inside the land grid if(Source%lonb(1) .lt. lon_start .or. Source%lonb(nlon_src+1) .gt. lon_end .or. & Source%latb(1) .lt. lat_start .or. Source%latb(nlat_src+1) .gt. lat_end) & call mpp_error(FATAL,'river_regrid: static river grid is not inside the region bounded by '// & 'lon_start, lon_end, lat_start and lat_end' ) !--- find how many points need to be added at the begining and end call find_grid_addition(lon_start, lon_end, Source%lonb(1), & Source%lonb(size(Source%lonb)), dx, num_lon_begin, num_lon_end) call find_grid_addition(lat_start, lat_end, Source%latb(1), & Source%latb(size(Source%latb)), dy, num_lat_begin, num_lat_end) River%nlon = nlon_src + num_lon_begin + num_lon_end River%nlat = nlat_src + num_lat_begin + num_lat_end nlon = River%nlon nlat = River%nlat !--- memory allocation allocate(River%lonb(nlon+1), River%latb(nlat+1), River%cellarea(nlon,nlat) ) allocate(River%subL(0:nlon+1,0:nlat+1), River%subA(0:nlon+1,0:nlat+1) ) allocate(River%disttoocean(nlon,nlat) ) allocate(River%celllength(nlon,nlat), River%order(0:nlon+1,0:nlat+1) ) allocate(River%basinid(nlon,nlat), River%tocell(0:nlon+1,0:nlat+1) ) allocate(River%fromcell(nlon,nlat), River%basincells(nlon,nlat) ) allocate(River%travel(nlon,nlat), River%mask(-1:nlon+2,-1:nlat+2) ) allocate(River%neighbor(nlon,nlat), River%land_order(nlon,nlat) ) allocate(River%dist(nlon, nlat, 8), River%lon(nlon), River%lat(nlat) ) allocate(River%slope(nlon,nlat) ) !--- get the expanded river grid call grid_expansion(River%lonb, Source%lonb, lon_start, lon_end, dx, num_lon_begin, num_lon_end) call grid_expansion(River%latb, Source%latb, lat_start, lat_end, dy, num_lat_begin, num_lat_end) write(stdout(),*) num_lon_begin, 'points is added at the west bound. ', num_lon_end, 'points is added at the east bound' write(stdout(),*) num_lat_begin, 'points is added at the south bound. ', num_lat_end, 'points is added at the north bound' do i = 1, nlon River%lon(i) = ( River%lonb(i) + River%lonb(i+1) ) * 0.5 enddo do j = 1, nlat River%lat(j) = ( River%latb(j) + River%latb(j+1) ) * 0.5 enddo !--- fill it with nan value River%slope = missing_value River%cellarea = missing_value River%subL = missing_value River%subA = missing_value River%disttoocean = missing_value River%celllength = missing_value River%order = missing_value River%basinid = missing_value River%tocell = missing_value River%fromcell = missing_value River%basincells = missing_value River%travel = missing_value !--- file it with orginal grid data do j = 1, nlat_src do i = 1, nlon_src i_trans = num_lon_begin + i j_trans = num_lat_begin + j River%slope (i_trans,j_trans) = Source%slope (i,j) River%cellarea (i_trans,j_trans) = Source%cellarea (i,j) River%subL (i_trans,j_trans) = Source%subL (i,j) River%subA (i_trans,j_trans) = Source%subA (i,j) River%disttoocean(i_trans,j_trans) = Source%disttoocean(i,j) River%celllength (i_trans,j_trans) = Source%celllength (i,j) River%order (i_trans,j_trans) = Source%order (i,j) River%basinid (i_trans,j_trans) = Source%basinid (i,j) River%tocell (i_trans,j_trans) = Source%tocell (i,j) River%fromcell (i_trans,j_trans) = Source%fromcell (i,j) River%basincells (i_trans,j_trans) = Source%basincells (i,j) River%travel (i_trans,j_trans) = Source%travel (i,j) enddo enddo !--- we assume the cyclic condition River%order(0, 1:nlat) = River%order(nlon,1:nlat) River%order(nlon+1,1:nlat) = River%order(1, 1:nlat) River%subL (0, 1:nlat) = River%subL (nlon,1:nlat) River%subL (nlon+1,1:nlat) = River%subL (1, 1:nlat) River%subA (0, 1:nlat) = River%subA (nlon,1:nlat) River%subA (nlon+1,1:nlat) = River%subA (1, 1:nlat) !--- define the mask of river grid according to land grid mask. call define_river_mask(River) !--- here we suppose the cyclic condition exists River%tocell(0,1:nlat) = River%tocell(nlon,1:nlat) River%tocell(nlon+1,1:nlat) = River%tocell(1,1:nlat) !--- define the distance to the neighbor at each point River%dist = 1.0e20 do j = 1, nlat do i = 1, nlon ip1 = i + 1; im1 = i - 1 jp1 = j + 1; jm1 = j - 1 if(im1 == 0) im1 = nlon if(ip1 == nlon+1) ip1 = 1 River%dist(i,j,1) = dist(River%lon(i), River%lat(j), River%lon(ip1), River%lat(j) ) if(jm1 .ne. 0 ) then River%dist(i,j,2) = dist(River%lon(i), River%lat(j), River%lon(ip1), River%lat(jm1) ) River%dist(i,j,3) = dist(River%lon(i), River%lat(j), River%lon(i ), River%lat(jm1) ) River%dist(i,j,4) = dist(River%lon(i), River%lat(j), River%lon(im1), River%lat(jm1) ) endif River%dist(i,j,5) = dist(River%lon(i), River%lat(j), River%lon(im1), River%lat(j) ) if(jp1 .ne. nlat+1) then River%dist(i,j,6) = dist(River%lon(i), River%lat(j), River%lon(im1), River%lat(jp1) ) River%dist(i,j,7) = dist(River%lon(i), River%lat(j), River%lon(i ), River%lat(jp1) ) River%dist(i,j,8) = dist(River%lon(i), River%lat(j), River%lon(ip1), River%lat(jp1) ) endif enddo enddo next_basinid = maxval(Source%basinid) + 1 end subroutine define_new_grid !##################################################################### !--- find number of points needed to be extended. subroutine find_grid_addition(lnd_start, lnd_end, river_start, river_end, dx, num_begin, num_end) real, intent(in) :: lnd_start, lnd_end, river_start, river_end, dx integer, intent(out) :: num_begin, num_end real :: diff, min_size min_size = 0.05 if(dx .lt. min_size) call mpp_error(FATAL,'river_routing_mod: river grid size is too small') !---first check how many points we need to add at the begining. num_begin = 0 diff = river_start - lnd_start if( diff .gt. min_size) then num_begin = int(diff / dx) if(diff-num_begin*dx .gt. min_size) num_begin = num_begin + 1 endif num_end = 0 diff = lnd_end - river_end if( diff .gt. min_size) then num_end = int(diff / dx) if(diff-num_end*dx .gt. min_size) num_end = num_end + 1 endif end subroutine find_grid_addition !##################################################################### !--- define new river grid subroutine grid_expansion(river_grid, orig_grid, lnd_start,lnd_end, dx, num_begin, num_end) real, dimension(:), intent(out) :: river_grid real, dimension(:), intent(in) :: orig_grid real, intent(in) :: lnd_start, lnd_end, dx integer, intent(in) :: num_begin, num_end integer :: num_orig, i num_orig = size(orig_grid) river_grid(num_begin+1:num_begin+num_orig) = orig_grid(:) do i=num_begin,2,-1 river_grid(i) = orig_grid(1) - (num_begin-i+1)*dx enddo if(num_begin .gt. 0) river_grid(1) = lnd_start do i=1,num_end-1 river_grid(num_begin+num_orig+i) = orig_grid(num_orig)+dx*i enddo if(num_end .gt. 0) river_grid(size(river_grid)) = lnd_end return end subroutine grid_expansion !##################################################################### !--- define land order for new river grid. subroutine define_new_land_order(River) type(river_regrid_type), intent(inout) :: River integer, dimension(:,:), allocatable :: land_order integer :: i, j, num_order logical :: found_new_land_pt write(stdout(),*) 'define land order for new river grid.' allocate(land_order(0:nlon+1,0:nlat+1) ) !---set the initial value to some dummy number land_order = -1 where( River%mask(1:nlon,1:nlat) .gt. lnd_thresh .and. River%travel(1:nlon,1:nlat) .eq. missing_value ) land_order(1:nlon,1:nlat) = 0 ! new land point end where !--- continue if there is any new land point to check !--- first find the coastal points River%neighbor = 0 do j = 1, nlat do i = 1, nlon if(land_order(i,j) == 0) then River%neighbor(i,j) = get_neighbor( River%mask(i-1:i+1,j-1:j+1) .le. lnd_thresh ) if(River%neighbor(i,j) .gt. 0) land_order(i,j) = 1 endif enddo enddo land_order(0,1:nlat) = land_order(nlon,1:nlat) land_order(nlon+1,1:nlat) = land_order(1,1:nlat) num_order = 2 do while(any(land_order(1:nlon,1:nlat) == 0) ) found_new_land_pt = .FALSE. do j = 1, nlat do i = 1, nlon if(land_order(i,j) == 0) then River%neighbor(i,j) = get_neighbor(land_order(i-1:i+1,j-1:j+1) .eq. num_order-1) if( River%neighbor(i,j) .gt. 0 ) then found_new_land_pt = .true. land_order(i,j) = num_order if(i == 1) land_order(nlon+1,j) = num_order if(i == nlon) land_order(0,j) = num_order endif endif enddo enddo if(.not. found_new_land_pt ) exit num_order = num_order + 1 enddo River%land_order(1:nlon,1:nlat) = land_order(1:nlon,1:nlat) deallocate(land_order) return end subroutine define_new_land_order !##################################################################### !--- define river routing data for new river grid subroutine define_new_land_data(River) type(river_regrid_type), intent(inout) :: River integer :: max_land_order, num_nbrs, num_max_order, num_max_subL integer :: i, j, k, n, i_lo, the_basinid, ii, jj, num_max_subA, fromcell logical :: is_neighbor(8) integer :: i_nbr, j_nbr, i_array(8), j_array(8), i_in(8), j_in(8), i_out(8), j_out(8) integer :: basinid_cur !--- first initialialize some field do j = 1, nlat do i = 1, nlon if(River%land_order(i,j) .ge. 0) then River%tocell(i,j) = 0 River%fromcell(i,j) = 0 River%travel(i,j) = 0 River%disttoocean(i,j) = 0 River%celllength(i,j) = 0 end if end do end do !--- first define the outflow direction for new land grid do j = 1, nlat do i = 1, nlon if(River%land_order(i,j) .ge. 1) then do k = 1,8 is_neighbor(k) = btest(River%neighbor(i,j),k-1) enddo River%tocell(i,j) = outflow_direction(is_neighbor, River%dist(i,j,:)) endif enddo enddo !--- update halo points of tocell River%tocell(0,1:nlat) = River%tocell(nlon,1:nlat) River%tocell(nlon+1,1:nlat) = River%tocell(1,1:nlat) !--- then define the inflow direction for new land grid do j = 1, nlat do i = 1, nlon if(River%land_order(i,j) .ge. 1) then River%fromcell(i,j) = inflow_direction(River%tocell(i-1:i+1,j-1:j+1)) else if(River%land_order(i,j) ==0) then fromcell = inflow_direction(River%tocell(i-1:i+1,j-1:j+1)) if(fromcell >0) then River%fromcell(i,j) = fromcell River%land_order(i,j) = 1 end if endif enddo enddo !--- extend river with travel = 0 , tocell not zero, full land cell an extra points. ! **************************************************************** ! * Update properties of new land cells * ! * (and attributes of other cells impacted by the new land) * ! **************************************************************** ! First: properties that are only about each individual cell ! only have to define these for the new points added to the system do j = 1, nlat do i = 1, nlon River%cellarea(i,j) = area(River%lonb(i:i+1), River%latb(j:j+1) ) if(River%land_order(i,j) .ge. 1) then ! River%cellarea(i,j) = area(River%lonb(i:i+1), River%latb(j:j+1) ) if(River%tocell(i,j) ==0) cycle call get_nbr_index(River%tocell(i,j), i, j, i_array, j_array, num_nbrs) if(num_nbrs .ne. 1) call mpp_error(FATAL,'River can only flow to one direction') i_nbr = i_array(1) j_nbr = j_array(1) River%celllength(i,j) = dist(River%lon(i),River%lat(j), River%lon(i_nbr), River%lat(j_nbr) ) endif enddo enddo !--- extend river with travel = 0 , tocell not zero, full land cell an extra points. !--multiple river%mask to get partial cellarea and remove previously land point do j = 1, nlat do i = 1, nlon if(River%cellarea(i,j) .NE. missing_value) then River%cellarea(i,j) = River%cellarea(i,j) *River%mask(i,j) end if end do end do !--- extend river with travel = 0 , tocell not zero, full land cell an extra points. ! Now update properties that are dependent on upstream cells (fromcell) ! Need to do this from the inner-most new land points downstream toward the ocean ! Loop: for new points, from max(River%land_order(i,j)) to 1, counting down max_land_order = maxval(River%land_order) do i_lo = max_land_order, 1, -1 do j = 1, nlat do i = 1, nlon if (River%land_order(i,j) .eq. i_lo) then !--- find neighbors -------------- call get_nbr_index(River%fromcell(i,j), i,j,i_array, j_array, num_nbrs) ! No neighbors feed this cell (fromcell = 0) if (num_nbrs .eq. 0) then River%basinid(i,j) = next_basinid next_basinid = next_basinid + 1 River%order(i,j) = 1 River%subL(i,j) = River%celllength(i,j) River%subA(i,j) = River%cellarea(i,j) River%basincells(i,j) = 1 ! only one neighbor feeds this cell else if(num_nbrs == 1 ) then i_nbr = i_array(1) j_nbr = j_array(1) River%order(i,j) = River%order(i_nbr,j_nbr) River%basinid(i,j) = River%basinid(i_nbr,j_nbr) River%subL(i,j) = River%celllength(i,j) + River%subL(i_nbr,j_nbr) River%subA(i,j) = River%cellarea(i,j) + River%subA(i_nbr,j_nbr) River%basincells(i,j) = 1 + River%basincells(i_nbr,j_nbr) else ! multiple neighbors feed this cell ! one neighbor is the clear mainstem (by stream order) i_in(1:num_nbrs) = i_array(1:num_nbrs) j_in(1:num_nbrs) = j_array(1:num_nbrs) call find_max_int ( River%order, i_in, j_in, num_nbrs, i_out, j_out, num_max_order ) if( num_max_order == 1) then i_nbr = i_out(1) j_nbr = j_out(1) River%order(i,j) = River%order(i_nbr,j_nbr) ! no neighbor is the clear mainstem (by stream order) else ! multiple neighbors feeding in have the same, max(order)) ! determine mainstem by largest subL, then largest subA, then arbitrary i_in(1:num_max_order) = i_out(1:num_max_order) j_in(1:num_max_order) = j_out(1:num_max_order) call find_max_real( River%subL, i_in, j_in, num_max_order, i_out, j_out, num_max_subL ) if(num_max_subL == 1) then i_nbr = i_out(1) j_nbr = j_out(1) River%order(i,j) = 1 + River%order(i_nbr,j_nbr) else i_in(1:num_max_subL) = i_out(1:num_max_subL) j_in(1:num_max_subL) = j_out(1:num_max_subL) call find_max_real( River%subA, i_in, j_in, num_max_subL, i_out, j_out, num_max_subA ) if(num_max_subA == 1) then i_nbr = i_out(1) j_nbr = j_out(1) River%order(i,j) = 1 + River%order(i_nbr,j_nbr) else i_nbr = i_out(1) j_nbr = j_out(1) River%order(i,j) = 1 + River%order(i_nbr,j_nbr) write(stdout(),*) 'i,j, num_max_subA, i_out, j_out', i,j, & num_max_subA, i_out(1:num_max_subA), j_out(1:num_max_subA) call mpp_error(NOTE,'river_routing_mod: that is impossible') endif endif endif ! These properties depend on only one input cell River%basinid(i,j) = River%basinid(i_nbr,j_nbr) River%subL(i,j) = River%celllength(i,j) + River%subL(i_nbr,j_nbr) River%subA(i,j) = River%cellarea(i,j) River%basincells(i,j) = 1 do n = 1, num_nbrs River%subA(i,j) = River%subA(i,j) + River%subA(i_array(n),j_array(n)) River%basincells(i,j) = River%basincells(i,j) + River%basincells(i_array(n),j_array(n)) enddo ! These properties depend on all the input neighbor cells ! River%subA(i,j) = River%cellarea(i,j) + SUMOVER_NEIGHBORS(River%subA(?,?)) ! River%basincells(i,j) = 1 + SUMOVER_NEIGHBORS(River%basincells(?,?)) ! update basinid of other neighbors of point (i,j) do n = 1, num_nbrs where(River%basinid == River%basinid(i_array(n),j_array(n)) ) & River%basinid = River%basinid(i,j) enddo endif if(i == 1) then River%order(nlon+1,j) = River%order(i,j) River%subL(nlon+1,j) = River%subL(i,j) else if(i == nlon) then River%order(0,j) = River%order(i,j) River%subL(0,j) = River%subL(i,j) endif endif enddo enddo enddo !--- extend river with travel = 0 , tocell not zero, full land cell an extra points. ! Now update properties that are dependent on downstream cells (tocell) ! Loop: start at the coast and move upstream do i_lo = 1, max_land_order do j = 1, nlat do i = 1, nlon if (River%land_order(i,j) .eq. i_lo) then River%travel(i,j) = River%land_order(i,j) - 1 if (River%travel(i,j) .eq. 0) then River%disttoocean(i,j) = River%celllength(i,j) else call get_nbr_index(River%tocell(i,j), i, j, i_array, j_array, num_nbrs) i_nbr = i_array(1) j_nbr = j_array(1) River%disttoocean(i,j) = River%celllength(i,j) + River%disttoocean(i_nbr,j_nbr) endif endif enddo enddo enddo !--- extend river with travel = 0 , tocell not zero, full land cell an extra points. ! Now must update pre-existing network (anywhere that it used to go to the ocean and now it goes to land) ! Only the three cell attributes which depend on downstream cells need to be updated. do j = 1, nlat do i = 1, nlon if ((River%travel(i,j) .eq. 0) .and. (River%land_order(i,j) .lt. 0) ) then call get_nbr_index(River%tocell(i,j), i, j, i_array, j_array, num_nbrs) if(num_nbrs == 0) cycle i_nbr = i_array(1) j_nbr = j_array(1) if(River%land_order(i_nbr, j_nbr) .gt. 0) then River%travel(i,j) = River%travel(i_nbr, j_nbr) + 1 !River%travel(i,j) = River%travel(i,j) + River%travel(i_nbr, j_nbr) !??? River%disttoocean(i,j) = River%disttoocean(i,j) + River%disttoocean(i_nbr, j_nbr) the_basinid = River%basinid(i,j) do jj = 1, nlat do ii = 1, nlon if(River%land_order(ii,jj) .lt. 0 .and. River%basinid(ii,jj) .EQ. the_basinid) then if( is_connected(River%tocell(1:nlon,1:nlat), ii, jj, i, j) )then River%travel(ii,jj) = River%travel(ii,jj) + River%travel(i, j) River%disttoocean(ii,jj) = River%disttoocean(ii,jj) + River%disttoocean(i, j) endif endif enddo enddo endif endif enddo enddo !--- extend river with travel = 0 , tocell not zero, full land cell an extra points. !--- deal with in-land ocean, all the in-land ocean will be fefined as isolated river. do j = 1, nlat do i = 1, nlon if (River%land_order(i,j) == 0 ) then River%travel(i,j) = 0 River%basinid(i,j) = next_basinid next_basinid = next_basinid + 1 end if end do end do !--- the cell area will be cell area, not counted percentage of land do j = 1, nlat do i = 1, nlon River%cellarea(i,j) = area(River%lonb(i:i+1), River%latb(j:j+1) ) end do end do return end subroutine define_new_land_data !##################################################################### !--- this function will return an integer of power of 2. function outflow_direction(neighbor, dist) logical, dimension(:), intent(in) :: neighbor real, dimension(:), intent(in) :: dist integer :: outflow_direction integer :: max_count, max_adj, num_set, start(4) integer :: i, j, ii, n, outflow, num_min_points, index_min(8) logical :: keep_going real :: min_dist !--- first find the maximum adjacent ocean points start = 0 max_adj = 0 num_set = 1 i = 1 if(count(neighbor) == 8) then ! surrouding points are all ocean max_adj = 8 start = 1 else do while (i .le. 8) max_count = 0 if(neighbor(i)) then keep_going = .true. max_count = 1 j = i + 1 do while(keep_going) if(j .gt. 8) j = j-8 if(neighbor(j)) then max_count = max_count + 1 else keep_going = .false. exit endif j = j + 1 enddo if(max_count .gt. max_adj) then num_set = 1 max_adj = max_count start(num_set) = i else if(max_count .eq. max_adj) then num_set = num_set + 1 start(num_set) = i endif endif i = i + max_count + 1 enddo endif !--- find the outflow direction -------------------------------------- if(num_set .eq. 1 .and. mod(max_adj,2) == 1) then !--- There will be a center point if max_adj is odd -------------- outflow = start(1) + max_count/2 if(outflow .gt. 8) outflow = outflow - 8 else !--- find the shortest distance point min_dist = dist(start(1)) num_min_points = 1 index_min(num_min_points) = start(num_set) do n = 1, num_set do i = 1, max_adj - 1 ii = start(n)+i if(ii .gt. 8 ) ii = ii - 8 if(dist(ii) .lt. min_dist) then min_dist = dist(ii) num_min_points = 1 index_min(1) = ii else if(dist(ii) .eq. min_dist) then num_min_points = num_min_points + 1 index_min(num_min_points) = ii endif enddo enddo if(num_min_points .eq. 1) then outflow = index_min(num_min_points) else outflow = random_select(index_min(1:num_min_points)) endif endif outflow_direction = 2 ** (outflow - 1) return end function outflow_direction !##################################################################### !--- calculate inflow direction from outflow data. function inflow_direction(outflow) integer, dimension(:,:), intent(in) :: outflow integer :: inflow_direction integer :: i, j i = 2; j = 2 inflow_direction = 0 if( outflow(i+1,j) == 16 ) inflow_direction = inflow_direction + 1 if( outflow(i+1,j-1) == 32) inflow_direction = inflow_direction + 2 if( outflow(i,j-1) == 64) inflow_direction = inflow_direction + 4 if( outflow(i-1,j-1) == 128) inflow_direction = inflow_direction + 8 if( outflow(i-1,j) == 1) inflow_direction = inflow_direction + 16 if( outflow(i-1,j+1) == 2) inflow_direction = inflow_direction + 32 if( outflow(i,j+1) == 4) inflow_direction = inflow_direction + 64 if( outflow(i+1,j+1) == 8) inflow_direction = inflow_direction + 128 return end function inflow_direction !##################################################################### !--- find neighbor points. function get_neighbor(is_neighbor ) logical, dimension(:,:), intent(in) :: is_neighbor integer :: get_neighbor integer :: i,j i=2; j=2 get_neighbor = 0 if(is_neighbor(i+1,j)) get_neighbor = get_neighbor + 1 if(is_neighbor(i+1,j-1)) get_neighbor = get_neighbor + 2 if(is_neighbor(i,j-1)) get_neighbor = get_neighbor + 4 if(is_neighbor(i-1,j-1)) get_neighbor = get_neighbor + 8 if(is_neighbor(i-1,j)) get_neighbor = get_neighbor + 16 if(is_neighbor(i-1,j+1)) get_neighbor = get_neighbor + 32 if(is_neighbor(i,j+1)) get_neighbor = get_neighbor + 64 if(is_neighbor(i+1,j+1)) get_neighbor = get_neighbor + 128 return end function get_neighbor !##################################################################### ! --- this is only for rectangular grid -------------------------------------- function area(x, y) real, dimension(2), intent(in) :: x,y real :: area real :: dx dx = (x(2)-x(1)) * D2R if(dx > PI) dx = dx - 2.0*PI if(dx < -PI) dx = dx + 2.0*PI !??? Do we need to multiple radius*radius area = radius*radius*dx*(sin(y(2)*D2R) - sin(y(1)*D2R)) return end function area !##################################################################### !--- find the distance of any two grid. function dist(lon1, lat1, lon2, lat2) real, intent(in) :: lon1,lat1,lon2,lat2 real :: dist real :: s1, s2, dx dx = lon2 - lon1 if(dx .gt. 180.) dx = dx - 360. if(dx .lt. -180.) dx = dx + 360. if(lon1 == lon2) then dist = abs(lat2 - lat1) * D2R else if(lat1 == lat2) then dist = abs(dx) * D2R * cos(lat1*D2R) else ! diagonal distance s1 = abs(dx) * D2R * cos(lat1*D2R) s2 = abs(lat2 - lat1) * D2R dist = sqrt(s1*s1+s2*s2) endif dist = radius * dist return end function dist !##################################################################### !--- find the max value of real data array subroutine find_max_real(data, i_in, j_in, num_in, i_out, j_out, num_out) real, dimension(0:,0:), intent(in) :: data integer, dimension(:), intent(in) :: i_in, j_in integer, intent(in) :: num_in integer, dimension(:), intent(out) :: i_out, j_out integer, intent(out) :: num_out integer, dimension(num_in) :: index integer :: n i_out(1) = i_in(1) j_out(1) = j_in(1) index(1) = 1 num_out = 1 do n = 2, num_in if(data(i_in(n),j_in(n)) .gt. data(i_out(num_out), j_out(num_out))) then num_out = 1 i_out(num_out) = i_in(n) j_out(num_out) = j_in(n) index(num_out) = n else if(data(i_in(n),j_in(n)) .eq. data(i_out(num_out), j_out(num_out))) then num_out = num_out + 1 i_out(num_out) = i_in(n) j_out(num_out) = j_in(n) index(num_out) = n endif enddo return end subroutine find_max_real !##################################################################### !--- find the max value of integer data array subroutine find_max_int(data, i_in, j_in, num_in, i_out, j_out, num_out) integer, dimension(0:,0:), intent(in) :: data integer, dimension(:), intent(in) :: i_in, j_in integer, intent(in) :: num_in integer, dimension(:), intent(out) :: i_out, j_out integer, intent(out) :: num_out real, dimension(size(data,1), size(data,2) ) :: real_data real_data = data call find_max_real(real_data, i_in, j_in, num_in, i_out, j_out, num_out) return end subroutine find_max_int !##################################################################### !--- remove land point in source data but is ocean recognized by land model. subroutine trim_river(River) type(river_regrid_type), intent(inout) :: River integer, dimension(:,:), allocatable :: land_order integer :: i, j logical :: need_to_modify write(stdout(),*) 'remove previously land point ( is ocean after coupled with land grid). ' !---set the initial value to some dummy number allocate(land_order(nlon, nlat) ) land_order = -1 !---find points that have river network info but the land model thinks are ocean points do j = 1, nlat do i = 1, nlon if(River%mask(i,j) .lt. lnd_thresh .and. River%travel(i,j) .ne. missing_value ) land_order(i,j) = 1 enddo enddo !--- continue if there is any land point in the river network to change to ocean do while(any(land_order == 1) ) write(stdout(), *)' number of points land_order == 1', count(land_order == 1) write(stdout(), *)' number of points land_order == 1 and travel == 0', & count(land_order == 1.and. River%travel==0) if(.not.( any((land_order == 1) .and. (River%travel .eq. 0) ) .or. & any (land_order == 1 .and. River%travel .gt. 0 .and. River%fromcell .le. 0) ) )then do j = 1, nlat do i = 1, nlon if(land_order(i,j) == 1) then write(stdout(),*)i,j, River%lon(i), & River%lat(j), land_order(i,j), River%travel(i,j) endif enddo enddo exit endif do j =1, nlat do i =1, nlon !--- first situation: The previously land point is at coast. if(land_order(i,j) == 1) then need_to_modify = .false. if(River%travel(i,j) .eq. 0) then call update_upstream(River,land_order, i,j) ! coast point need_to_modify = .true. !--- second situation: The previously land point is not at coast and is start point of a river else if(River%travel(i,j) .gt. 0 .and. River%fromcell(i,j) .le. 0) then call update_downstream(River,i,j) need_to_modify = .true. endif if(need_to_modify) then land_order(i,j) = -1 !--- return it to dummy value !--- fill it with nan value River%cellarea(i,j) = missing_value River%subL(i,j) = missing_value River%subA(i,j) = missing_value River%disttoocean(i,j) = missing_value River%celllength(i,j) = missing_value River%order(i,j) = missing_value River%basinid(i,j) = missing_value River%tocell(i,j) = missing_value River%fromcell(i,j) = missing_value River%basincells(i,j) = missing_value River%travel(i,j) = missing_value endif endif enddo enddo enddo do while(any(land_order == 1) ) write(stdout(), *)' number of points land_order == 1', count(land_order == 1) if(.not. any(land_order == 1 .and. River%travel .gt. 0 .and. River%fromcell .gt. 0) ) & call mpp_error(FATAL,'infinity loop') do j =1, nlat do i =1, nlon !--- first situation: The previously land point is at coast. if(land_order(i,j) == 1) then if(River%travel(i,j) .gt. 0) then if(River%fromcell(i,j) .gt. 0) call update_upstream(River,land_order,i,j) call update_downstream(River,i,j) endif land_order(i,j) = -1 !--- return it to dummy value !--- fill it with nan value River%cellarea(i,j) = missing_value River%subL(i,j) = missing_value River%subA(i,j) = missing_value River%disttoocean(i,j) = missing_value River%celllength(i,j) = missing_value River%order(i,j) = missing_value River%basinid(i,j) = missing_value River%tocell(i,j) = missing_value River%fromcell(i,j) = missing_value River%basincells(i,j) = missing_value River%travel(i,j) = missing_value endif enddo enddo enddo end subroutine trim_river !##################################################################### !--- update downstream points. subroutine update_downstream(River,i,j) type(river_regrid_type), intent(inout) :: River integer, intent(in) :: i,j integer :: i_array(8), j_array(8), i_in(8), j_in(8), i_out(8), j_out(8) integer :: i_nbr,j_nbr, ii,jj, iii, jjj, num_nbrs integer :: num_max_subL, num_max_subA, num_max_order, n, nn logical :: keep_going call get_nbr_index(River%tocell(i,j), i, j, i_array, j_array, num_nbrs) if(num_nbrs .NE. 1) return i_nbr = i_array(1); j_nbr = j_array(1) if(River%fromcell(i_nbr,j_nbr) == missing_value) return call get_nbr_index(River%fromcell(i_nbr,j_nbr), i_nbr, j_nbr, i_array, j_array, num_nbrs) ii = i_nbr; jj = j_nbr iii = i; jjj = j do while (River%tocell(ii,jj) .gt. 0) call get_nbr_index(River%fromcell(ii,jj), ii, jj, i_array, j_array, num_nbrs) if(num_nbrs == 1) then if(i_array(1) == i .and. j_array(1) == j) then River%order(ii,jj) = 1 else River%order(ii,jj) = River%order(i_array(1), j_array(1)) endif River%subL(ii,jj) = River%subL(ii,jj) - River%subL(i,j) else !--- first find the largest order i_in(1:num_nbrs) = i_array(1:num_nbrs) j_in(1:num_nbrs) = j_array(1:num_nbrs) call find_max_int ( River%order, i_in, j_in, num_nbrs, i_out, j_out, num_max_order ) ! if (iii,jjj) is not among the points with max order, we can stop keep_going = .false. do n = 1, num_max_order if(i_out(n) .eq. iii .and. j_out(n) .eq. jjj) keep_going = .true. enddo if(.not. keep_going) exit if( num_max_order == 1) then River%subL(ii,jj) = River%subL(ii,jj) - River%subL(i,j) nn = 0 do n = 1, num_nbrs if( .not. (i_in(n) == i .and. j_in(n) == j ) ) then nn = nn + 1 i_in(nn) = i_in(n) j_in(nn) = j_in(n) endif enddo call find_max_int(River%order, i_in, j_in, nn, i_out, j_out, num_max_order) if(num_max_order == 1 )then River%order(ii,jj) = River%order(i_out(1), j_out(1) ) else River%order(ii,jj) = River%order(i_out(1), j_out(1) ) + 1 endif ! no neighbor is the clear mainstem (by stream order) else ! multiple neighbors feeding in have the same, max(order)) ! determine mainstem by largest subL, then largest subA, then arbitrary !--- if num_max_order is greater than 2, do not need to modify order. if(num_max_order .gt. 2) exit if(iii == i .and. jjj == j) then !--- (iii, jjj ) is the point we are going to remove keep_going = .false. do n = 1, num_max_order if( i_out(n) .eq. i .and. j_out(n) .eq. j) then River%order(ii,jj) = River%order(i_out(1), j_out(1) ) keep_going = .true. endif enddo else !--- (iii, jjj ) is not the point we are going to remove if(River%order(ii,jj) == River%order(i_out(1), j_out(1)) +1 ) then keep_going = .false. else River%order(ii,jj) = River%order(i_out(1), j_out(1) ) + 1 endif endif if(.not. keep_going) exit !--- change subL. i_in(1:num_max_order) = i_out(1:num_max_order) j_in(1:num_max_order) = j_out(1:num_max_order) call find_max_real( River%subL, i_in, j_in, num_max_order, i_out, j_out, num_max_subL ) if(num_max_subL == 1) then if(i_out(1) .eq. iii .and. j_out(1) .eq. jjj) then River%subL(ii,jj) = River%subL(ii,jj) - River%subL(i,j) else exit endif else i_in(1:num_max_subL) = i_out(1:num_max_subL) j_in(1:num_max_subL) = j_out(1:num_max_subL) call find_max_real( River%subA, i_in, j_in, num_max_subL, i_out, j_out, num_max_subA ) if(num_max_subA == 1) then if(i_out(1) .eq. iii .and. j_out(1) .eq. jjj) then River%subL(ii,jj) = River%subL(ii,jj) - River%subL(i,j) else exit endif else exit call mpp_error(FATAL,'river_routing_mod: that is impossible') endif endif endif endif call get_nbr_index(River%tocell(ii,jj), ii, jj, i_array, j_array, num_nbrs) iii = ii; jjj = jj ii = i_array(1); jj = j_array(1) enddo ii = i_nbr; jj = j_nbr do while(River%tocell(ii,jj) > 0) River%subA(ii,jj) = River%subA(ii,jj) - River%subA(i,j) River%basincells(ii,jj) = River%basincells(ii,jj) - River%basincells(i,j) call get_nbr_index(River%tocell(ii,jj), ii, jj, i_array, j_array, num_nbrs) if(num_nbrs .ne. 1) then call mpp_error(FATAL,'num_nbrs should be 1 here' ) endif ii = i_array(1); jj = j_array(1) enddo if(River%tocell(i,j) .lt. 16) then River%fromcell(i_nbr,j_nbr) = River%fromcell(i_nbr,j_nbr) - River%tocell(i,j)*16 else if(River%tocell(i,j) .ge. 16) then River%fromcell(i_nbr,j_nbr) = River%fromcell(i_nbr,j_nbr) - River%tocell(i,j)/16 endif end subroutine update_downstream !####################################################################### !--- update upstream points subroutine update_upstream(River, land_order, i, j) type(river_regrid_type), intent(inout) :: River integer, dimension(:,:), intent(in) :: land_order integer, intent(in) :: i,j integer :: i_array(8), j_array(8) integer :: ii,jj, num_nbrs, n logical :: connect call get_nbr_index(River%fromcell(i,j), i, j, i_array, j_array, num_nbrs) do n = 1, num_nbrs !--- if the from cell also need to be removed, will update upstream through the from cell. if(land_order(i_array(n),j_array(n)) == 1) cycle River%basinid(i_array(n),j_array(n)) = next_basinid River%travel(i_array(n),j_array(n)) = River%travel(i_array(n),j_array(n)) - River%travel(i,j) - 1 River%disttoocean(i_array(n),j_array(n)) = & River%disttoocean(i_array(n),j_array(n)) - River%disttoocean(i,j) !--- Search all the points to see which point is connected with i_array(n), j_array(n) do jj = 1, nlat do ii = 1, nlon if(River%basinid(ii,jj) .eq. River%basinid(i,j) ) then connect = is_connected(River%tocell(1:nlon,1:nlat), ii, jj, i_array(n), j_array(n)) if( connect) then River%basinid(ii,jj) = next_basinid River%travel(ii,jj) = River%travel(ii,jj) - River%travel(i,j) - 1 River%disttoocean(ii,jj) = River%disttoocean(ii,jj) - River%disttoocean(i,j) endif endif enddo enddo next_basinid = next_basinid + 1 enddo end subroutine update_upstream !##################################################################### !--- check if two point are connected by a river function is_connected(tocell, i, j, i_dst, j_dst) integer, dimension(:,:), intent(in) :: tocell integer, intent(in) :: i, j, i_dst, j_dst logical :: is_connected integer :: cell, ii, jj, m, n, num_nbr, i_array(8), j_array(8) is_connected = .false. cell = tocell(i,j) ii = i; jj = j do while(cell .gt. 0) call get_nbr_index(cell, ii, jj, i_array, j_array, num_nbr) if(num_nbr .ne. 1) call mpp_error(FATAL,'river_regrid: num_nbr should be 1') m = i_array(1); n = j_array(1) if(m == i_dst .and. n == j_dst) then is_connected = .true. return else cell = tocell(m,n) ii = m; jj = n endif enddo end function is_connected !##################################################################### !--- random select a direction. function random_select(array) integer, dimension(:), intent(in) :: array integer :: random_select integer, save :: prev = 0 integer :: i, num_ele num_ele = size(array) do prev = prev + 1 if(prev .gt. 8) prev = prev - 8 do i = 1, num_ele if(array(i) .eq. prev) then random_select = prev return endif enddo enddo end function random_select !##################################################################### !--- get the index of neighbor point subroutine get_nbr_index(number, i_in, j_in, i_out, j_out, num_nbr) integer, intent(in) :: number !number should be between 0 to 255 integer, intent(in) :: i_in, j_in integer, dimension(:), intent(out) :: i_out, j_out integer, intent(out) :: num_nbr integer :: n num_nbr = 0 n = number if(n .ge. 128) then num_nbr = num_nbr + 1 n = n - 128 i_out(num_nbr) = i_in+1; j_out(num_nbr) = j_in + 1 endif if(n .ge. 64) then num_nbr = num_nbr + 1 n = n - 64 i_out(num_nbr) = i_in; j_out(num_nbr) = j_in + 1 endif if(n .ge. 32) then num_nbr = num_nbr + 1 n = n - 32 i_out(num_nbr) = i_in-1; j_out(num_nbr) = j_in + 1 endif if(n .ge. 16) then num_nbr = num_nbr + 1 n = n - 16 i_out(num_nbr) = i_in-1; j_out(num_nbr) = j_in endif if(n .ge. 8) then num_nbr = num_nbr + 1 n = n - 8 i_out(num_nbr) = i_in-1; j_out(num_nbr) = j_in - 1 endif if(n .ge. 4) then num_nbr = num_nbr + 1 n = n - 4 i_out(num_nbr) = i_in; j_out(num_nbr) = j_in - 1 endif if(n .ge. 2) then num_nbr = num_nbr + 1 n = n - 2 i_out(num_nbr) = i_in+1; j_out(num_nbr) = j_in - 1 endif if(n .ge. 1) then num_nbr = num_nbr + 1 n = n - 1 i_out(num_nbr) = i_in+1; j_out(num_nbr) = j_in endif do n = 1, num_nbr if(i_out(n) .eq. nlon+1) i_out(n) = 1 if(i_out(n) .eq. 0) i_out(n) = nlon if(j_out(n) .eq. 0 .or. j_out(n) .eq. nlat+1) & call mpp_error(FATAL,'river_regrid: neighbor latitude index should be between 1 and nj') enddo return end subroutine get_nbr_index !##################################################################### ! define river grid mask. river mask will be defined through ocean land/sea mask. ! conservative remapping will be done from ocean grid onto river grid. subroutine define_river_mask(River) type(river_regrid_type), intent(inout) :: River integer :: i, j, layout(2), isc, iec, jsc, jec integer :: siz(4), nlon_ocn, nlat_ocn real, dimension(:,:,:), allocatable :: x_vert_t, y_vert_t real, dimension(:,:), allocatable :: x_vert_ocn, y_vert_ocn real, dimension(:,:), allocatable :: local_mask, global_mask type(horiz_interp_type) :: Interp type(domain2D) :: Domain real :: diff real, parameter :: small = 1.e-6 River%mask = 0 ! 0 means ocean points !--- read ocean grid location and land/sea mask. call field_size(grid_file, 'wet', siz) nlon_ocn = siz(1) nlat_ocn = siz(2) allocate(x_vert_ocn(nlon_ocn+1, nlat_ocn+1)) allocate(y_vert_ocn(nlon_ocn+1, nlat_ocn+1)) allocate(mask_ocn (nlon_ocn, nlat_ocn )) allocate(lon_ocn (nlon_ocn, nlat_ocn )) allocate(lat_ocn (nlon_ocn, nlat_ocn )) call read_data(grid_file, 'wet', mask_ocn, no_domain=.true.) if(field_exist(grid_file, 'geolon_vert_t') )then call read_data(grid_file, 'geolon_vert_t', x_vert_ocn, no_domain=.true.) call read_data(grid_file, 'geolat_vert_t', y_vert_ocn, no_domain=.true.) call read_data(grid_file, 'geolon_t', lon_ocn, no_domain=.true.) call read_data(grid_file, 'geolat_t', lat_ocn, no_domain=.true.) else if(field_exist(grid_file, 'x_vert_T') )then allocate(x_vert_t(nlon_ocn, nlat_ocn, 4)) allocate(y_vert_t(nlon_ocn, nlat_ocn, 4)) call read_data(grid_file, 'x_vert_T', x_vert_t, no_domain=.true.) call read_data(grid_file, 'y_vert_T', y_vert_t, no_domain=.true.) call read_data(grid_file, 'x_T', lon_ocn, no_domain=.true.) call read_data(grid_file, 'y_T', lat_ocn, no_domain=.true.) x_vert_ocn(1:nlon_ocn,1:nlat_ocn) = x_vert_t(1:nlon_ocn,1:nlat_ocn,1) x_vert_ocn(nlon_ocn+1,1:nlat_ocn) = x_vert_t(nlon_ocn,1:nlat_ocn,2) x_vert_ocn(1:nlon_ocn,nlat_ocn+1) = x_vert_t(1:nlon_ocn,nlat_ocn,4) x_vert_ocn(nlon_ocn+1,nlat_ocn+1) = x_vert_t(nlon_ocn,nlat_ocn,3) y_vert_ocn(1:nlon_ocn,1:nlat_ocn) = y_vert_t(1:nlon_ocn,1:nlat_ocn,1) y_vert_ocn(nlon_ocn+1,1:nlat_ocn) = y_vert_t(nlon_ocn,1:nlat_ocn,2) y_vert_ocn(1:nlon_ocn,nlat_ocn+1) = y_vert_t(1:nlon_ocn,nlat_ocn,4) y_vert_ocn(nlon_ocn+1,nlat_ocn+1) = y_vert_t(nlon_ocn,nlat_ocn,3) deallocate(x_vert_t) deallocate(y_vert_t) else call mpp_error(FATAL,'river_regrid: both geolon_vert_t and x_vert_T do not exist in file '//trim(grid_file)) end if ! There is some truncation error in some latitude, adjust the small difference for non-folded region do j = 1, nlat_ocn+1 if(ANY( y_vert_ocn(:,j) .NE. y_vert_ocn(1,j)) ) exit diff = abs(y_vert_ocn(1,j) - int(y_vert_ocn(1,j))) if( diff < small .AND. diff > 0) then write(stdout(),*)'y_vert_ocn is adjusted from ', y_vert_ocn(1,j), ' to ', int(y_vert_ocn(1,j)), ' at j = ', j y_vert_ocn(:,j) = int(y_vert_ocn(1,j)) end if end do do j = 1, nlat_ocn if(ANY( lat_ocn(:,j) .NE. lat_ocn(1,j)) ) exit if( abs(lat_ocn(1,j) - int(lat_ocn(1,j))) < small ) then lat_ocn(:,j) = int(lat_ocn(1,j)) end if end do call horiz_interp_init ! The following procedure is very expensive, so parallization is needed call mpp_define_layout( (/1,nlon,1,nlat/), mpp_npes(), layout) call mpp_define_domains((/1,nlon,1,nlat/),layout, Domain,xhalo=0,yhalo=0) call mpp_get_compute_domain( Domain, isc, iec, jsc, jec ) call horiz_interp_new(Interp, x_vert_ocn*DEG_TO_RAD, y_vert_ocn*DEG_TO_RAD, River%lonb(isc:iec+1)*DEG_TO_RAD, & River%latb(jsc:jec+1)*DEG_TO_RAD, interp_method='conservative' ) allocate(local_mask(isc:iec,jsc:jec), global_mask(nlon,nlat)) call horiz_interp(Interp, mask_ocn, local_mask) call mpp_global_field(Domain, local_mask, global_mask) River%mask(1:nlon,1:nlat) = global_mask call horiz_interp_del(Interp) deallocate(x_vert_ocn, y_vert_ocn, local_mask, global_mask) !--- currently the mask is the ocean mask. do j = 1, nlat do i = 1, nlon River%mask(i,j) = 1 - River%mask(i,j) if( abs(River%mask(i,j)) < lnd_thresh ) River%mask(i,j) = 0.0 if( abs(River%mask(i,j)-1) < lnd_thresh) River%mask(i,j) = 1.0 if( River%mask(i,j) < 0 .or. River%mask(i,j) > 1) & call mpp_error(FATAL,'river_regrid: river mask should be between 0 or 1') end do end do !--- here we suppose the cyclic condition exists call update_halo(River%mask(-1:nlon+2,1:nlat), 2) !--- set mask to large positive value for the purpose of defining neighbor points. River%mask(:,-1:0) = 999.0 River%mask(:,nlat+1:nlat+2) = 999.0 end subroutine define_river_mask !##################################################################### !--- update point on the global halo. subroutine update_halo(data, halo) integer, intent(in) :: halo real, dimension(1-halo:,:), intent(inout) :: data integer :: n, ni ni = size(data,1) - 2*halo do n = 1, halo data(1-n,:) = data(ni+1-n,:) data(ni+n,:) = data(halo,:) enddo end subroutine update_halo !##################################################################### !--- read each line of the file grid_edits subroutine parse_edits(txt,is,ie,js,je,flag) character(len=*), intent(in) :: txt integer, intent(inout) :: is,ie,js,je logical, intent(inout) :: flag integer :: i1,i2, i3 character(len=128) :: txt2 flag = .true. i1 = scan(txt,',') if (i1 <= 0) goto 90 txt2 = txt(1:i1-1) i2 = scan(txt2,':') if (i2 <= 0) then read(txt2,*,err=90) is ie = is else read(txt2(1:i2-1),*,err=90) is read(txt2(i2+1:),*,err=90) ie endif txt2 = txt(i1+1:) i3 = scan(txt2,':') if (i3 <= 0) then read(txt2,*,err=90) js je = js else read(txt2(1:i3-1),*,err=90) js read(txt2(i3+1:),*,err=90) je endif return 90 continue flag = .false. return end subroutine parse_edits !##################################################################### end program river_regrid
gpl-2.0
astrofrog/fortranlib
templates/lib_statistics_template.f90
1
4531
! Statistics ! ! ------------------------------------------------------------------------------ ! Copyright (c) 2009-13, Thomas P. Robitaille ! ! All rights reserved. ! ! Redistribution and use in source and binary forms, with or without ! modification, are permitted provided that the following conditions are met: ! ! * Redistributions of source code must retain the above copyright notice, this ! list of conditions and the following disclaimer. ! ! * Redistributions in binary form must reproduce the above copyright notice, ! this list of conditions and the following disclaimer in the documentation ! and/or other materials provided with the distribution. ! ! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ! DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ! FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ! SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ! OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ! ------------------------------------------------------------------------------ module lib_statistics use lib_array implicit none save private integer,parameter :: idp = selected_int_kind(13) integer,parameter :: sp = selected_real_kind(p=6,r=37) integer,parameter :: dp = selected_real_kind(p=15,r=307) public :: mean interface mean module procedure mean_sp module procedure mean_dp end interface mean public :: median interface median module procedure median_sp module procedure median_dp end interface median public :: quantile interface quantile module procedure quantile_sp module procedure quantile_dp end interface quantile public :: variance interface variance module procedure variance_sp module procedure variance_dp end interface variance public :: clipped_mean interface clipped_mean module procedure clipped_mean_sp module procedure clipped_mean_dp end interface clipped_mean contains !!@FOR real(sp):sp real(dp):dp @T function mean_<T>(x, mask) implicit none @T,intent(in) :: x(:) logical,intent(in),optional :: mask(:) if(present(mask)) then mean_<T> = sum(x, mask=mask)/size(x) else mean_<T> = sum(x)/size(x) end if end function mean_<T> @T function median_<T>(x) implicit none @T,intent(in) :: x(:) @T,dimension(size(x)) :: x_sorted integer :: n n = size(x) x_sorted = x call quicksort(x_sorted) if(mod(n,2).eq.0) then median_<T>=(x_sorted(n/2)+x_sorted(n/2+1))/2. else median_<T>=x_sorted((n-1)/2+1) end if end function median_<T> @T function quantile_<T>(x, percent, mask) implicit none @T,intent(in) :: x(:), percent logical,intent(in),optional :: mask(:) @T,allocatable :: x_sorted(:) integer :: n, ipos if(present(mask)) then n = count(mask) allocate(x_sorted(n)) x_sorted = pack(x, mask) else n = size(x) allocate(x_sorted(n)) x_sorted = x end if call quicksort(x_sorted) if(percent >= 100._<T>) then ipos = n else if(percent <= 0._<T>) then ipos = 1 else ipos=nint(percent/100._<T>*real(n-1, <T>))+1 end if quantile_<T>=x_sorted(ipos) end function quantile_<T> @T function variance_<T>(x, mask) implicit none @T,intent(in) :: x(:) logical,intent(in),optional :: mask(:) variance_<T> = sum(x-mean(x, mask=mask)**2._<T>)/(size(x)-1) end function variance_<T> @T function clipped_mean_<T>(x, n) implicit none @T,intent(in) :: x(:) integer,intent(in) :: n logical,dimension(size(x)) :: keep @T :: sigma integer :: n_before keep = .true. n_before = 0 do clipped_mean_<T> = mean(x, mask=keep) sigma = sqrt(variance(x, mask=keep)) keep = keep .and. abs(x-clipped_mean_<T>) < real(n, <T>) * sigma if(count(keep)==n_before) exit n_before = count(keep) end do end function clipped_mean_<T> !!@END FOR end module lib_statistics
bsd-2-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/TESTING/LIN/derrtr.f
32
17462
*> \brief \b DERRTR * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE DERRTR( PATH, NUNIT ) * * .. Scalar Arguments .. * CHARACTER*3 PATH * INTEGER NUNIT * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DERRTR tests the error exits for the DOUBLE PRECISION triangular *> routines. *> \endverbatim * * Arguments: * ========== * *> \param[in] PATH *> \verbatim *> PATH is CHARACTER*3 *> The LAPACK path name for the routines to be tested. *> \endverbatim *> *> \param[in] NUNIT *> \verbatim *> NUNIT is INTEGER *> The unit number for output. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup double_lin * * ===================================================================== SUBROUTINE DERRTR( PATH, NUNIT ) * * -- LAPACK test routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER*3 PATH INTEGER NUNIT * .. * * ===================================================================== * * .. Parameters .. INTEGER NMAX PARAMETER ( NMAX = 2 ) * .. * .. Local Scalars .. CHARACTER*2 C2 INTEGER INFO DOUBLE PRECISION RCOND, SCALE * .. * .. Local Arrays .. INTEGER IW( NMAX ) DOUBLE PRECISION A( NMAX, NMAX ), B( NMAX ), R1( NMAX ), $ R2( NMAX ), W( NMAX ), X( NMAX ) * .. * .. External Functions .. LOGICAL LSAMEN EXTERNAL LSAMEN * .. * .. External Subroutines .. EXTERNAL ALAESM, CHKXER, DLATBS, DLATPS, DLATRS, DTBCON, $ DTBRFS, DTBTRS, DTPCON, DTPRFS, DTPTRI, DTPTRS, $ DTRCON, DTRRFS, DTRTI2, DTRTRI, DTRTRS * .. * .. Scalars in Common .. LOGICAL LERR, OK CHARACTER*32 SRNAMT INTEGER INFOT, NOUT * .. * .. Common blocks .. COMMON / INFOC / INFOT, NOUT, OK, LERR COMMON / SRNAMC / SRNAMT * .. * .. Executable Statements .. * NOUT = NUNIT WRITE( NOUT, FMT = * ) C2 = PATH( 2: 3 ) A( 1, 1 ) = 1.D0 A( 1, 2 ) = 2.D0 A( 2, 2 ) = 3.D0 A( 2, 1 ) = 4.D0 OK = .TRUE. * IF( LSAMEN( 2, C2, 'TR' ) ) THEN * * Test error exits for the general triangular routines. * * DTRTRI * SRNAMT = 'DTRTRI' INFOT = 1 CALL DTRTRI( '/', 'N', 0, A, 1, INFO ) CALL CHKXER( 'DTRTRI', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTRTRI( 'U', '/', 0, A, 1, INFO ) CALL CHKXER( 'DTRTRI', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTRTRI( 'U', 'N', -1, A, 1, INFO ) CALL CHKXER( 'DTRTRI', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTRTRI( 'U', 'N', 2, A, 1, INFO ) CALL CHKXER( 'DTRTRI', INFOT, NOUT, LERR, OK ) * * DTRTI2 * SRNAMT = 'DTRTI2' INFOT = 1 CALL DTRTI2( '/', 'N', 0, A, 1, INFO ) CALL CHKXER( 'DTRTI2', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTRTI2( 'U', '/', 0, A, 1, INFO ) CALL CHKXER( 'DTRTI2', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTRTI2( 'U', 'N', -1, A, 1, INFO ) CALL CHKXER( 'DTRTI2', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTRTI2( 'U', 'N', 2, A, 1, INFO ) CALL CHKXER( 'DTRTI2', INFOT, NOUT, LERR, OK ) * * DTRTRS * SRNAMT = 'DTRTRS' INFOT = 1 CALL DTRTRS( '/', 'N', 'N', 0, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTRTRS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTRTRS( 'U', '/', 'N', 0, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTRTRS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTRTRS( 'U', 'N', '/', 0, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTRTRS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTRTRS( 'U', 'N', 'N', -1, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTRTRS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTRTRS( 'U', 'N', 'N', 0, -1, A, 1, X, 1, INFO ) CALL CHKXER( 'DTRTRS', INFOT, NOUT, LERR, OK ) INFOT = 7 CALL DTRTRS( 'U', 'N', 'N', 2, 1, A, 1, X, 2, INFO ) CALL CHKXER( 'DTRTRS', INFOT, NOUT, LERR, OK ) INFOT = 9 CALL DTRTRS( 'U', 'N', 'N', 2, 1, A, 2, X, 1, INFO ) CALL CHKXER( 'DTRTRS', INFOT, NOUT, LERR, OK ) * * DTRRFS * SRNAMT = 'DTRRFS' INFOT = 1 CALL DTRRFS( '/', 'N', 'N', 0, 0, A, 1, B, 1, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTRRFS( 'U', '/', 'N', 0, 0, A, 1, B, 1, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTRRFS( 'U', 'N', '/', 0, 0, A, 1, B, 1, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTRRFS( 'U', 'N', 'N', -1, 0, A, 1, B, 1, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTRRFS( 'U', 'N', 'N', 0, -1, A, 1, B, 1, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) INFOT = 7 CALL DTRRFS( 'U', 'N', 'N', 2, 1, A, 1, B, 2, X, 2, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) INFOT = 9 CALL DTRRFS( 'U', 'N', 'N', 2, 1, A, 2, B, 1, X, 2, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) INFOT = 11 CALL DTRRFS( 'U', 'N', 'N', 2, 1, A, 2, B, 2, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTRRFS', INFOT, NOUT, LERR, OK ) * * DTRCON * SRNAMT = 'DTRCON' INFOT = 1 CALL DTRCON( '/', 'U', 'N', 0, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTRCON', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTRCON( '1', '/', 'N', 0, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTRCON', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTRCON( '1', 'U', '/', 0, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTRCON', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTRCON( '1', 'U', 'N', -1, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTRCON', INFOT, NOUT, LERR, OK ) INFOT = 6 CALL DTRCON( '1', 'U', 'N', 2, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTRCON', INFOT, NOUT, LERR, OK ) * * DLATRS * SRNAMT = 'DLATRS' INFOT = 1 CALL DLATRS( '/', 'N', 'N', 'N', 0, A, 1, X, SCALE, W, INFO ) CALL CHKXER( 'DLATRS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DLATRS( 'U', '/', 'N', 'N', 0, A, 1, X, SCALE, W, INFO ) CALL CHKXER( 'DLATRS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DLATRS( 'U', 'N', '/', 'N', 0, A, 1, X, SCALE, W, INFO ) CALL CHKXER( 'DLATRS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DLATRS( 'U', 'N', 'N', '/', 0, A, 1, X, SCALE, W, INFO ) CALL CHKXER( 'DLATRS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DLATRS( 'U', 'N', 'N', 'N', -1, A, 1, X, SCALE, W, INFO ) CALL CHKXER( 'DLATRS', INFOT, NOUT, LERR, OK ) INFOT = 7 CALL DLATRS( 'U', 'N', 'N', 'N', 2, A, 1, X, SCALE, W, INFO ) CALL CHKXER( 'DLATRS', INFOT, NOUT, LERR, OK ) * ELSE IF( LSAMEN( 2, C2, 'TP' ) ) THEN * * Test error exits for the packed triangular routines. * * DTPTRI * SRNAMT = 'DTPTRI' INFOT = 1 CALL DTPTRI( '/', 'N', 0, A, INFO ) CALL CHKXER( 'DTPTRI', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTPTRI( 'U', '/', 0, A, INFO ) CALL CHKXER( 'DTPTRI', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTPTRI( 'U', 'N', -1, A, INFO ) CALL CHKXER( 'DTPTRI', INFOT, NOUT, LERR, OK ) * * DTPTRS * SRNAMT = 'DTPTRS' INFOT = 1 CALL DTPTRS( '/', 'N', 'N', 0, 0, A, X, 1, INFO ) CALL CHKXER( 'DTPTRS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTPTRS( 'U', '/', 'N', 0, 0, A, X, 1, INFO ) CALL CHKXER( 'DTPTRS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTPTRS( 'U', 'N', '/', 0, 0, A, X, 1, INFO ) CALL CHKXER( 'DTPTRS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTPTRS( 'U', 'N', 'N', -1, 0, A, X, 1, INFO ) CALL CHKXER( 'DTPTRS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTPTRS( 'U', 'N', 'N', 0, -1, A, X, 1, INFO ) CALL CHKXER( 'DTPTRS', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL DTPTRS( 'U', 'N', 'N', 2, 1, A, X, 1, INFO ) CALL CHKXER( 'DTPTRS', INFOT, NOUT, LERR, OK ) * * DTPRFS * SRNAMT = 'DTPRFS' INFOT = 1 CALL DTPRFS( '/', 'N', 'N', 0, 0, A, B, 1, X, 1, R1, R2, W, IW, $ INFO ) CALL CHKXER( 'DTPRFS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTPRFS( 'U', '/', 'N', 0, 0, A, B, 1, X, 1, R1, R2, W, IW, $ INFO ) CALL CHKXER( 'DTPRFS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTPRFS( 'U', 'N', '/', 0, 0, A, B, 1, X, 1, R1, R2, W, IW, $ INFO ) CALL CHKXER( 'DTPRFS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTPRFS( 'U', 'N', 'N', -1, 0, A, B, 1, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTPRFS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTPRFS( 'U', 'N', 'N', 0, -1, A, B, 1, X, 1, R1, R2, W, $ IW, INFO ) CALL CHKXER( 'DTPRFS', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL DTPRFS( 'U', 'N', 'N', 2, 1, A, B, 1, X, 2, R1, R2, W, IW, $ INFO ) CALL CHKXER( 'DTPRFS', INFOT, NOUT, LERR, OK ) INFOT = 10 CALL DTPRFS( 'U', 'N', 'N', 2, 1, A, B, 2, X, 1, R1, R2, W, IW, $ INFO ) CALL CHKXER( 'DTPRFS', INFOT, NOUT, LERR, OK ) * * DTPCON * SRNAMT = 'DTPCON' INFOT = 1 CALL DTPCON( '/', 'U', 'N', 0, A, RCOND, W, IW, INFO ) CALL CHKXER( 'DTPCON', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTPCON( '1', '/', 'N', 0, A, RCOND, W, IW, INFO ) CALL CHKXER( 'DTPCON', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTPCON( '1', 'U', '/', 0, A, RCOND, W, IW, INFO ) CALL CHKXER( 'DTPCON', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTPCON( '1', 'U', 'N', -1, A, RCOND, W, IW, INFO ) CALL CHKXER( 'DTPCON', INFOT, NOUT, LERR, OK ) * * DLATPS * SRNAMT = 'DLATPS' INFOT = 1 CALL DLATPS( '/', 'N', 'N', 'N', 0, A, X, SCALE, W, INFO ) CALL CHKXER( 'DLATPS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DLATPS( 'U', '/', 'N', 'N', 0, A, X, SCALE, W, INFO ) CALL CHKXER( 'DLATPS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DLATPS( 'U', 'N', '/', 'N', 0, A, X, SCALE, W, INFO ) CALL CHKXER( 'DLATPS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DLATPS( 'U', 'N', 'N', '/', 0, A, X, SCALE, W, INFO ) CALL CHKXER( 'DLATPS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DLATPS( 'U', 'N', 'N', 'N', -1, A, X, SCALE, W, INFO ) CALL CHKXER( 'DLATPS', INFOT, NOUT, LERR, OK ) * ELSE IF( LSAMEN( 2, C2, 'TB' ) ) THEN * * Test error exits for the banded triangular routines. * * DTBTRS * SRNAMT = 'DTBTRS' INFOT = 1 CALL DTBTRS( '/', 'N', 'N', 0, 0, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTBTRS( 'U', '/', 'N', 0, 0, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTBTRS( 'U', 'N', '/', 0, 0, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTBTRS( 'U', 'N', 'N', -1, 0, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTBTRS( 'U', 'N', 'N', 0, -1, 0, A, 1, X, 1, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) INFOT = 6 CALL DTBTRS( 'U', 'N', 'N', 0, 0, -1, A, 1, X, 1, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL DTBTRS( 'U', 'N', 'N', 2, 1, 1, A, 1, X, 2, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) INFOT = 10 CALL DTBTRS( 'U', 'N', 'N', 2, 0, 1, A, 1, X, 1, INFO ) CALL CHKXER( 'DTBTRS', INFOT, NOUT, LERR, OK ) * * DTBRFS * SRNAMT = 'DTBRFS' INFOT = 1 CALL DTBRFS( '/', 'N', 'N', 0, 0, 0, A, 1, B, 1, X, 1, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTBRFS( 'U', '/', 'N', 0, 0, 0, A, 1, B, 1, X, 1, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTBRFS( 'U', 'N', '/', 0, 0, 0, A, 1, B, 1, X, 1, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTBRFS( 'U', 'N', 'N', -1, 0, 0, A, 1, B, 1, X, 1, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTBRFS( 'U', 'N', 'N', 0, -1, 0, A, 1, B, 1, X, 1, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 6 CALL DTBRFS( 'U', 'N', 'N', 0, 0, -1, A, 1, B, 1, X, 1, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL DTBRFS( 'U', 'N', 'N', 2, 1, 1, A, 1, B, 2, X, 2, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 10 CALL DTBRFS( 'U', 'N', 'N', 2, 1, 1, A, 2, B, 1, X, 2, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) INFOT = 12 CALL DTBRFS( 'U', 'N', 'N', 2, 1, 1, A, 2, B, 2, X, 1, R1, R2, $ W, IW, INFO ) CALL CHKXER( 'DTBRFS', INFOT, NOUT, LERR, OK ) * * DTBCON * SRNAMT = 'DTBCON' INFOT = 1 CALL DTBCON( '/', 'U', 'N', 0, 0, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTBCON', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DTBCON( '1', '/', 'N', 0, 0, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTBCON', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DTBCON( '1', 'U', '/', 0, 0, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTBCON', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DTBCON( '1', 'U', 'N', -1, 0, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTBCON', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DTBCON( '1', 'U', 'N', 0, -1, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTBCON', INFOT, NOUT, LERR, OK ) INFOT = 7 CALL DTBCON( '1', 'U', 'N', 2, 1, A, 1, RCOND, W, IW, INFO ) CALL CHKXER( 'DTBCON', INFOT, NOUT, LERR, OK ) * * DLATBS * SRNAMT = 'DLATBS' INFOT = 1 CALL DLATBS( '/', 'N', 'N', 'N', 0, 0, A, 1, X, SCALE, W, $ INFO ) CALL CHKXER( 'DLATBS', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DLATBS( 'U', '/', 'N', 'N', 0, 0, A, 1, X, SCALE, W, $ INFO ) CALL CHKXER( 'DLATBS', INFOT, NOUT, LERR, OK ) INFOT = 3 CALL DLATBS( 'U', 'N', '/', 'N', 0, 0, A, 1, X, SCALE, W, $ INFO ) CALL CHKXER( 'DLATBS', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DLATBS( 'U', 'N', 'N', '/', 0, 0, A, 1, X, SCALE, W, $ INFO ) CALL CHKXER( 'DLATBS', INFOT, NOUT, LERR, OK ) INFOT = 5 CALL DLATBS( 'U', 'N', 'N', 'N', -1, 0, A, 1, X, SCALE, W, $ INFO ) CALL CHKXER( 'DLATBS', INFOT, NOUT, LERR, OK ) INFOT = 6 CALL DLATBS( 'U', 'N', 'N', 'N', 1, -1, A, 1, X, SCALE, W, $ INFO ) CALL CHKXER( 'DLATBS', INFOT, NOUT, LERR, OK ) INFOT = 8 CALL DLATBS( 'U', 'N', 'N', 'N', 2, 1, A, 1, X, SCALE, W, $ INFO ) CALL CHKXER( 'DLATBS', INFOT, NOUT, LERR, OK ) END IF * * Print a summary line. * CALL ALAESM( PATH, OK, NOUT ) * RETURN * * End of DERRTR * END
bsd-3-clause
nicjhan/MOM5
src/land_lad2/land_data.F90
10
28721
module land_data_mod use mpp_mod , only : mpp_get_current_pelist, mpp_pe use constants_mod , only : PI use mpp_domains_mod , only : domain2d, mpp_get_compute_domain, & mpp_define_layout, mpp_define_domains, mpp_define_io_domain, & mpp_get_current_ntile, mpp_get_tile_id, CYCLIC_GLOBAL_DOMAIN, & mpp_get_io_domain, mpp_get_pelist, mpp_get_layout use mpp_mod, only : mpp_chksum use fms_mod , only : write_version_number, mpp_npes, & error_mesg, FATAL, stdout use time_manager_mod , only : time_type use tracer_manager_mod, only : register_tracers, get_tracer_index, NO_TRACER use field_manager_mod , only : MODEL_LAND use grid_mod , only : get_grid_ntiles, get_grid_size, get_grid_cell_vertices, & get_grid_cell_centers, get_grid_cell_area, get_grid_comp_area, & define_cube_mosaic use land_tile_mod , only : land_tile_type, land_tile_list_type, & land_tile_list_init, land_tile_list_end, nitems implicit none private ! ==== public interfaces ===================================================== public :: land_data_init public :: land_data_end public :: lnd ! global data public :: atmos_land_boundary_type ! container for information passed from the ! atmosphere to land public :: land_data_type ! container for information passed from land to ! the atmosphere ! both hold information on land grid (that is, after flux exchange translated ! it from the atmosphere) public land_data_type_chksum ! routine to print checksums for land_data_type public atm_lnd_bnd_type_chksum ! routine to print checksums for atmos_land_boundary_type public :: dealloc_land2cplr ! deallocates a land_data_type structure public :: realloc_land2cplr ! allocates a land_data_type members for current ! number of tiles public :: dealloc_cplr2land ! deallocates an atmos_land_boundary_type structure public :: realloc_cplr2land ! allocates an atmos_land_boundary_type members ! for current number of tiles ! NOTE: realloc_* procedures can be called regardless of the current state ! of the argument data structures, since they deallocate data first. public :: land_state_type ! ==== end of public interfaces ============================================== ! ---- module constants ------------------------------------------------------ character(len=*), parameter :: & module_name = 'land_data_mod', & version = '$Id: land_data.F90,v 20.0 2013/12/13 23:29:24 fms Exp $', & tagname = '$Name: tikal $' ! init_value is used to fill most of the allocated boundary condition arrays. ! It is supposed to be double-precision signaling NaN, to trigger a trap when ! the program is compiled with trapping non-initialized values. ! See http://ftp.uniovi.es/~antonio/uned/ieee754/IEEE-754references.html real, parameter :: init_value = Z'FFF0000000000001' ! ---- types ----------------------------------------------------------------- type :: atmos_land_boundary_type ! data passed from the coupler to the surface real, dimension(:,:,:), pointer :: & ! (lon, lat, tile) t_flux => NULL(), & ! sensible heat flux, W/m2 lw_flux => NULL(), & ! net longwave radiation flux, W/m2 lwdn_flux => NULL(), & ! downward longwave radiation flux, W/m2 sw_flux => NULL(), & ! net shortwave radiation flux, W/m2 swdn_flux => NULL(), & ! downward shortwave radiation flux, W/m2 lprec => NULL(), & ! liquid precipitation rate, kg/(m2 s) fprec => NULL(), & ! frozen precipitation rate, kg/(m2 s) tprec => NULL(), & ! temperature of precipitation, degK ! components of downward shortwave flux, W/m2 sw_flux_down_vis_dir => NULL(), & ! visible direct sw_flux_down_total_dir => NULL(), & ! total direct sw_flux_down_vis_dif => NULL(), & ! visible diffuse sw_flux_down_total_dif => NULL(), & ! total diffuse ! derivatives of the fluxes dhdt => NULL(), & ! sensible w.r.t. surface temperature dhdq => NULL(), & ! sensible w.r.t. surface humidity drdt => NULL(), & ! longwave w.r.t. surface radiative temperature ! cd_m => NULL(), & ! drag coefficient for momentum, dimensionless cd_t => NULL(), & ! drag coefficient for tracers, dimensionless ustar => NULL(), & ! turbulent wind scale, m/s bstar => NULL(), & ! turbulent buoyancy scale, m/s wind => NULL(), & ! abs wind speed at the bottom of the atmos, m/s z_bot => NULL(), & ! height of the bottom atmospheric layer above the surface, m drag_q => NULL(), & ! product of cd_q by wind p_surf => NULL() ! surface pressure, Pa real, dimension(:,:,:,:), pointer :: & ! (lon, lat, tile, tracer) tr_flux => NULL(), & ! tracer flux, including water vapor flux dfdtr => NULL() ! derivative of the flux w.r.t. tracer surface value, ! including evap over surface specific humidity integer :: xtype !REGRID, REDIST or DIRECT end type atmos_land_boundary_type type :: land_data_type ! data passed from the surface to the coupler logical :: pe ! data presence indicator for stock calculations real, pointer, dimension(:,:,:) :: & ! (lon, lat, tile) tile_size => NULL(), & ! fractional coverage of cell by tile, dimensionless t_surf => NULL(), & ! ground surface temperature, degK t_ca => NULL(), & ! canopy air temperature, degK albedo => NULL(), & ! broadband land albedo [unused?] albedo_vis_dir => NULL(), & ! albedo for direct visible radiation albedo_nir_dir => NULL(), & ! albedo for direct NIR radiation albedo_vis_dif => NULL(), & ! albedo for diffuse visible radiation albedo_nir_dif => NULL(), & ! albedo for diffuse NIR radiation rough_mom => NULL(), & ! surface roughness length for momentum, m rough_heat => NULL(), & ! roughness length for tracers and heat, m rough_scale => NULL() ! topographic scaler for momentum drag, m real, pointer, dimension(:,:,:,:) :: & ! (lon, lat, tile, tracer) tr => NULL() ! tracers, including canopy air specific humidity ! NOTE that in contrast to most of the other fields in this structure, the discharges ! hold data per-gridcell, rather than per-tile basis. This, and the order of updates, ! have implications for the data reallocation procedure. real, pointer, dimension(:,:) :: & ! (lon, lat) discharge => NULL(), & ! liquid water flux from land to ocean discharge_heat => NULL(), & ! sensible heat of discharge (0 C datum) discharge_snow => NULL(), & ! solid water flux from land to ocean discharge_snow_heat => NULL() ! sensible heat of discharge_snow (0 C datum) logical, pointer, dimension(:,:,:):: & mask => NULL() ! true if land integer :: axes(2) ! IDs of diagnostic axes type(domain2d) :: domain ! our computation domain logical, pointer :: maskmap(:,:) integer, pointer, dimension(:) :: pelist end type land_data_type ! land_state_type combines the general information about state of the land model: ! domain, coordinates, time steps, etc. There is only one variable of this type, ! and it is public in this module. type :: land_state_type integer :: is,ie,js,je ! compute domain boundaries integer :: nlon,nlat ! size of global grid integer :: ntprog ! number of prognostic tracers integer :: isphum ! index of specific humidity in tracer table integer :: ico2 ! index of carbon dioxide in tracer table type(time_type):: dt_fast ! fast (physical) time step type(time_type):: dt_slow ! slow time step type(time_type):: time ! current time real, pointer :: lon (:,:), lat (:,:) ! domain grid center coordinates, radian real, pointer :: lonb(:,:), latb(:,:) ! domain grid vertices, radian real, pointer :: area(:,:) ! land area per grid cell, m2 real, pointer :: cellarea(:,:) ! grid cell area, m2 real, pointer :: coord_glon(:), coord_glonb(:) ! longitudes for use in diag axis and such, degrees East real, pointer :: coord_glat(:), coord_glatb(:) ! latitudes for use in diag axis and such, degrees North ! map of tiles type(land_tile_list_type), pointer :: tile_map(:,:) type(domain2d) :: domain ! our domain -- should be the last since it simplifies ! debugging in totalview integer :: nfaces ! number of mosaic faces integer :: face ! the current mosaic face integer, allocatable :: pelist(:) ! list of processors that run land model integer, allocatable :: io_pelist(:) ! list of processors in our io_domain ! if io_domain was not defined, then there is just one element in this ! array, and it's equal to current PE integer :: io_id ! suffix in the distributed files. logical :: append_io_id ! if FALSE, io_id is not appended to the file names ! (for the case io_layout = 1,1) end type land_state_type ! ---- public module variables ----------------------------------------------- type(land_state_type),save :: lnd ! ---- private module variables ---------------------------------------------- logical :: module_is_initialized =.FALSE. #define __DEALLOC__(x) if (associated(x)) deallocate(x) contains ! -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ! ============================================================================ subroutine land_data_init(layout, io_layout, time, dt_fast, dt_slow) integer, intent(inout) :: layout(2) ! layout of our domains integer, intent(inout) :: io_layout(2) ! layout for land model io type(time_type), intent(in) :: & time, & ! current model time dt_fast, & ! fast (physical) time step dt_slow ! slow time step ! ---- local vars integer :: nlon, nlat ! size of global grid in lon and lat directions integer :: ntiles ! number of tiles in the mosaic grid integer :: ntracers, ndiag ! non-optional output from register_tracers integer, allocatable :: tile_ids(:) ! mosaic tile IDs for the current PE integer :: i,j type(domain2d), pointer :: io_domain ! our io_domain integer :: n_io_pes(2) ! number of PEs in our io_domain along x and y integer :: io_id(1) ! write the version and tag name to the logfile call write_version_number(version, tagname) ! define the processor layout information according to the global grid size call get_grid_ntiles('LND',ntiles) lnd%nfaces = ntiles call get_grid_size('LND',1,nlon,nlat) ! set the size of global grid lnd%nlon = nlon; lnd%nlat = nlat if( layout(1)==0 .AND. layout(2)==0 ) & call mpp_define_layout( (/1,nlon,1,nlat/), mpp_npes()/ntiles, layout ) if( layout(1)/=0 .AND. layout(2)==0 )layout(2) = mpp_npes()/(layout(1)*ntiles) if( layout(1)==0 .AND. layout(2)/=0 )layout(1) = mpp_npes()/(layout(2)*ntiles) ! define land model domain if (ntiles==1) then call mpp_define_domains ((/1,nlon, 1, nlat/), layout, lnd%domain, xhalo=1, yhalo=1,& xflags = CYCLIC_GLOBAL_DOMAIN, name = 'LAND MODEL') else call define_cube_mosaic ('LND', lnd%domain, layout, halo=1) endif ! define io domain call mpp_define_io_domain(lnd%domain, io_layout) ! set up list of processors for collective io: only the first processor in this ! list actually writes data, the rest just send the data to it. io_domain=>mpp_get_io_domain(lnd%domain) if (associated(io_domain)) then call mpp_get_layout(io_domain,n_io_pes) allocate(lnd%io_pelist(n_io_pes(1)*n_io_pes(2))) call mpp_get_pelist(io_domain,lnd%io_pelist) io_id = mpp_get_tile_id(io_domain) lnd%io_id = io_id(1) else allocate(lnd%io_pelist(1)) lnd%io_pelist(1) = mpp_pe() lnd%io_id = mpp_pe() endif lnd%append_io_id = (io_layout(1)/=1.or.io_layout(2)/=1) ! get the domain information call mpp_get_compute_domain(lnd%domain, lnd%is,lnd%ie,lnd%js,lnd%je) ! get the mosaic tile number for this processor: this assumes that there is only one ! mosaic tile per PE. allocate(tile_ids(mpp_get_current_ntile(lnd%domain))) tile_ids = mpp_get_tile_id(lnd%domain) lnd%face = tile_ids(1) deallocate(tile_ids) allocate(lnd%tile_map (lnd%is:lnd%ie, lnd%js:lnd%je)) allocate(lnd%lonb (lnd%is:lnd%ie+1, lnd%js:lnd%je+1)) allocate(lnd%latb (lnd%is:lnd%ie+1, lnd%js:lnd%je+1)) allocate(lnd%lon (lnd%is:lnd%ie, lnd%js:lnd%je)) allocate(lnd%lat (lnd%is:lnd%ie, lnd%js:lnd%je)) allocate(lnd%area (lnd%is:lnd%ie, lnd%js:lnd%je)) allocate(lnd%cellarea(lnd%is:lnd%ie, lnd%js:lnd%je)) allocate(lnd%coord_glon(nlon), lnd%coord_glonb(nlon+1)) allocate(lnd%coord_glat(nlat), lnd%coord_glatb(nlat+1)) ! initialize coordinates call get_grid_cell_vertices('LND',lnd%face,lnd%coord_glonb,lnd%coord_glatb) call get_grid_cell_centers ('LND',lnd%face,lnd%coord_glon, lnd%coord_glat) call get_grid_cell_area ('LND',lnd%face,lnd%cellarea, domain=lnd%domain) call get_grid_comp_area ('LND',lnd%face,lnd%area, domain=lnd%domain) ! set local coordinates arrays -- temporary, till such time as the global arrays ! are not necessary call get_grid_cell_vertices('LND',lnd%face,lnd%lonb,lnd%latb, domain=lnd%domain) call get_grid_cell_centers ('LND',lnd%face,lnd%lon, lnd%lat, domain=lnd%domain) ! convert coordinates to radian; note that 1D versions stay in degrees lnd%lonb = lnd%lonb*pi/180.0 ; lnd%lon = lnd%lon*pi/180.0 lnd%latb = lnd%latb*pi/180.0 ; lnd%lat = lnd%lat*pi/180.0 ! initialize land tile map do j = lnd%js,lnd%je do i = lnd%is,lnd%ie call land_tile_list_init(lnd%tile_map(i,j)) enddo enddo ! initialize land model tracers, if necessary ! register land model tracers and find specific humidity call register_tracers ( MODEL_LAND, ntracers, lnd%ntprog, ndiag ) lnd%isphum = get_tracer_index ( MODEL_LAND, 'sphum' ) if (lnd%isphum==NO_TRACER) then call error_mesg('land_model_init','no required "sphum" tracer',FATAL) endif lnd%ico2 = get_tracer_index ( MODEL_LAND, 'co2' ) ! NB: co2 might be absent, in this case ico2 == NO_TRACER ! initialize model's time-related parameters lnd%time = time lnd%dt_fast = dt_fast lnd%dt_slow = dt_slow ! initialize the land model processor list allocate(lnd%pelist(0:mpp_npes()-1)) call mpp_get_current_pelist(lnd%pelist) end subroutine land_data_init ! ============================================================================ subroutine land_data_end() integer :: i,j module_is_initialized = .FALSE. ! deallocate land tile map here. do j = lnd%js,lnd%je do i = lnd%is,lnd%ie call land_tile_list_end(lnd%tile_map(i,j)) enddo enddo ! deallocate grid data deallocate(lnd%lonb, lnd%latb, lnd%lon, lnd%lat,& lnd%area, lnd%cellarea,& lnd%coord_glonb, lnd%coord_glon, & lnd%coord_glatb, lnd%coord_glat, & lnd%tile_map,& lnd%pelist, lnd%io_pelist) end subroutine land_data_end ! ============================================================================ ! allocates boundary data for land domain and current number of tiles subroutine realloc_land2cplr ( bnd ) type(land_data_type), intent(inout) :: bnd ! data to allocate ! ---- local vars integer :: n_tiles call dealloc_land2cplr(bnd, dealloc_discharges=.FALSE.) bnd%domain = lnd%domain n_tiles = max_n_tiles() ! allocate data according to the domain boundaries allocate( bnd%mask(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%tile_size(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%t_surf(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%t_ca(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%tr(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles,lnd%ntprog) ) allocate( bnd%albedo(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%albedo_vis_dir(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%albedo_nir_dir(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%albedo_vis_dif(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%albedo_nir_dif(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%rough_mom(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%rough_heat(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) allocate( bnd%rough_scale(lnd%is:lnd%ie,lnd%js:lnd%je,n_tiles) ) bnd%mask = .FALSE. bnd%tile_size = init_value bnd%t_surf = init_value bnd%t_ca = init_value bnd%tr = init_value bnd%albedo = init_value bnd%albedo_vis_dir = init_value bnd%albedo_nir_dir = init_value bnd%albedo_vis_dif = init_value bnd%albedo_nir_dif = init_value bnd%rough_mom = init_value bnd%rough_heat = init_value bnd%rough_scale = init_value ! in contrast to the rest of the land boundary condition fields, discharges ! are specified per grid cell, not per tile; therefore they should not be ! re-allocated when the number of tiles changes. In fact, they must not be ! changed at all here because their values are assigned in update_land_model_fast, ! not in update_land_bc_*, and therefore would be lost if re-allocated. if (.not.associated(bnd%discharge)) then allocate( bnd%discharge (lnd%is:lnd%ie,lnd%js:lnd%je) ) allocate( bnd%discharge_heat (lnd%is:lnd%ie,lnd%js:lnd%je) ) allocate( bnd%discharge_snow (lnd%is:lnd%ie,lnd%js:lnd%je) ) allocate( bnd%discharge_snow_heat(lnd%is:lnd%ie,lnd%js:lnd%je) ) ! discharge and discaharge_snow must be, in contrast to the rest of the boundary ! values, filled with zeroes. The reason is because not all of the usable elements ! are updated by the land model (only coastal points are). bnd%discharge = 0.0 bnd%discharge_heat = 0.0 bnd%discharge_snow = 0.0 bnd%discharge_snow_heat = 0.0 endif end subroutine realloc_land2cplr ! ============================================================================ ! deallocates boundary data memory ! NOTE that the discharges should be deallocated only at the final clean-up ! stage; during the model run they should be preserved unchanged even when ! other fields are reallocated. subroutine dealloc_land2cplr ( bnd, dealloc_discharges ) type(land_data_type), intent(inout) :: bnd ! data to de-allocate logical, intent(in) :: dealloc_discharges __DEALLOC__( bnd%tile_size ) __DEALLOC__( bnd%tile_size ) __DEALLOC__( bnd%t_surf ) __DEALLOC__( bnd%t_ca ) __DEALLOC__( bnd%tr ) __DEALLOC__( bnd%albedo ) __DEALLOC__( bnd%albedo_vis_dir ) __DEALLOC__( bnd%albedo_nir_dir ) __DEALLOC__( bnd%albedo_vis_dif ) __DEALLOC__( bnd%albedo_nir_dif ) __DEALLOC__( bnd%rough_mom ) __DEALLOC__( bnd%rough_heat ) __DEALLOC__( bnd%rough_scale ) __DEALLOC__( bnd%mask ) if (dealloc_discharges) then __DEALLOC__( bnd%discharge ) __DEALLOC__( bnd%discharge_heat ) __DEALLOC__( bnd%discharge_snow ) __DEALLOC__( bnd%discharge_snow_heat ) end if end subroutine dealloc_land2cplr ! ============================================================================ ! allocates boundary data for land domain and current number of tiles; ! initializes data for data override. ! NOTE: previously the body of the procedure was in the flux_exchange_init, ! currently it is called from land_model_init subroutine realloc_cplr2land( bnd ) type(atmos_land_boundary_type), intent(inout) :: bnd ! ---- local vars integer :: kd call dealloc_cplr2land(bnd) ! allocate data according to the domain boundaries kd = max_n_tiles() allocate( bnd%t_flux(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%lw_flux(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%sw_flux(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%lprec(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%fprec(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%tprec(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%dhdt(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%dhdq(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%drdt(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%p_surf(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%tr_flux(lnd%is:lnd%ie,lnd%js:lnd%je,kd,lnd%ntprog) ) allocate( bnd%dfdtr(lnd%is:lnd%ie,lnd%js:lnd%je,kd,lnd%ntprog) ) allocate( bnd%lwdn_flux(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%swdn_flux(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%sw_flux_down_vis_dir(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%sw_flux_down_total_dir(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%sw_flux_down_vis_dif(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%sw_flux_down_total_dif(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%cd_t(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%cd_m(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%bstar(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%ustar(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%wind(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%z_bot(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) allocate( bnd%drag_q(lnd%is:lnd%ie,lnd%js:lnd%je,kd) ) bnd%t_flux = init_value bnd%lw_flux = init_value bnd%sw_flux = init_value bnd%lprec = init_value bnd%fprec = init_value bnd%tprec = init_value bnd%dhdt = init_value bnd%dhdq = init_value bnd%drdt = init_value bnd%p_surf = init_value bnd%tr_flux = init_value bnd%dfdtr = init_value bnd%lwdn_flux = init_value bnd%swdn_flux = init_value bnd%sw_flux_down_vis_dir = init_value bnd%sw_flux_down_total_dir = init_value bnd%sw_flux_down_vis_dif = init_value bnd%sw_flux_down_total_dif = init_value bnd%cd_t = init_value bnd%cd_m = init_value bnd%bstar = init_value bnd%ustar = init_value bnd%wind = init_value bnd%z_bot = init_value bnd%drag_q = init_value end subroutine realloc_cplr2land ! ============================================================================ subroutine dealloc_cplr2land( bnd ) type(atmos_land_boundary_type), intent(inout) :: bnd __DEALLOC__( bnd%t_flux ) __DEALLOC__( bnd%lw_flux ) __DEALLOC__( bnd%sw_flux ) __DEALLOC__( bnd%lprec ) __DEALLOC__( bnd%fprec ) __DEALLOC__( bnd%dhdt ) __DEALLOC__( bnd%dhdq ) __DEALLOC__( bnd%drdt ) __DEALLOC__( bnd%p_surf ) __DEALLOC__( bnd%lwdn_flux ) __DEALLOC__( bnd%swdn_flux ) __DEALLOC__( bnd%sw_flux_down_vis_dir ) __DEALLOC__( bnd%sw_flux_down_total_dir ) __DEALLOC__( bnd%sw_flux_down_vis_dif ) __DEALLOC__( bnd%sw_flux_down_total_dif ) __DEALLOC__( bnd%cd_t ) __DEALLOC__( bnd%cd_m ) __DEALLOC__( bnd%bstar ) __DEALLOC__( bnd%ustar ) __DEALLOC__( bnd%wind ) __DEALLOC__( bnd%z_bot ) __DEALLOC__( bnd%tr_flux ) __DEALLOC__( bnd%dfdtr ) end subroutine dealloc_cplr2land ! ============================================================================ ! get max number of tiles in the domain function max_n_tiles() result(n) integer :: n integer :: i,j n=1 do j=lnd%js,lnd%je do i=lnd%is,lnd%ie n=max(n, nitems(lnd%tile_map(i,j))) enddo enddo end function ! =========================================================================== ! Prints checksums of the various fields in the atmos_land_boundary_type. subroutine atm_lnd_bnd_type_chksum(id, timestep, albt) character(len=*), intent(in) :: id ! Label to differentiate where this ! routine is being called from. integer , intent(in) :: timestep ! An integer to indicate which ! timestep this routine is being called for. type(atmos_land_boundary_type), intent(in) :: albt integer :: n, outunit outunit = stdout() write(outunit,*) 'BEGIN CHECKSUM(atmos_land_boundary_type):: ', id, timestep write(outunit,100) 'albt%t_flux ', mpp_chksum( albt%t_flux) write(outunit,100) 'albt%lw_flux ', mpp_chksum( albt%lw_flux) write(outunit,100) 'albt%lwdn_flux ', mpp_chksum( albt%lwdn_flux) write(outunit,100) 'albt%sw_flux ', mpp_chksum( albt%sw_flux) write(outunit,100) 'albt%swdn_flux ', mpp_chksum( albt%swdn_flux) write(outunit,100) 'albt%lprec ', mpp_chksum( albt%lprec) write(outunit,100) 'albt%fprec ', mpp_chksum( albt%fprec) write(outunit,100) 'albt%tprec ', mpp_chksum( albt%tprec) write(outunit,100) 'albt%sw_flux_down_vis_dir ', mpp_chksum( albt%sw_flux_down_vis_dir) write(outunit,100) 'albt%sw_flux_down_total_dir', mpp_chksum( albt%sw_flux_down_total_dir) write(outunit,100) 'albt%sw_flux_down_vis_dif ', mpp_chksum( albt%sw_flux_down_vis_dif) write(outunit,100) 'albt%sw_flux_down_total_dif', mpp_chksum( albt%sw_flux_down_total_dif) write(outunit,100) 'albt%dhdt ', mpp_chksum( albt%dhdt) write(outunit,100) 'albt%dhdq ', mpp_chksum( albt%dhdq) write(outunit,100) 'albt%drdt ', mpp_chksum( albt%drdt) write(outunit,100) 'albt%cd_m ', mpp_chksum( albt%cd_m) write(outunit,100) 'albt%cd_t ', mpp_chksum( albt%cd_t) write(outunit,100) 'albt%ustar ', mpp_chksum( albt%ustar) write(outunit,100) 'albt%bstar ', mpp_chksum( albt%bstar) write(outunit,100) 'albt%wind ', mpp_chksum( albt%wind) write(outunit,100) 'albt%z_bot ', mpp_chksum( albt%z_bot) write(outunit,100) 'albt%drag_q ', mpp_chksum( albt%drag_q) write(outunit,100) 'albt%p_surf ', mpp_chksum( albt%p_surf) do n = 1,size(albt%tr_flux,4) write(outunit,100) 'albt%tr_flux ', mpp_chksum( albt%tr_flux(:,:,:,n)) enddo do n = 1,size(albt%dfdtr,4) write(outunit,100) 'albt%dfdtr ', mpp_chksum( albt%dfdtr(:,:,:,n)) enddo 100 FORMAT("CHECKSUM::",A32," = ",Z20) end subroutine atm_lnd_bnd_type_chksum ! =========================================================================== ! Prints checksums of the various fields in the land_data_type. subroutine land_data_type_chksum(id, timestep, land) character(len=*), intent(in) :: id ! Label to differentiate where this ! routine in being called from. integer , intent(in) :: timestep ! An integer to indicate which ! timestep this routine is being called for. type(land_data_type), intent(in) :: land integer :: n, outunit outunit = stdout() write(outunit,*) 'BEGIN CHECKSUM(land_data_type):: ', id, timestep write(outunit,100) 'land%tile_size ',mpp_chksum(land%tile_size) write(outunit,100) 'land%t_surf ',mpp_chksum(land%t_surf) write(outunit,100) 'land%t_ca ',mpp_chksum(land%t_ca) write(outunit,100) 'land%albedo ',mpp_chksum(land%albedo) write(outunit,100) 'land%albedo_vis_dir ',mpp_chksum(land%albedo_vis_dir) write(outunit,100) 'land%albedo_nir_dir ',mpp_chksum(land%albedo_nir_dir) write(outunit,100) 'land%albedo_vis_dif ',mpp_chksum(land%albedo_vis_dif) write(outunit,100) 'land%albedo_nir_dif ',mpp_chksum(land%albedo_nir_dif) write(outunit,100) 'land%rough_mom ',mpp_chksum(land%rough_mom) write(outunit,100) 'land%rough_heat ',mpp_chksum(land%rough_heat) write(outunit,100) 'land%rough_scale ',mpp_chksum(land%rough_scale) do n = 1, size(land%tr,4) write(outunit,100) 'land%tr ',mpp_chksum(land%tr(:,:,:,n)) enddo write(outunit,100) 'land%discharge ',mpp_chksum(land%discharge) write(outunit,100) 'land%discharge_snow ',mpp_chksum(land%discharge_snow) write(outunit,100) 'land%discharge_heat ',mpp_chksum(land%discharge_heat) 100 FORMAT("CHECKSUM::",A32," = ",Z20) end subroutine land_data_type_chksum end module land_data_mod
gpl-2.0
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/slatps.f
24
24381
*> \brief \b SLATPS solves a triangular system of equations with the matrix held in packed storage. * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download SLATPS + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/slatps.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/slatps.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/slatps.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE SLATPS( UPLO, TRANS, DIAG, NORMIN, N, AP, X, SCALE, * CNORM, INFO ) * * .. Scalar Arguments .. * CHARACTER DIAG, NORMIN, TRANS, UPLO * INTEGER INFO, N * REAL SCALE * .. * .. Array Arguments .. * REAL AP( * ), CNORM( * ), X( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> SLATPS solves one of the triangular systems *> *> A *x = s*b or A**T*x = s*b *> *> with scaling to prevent overflow, where A is an upper or lower *> triangular matrix stored in packed form. Here A**T denotes the *> transpose of A, x and b are n-element vectors, and s is a scaling *> factor, usually less than or equal to 1, chosen so that the *> components of x will be less than the overflow threshold. If the *> unscaled problem will not cause overflow, the Level 2 BLAS routine *> STPSV is called. If the matrix A is singular (A(j,j) = 0 for some j), *> then s is set to 0 and a non-trivial solution to A*x = 0 is returned. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> Specifies whether the matrix A is upper or lower triangular. *> = 'U': Upper triangular *> = 'L': Lower triangular *> \endverbatim *> *> \param[in] TRANS *> \verbatim *> TRANS is CHARACTER*1 *> Specifies the operation applied to A. *> = 'N': Solve A * x = s*b (No transpose) *> = 'T': Solve A**T* x = s*b (Transpose) *> = 'C': Solve A**T* x = s*b (Conjugate transpose = Transpose) *> \endverbatim *> *> \param[in] DIAG *> \verbatim *> DIAG is CHARACTER*1 *> Specifies whether or not the matrix A is unit triangular. *> = 'N': Non-unit triangular *> = 'U': Unit triangular *> \endverbatim *> *> \param[in] NORMIN *> \verbatim *> NORMIN is CHARACTER*1 *> Specifies whether CNORM has been set or not. *> = 'Y': CNORM contains the column norms on entry *> = 'N': CNORM is not set on entry. On exit, the norms will *> be computed and stored in CNORM. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix A. N >= 0. *> \endverbatim *> *> \param[in] AP *> \verbatim *> AP is REAL array, dimension (N*(N+1)/2) *> The upper or lower triangular matrix A, packed columnwise in *> a linear array. The j-th column of A is stored in the array *> AP as follows: *> if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; *> if UPLO = 'L', AP(i + (j-1)*(2n-j)/2) = A(i,j) for j<=i<=n. *> \endverbatim *> *> \param[in,out] X *> \verbatim *> X is REAL array, dimension (N) *> On entry, the right hand side b of the triangular system. *> On exit, X is overwritten by the solution vector x. *> \endverbatim *> *> \param[out] SCALE *> \verbatim *> SCALE is REAL *> The scaling factor s for the triangular system *> A * x = s*b or A**T* x = s*b. *> If SCALE = 0, the matrix A is singular or badly scaled, and *> the vector x is an exact or approximate solution to A*x = 0. *> \endverbatim *> *> \param[in,out] CNORM *> \verbatim *> CNORM is REAL array, dimension (N) *> *> If NORMIN = 'Y', CNORM is an input argument and CNORM(j) *> contains the norm of the off-diagonal part of the j-th column *> of A. If TRANS = 'N', CNORM(j) must be greater than or equal *> to the infinity-norm, and if TRANS = 'T' or 'C', CNORM(j) *> must be greater than or equal to the 1-norm. *> *> If NORMIN = 'N', CNORM is an output argument and CNORM(j) *> returns the 1-norm of the offdiagonal part of the j-th column *> of A. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -k, the k-th argument had an illegal value *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date September 2012 * *> \ingroup realOTHERauxiliary * *> \par Further Details: * ===================== *> *> \verbatim *> *> A rough bound on x is computed; if that is less than overflow, STPSV *> is called, otherwise, specific code is used which checks for possible *> overflow or divide-by-zero at every operation. *> *> A columnwise scheme is used for solving A*x = b. The basic algorithm *> if A is lower triangular is *> *> x[1:n] := b[1:n] *> for j = 1, ..., n *> x(j) := x(j) / A(j,j) *> x[j+1:n] := x[j+1:n] - x(j) * A[j+1:n,j] *> end *> *> Define bounds on the components of x after j iterations of the loop: *> M(j) = bound on x[1:j] *> G(j) = bound on x[j+1:n] *> Initially, let M(0) = 0 and G(0) = max{x(i), i=1,...,n}. *> *> Then for iteration j+1 we have *> M(j+1) <= G(j) / | A(j+1,j+1) | *> G(j+1) <= G(j) + M(j+1) * | A[j+2:n,j+1] | *> <= G(j) ( 1 + CNORM(j+1) / | A(j+1,j+1) | ) *> *> where CNORM(j+1) is greater than or equal to the infinity-norm of *> column j+1 of A, not counting the diagonal. Hence *> *> G(j) <= G(0) product ( 1 + CNORM(i) / | A(i,i) | ) *> 1<=i<=j *> and *> *> |x(j)| <= ( G(0) / |A(j,j)| ) product ( 1 + CNORM(i) / |A(i,i)| ) *> 1<=i< j *> *> Since |x(j)| <= M(j), we use the Level 2 BLAS routine STPSV if the *> reciprocal of the largest M(j), j=1,..,n, is larger than *> max(underflow, 1/overflow). *> *> The bound on x(j) is also used to determine when a step in the *> columnwise method can be performed without fear of overflow. If *> the computed bound is greater than a large constant, x is scaled to *> prevent overflow, but if the bound overflows, x is set to 0, x(j) to *> 1, and scale to 0, and a non-trivial solution to A*x = 0 is found. *> *> Similarly, a row-wise scheme is used to solve A**T*x = b. The basic *> algorithm for A upper triangular is *> *> for j = 1, ..., n *> x(j) := ( b(j) - A[1:j-1,j]**T * x[1:j-1] ) / A(j,j) *> end *> *> We simultaneously compute two bounds *> G(j) = bound on ( b(i) - A[1:i-1,i]**T * x[1:i-1] ), 1<=i<=j *> M(j) = bound on x(i), 1<=i<=j *> *> The initial values are G(0) = 0, M(0) = max{b(i), i=1,..,n}, and we *> add the constraint G(j) >= G(j-1) and M(j) >= M(j-1) for j >= 1. *> Then the bound on x(j) is *> *> M(j) <= M(j-1) * ( 1 + CNORM(j) ) / | A(j,j) | *> *> <= M(0) * product ( ( 1 + CNORM(i) ) / |A(i,i)| ) *> 1<=i<=j *> *> and we can safely call STPSV if 1/M(n) and 1/G(n) are both greater *> than max(underflow, 1/overflow). *> \endverbatim *> * ===================================================================== SUBROUTINE SLATPS( UPLO, TRANS, DIAG, NORMIN, N, AP, X, SCALE, $ CNORM, INFO ) * * -- LAPACK auxiliary routine (version 3.4.2) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * September 2012 * * .. Scalar Arguments .. CHARACTER DIAG, NORMIN, TRANS, UPLO INTEGER INFO, N REAL SCALE * .. * .. Array Arguments .. REAL AP( * ), CNORM( * ), X( * ) * .. * * ===================================================================== * * .. Parameters .. REAL ZERO, HALF, ONE PARAMETER ( ZERO = 0.0E+0, HALF = 0.5E+0, ONE = 1.0E+0 ) * .. * .. Local Scalars .. LOGICAL NOTRAN, NOUNIT, UPPER INTEGER I, IMAX, IP, J, JFIRST, JINC, JLAST, JLEN REAL BIGNUM, GROW, REC, SMLNUM, SUMJ, TJJ, TJJS, $ TMAX, TSCAL, USCAL, XBND, XJ, XMAX * .. * .. External Functions .. LOGICAL LSAME INTEGER ISAMAX REAL SASUM, SDOT, SLAMCH EXTERNAL LSAME, ISAMAX, SASUM, SDOT, SLAMCH * .. * .. External Subroutines .. EXTERNAL SAXPY, SSCAL, STPSV, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC ABS, MAX, MIN * .. * .. Executable Statements .. * INFO = 0 UPPER = LSAME( UPLO, 'U' ) NOTRAN = LSAME( TRANS, 'N' ) NOUNIT = LSAME( DIAG, 'N' ) * * Test the input parameters. * IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( .NOT.NOTRAN .AND. .NOT.LSAME( TRANS, 'T' ) .AND. .NOT. $ LSAME( TRANS, 'C' ) ) THEN INFO = -2 ELSE IF( .NOT.NOUNIT .AND. .NOT.LSAME( DIAG, 'U' ) ) THEN INFO = -3 ELSE IF( .NOT.LSAME( NORMIN, 'Y' ) .AND. .NOT. $ LSAME( NORMIN, 'N' ) ) THEN INFO = -4 ELSE IF( N.LT.0 ) THEN INFO = -5 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'SLATPS', -INFO ) RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * * Determine machine dependent parameters to control overflow. * SMLNUM = SLAMCH( 'Safe minimum' ) / SLAMCH( 'Precision' ) BIGNUM = ONE / SMLNUM SCALE = ONE * IF( LSAME( NORMIN, 'N' ) ) THEN * * Compute the 1-norm of each column, not including the diagonal. * IF( UPPER ) THEN * * A is upper triangular. * IP = 1 DO 10 J = 1, N CNORM( J ) = SASUM( J-1, AP( IP ), 1 ) IP = IP + J 10 CONTINUE ELSE * * A is lower triangular. * IP = 1 DO 20 J = 1, N - 1 CNORM( J ) = SASUM( N-J, AP( IP+1 ), 1 ) IP = IP + N - J + 1 20 CONTINUE CNORM( N ) = ZERO END IF END IF * * Scale the column norms by TSCAL if the maximum element in CNORM is * greater than BIGNUM. * IMAX = ISAMAX( N, CNORM, 1 ) TMAX = CNORM( IMAX ) IF( TMAX.LE.BIGNUM ) THEN TSCAL = ONE ELSE TSCAL = ONE / ( SMLNUM*TMAX ) CALL SSCAL( N, TSCAL, CNORM, 1 ) END IF * * Compute a bound on the computed solution vector to see if the * Level 2 BLAS routine STPSV can be used. * J = ISAMAX( N, X, 1 ) XMAX = ABS( X( J ) ) XBND = XMAX IF( NOTRAN ) THEN * * Compute the growth in A * x = b. * IF( UPPER ) THEN JFIRST = N JLAST = 1 JINC = -1 ELSE JFIRST = 1 JLAST = N JINC = 1 END IF * IF( TSCAL.NE.ONE ) THEN GROW = ZERO GO TO 50 END IF * IF( NOUNIT ) THEN * * A is non-unit triangular. * * Compute GROW = 1/G(j) and XBND = 1/M(j). * Initially, G(0) = max{x(i), i=1,...,n}. * GROW = ONE / MAX( XBND, SMLNUM ) XBND = GROW IP = JFIRST*( JFIRST+1 ) / 2 JLEN = N DO 30 J = JFIRST, JLAST, JINC * * Exit the loop if the growth factor is too small. * IF( GROW.LE.SMLNUM ) $ GO TO 50 * * M(j) = G(j-1) / abs(A(j,j)) * TJJ = ABS( AP( IP ) ) XBND = MIN( XBND, MIN( ONE, TJJ )*GROW ) IF( TJJ+CNORM( J ).GE.SMLNUM ) THEN * * G(j) = G(j-1)*( 1 + CNORM(j) / abs(A(j,j)) ) * GROW = GROW*( TJJ / ( TJJ+CNORM( J ) ) ) ELSE * * G(j) could overflow, set GROW to 0. * GROW = ZERO END IF IP = IP + JINC*JLEN JLEN = JLEN - 1 30 CONTINUE GROW = XBND ELSE * * A is unit triangular. * * Compute GROW = 1/G(j), where G(0) = max{x(i), i=1,...,n}. * GROW = MIN( ONE, ONE / MAX( XBND, SMLNUM ) ) DO 40 J = JFIRST, JLAST, JINC * * Exit the loop if the growth factor is too small. * IF( GROW.LE.SMLNUM ) $ GO TO 50 * * G(j) = G(j-1)*( 1 + CNORM(j) ) * GROW = GROW*( ONE / ( ONE+CNORM( J ) ) ) 40 CONTINUE END IF 50 CONTINUE * ELSE * * Compute the growth in A**T * x = b. * IF( UPPER ) THEN JFIRST = 1 JLAST = N JINC = 1 ELSE JFIRST = N JLAST = 1 JINC = -1 END IF * IF( TSCAL.NE.ONE ) THEN GROW = ZERO GO TO 80 END IF * IF( NOUNIT ) THEN * * A is non-unit triangular. * * Compute GROW = 1/G(j) and XBND = 1/M(j). * Initially, M(0) = max{x(i), i=1,...,n}. * GROW = ONE / MAX( XBND, SMLNUM ) XBND = GROW IP = JFIRST*( JFIRST+1 ) / 2 JLEN = 1 DO 60 J = JFIRST, JLAST, JINC * * Exit the loop if the growth factor is too small. * IF( GROW.LE.SMLNUM ) $ GO TO 80 * * G(j) = max( G(j-1), M(j-1)*( 1 + CNORM(j) ) ) * XJ = ONE + CNORM( J ) GROW = MIN( GROW, XBND / XJ ) * * M(j) = M(j-1)*( 1 + CNORM(j) ) / abs(A(j,j)) * TJJ = ABS( AP( IP ) ) IF( XJ.GT.TJJ ) $ XBND = XBND*( TJJ / XJ ) JLEN = JLEN + 1 IP = IP + JINC*JLEN 60 CONTINUE GROW = MIN( GROW, XBND ) ELSE * * A is unit triangular. * * Compute GROW = 1/G(j), where G(0) = max{x(i), i=1,...,n}. * GROW = MIN( ONE, ONE / MAX( XBND, SMLNUM ) ) DO 70 J = JFIRST, JLAST, JINC * * Exit the loop if the growth factor is too small. * IF( GROW.LE.SMLNUM ) $ GO TO 80 * * G(j) = ( 1 + CNORM(j) )*G(j-1) * XJ = ONE + CNORM( J ) GROW = GROW / XJ 70 CONTINUE END IF 80 CONTINUE END IF * IF( ( GROW*TSCAL ).GT.SMLNUM ) THEN * * Use the Level 2 BLAS solve if the reciprocal of the bound on * elements of X is not too small. * CALL STPSV( UPLO, TRANS, DIAG, N, AP, X, 1 ) ELSE * * Use a Level 1 BLAS solve, scaling intermediate results. * IF( XMAX.GT.BIGNUM ) THEN * * Scale X so that its components are less than or equal to * BIGNUM in absolute value. * SCALE = BIGNUM / XMAX CALL SSCAL( N, SCALE, X, 1 ) XMAX = BIGNUM END IF * IF( NOTRAN ) THEN * * Solve A * x = b * IP = JFIRST*( JFIRST+1 ) / 2 DO 100 J = JFIRST, JLAST, JINC * * Compute x(j) = b(j) / A(j,j), scaling x if necessary. * XJ = ABS( X( J ) ) IF( NOUNIT ) THEN TJJS = AP( IP )*TSCAL ELSE TJJS = TSCAL IF( TSCAL.EQ.ONE ) $ GO TO 95 END IF TJJ = ABS( TJJS ) IF( TJJ.GT.SMLNUM ) THEN * * abs(A(j,j)) > SMLNUM: * IF( TJJ.LT.ONE ) THEN IF( XJ.GT.TJJ*BIGNUM ) THEN * * Scale x by 1/b(j). * REC = ONE / XJ CALL SSCAL( N, REC, X, 1 ) SCALE = SCALE*REC XMAX = XMAX*REC END IF END IF X( J ) = X( J ) / TJJS XJ = ABS( X( J ) ) ELSE IF( TJJ.GT.ZERO ) THEN * * 0 < abs(A(j,j)) <= SMLNUM: * IF( XJ.GT.TJJ*BIGNUM ) THEN * * Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM * to avoid overflow when dividing by A(j,j). * REC = ( TJJ*BIGNUM ) / XJ IF( CNORM( J ).GT.ONE ) THEN * * Scale by 1/CNORM(j) to avoid overflow when * multiplying x(j) times column j. * REC = REC / CNORM( J ) END IF CALL SSCAL( N, REC, X, 1 ) SCALE = SCALE*REC XMAX = XMAX*REC END IF X( J ) = X( J ) / TJJS XJ = ABS( X( J ) ) ELSE * * A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and * scale = 0, and compute a solution to A*x = 0. * DO 90 I = 1, N X( I ) = ZERO 90 CONTINUE X( J ) = ONE XJ = ONE SCALE = ZERO XMAX = ZERO END IF 95 CONTINUE * * Scale x if necessary to avoid overflow when adding a * multiple of column j of A. * IF( XJ.GT.ONE ) THEN REC = ONE / XJ IF( CNORM( J ).GT.( BIGNUM-XMAX )*REC ) THEN * * Scale x by 1/(2*abs(x(j))). * REC = REC*HALF CALL SSCAL( N, REC, X, 1 ) SCALE = SCALE*REC END IF ELSE IF( XJ*CNORM( J ).GT.( BIGNUM-XMAX ) ) THEN * * Scale x by 1/2. * CALL SSCAL( N, HALF, X, 1 ) SCALE = SCALE*HALF END IF * IF( UPPER ) THEN IF( J.GT.1 ) THEN * * Compute the update * x(1:j-1) := x(1:j-1) - x(j) * A(1:j-1,j) * CALL SAXPY( J-1, -X( J )*TSCAL, AP( IP-J+1 ), 1, X, $ 1 ) I = ISAMAX( J-1, X, 1 ) XMAX = ABS( X( I ) ) END IF IP = IP - J ELSE IF( J.LT.N ) THEN * * Compute the update * x(j+1:n) := x(j+1:n) - x(j) * A(j+1:n,j) * CALL SAXPY( N-J, -X( J )*TSCAL, AP( IP+1 ), 1, $ X( J+1 ), 1 ) I = J + ISAMAX( N-J, X( J+1 ), 1 ) XMAX = ABS( X( I ) ) END IF IP = IP + N - J + 1 END IF 100 CONTINUE * ELSE * * Solve A**T * x = b * IP = JFIRST*( JFIRST+1 ) / 2 JLEN = 1 DO 140 J = JFIRST, JLAST, JINC * * Compute x(j) = b(j) - sum A(k,j)*x(k). * k<>j * XJ = ABS( X( J ) ) USCAL = TSCAL REC = ONE / MAX( XMAX, ONE ) IF( CNORM( J ).GT.( BIGNUM-XJ )*REC ) THEN * * If x(j) could overflow, scale x by 1/(2*XMAX). * REC = REC*HALF IF( NOUNIT ) THEN TJJS = AP( IP )*TSCAL ELSE TJJS = TSCAL END IF TJJ = ABS( TJJS ) IF( TJJ.GT.ONE ) THEN * * Divide by A(j,j) when scaling x if A(j,j) > 1. * REC = MIN( ONE, REC*TJJ ) USCAL = USCAL / TJJS END IF IF( REC.LT.ONE ) THEN CALL SSCAL( N, REC, X, 1 ) SCALE = SCALE*REC XMAX = XMAX*REC END IF END IF * SUMJ = ZERO IF( USCAL.EQ.ONE ) THEN * * If the scaling needed for A in the dot product is 1, * call SDOT to perform the dot product. * IF( UPPER ) THEN SUMJ = SDOT( J-1, AP( IP-J+1 ), 1, X, 1 ) ELSE IF( J.LT.N ) THEN SUMJ = SDOT( N-J, AP( IP+1 ), 1, X( J+1 ), 1 ) END IF ELSE * * Otherwise, use in-line code for the dot product. * IF( UPPER ) THEN DO 110 I = 1, J - 1 SUMJ = SUMJ + ( AP( IP-J+I )*USCAL )*X( I ) 110 CONTINUE ELSE IF( J.LT.N ) THEN DO 120 I = 1, N - J SUMJ = SUMJ + ( AP( IP+I )*USCAL )*X( J+I ) 120 CONTINUE END IF END IF * IF( USCAL.EQ.TSCAL ) THEN * * Compute x(j) := ( x(j) - sumj ) / A(j,j) if 1/A(j,j) * was not used to scale the dotproduct. * X( J ) = X( J ) - SUMJ XJ = ABS( X( J ) ) IF( NOUNIT ) THEN * * Compute x(j) = x(j) / A(j,j), scaling if necessary. * TJJS = AP( IP )*TSCAL ELSE TJJS = TSCAL IF( TSCAL.EQ.ONE ) $ GO TO 135 END IF TJJ = ABS( TJJS ) IF( TJJ.GT.SMLNUM ) THEN * * abs(A(j,j)) > SMLNUM: * IF( TJJ.LT.ONE ) THEN IF( XJ.GT.TJJ*BIGNUM ) THEN * * Scale X by 1/abs(x(j)). * REC = ONE / XJ CALL SSCAL( N, REC, X, 1 ) SCALE = SCALE*REC XMAX = XMAX*REC END IF END IF X( J ) = X( J ) / TJJS ELSE IF( TJJ.GT.ZERO ) THEN * * 0 < abs(A(j,j)) <= SMLNUM: * IF( XJ.GT.TJJ*BIGNUM ) THEN * * Scale x by (1/abs(x(j)))*abs(A(j,j))*BIGNUM. * REC = ( TJJ*BIGNUM ) / XJ CALL SSCAL( N, REC, X, 1 ) SCALE = SCALE*REC XMAX = XMAX*REC END IF X( J ) = X( J ) / TJJS ELSE * * A(j,j) = 0: Set x(1:n) = 0, x(j) = 1, and * scale = 0, and compute a solution to A**T*x = 0. * DO 130 I = 1, N X( I ) = ZERO 130 CONTINUE X( J ) = ONE SCALE = ZERO XMAX = ZERO END IF 135 CONTINUE ELSE * * Compute x(j) := x(j) / A(j,j) - sumj if the dot * product has already been divided by 1/A(j,j). * X( J ) = X( J ) / TJJS - SUMJ END IF XMAX = MAX( XMAX, ABS( X( J ) ) ) JLEN = JLEN + 1 IP = IP + JINC*JLEN 140 CONTINUE END IF SCALE = SCALE / TSCAL END IF * * Scale the column norms by 1/TSCAL for return. * IF( TSCAL.NE.ONE ) THEN CALL SSCAL( N, ONE / TSCAL, CNORM, 1 ) END IF * RETURN * * End of SLATPS * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/ssysvx.f
28
14207
*> \brief <b> SSYSVX computes the solution to system of linear equations A * X = B for SY matrices</b> * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download SSYSVX + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/ssysvx.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/ssysvx.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/ssysvx.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE SSYSVX( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, * LDB, X, LDX, RCOND, FERR, BERR, WORK, LWORK, * IWORK, INFO ) * * .. Scalar Arguments .. * CHARACTER FACT, UPLO * INTEGER INFO, LDA, LDAF, LDB, LDX, LWORK, N, NRHS * REAL RCOND * .. * .. Array Arguments .. * INTEGER IPIV( * ), IWORK( * ) * REAL A( LDA, * ), AF( LDAF, * ), B( LDB, * ), * $ BERR( * ), FERR( * ), WORK( * ), X( LDX, * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> SSYSVX uses the diagonal pivoting factorization to compute the *> solution to a real system of linear equations A * X = B, *> where A is an N-by-N symmetric matrix and X and B are N-by-NRHS *> matrices. *> *> Error bounds on the solution and a condition estimate are also *> provided. *> \endverbatim * *> \par Description: * ================= *> *> \verbatim *> *> The following steps are performed: *> *> 1. If FACT = 'N', the diagonal pivoting method is used to factor A. *> The form of the factorization is *> A = U * D * U**T, if UPLO = 'U', or *> A = L * D * L**T, 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(i,i)=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 calculate error bounds and backward error estimates *> for it. *> \endverbatim * * Arguments: * ========== * *> \param[in] FACT *> \verbatim *> FACT is CHARACTER*1 *> Specifies whether or not the factored form of A has been *> supplied on entry. *> = 'F': On entry, AF and IPIV contain the factored form of *> A. AF and IPIV will not be modified. *> = 'N': The matrix A will be copied to AF and factored. *> \endverbatim *> *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> = 'U': Upper triangle of A is stored; *> = 'L': Lower triangle of A is stored. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of linear equations, i.e., the order of the *> matrix A. N >= 0. *> \endverbatim *> *> \param[in] NRHS *> \verbatim *> NRHS is INTEGER *> The number of right hand sides, i.e., the number of columns *> of the matrices B and X. NRHS >= 0. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is REAL array, dimension (LDA,N) *> The 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. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,N). *> \endverbatim *> *> \param[in,out] AF *> \verbatim *> AF is REAL array, dimension (LDAF,N) *> If FACT = 'F', then AF is an input argument and on entry *> contains the block diagonal matrix D and the multipliers used *> to obtain the factor U or L from the factorization *> A = U*D*U**T or A = L*D*L**T as computed by SSYTRF. *> *> If FACT = 'N', then AF is an output argument and on exit *> returns the block diagonal matrix D and the multipliers used *> to obtain the factor U or L from the factorization *> A = U*D*U**T or A = L*D*L**T. *> \endverbatim *> *> \param[in] LDAF *> \verbatim *> LDAF is INTEGER *> The leading dimension of the array AF. LDAF >= max(1,N). *> \endverbatim *> *> \param[in,out] IPIV *> \verbatim *> IPIV is INTEGER array, dimension (N) *> If FACT = 'F', then IPIV is an input argument and on entry *> contains details of the interchanges and the block structure *> of D, as determined by SSYTRF. *> If IPIV(k) > 0, then rows and columns k and IPIV(k) were *> interchanged and D(k,k) 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. *> *> If FACT = 'N', then IPIV is an output argument and on exit *> contains details of the interchanges and the block structure *> of D, as determined by SSYTRF. *> \endverbatim *> *> \param[in] B *> \verbatim *> B is REAL array, dimension (LDB,NRHS) *> The N-by-NRHS right hand side matrix B. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> The leading dimension of the array B. LDB >= max(1,N). *> \endverbatim *> *> \param[out] X *> \verbatim *> X is REAL array, dimension (LDX,NRHS) *> If INFO = 0 or INFO = N+1, the N-by-NRHS solution matrix X. *> \endverbatim *> *> \param[in] LDX *> \verbatim *> LDX is INTEGER *> The leading dimension of the array X. LDX >= max(1,N). *> \endverbatim *> *> \param[out] RCOND *> \verbatim *> RCOND is REAL *> The estimate of the reciprocal condition number of the matrix *> A. If RCOND is less than the machine precision (in *> particular, if RCOND = 0), the matrix is singular to working *> precision. This condition is indicated by a return code of *> INFO > 0. *> \endverbatim *> *> \param[out] FERR *> \verbatim *> FERR is REAL array, dimension (NRHS) *> The estimated forward error bound for each solution vector *> X(j) (the j-th column of the solution matrix X). *> If XTRUE 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) - XTRUE) divided by the magnitude of the *> largest element in X(j). The estimate is as reliable as *> the estimate for RCOND, and is almost always a slight *> overestimate of the true error. *> \endverbatim *> *> \param[out] BERR *> \verbatim *> BERR is REAL array, dimension (NRHS) *> The componentwise 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). *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is REAL array, dimension (MAX(1,LWORK)) *> On exit, if INFO = 0, WORK(1) returns the optimal LWORK. *> \endverbatim *> *> \param[in] LWORK *> \verbatim *> LWORK is INTEGER *> The length of WORK. LWORK >= max(1,3*N), and for best *> performance, when FACT = 'N', LWORK >= max(1,3*N,N*NB), where *> NB is the optimal blocksize for SSYTRF. *> *> If LWORK = -1, then 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 by XERBLA. *> \endverbatim *> *> \param[out] IWORK *> \verbatim *> IWORK is INTEGER array, dimension (N) *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> > 0: if INFO = i, and i is *> <= N: D(i,i) 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 is returned. *> = 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. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date April 2012 * *> \ingroup realSYsolve * * ===================================================================== SUBROUTINE SSYSVX( FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, $ LDB, X, LDX, RCOND, FERR, BERR, WORK, LWORK, $ IWORK, INFO ) * * -- LAPACK driver routine (version 3.4.1) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * April 2012 * * .. Scalar Arguments .. CHARACTER FACT, UPLO INTEGER INFO, LDA, LDAF, LDB, LDX, LWORK, N, NRHS REAL RCOND * .. * .. Array Arguments .. INTEGER IPIV( * ), IWORK( * ) REAL A( LDA, * ), AF( LDAF, * ), B( LDB, * ), $ BERR( * ), FERR( * ), WORK( * ), X( LDX, * ) * .. * * ===================================================================== * * .. Parameters .. REAL ZERO PARAMETER ( ZERO = 0.0E+0 ) * .. * .. Local Scalars .. LOGICAL LQUERY, NOFACT INTEGER LWKOPT, NB REAL ANORM * .. * .. External Functions .. LOGICAL LSAME INTEGER ILAENV REAL SLAMCH, SLANSY EXTERNAL ILAENV, LSAME, SLAMCH, SLANSY * .. * .. External Subroutines .. EXTERNAL SLACPY, SSYCON, SSYRFS, SSYTRF, SSYTRS, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 NOFACT = LSAME( FACT, 'N' ) LQUERY = ( LWORK.EQ.-1 ) IF( .NOT.NOFACT .AND. .NOT.LSAME( FACT, 'F' ) ) THEN INFO = -1 ELSE IF( .NOT.LSAME( UPLO, 'U' ) .AND. .NOT.LSAME( UPLO, 'L' ) ) $ THEN INFO = -2 ELSE IF( N.LT.0 ) THEN INFO = -3 ELSE IF( NRHS.LT.0 ) THEN INFO = -4 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -6 ELSE IF( LDAF.LT.MAX( 1, N ) ) THEN INFO = -8 ELSE IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -11 ELSE IF( LDX.LT.MAX( 1, N ) ) THEN INFO = -13 ELSE IF( LWORK.LT.MAX( 1, 3*N ) .AND. .NOT.LQUERY ) THEN INFO = -18 END IF * IF( INFO.EQ.0 ) THEN LWKOPT = MAX( 1, 3*N ) IF( NOFACT ) THEN NB = ILAENV( 1, 'SSYTRF', UPLO, N, -1, -1, -1 ) LWKOPT = MAX( LWKOPT, N*NB ) END IF WORK( 1 ) = LWKOPT END IF * IF( INFO.NE.0 ) THEN CALL XERBLA( 'SSYSVX', -INFO ) RETURN ELSE IF( LQUERY ) THEN RETURN END IF * IF( NOFACT ) THEN * * Compute the factorization A = U*D*U**T or A = L*D*L**T. * CALL SLACPY( UPLO, N, N, A, LDA, AF, LDAF ) CALL SSYTRF( UPLO, N, AF, LDAF, IPIV, WORK, LWORK, INFO ) * * Return if INFO is non-zero. * IF( INFO.GT.0 )THEN RCOND = ZERO RETURN END IF END IF * * Compute the norm of the matrix A. * ANORM = SLANSY( 'I', UPLO, N, A, LDA, WORK ) * * Compute the reciprocal of the condition number of A. * CALL SSYCON( UPLO, N, AF, LDAF, IPIV, ANORM, RCOND, WORK, IWORK, $ INFO ) * * Compute the solution vectors X. * CALL SLACPY( 'Full', N, NRHS, B, LDB, X, LDX ) CALL SSYTRS( UPLO, N, NRHS, AF, LDAF, IPIV, X, LDX, INFO ) * * Use iterative refinement to improve the computed solutions and * compute error bounds and backward error estimates for them. * CALL SSYRFS( UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, $ LDX, FERR, BERR, WORK, IWORK, INFO ) * * Set INFO = N+1 if the matrix is singular to working precision. * IF( RCOND.LT.SLAMCH( 'Epsilon' ) ) $ INFO = N + 1 * WORK( 1 ) = LWKOPT * RETURN * * End of SSYSVX * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/zunmr3.f
24
8053
*> \brief \b ZUNMR3 multiplies a general matrix by the unitary matrix from a RZ factorization determined by ctzrzf (unblocked algorithm). * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download ZUNMR3 + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zunmr3.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zunmr3.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zunmr3.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE ZUNMR3( SIDE, TRANS, M, N, K, L, A, LDA, TAU, C, LDC, * WORK, INFO ) * * .. Scalar Arguments .. * CHARACTER SIDE, TRANS * INTEGER INFO, K, L, LDA, LDC, M, N * .. * .. Array Arguments .. * COMPLEX*16 A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> ZUNMR3 overwrites the general complex m by n matrix C with *> *> Q * C if SIDE = 'L' and TRANS = 'N', or *> *> Q**H* C if SIDE = 'L' and TRANS = 'C', or *> *> C * Q if SIDE = 'R' and TRANS = 'N', or *> *> C * Q**H if SIDE = 'R' and TRANS = 'C', *> *> where Q is a complex unitary matrix defined as the product of k *> elementary reflectors *> *> Q = H(1) H(2) . . . H(k) *> *> as returned by ZTZRZF. Q is of order m if SIDE = 'L' and of order n *> if SIDE = 'R'. *> \endverbatim * * Arguments: * ========== * *> \param[in] SIDE *> \verbatim *> SIDE is CHARACTER*1 *> = 'L': apply Q or Q**H from the Left *> = 'R': apply Q or Q**H from the Right *> \endverbatim *> *> \param[in] TRANS *> \verbatim *> TRANS is CHARACTER*1 *> = 'N': apply Q (No transpose) *> = 'C': apply Q**H (Conjugate transpose) *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> The number of rows of the matrix C. M >= 0. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of columns of the matrix C. N >= 0. *> \endverbatim *> *> \param[in] K *> \verbatim *> K is INTEGER *> The number of elementary reflectors whose product defines *> the matrix Q. *> If SIDE = 'L', M >= K >= 0; *> if SIDE = 'R', N >= K >= 0. *> \endverbatim *> *> \param[in] L *> \verbatim *> L is INTEGER *> The number of columns of the matrix A containing *> the meaningful part of the Householder reflectors. *> If SIDE = 'L', M >= L >= 0, if SIDE = 'R', N >= L >= 0. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is COMPLEX*16 array, dimension *> (LDA,M) if SIDE = 'L', *> (LDA,N) if SIDE = 'R' *> The i-th row must contain the vector which defines the *> elementary reflector H(i), for i = 1,2,...,k, as returned by *> ZTZRZF in the last k rows of its array argument A. *> A is modified by the routine but restored on exit. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,K). *> \endverbatim *> *> \param[in] TAU *> \verbatim *> TAU is COMPLEX*16 array, dimension (K) *> TAU(i) must contain the scalar factor of the elementary *> reflector H(i), as returned by ZTZRZF. *> \endverbatim *> *> \param[in,out] C *> \verbatim *> C is COMPLEX*16 array, dimension (LDC,N) *> On entry, the m-by-n matrix C. *> On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. *> \endverbatim *> *> \param[in] LDC *> \verbatim *> LDC is INTEGER *> The leading dimension of the array C. LDC >= max(1,M). *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is COMPLEX*16 array, dimension *> (N) if SIDE = 'L', *> (M) if SIDE = 'R' *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date September 2012 * *> \ingroup complex16OTHERcomputational * *> \par Contributors: * ================== *> *> A. Petitet, Computer Science Dept., Univ. of Tenn., Knoxville, USA * *> \par Further Details: * ===================== *> *> \verbatim *> \endverbatim *> * ===================================================================== SUBROUTINE ZUNMR3( SIDE, TRANS, M, N, K, L, A, LDA, TAU, C, LDC, $ WORK, INFO ) * * -- LAPACK computational routine (version 3.4.2) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * September 2012 * * .. Scalar Arguments .. CHARACTER SIDE, TRANS INTEGER INFO, K, L, LDA, LDC, M, N * .. * .. Array Arguments .. COMPLEX*16 A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) * .. * * ===================================================================== * * .. Local Scalars .. LOGICAL LEFT, NOTRAN INTEGER I, I1, I2, I3, IC, JA, JC, MI, NI, NQ COMPLEX*16 TAUI * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL XERBLA, ZLARZ * .. * .. Intrinsic Functions .. INTRINSIC DCONJG, MAX * .. * .. Executable Statements .. * * Test the input arguments * INFO = 0 LEFT = LSAME( SIDE, 'L' ) NOTRAN = LSAME( TRANS, 'N' ) * * NQ is the order of Q * IF( LEFT ) THEN NQ = M ELSE NQ = N END IF IF( .NOT.LEFT .AND. .NOT.LSAME( SIDE, 'R' ) ) THEN INFO = -1 ELSE IF( .NOT.NOTRAN .AND. .NOT.LSAME( TRANS, 'C' ) ) THEN INFO = -2 ELSE IF( M.LT.0 ) THEN INFO = -3 ELSE IF( N.LT.0 ) THEN INFO = -4 ELSE IF( K.LT.0 .OR. K.GT.NQ ) THEN INFO = -5 ELSE IF( L.LT.0 .OR. ( LEFT .AND. ( L.GT.M ) ) .OR. $ ( .NOT.LEFT .AND. ( L.GT.N ) ) ) THEN INFO = -6 ELSE IF( LDA.LT.MAX( 1, K ) ) THEN INFO = -8 ELSE IF( LDC.LT.MAX( 1, M ) ) THEN INFO = -11 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'ZUNMR3', -INFO ) RETURN END IF * * Quick return if possible * IF( M.EQ.0 .OR. N.EQ.0 .OR. K.EQ.0 ) $ RETURN * IF( ( LEFT .AND. .NOT.NOTRAN .OR. .NOT.LEFT .AND. NOTRAN ) ) THEN I1 = 1 I2 = K I3 = 1 ELSE I1 = K I2 = 1 I3 = -1 END IF * IF( LEFT ) THEN NI = N JA = M - L + 1 JC = 1 ELSE MI = M JA = N - L + 1 IC = 1 END IF * DO 10 I = I1, I2, I3 IF( LEFT ) THEN * * H(i) or H(i)**H is applied to C(i:m,1:n) * MI = M - I + 1 IC = I ELSE * * H(i) or H(i)**H is applied to C(1:m,i:n) * NI = N - I + 1 JC = I END IF * * Apply H(i) or H(i)**H * IF( NOTRAN ) THEN TAUI = TAU( I ) ELSE TAUI = DCONJG( TAU( I ) ) END IF CALL ZLARZ( SIDE, MI, NI, L, A( I, JA ), LDA, TAUI, $ C( IC, JC ), LDC, WORK ) * 10 CONTINUE * RETURN * * End of ZUNMR3 * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/reference/chemvf.f
50
10919
SUBROUTINE CHEMVF ( UPLO, N, ALPHA, A, LDA, X, INCX, $ BETA, Y, INCY ) * .. Scalar Arguments .. COMPLEX ALPHA, BETA INTEGER INCX, INCY, LDA, N CHARACTER*1 UPLO * .. Array Arguments .. COMPLEX A( LDA, * ), X( * ), Y( * ) * .. * * Purpose * ======= * * CHEMV performs the matrix-vector operation * * y := alpha*A*x + beta*y, * * where alpha and beta are scalars, x and y are n element vectors and * A is an n by n hermitian matrix. * * Parameters * ========== * * UPLO - CHARACTER*1. * On entry, UPLO specifies whether the upper or lower * triangular part of the array A is to be referenced as * follows: * * UPLO = 'U' or 'u' Only the upper triangular part of A * is to be referenced. * * UPLO = 'L' or 'l' Only the lower triangular part of A * is to be referenced. * * Unchanged on exit. * * N - INTEGER. * On entry, N specifies the order of the matrix A. * N must be at least zero. * Unchanged on exit. * * ALPHA - COMPLEX . * On entry, ALPHA specifies the scalar alpha. * Unchanged on exit. * * A - COMPLEX array of DIMENSION ( LDA, n ). * Before entry with UPLO = 'U' or 'u', the leading n by n * upper triangular part of the array A must contain the upper * triangular part of the hermitian matrix and the strictly * lower triangular part of A is not referenced. * Before entry with UPLO = 'L' or 'l', the leading n by n * lower triangular part of the array A must contain the lower * triangular part of the hermitian matrix and the strictly * upper triangular part of A is not referenced. * Note that the imaginary parts of the diagonal elements need * not be set and are assumed to be zero. * Unchanged on exit. * * LDA - INTEGER. * On entry, LDA specifies the first dimension of A as declared * in the calling (sub) program. LDA must be at least * max( 1, n ). * Unchanged on exit. * * X - COMPLEX array of dimension at least * ( 1 + ( n - 1 )*abs( INCX ) ). * Before entry, the incremented array X must contain the n * element vector x. * Unchanged on exit. * * INCX - INTEGER. * On entry, INCX specifies the increment for the elements of * X. INCX must not be zero. * Unchanged on exit. * * BETA - COMPLEX . * On entry, BETA specifies the scalar beta. When BETA is * supplied as zero then Y need not be set on input. * Unchanged on exit. * * Y - COMPLEX array of dimension at least * ( 1 + ( n - 1 )*abs( INCY ) ). * Before entry, the incremented array Y must contain the n * element vector y. On exit, Y is overwritten by the updated * vector y. * * INCY - INTEGER. * On entry, INCY specifies the increment for the elements of * Y. INCY must not be zero. * Unchanged on exit. * * * Level 2 Blas routine. * * -- Written on 22-October-1986. * Jack Dongarra, Argonne National Lab. * Jeremy Du Croz, Nag Central Office. * Sven Hammarling, Nag Central Office. * Richard Hanson, Sandia National Labs. * * * .. Parameters .. COMPLEX ONE PARAMETER ( ONE = ( 1.0E+0, 0.0E+0 ) ) COMPLEX ZERO PARAMETER ( ZERO = ( 0.0E+0, 0.0E+0 ) ) * .. Local Scalars .. COMPLEX TEMP1, TEMP2 INTEGER I, INFO, IX, IY, J, JX, JY, KX, KY * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. External Subroutines .. EXTERNAL XERBLA * .. Intrinsic Functions .. INTRINSIC CONJG, MAX, REAL * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 IF ( .NOT.LSAME( UPLO, 'U' ).AND. $ .NOT.LSAME( UPLO, 'L' ).AND. $ .NOT.LSAME( UPLO, 'V' ).AND. $ .NOT.LSAME( UPLO, 'M' ))THEN INFO = 1 ELSE IF( N.LT.0 )THEN INFO = 2 ELSE IF( LDA.LT.MAX( 1, N ) )THEN INFO = 5 ELSE IF( INCX.EQ.0 )THEN INFO = 7 ELSE IF( INCY.EQ.0 )THEN INFO = 10 END IF IF( INFO.NE.0 )THEN CALL XERBLA( 'CHEMV ', INFO ) RETURN END IF * * Quick return if possible. * IF( ( N.EQ.0 ).OR.( ( ALPHA.EQ.ZERO ).AND.( BETA.EQ.ONE ) ) ) $ RETURN * * Set up the start points in X and Y. * IF( INCX.GT.0 )THEN KX = 1 ELSE KX = 1 - ( N - 1 )*INCX END IF IF( INCY.GT.0 )THEN KY = 1 ELSE KY = 1 - ( N - 1 )*INCY END IF * * Start the operations. In this version the elements of A are * accessed sequentially with one pass through the triangular part * of A. * * First form y := beta*y. * IF( BETA.NE.ONE )THEN IF( INCY.EQ.1 )THEN IF( BETA.EQ.ZERO )THEN DO 10, I = 1, N Y( I ) = ZERO 10 CONTINUE ELSE DO 20, I = 1, N Y( I ) = BETA*Y( I ) 20 CONTINUE END IF ELSE IY = KY IF( BETA.EQ.ZERO )THEN DO 30, I = 1, N Y( IY ) = ZERO IY = IY + INCY 30 CONTINUE ELSE DO 40, I = 1, N Y( IY ) = BETA*Y( IY ) IY = IY + INCY 40 CONTINUE END IF END IF END IF IF( ALPHA.EQ.ZERO ) $ RETURN IF( LSAME( UPLO, 'U' ) )THEN * * Form y when A is stored in upper triangle. * IF( ( INCX.EQ.1 ).AND.( INCY.EQ.1 ) )THEN DO 60, J = 1, N TEMP1 = ALPHA*X( J ) TEMP2 = ZERO DO 50, I = 1, J - 1 Y( I ) = Y( I ) + TEMP1*A( I, J ) TEMP2 = TEMP2 + CONJG( A( I, J ) )*X( I ) 50 CONTINUE Y( J ) = Y( J ) + TEMP1*REAL( A( J, J ) ) + ALPHA*TEMP2 60 CONTINUE ELSE JX = KX JY = KY DO 80, J = 1, N TEMP1 = ALPHA*X( JX ) TEMP2 = ZERO IX = KX IY = KY DO 70, I = 1, J - 1 Y( IY ) = Y( IY ) + TEMP1*A( I, J ) TEMP2 = TEMP2 + CONJG( A( I, J ) )*X( IX ) IX = IX + INCX IY = IY + INCY 70 CONTINUE Y( JY ) = Y( JY ) + TEMP1*REAL( A( J, J ) ) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY 80 CONTINUE END IF RETURN ENDIF IF( LSAME( UPLO, 'L' ) )THEN * * Form y when A is stored in lower triangle. * IF( ( INCX.EQ.1 ).AND.( INCY.EQ.1 ) )THEN DO 100, J = 1, N TEMP1 = ALPHA*X( J ) TEMP2 = ZERO Y( J ) = Y( J ) + TEMP1*REAL( A( J, J ) ) DO 90, I = J + 1, N Y( I ) = Y( I ) + TEMP1*A( I, J ) TEMP2 = TEMP2 + CONJG( A( I, J ) )*X( I ) 90 CONTINUE Y( J ) = Y( J ) + ALPHA*TEMP2 100 CONTINUE ELSE JX = KX JY = KY DO 120, J = 1, N TEMP1 = ALPHA*X( JX ) TEMP2 = ZERO Y( JY ) = Y( JY ) + TEMP1*REAL( A( J, J ) ) IX = JX IY = JY DO 110, I = J + 1, N IX = IX + INCX IY = IY + INCY Y( IY ) = Y( IY ) + TEMP1*A( I, J ) TEMP2 = TEMP2 + CONJG( A( I, J ) )*X( IX ) 110 CONTINUE Y( JY ) = Y( JY ) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY 120 CONTINUE END IF RETURN END IF IF( LSAME( UPLO, 'V' ) )THEN * * Form y when A is stored in upper triangle. * IF( ( INCX.EQ.1 ).AND.( INCY.EQ.1 ) )THEN DO 160, J = 1, N TEMP1 = ALPHA*X( J ) TEMP2 = ZERO DO 150, I = 1, J - 1 Y( I ) = Y( I ) + TEMP1* CONJG(A( I, J )) TEMP2 = TEMP2 + A( I, J )*X( I ) 150 CONTINUE Y( J ) = Y( J ) + TEMP1*REAL( A( J, J ) ) + ALPHA*TEMP2 160 CONTINUE ELSE JX = KX JY = KY DO 180, J = 1, N TEMP1 = ALPHA*X( JX ) TEMP2 = ZERO IX = KX IY = KY DO 170, I = 1, J - 1 Y( IY ) = Y( IY ) + TEMP1* CONJG(A( I, J )) TEMP2 = TEMP2 + A( I, J )*X( IX ) IX = IX + INCX IY = IY + INCY 170 CONTINUE Y( JY ) = Y( JY ) + TEMP1*REAL( A( J, J ) ) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY 180 CONTINUE END IF RETURN ENDIF IF( LSAME( UPLO, 'M' ) )THEN * * Form y when A is stored in lower triangle. * IF( ( INCX.EQ.1 ).AND.( INCY.EQ.1 ) )THEN DO 200, J = 1, N TEMP1 = ALPHA*X( J ) TEMP2 = ZERO Y( J ) = Y( J ) + TEMP1*REAL( A( J, J ) ) DO 190, I = J + 1, N Y( I ) = Y( I ) + TEMP1*CONJG(A( I, J )) TEMP2 = TEMP2 + A( I, J )*X( I ) 190 CONTINUE Y( J ) = Y( J ) + ALPHA*TEMP2 200 CONTINUE ELSE JX = KX JY = KY DO 220, J = 1, N TEMP1 = ALPHA*X( JX ) TEMP2 = ZERO Y( JY ) = Y( JY ) + TEMP1*REAL( A( J, J ) ) IX = JX IY = JY DO 210, I = J + 1, N IX = IX + INCX IY = IY + INCY Y( IY ) = Y( IY ) + TEMP1*CONJG(A( I, J )) TEMP2 = TEMP2 + A( I, J )*X( IX ) 210 CONTINUE Y( JY ) = Y( JY ) + ALPHA*TEMP2 JX = JX + INCX JY = JY + INCY 220 CONTINUE END IF RETURN END IF * * * End of CHEMV . * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/TESTING/MATGEN/dlaran.f
33
4113
*> \brief \b DLARAN * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * DOUBLE PRECISION FUNCTION DLARAN( ISEED ) * * .. Array Arguments .. * INTEGER ISEED( 4 ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DLARAN returns a random real number from a uniform (0,1) *> distribution. *> \endverbatim * * Arguments: * ========== * *> \param[in,out] ISEED *> \verbatim *> ISEED is INTEGER array, dimension (4) *> On entry, the seed of the random number generator; the array *> elements must be between 0 and 4095, and ISEED(4) must be *> odd. *> On exit, the seed is updated. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup list_temp * *> \par Further Details: * ===================== *> *> \verbatim *> *> This routine uses a multiplicative congruential method with modulus *> 2**48 and multiplier 33952834046453 (see G.S.Fishman, *> 'Multiplicative congruential random number generators with modulus *> 2**b: an exhaustive analysis for b = 32 and a partial analysis for *> b = 48', Math. Comp. 189, pp 331-344, 1990). *> *> 48-bit integers are stored in 4 integer array elements with 12 bits *> per element. Hence the routine is portable across machines with *> integers of 32 bits or more. *> \endverbatim *> * ===================================================================== DOUBLE PRECISION FUNCTION DLARAN( ISEED ) * * -- LAPACK auxiliary routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Array Arguments .. INTEGER ISEED( 4 ) * .. * * ===================================================================== * * .. Parameters .. INTEGER M1, M2, M3, M4 PARAMETER ( M1 = 494, M2 = 322, M3 = 2508, M4 = 2549 ) DOUBLE PRECISION ONE PARAMETER ( ONE = 1.0D+0 ) INTEGER IPW2 DOUBLE PRECISION R PARAMETER ( IPW2 = 4096, R = ONE / IPW2 ) * .. * .. Local Scalars .. INTEGER IT1, IT2, IT3, IT4 DOUBLE PRECISION RNDOUT * .. * .. Intrinsic Functions .. INTRINSIC DBLE, MOD * .. * .. Executable Statements .. 10 CONTINUE * * multiply the seed by the multiplier modulo 2**48 * IT4 = ISEED( 4 )*M4 IT3 = IT4 / IPW2 IT4 = IT4 - IPW2*IT3 IT3 = IT3 + ISEED( 3 )*M4 + ISEED( 4 )*M3 IT2 = IT3 / IPW2 IT3 = IT3 - IPW2*IT2 IT2 = IT2 + ISEED( 2 )*M4 + ISEED( 3 )*M3 + ISEED( 4 )*M2 IT1 = IT2 / IPW2 IT2 = IT2 - IPW2*IT1 IT1 = IT1 + ISEED( 1 )*M4 + ISEED( 2 )*M3 + ISEED( 3 )*M2 + $ ISEED( 4 )*M1 IT1 = MOD( IT1, IPW2 ) * * return updated seed * ISEED( 1 ) = IT1 ISEED( 2 ) = IT2 ISEED( 3 ) = IT3 ISEED( 4 ) = IT4 * * convert 48-bit integer to a real number in the interval (0,1) * RNDOUT = R*( DBLE( IT1 )+R*( DBLE( IT2 )+R*( DBLE( IT3 )+R* $ ( DBLE( IT4 ) ) ) ) ) * IF (RNDOUT.EQ.1.0D+0) THEN * If a real number has n bits of precision, and the first * n bits of the 48-bit integer above happen to be all 1 (which * will occur about once every 2**n calls), then DLARAN will * be rounded to exactly 1.0. * Since DLARAN is not supposed to return exactly 0.0 or 1.0 * (and some callers of DLARAN, such as CLARND, depend on that), * the statistically correct thing to do in this situation is * simply to iterate again. * N.B. the case DLARAN = 0.0 should not be possible. * GOTO 10 END IF * DLARAN = RNDOUT RETURN * * End of DLARAN * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/TESTING/LIN/derrab.f
32
3749
*> \brief \b DERRAB * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE DERRAB( NUNIT ) * * .. Scalar Arguments .. * INTEGER NUNIT * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DERRAB tests the error exits for DSGESV. *> \endverbatim * * Arguments: * ========== * *> \param[in] NUNIT *> \verbatim *> NUNIT is INTEGER *> The unit number for output. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup double_lin * * ===================================================================== SUBROUTINE DERRAB( NUNIT ) * * -- LAPACK test routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. INTEGER NUNIT * .. * * ===================================================================== * * .. Parameters .. INTEGER NMAX PARAMETER ( NMAX = 4 ) * .. * .. Local Scalars .. INTEGER I, INFO, ITER, J * .. * .. Local Arrays .. INTEGER IP( NMAX ) DOUBLE PRECISION A( NMAX, NMAX ), AF( NMAX, NMAX ), B( NMAX ), $ C( NMAX ), R( NMAX ), R1( NMAX ), R2( NMAX ), $ W( 2*NMAX ), X( NMAX ) DOUBLE PRECISION WORK(1) REAL SWORK(1) * .. * .. External Subroutines .. EXTERNAL CHKXER, DSGESV * .. * .. Scalars in Common .. LOGICAL LERR, OK CHARACTER*32 SRNAMT INTEGER INFOT, NOUT * .. * .. Common blocks .. COMMON / INFOC / INFOT, NOUT, OK, LERR COMMON / SRNAMC / SRNAMT * .. * .. Intrinsic Functions .. INTRINSIC DBLE * .. * .. Executable Statements .. * NOUT = NUNIT WRITE( NOUT, FMT = * ) * * Set the variables to innocuous values. * DO 20 J = 1, NMAX DO 10 I = 1, NMAX A( I, J ) = 1.D0 / DBLE( I+J ) AF( I, J ) = 1.D0 / DBLE( I+J ) 10 CONTINUE B( J ) = 0.D0 R1( J ) = 0.D0 R2( J ) = 0.D0 W( J ) = 0.D0 X( J ) = 0.D0 C( J ) = 0.D0 R( J ) = 0.D0 IP( J ) = J 20 CONTINUE OK = .TRUE. * SRNAMT = 'DSGESV' INFOT = 1 CALL DSGESV(-1,0,A,1,IP,B,1,X,1,WORK,SWORK,ITER,INFO) CALL CHKXER( 'DSGESV', INFOT, NOUT, LERR, OK ) INFOT = 2 CALL DSGESV(0,-1,A,1,IP,B,1,X,1,WORK,SWORK,ITER,INFO) CALL CHKXER( 'DSGESV', INFOT, NOUT, LERR, OK ) INFOT = 4 CALL DSGESV(2,1,A,1,IP,B,2,X,2,WORK,SWORK,ITER,INFO) CALL CHKXER( 'DSGESV', INFOT, NOUT, LERR, OK ) INFOT = 7 CALL DSGESV(2,1,A,2,IP,B,1,X,2,WORK,SWORK,ITER,INFO) CALL CHKXER( 'DSGESV', INFOT, NOUT, LERR, OK ) INFOT = 9 CALL DSGESV(2,1,A,2,IP,B,2,X,1,WORK,SWORK,ITER,INFO) CALL CHKXER( 'DSGESV', INFOT, NOUT, LERR, OK ) * * Print a summary line. * IF( OK ) THEN WRITE( NOUT, FMT = 9999 )'DSGESV' ELSE WRITE( NOUT, FMT = 9998 )'DSGESV' END IF * 9999 FORMAT( 1X, A6, ' drivers passed the tests of the error exits' ) 9998 FORMAT( ' *** ', A6, ' drivers failed the tests of the error ', $ 'exits ***' ) * RETURN * * End of DERRAB * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/slarre.f
24
31997
*> \brief \b SLARRE given the tridiagonal matrix T, sets small off-diagonal elements to zero and for each unreduced block Ti, finds base representations and eigenvalues. * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download SLARRE + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/slarre.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/slarre.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/slarre.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE SLARRE( RANGE, N, VL, VU, IL, IU, D, E, E2, * RTOL1, RTOL2, SPLTOL, NSPLIT, ISPLIT, M, * W, WERR, WGAP, IBLOCK, INDEXW, GERS, PIVMIN, * WORK, IWORK, INFO ) * * .. Scalar Arguments .. * CHARACTER RANGE * INTEGER IL, INFO, IU, M, N, NSPLIT * REAL PIVMIN, RTOL1, RTOL2, SPLTOL, VL, VU * .. * .. Array Arguments .. * INTEGER IBLOCK( * ), ISPLIT( * ), IWORK( * ), * $ INDEXW( * ) * REAL D( * ), E( * ), E2( * ), GERS( * ), * $ W( * ),WERR( * ), WGAP( * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> To find the desired eigenvalues of a given real symmetric *> tridiagonal matrix T, SLARRE sets any "small" off-diagonal *> elements to zero, and for each unreduced block T_i, it finds *> (a) a suitable shift at one end of the block's spectrum, *> (b) the base representation, T_i - sigma_i I = L_i D_i L_i^T, and *> (c) eigenvalues of each L_i D_i L_i^T. *> The representations and eigenvalues found are then used by *> SSTEMR to compute the eigenvectors of T. *> The accuracy varies depending on whether bisection is used to *> find a few eigenvalues or the dqds algorithm (subroutine SLASQ2) to *> conpute all and then discard any unwanted one. *> As an added benefit, SLARRE also outputs the n *> Gerschgorin intervals for the matrices L_i D_i L_i^T. *> \endverbatim * * Arguments: * ========== * *> \param[in] RANGE *> \verbatim *> RANGE is CHARACTER*1 *> = 'A': ("All") all eigenvalues will be found. *> = 'V': ("Value") all eigenvalues in the half-open interval *> (VL, VU] will be found. *> = 'I': ("Index") the IL-th through IU-th eigenvalues (of the *> entire matrix) will be found. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix. N > 0. *> \endverbatim *> *> \param[in,out] VL *> \verbatim *> VL is REAL *> \endverbatim *> *> \param[in,out] VU *> \verbatim *> VU is REAL *> If RANGE='V', the lower and upper bounds for the eigenvalues. *> Eigenvalues less than or equal to VL, or greater than VU, *> will not be returned. VL < VU. *> If RANGE='I' or ='A', SLARRE computes bounds on the desired *> part of the spectrum. *> \endverbatim *> *> \param[in] IL *> \verbatim *> IL is INTEGER *> \endverbatim *> *> \param[in] IU *> \verbatim *> IU is INTEGER *> If RANGE='I', the indices (in ascending order) of the *> smallest and largest eigenvalues to be returned. *> 1 <= IL <= IU <= N. *> \endverbatim *> *> \param[in,out] D *> \verbatim *> D is REAL array, dimension (N) *> On entry, the N diagonal elements of the tridiagonal *> matrix T. *> On exit, the N diagonal elements of the diagonal *> matrices D_i. *> \endverbatim *> *> \param[in,out] E *> \verbatim *> E is REAL array, dimension (N) *> On entry, the first (N-1) entries contain the subdiagonal *> elements of the tridiagonal matrix T; E(N) need not be set. *> On exit, E contains the subdiagonal elements of the unit *> bidiagonal matrices L_i. The entries E( ISPLIT( I ) ), *> 1 <= I <= NSPLIT, contain the base points sigma_i on output. *> \endverbatim *> *> \param[in,out] E2 *> \verbatim *> E2 is REAL array, dimension (N) *> On entry, the first (N-1) entries contain the SQUARES of the *> subdiagonal elements of the tridiagonal matrix T; *> E2(N) need not be set. *> On exit, the entries E2( ISPLIT( I ) ), *> 1 <= I <= NSPLIT, have been set to zero *> \endverbatim *> *> \param[in] RTOL1 *> \verbatim *> RTOL1 is REAL *> \endverbatim *> *> \param[in] RTOL2 *> \verbatim *> RTOL2 is REAL *> Parameters for bisection. *> An interval [LEFT,RIGHT] has converged if *> RIGHT-LEFT.LT.MAX( RTOL1*GAP, RTOL2*MAX(|LEFT|,|RIGHT|) ) *> \endverbatim *> *> \param[in] SPLTOL *> \verbatim *> SPLTOL is REAL *> The threshold for splitting. *> \endverbatim *> *> \param[out] NSPLIT *> \verbatim *> NSPLIT is INTEGER *> The number of blocks T splits into. 1 <= NSPLIT <= N. *> \endverbatim *> *> \param[out] ISPLIT *> \verbatim *> ISPLIT is INTEGER array, dimension (N) *> The splitting points, at which T breaks up into blocks. *> The first block consists of rows/columns 1 to ISPLIT(1), *> the second of rows/columns ISPLIT(1)+1 through ISPLIT(2), *> etc., and the NSPLIT-th consists of rows/columns *> ISPLIT(NSPLIT-1)+1 through ISPLIT(NSPLIT)=N. *> \endverbatim *> *> \param[out] M *> \verbatim *> M is INTEGER *> The total number of eigenvalues (of all L_i D_i L_i^T) *> found. *> \endverbatim *> *> \param[out] W *> \verbatim *> W is REAL array, dimension (N) *> The first M elements contain the eigenvalues. The *> eigenvalues of each of the blocks, L_i D_i L_i^T, are *> sorted in ascending order ( SLARRE may use the *> remaining N-M elements as workspace). *> \endverbatim *> *> \param[out] WERR *> \verbatim *> WERR is REAL array, dimension (N) *> The error bound on the corresponding eigenvalue in W. *> \endverbatim *> *> \param[out] WGAP *> \verbatim *> WGAP is REAL array, dimension (N) *> The separation from the right neighbor eigenvalue in W. *> The gap is only with respect to the eigenvalues of the same block *> as each block has its own representation tree. *> Exception: at the right end of a block we store the left gap *> \endverbatim *> *> \param[out] IBLOCK *> \verbatim *> IBLOCK is INTEGER array, dimension (N) *> The indices of the blocks (submatrices) associated with the *> corresponding eigenvalues in W; IBLOCK(i)=1 if eigenvalue *> W(i) belongs to the first block from the top, =2 if W(i) *> belongs to the second block, etc. *> \endverbatim *> *> \param[out] INDEXW *> \verbatim *> INDEXW is INTEGER array, dimension (N) *> The indices of the eigenvalues within each block (submatrix); *> for example, INDEXW(i)= 10 and IBLOCK(i)=2 imply that the *> i-th eigenvalue W(i) is the 10-th eigenvalue in block 2 *> \endverbatim *> *> \param[out] GERS *> \verbatim *> GERS is REAL array, dimension (2*N) *> The N Gerschgorin intervals (the i-th Gerschgorin interval *> is (GERS(2*i-1), GERS(2*i)). *> \endverbatim *> *> \param[out] PIVMIN *> \verbatim *> PIVMIN is REAL *> The minimum pivot in the Sturm sequence for T. *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is REAL array, dimension (6*N) *> Workspace. *> \endverbatim *> *> \param[out] IWORK *> \verbatim *> IWORK is INTEGER array, dimension (5*N) *> Workspace. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> > 0: A problem occured in SLARRE. *> < 0: One of the called subroutines signaled an internal problem. *> Needs inspection of the corresponding parameter IINFO *> for further information. *> *> =-1: Problem in SLARRD. *> = 2: No base representation could be found in MAXTRY iterations. *> Increasing MAXTRY and recompilation might be a remedy. *> =-3: Problem in SLARRB when computing the refined root *> representation for SLASQ2. *> =-4: Problem in SLARRB when preforming bisection on the *> desired part of the spectrum. *> =-5: Problem in SLASQ2. *> =-6: Problem in SLASQ2. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date September 2012 * *> \ingroup auxOTHERauxiliary * *> \par Further Details: * ===================== *> *> \verbatim *> *> The base representations are required to suffer very little *> element growth and consequently define all their eigenvalues to *> high relative accuracy. *> \endverbatim * *> \par Contributors: * ================== *> *> Beresford Parlett, University of California, Berkeley, USA \n *> Jim Demmel, University of California, Berkeley, USA \n *> Inderjit Dhillon, University of Texas, Austin, USA \n *> Osni Marques, LBNL/NERSC, USA \n *> Christof Voemel, University of California, Berkeley, USA \n *> * ===================================================================== SUBROUTINE SLARRE( RANGE, N, VL, VU, IL, IU, D, E, E2, $ RTOL1, RTOL2, SPLTOL, NSPLIT, ISPLIT, M, $ W, WERR, WGAP, IBLOCK, INDEXW, GERS, PIVMIN, $ WORK, IWORK, INFO ) * * -- LAPACK auxiliary routine (version 3.4.2) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * September 2012 * * .. Scalar Arguments .. CHARACTER RANGE INTEGER IL, INFO, IU, M, N, NSPLIT REAL PIVMIN, RTOL1, RTOL2, SPLTOL, VL, VU * .. * .. Array Arguments .. INTEGER IBLOCK( * ), ISPLIT( * ), IWORK( * ), $ INDEXW( * ) REAL D( * ), E( * ), E2( * ), GERS( * ), $ W( * ),WERR( * ), WGAP( * ), WORK( * ) * .. * * ===================================================================== * * .. Parameters .. REAL FAC, FOUR, FOURTH, FUDGE, HALF, HNDRD, $ MAXGROWTH, ONE, PERT, TWO, ZERO PARAMETER ( ZERO = 0.0E0, ONE = 1.0E0, $ TWO = 2.0E0, FOUR=4.0E0, $ HNDRD = 100.0E0, $ PERT = 4.0E0, $ HALF = ONE/TWO, FOURTH = ONE/FOUR, FAC= HALF, $ MAXGROWTH = 64.0E0, FUDGE = 2.0E0 ) INTEGER MAXTRY, ALLRNG, INDRNG, VALRNG PARAMETER ( MAXTRY = 6, ALLRNG = 1, INDRNG = 2, $ VALRNG = 3 ) * .. * .. Local Scalars .. LOGICAL FORCEB, NOREP, USEDQD INTEGER CNT, CNT1, CNT2, I, IBEGIN, IDUM, IEND, IINFO, $ IN, INDL, INDU, IRANGE, J, JBLK, MB, MM, $ WBEGIN, WEND REAL AVGAP, BSRTOL, CLWDTH, DMAX, DPIVOT, EABS, $ EMAX, EOLD, EPS, GL, GU, ISLEFT, ISRGHT, RTL, $ RTOL, S1, S2, SAFMIN, SGNDEF, SIGMA, SPDIAM, $ TAU, TMP, TMP1 * .. * .. Local Arrays .. INTEGER ISEED( 4 ) * .. * .. External Functions .. LOGICAL LSAME REAL SLAMCH EXTERNAL SLAMCH, LSAME * .. * .. External Subroutines .. EXTERNAL SCOPY, SLARNV, SLARRA, SLARRB, SLARRC, SLARRD, $ SLASQ2 * .. * .. Intrinsic Functions .. INTRINSIC ABS, MAX, MIN * .. * .. Executable Statements .. * INFO = 0 * * Decode RANGE * IF( LSAME( RANGE, 'A' ) ) THEN IRANGE = ALLRNG ELSE IF( LSAME( RANGE, 'V' ) ) THEN IRANGE = VALRNG ELSE IF( LSAME( RANGE, 'I' ) ) THEN IRANGE = INDRNG END IF M = 0 * Get machine constants SAFMIN = SLAMCH( 'S' ) EPS = SLAMCH( 'P' ) * Set parameters RTL = HNDRD*EPS * If one were ever to ask for less initial precision in BSRTOL, * one should keep in mind that for the subset case, the extremal * eigenvalues must be at least as accurate as the current setting * (eigenvalues in the middle need not as much accuracy) BSRTOL = SQRT(EPS)*(0.5E-3) * Treat case of 1x1 matrix for quick return IF( N.EQ.1 ) THEN IF( (IRANGE.EQ.ALLRNG).OR. $ ((IRANGE.EQ.VALRNG).AND.(D(1).GT.VL).AND.(D(1).LE.VU)).OR. $ ((IRANGE.EQ.INDRNG).AND.(IL.EQ.1).AND.(IU.EQ.1)) ) THEN M = 1 W(1) = D(1) * The computation error of the eigenvalue is zero WERR(1) = ZERO WGAP(1) = ZERO IBLOCK( 1 ) = 1 INDEXW( 1 ) = 1 GERS(1) = D( 1 ) GERS(2) = D( 1 ) ENDIF * store the shift for the initial RRR, which is zero in this case E(1) = ZERO RETURN END IF * General case: tridiagonal matrix of order > 1 * * Init WERR, WGAP. Compute Gerschgorin intervals and spectral diameter. * Compute maximum off-diagonal entry and pivmin. GL = D(1) GU = D(1) EOLD = ZERO EMAX = ZERO E(N) = ZERO DO 5 I = 1,N WERR(I) = ZERO WGAP(I) = ZERO EABS = ABS( E(I) ) IF( EABS .GE. EMAX ) THEN EMAX = EABS END IF TMP1 = EABS + EOLD GERS( 2*I-1) = D(I) - TMP1 GL = MIN( GL, GERS( 2*I - 1)) GERS( 2*I ) = D(I) + TMP1 GU = MAX( GU, GERS(2*I) ) EOLD = EABS 5 CONTINUE * The minimum pivot allowed in the Sturm sequence for T PIVMIN = SAFMIN * MAX( ONE, EMAX**2 ) * Compute spectral diameter. The Gerschgorin bounds give an * estimate that is wrong by at most a factor of SQRT(2) SPDIAM = GU - GL * Compute splitting points CALL SLARRA( N, D, E, E2, SPLTOL, SPDIAM, $ NSPLIT, ISPLIT, IINFO ) * Can force use of bisection instead of faster DQDS. * Option left in the code for future multisection work. FORCEB = .FALSE. * Initialize USEDQD, DQDS should be used for ALLRNG unless someone * explicitly wants bisection. USEDQD = (( IRANGE.EQ.ALLRNG ) .AND. (.NOT.FORCEB)) IF( (IRANGE.EQ.ALLRNG) .AND. (.NOT. FORCEB) ) THEN * Set interval [VL,VU] that contains all eigenvalues VL = GL VU = GU ELSE * We call SLARRD to find crude approximations to the eigenvalues * in the desired range. In case IRANGE = INDRNG, we also obtain the * interval (VL,VU] that contains all the wanted eigenvalues. * An interval [LEFT,RIGHT] has converged if * RIGHT-LEFT.LT.RTOL*MAX(ABS(LEFT),ABS(RIGHT)) * SLARRD needs a WORK of size 4*N, IWORK of size 3*N CALL SLARRD( RANGE, 'B', N, VL, VU, IL, IU, GERS, $ BSRTOL, D, E, E2, PIVMIN, NSPLIT, ISPLIT, $ MM, W, WERR, VL, VU, IBLOCK, INDEXW, $ WORK, IWORK, IINFO ) IF( IINFO.NE.0 ) THEN INFO = -1 RETURN ENDIF * Make sure that the entries M+1 to N in W, WERR, IBLOCK, INDEXW are 0 DO 14 I = MM+1,N W( I ) = ZERO WERR( I ) = ZERO IBLOCK( I ) = 0 INDEXW( I ) = 0 14 CONTINUE END IF *** * Loop over unreduced blocks IBEGIN = 1 WBEGIN = 1 DO 170 JBLK = 1, NSPLIT IEND = ISPLIT( JBLK ) IN = IEND - IBEGIN + 1 * 1 X 1 block IF( IN.EQ.1 ) THEN IF( (IRANGE.EQ.ALLRNG).OR.( (IRANGE.EQ.VALRNG).AND. $ ( D( IBEGIN ).GT.VL ).AND.( D( IBEGIN ).LE.VU ) ) $ .OR. ( (IRANGE.EQ.INDRNG).AND.(IBLOCK(WBEGIN).EQ.JBLK)) $ ) THEN M = M + 1 W( M ) = D( IBEGIN ) WERR(M) = ZERO * The gap for a single block doesn't matter for the later * algorithm and is assigned an arbitrary large value WGAP(M) = ZERO IBLOCK( M ) = JBLK INDEXW( M ) = 1 WBEGIN = WBEGIN + 1 ENDIF * E( IEND ) holds the shift for the initial RRR E( IEND ) = ZERO IBEGIN = IEND + 1 GO TO 170 END IF * * Blocks of size larger than 1x1 * * E( IEND ) will hold the shift for the initial RRR, for now set it =0 E( IEND ) = ZERO * * Find local outer bounds GL,GU for the block GL = D(IBEGIN) GU = D(IBEGIN) DO 15 I = IBEGIN , IEND GL = MIN( GERS( 2*I-1 ), GL ) GU = MAX( GERS( 2*I ), GU ) 15 CONTINUE SPDIAM = GU - GL IF(.NOT. ((IRANGE.EQ.ALLRNG).AND.(.NOT.FORCEB)) ) THEN * Count the number of eigenvalues in the current block. MB = 0 DO 20 I = WBEGIN,MM IF( IBLOCK(I).EQ.JBLK ) THEN MB = MB+1 ELSE GOTO 21 ENDIF 20 CONTINUE 21 CONTINUE IF( MB.EQ.0) THEN * No eigenvalue in the current block lies in the desired range * E( IEND ) holds the shift for the initial RRR E( IEND ) = ZERO IBEGIN = IEND + 1 GO TO 170 ELSE * Decide whether dqds or bisection is more efficient USEDQD = ( (MB .GT. FAC*IN) .AND. (.NOT.FORCEB) ) WEND = WBEGIN + MB - 1 * Calculate gaps for the current block * In later stages, when representations for individual * eigenvalues are different, we use SIGMA = E( IEND ). SIGMA = ZERO DO 30 I = WBEGIN, WEND - 1 WGAP( I ) = MAX( ZERO, $ W(I+1)-WERR(I+1) - (W(I)+WERR(I)) ) 30 CONTINUE WGAP( WEND ) = MAX( ZERO, $ VU - SIGMA - (W( WEND )+WERR( WEND ))) * Find local index of the first and last desired evalue. INDL = INDEXW(WBEGIN) INDU = INDEXW( WEND ) ENDIF ENDIF IF(( (IRANGE.EQ.ALLRNG) .AND. (.NOT. FORCEB) ).OR.USEDQD) THEN * Case of DQDS * Find approximations to the extremal eigenvalues of the block CALL SLARRK( IN, 1, GL, GU, D(IBEGIN), $ E2(IBEGIN), PIVMIN, RTL, TMP, TMP1, IINFO ) IF( IINFO.NE.0 ) THEN INFO = -1 RETURN ENDIF ISLEFT = MAX(GL, TMP - TMP1 $ - HNDRD * EPS* ABS(TMP - TMP1)) CALL SLARRK( IN, IN, GL, GU, D(IBEGIN), $ E2(IBEGIN), PIVMIN, RTL, TMP, TMP1, IINFO ) IF( IINFO.NE.0 ) THEN INFO = -1 RETURN ENDIF ISRGHT = MIN(GU, TMP + TMP1 $ + HNDRD * EPS * ABS(TMP + TMP1)) * Improve the estimate of the spectral diameter SPDIAM = ISRGHT - ISLEFT ELSE * Case of bisection * Find approximations to the wanted extremal eigenvalues ISLEFT = MAX(GL, W(WBEGIN) - WERR(WBEGIN) $ - HNDRD * EPS*ABS(W(WBEGIN)- WERR(WBEGIN) )) ISRGHT = MIN(GU,W(WEND) + WERR(WEND) $ + HNDRD * EPS * ABS(W(WEND)+ WERR(WEND))) ENDIF * Decide whether the base representation for the current block * L_JBLK D_JBLK L_JBLK^T = T_JBLK - sigma_JBLK I * should be on the left or the right end of the current block. * The strategy is to shift to the end which is "more populated" * Furthermore, decide whether to use DQDS for the computation of * the eigenvalue approximations at the end of SLARRE or bisection. * dqds is chosen if all eigenvalues are desired or the number of * eigenvalues to be computed is large compared to the blocksize. IF( ( IRANGE.EQ.ALLRNG ) .AND. (.NOT.FORCEB) ) THEN * If all the eigenvalues have to be computed, we use dqd USEDQD = .TRUE. * INDL is the local index of the first eigenvalue to compute INDL = 1 INDU = IN * MB = number of eigenvalues to compute MB = IN WEND = WBEGIN + MB - 1 * Define 1/4 and 3/4 points of the spectrum S1 = ISLEFT + FOURTH * SPDIAM S2 = ISRGHT - FOURTH * SPDIAM ELSE * SLARRD has computed IBLOCK and INDEXW for each eigenvalue * approximation. * choose sigma IF( USEDQD ) THEN S1 = ISLEFT + FOURTH * SPDIAM S2 = ISRGHT - FOURTH * SPDIAM ELSE TMP = MIN(ISRGHT,VU) - MAX(ISLEFT,VL) S1 = MAX(ISLEFT,VL) + FOURTH * TMP S2 = MIN(ISRGHT,VU) - FOURTH * TMP ENDIF ENDIF * Compute the negcount at the 1/4 and 3/4 points IF(MB.GT.1) THEN CALL SLARRC( 'T', IN, S1, S2, D(IBEGIN), $ E(IBEGIN), PIVMIN, CNT, CNT1, CNT2, IINFO) ENDIF IF(MB.EQ.1) THEN SIGMA = GL SGNDEF = ONE ELSEIF( CNT1 - INDL .GE. INDU - CNT2 ) THEN IF( ( IRANGE.EQ.ALLRNG ) .AND. (.NOT.FORCEB) ) THEN SIGMA = MAX(ISLEFT,GL) ELSEIF( USEDQD ) THEN * use Gerschgorin bound as shift to get pos def matrix * for dqds SIGMA = ISLEFT ELSE * use approximation of the first desired eigenvalue of the * block as shift SIGMA = MAX(ISLEFT,VL) ENDIF SGNDEF = ONE ELSE IF( ( IRANGE.EQ.ALLRNG ) .AND. (.NOT.FORCEB) ) THEN SIGMA = MIN(ISRGHT,GU) ELSEIF( USEDQD ) THEN * use Gerschgorin bound as shift to get neg def matrix * for dqds SIGMA = ISRGHT ELSE * use approximation of the first desired eigenvalue of the * block as shift SIGMA = MIN(ISRGHT,VU) ENDIF SGNDEF = -ONE ENDIF * An initial SIGMA has been chosen that will be used for computing * T - SIGMA I = L D L^T * Define the increment TAU of the shift in case the initial shift * needs to be refined to obtain a factorization with not too much * element growth. IF( USEDQD ) THEN * The initial SIGMA was to the outer end of the spectrum * the matrix is definite and we need not retreat. TAU = SPDIAM*EPS*N + TWO*PIVMIN TAU = MAX( TAU,TWO*EPS*ABS(SIGMA) ) ELSE IF(MB.GT.1) THEN CLWDTH = W(WEND) + WERR(WEND) - W(WBEGIN) - WERR(WBEGIN) AVGAP = ABS(CLWDTH / REAL(WEND-WBEGIN)) IF( SGNDEF.EQ.ONE ) THEN TAU = HALF*MAX(WGAP(WBEGIN),AVGAP) TAU = MAX(TAU,WERR(WBEGIN)) ELSE TAU = HALF*MAX(WGAP(WEND-1),AVGAP) TAU = MAX(TAU,WERR(WEND)) ENDIF ELSE TAU = WERR(WBEGIN) ENDIF ENDIF * DO 80 IDUM = 1, MAXTRY * Compute L D L^T factorization of tridiagonal matrix T - sigma I. * Store D in WORK(1:IN), L in WORK(IN+1:2*IN), and reciprocals of * pivots in WORK(2*IN+1:3*IN) DPIVOT = D( IBEGIN ) - SIGMA WORK( 1 ) = DPIVOT DMAX = ABS( WORK(1) ) J = IBEGIN DO 70 I = 1, IN - 1 WORK( 2*IN+I ) = ONE / WORK( I ) TMP = E( J )*WORK( 2*IN+I ) WORK( IN+I ) = TMP DPIVOT = ( D( J+1 )-SIGMA ) - TMP*E( J ) WORK( I+1 ) = DPIVOT DMAX = MAX( DMAX, ABS(DPIVOT) ) J = J + 1 70 CONTINUE * check for element growth IF( DMAX .GT. MAXGROWTH*SPDIAM ) THEN NOREP = .TRUE. ELSE NOREP = .FALSE. ENDIF IF( USEDQD .AND. .NOT.NOREP ) THEN * Ensure the definiteness of the representation * All entries of D (of L D L^T) must have the same sign DO 71 I = 1, IN TMP = SGNDEF*WORK( I ) IF( TMP.LT.ZERO ) NOREP = .TRUE. 71 CONTINUE ENDIF IF(NOREP) THEN * Note that in the case of IRANGE=ALLRNG, we use the Gerschgorin * shift which makes the matrix definite. So we should end up * here really only in the case of IRANGE = VALRNG or INDRNG. IF( IDUM.EQ.MAXTRY-1 ) THEN IF( SGNDEF.EQ.ONE ) THEN * The fudged Gerschgorin shift should succeed SIGMA = $ GL - FUDGE*SPDIAM*EPS*N - FUDGE*TWO*PIVMIN ELSE SIGMA = $ GU + FUDGE*SPDIAM*EPS*N + FUDGE*TWO*PIVMIN END IF ELSE SIGMA = SIGMA - SGNDEF * TAU TAU = TWO * TAU END IF ELSE * an initial RRR is found GO TO 83 END IF 80 CONTINUE * if the program reaches this point, no base representation could be * found in MAXTRY iterations. INFO = 2 RETURN 83 CONTINUE * At this point, we have found an initial base representation * T - SIGMA I = L D L^T with not too much element growth. * Store the shift. E( IEND ) = SIGMA * Store D and L. CALL SCOPY( IN, WORK, 1, D( IBEGIN ), 1 ) CALL SCOPY( IN-1, WORK( IN+1 ), 1, E( IBEGIN ), 1 ) IF(MB.GT.1 ) THEN * * Perturb each entry of the base representation by a small * (but random) relative amount to overcome difficulties with * glued matrices. * DO 122 I = 1, 4 ISEED( I ) = 1 122 CONTINUE CALL SLARNV(2, ISEED, 2*IN-1, WORK(1)) DO 125 I = 1,IN-1 D(IBEGIN+I-1) = D(IBEGIN+I-1)*(ONE+EPS*PERT*WORK(I)) E(IBEGIN+I-1) = E(IBEGIN+I-1)*(ONE+EPS*PERT*WORK(IN+I)) 125 CONTINUE D(IEND) = D(IEND)*(ONE+EPS*FOUR*WORK(IN)) * ENDIF * * Don't update the Gerschgorin intervals because keeping track * of the updates would be too much work in SLARRV. * We update W instead and use it to locate the proper Gerschgorin * intervals. * Compute the required eigenvalues of L D L' by bisection or dqds IF ( .NOT.USEDQD ) THEN * If SLARRD has been used, shift the eigenvalue approximations * according to their representation. This is necessary for * a uniform SLARRV since dqds computes eigenvalues of the * shifted representation. In SLARRV, W will always hold the * UNshifted eigenvalue approximation. DO 134 J=WBEGIN,WEND W(J) = W(J) - SIGMA WERR(J) = WERR(J) + ABS(W(J)) * EPS 134 CONTINUE * call SLARRB to reduce eigenvalue error of the approximations * from SLARRD DO 135 I = IBEGIN, IEND-1 WORK( I ) = D( I ) * E( I )**2 135 CONTINUE * use bisection to find EV from INDL to INDU CALL SLARRB(IN, D(IBEGIN), WORK(IBEGIN), $ INDL, INDU, RTOL1, RTOL2, INDL-1, $ W(WBEGIN), WGAP(WBEGIN), WERR(WBEGIN), $ WORK( 2*N+1 ), IWORK, PIVMIN, SPDIAM, $ IN, IINFO ) IF( IINFO .NE. 0 ) THEN INFO = -4 RETURN END IF * SLARRB computes all gaps correctly except for the last one * Record distance to VU/GU WGAP( WEND ) = MAX( ZERO, $ ( VU-SIGMA ) - ( W( WEND ) + WERR( WEND ) ) ) DO 138 I = INDL, INDU M = M + 1 IBLOCK(M) = JBLK INDEXW(M) = I 138 CONTINUE ELSE * Call dqds to get all eigs (and then possibly delete unwanted * eigenvalues). * Note that dqds finds the eigenvalues of the L D L^T representation * of T to high relative accuracy. High relative accuracy * might be lost when the shift of the RRR is subtracted to obtain * the eigenvalues of T. However, T is not guaranteed to define its * eigenvalues to high relative accuracy anyway. * Set RTOL to the order of the tolerance used in SLASQ2 * This is an ESTIMATED error, the worst case bound is 4*N*EPS * which is usually too large and requires unnecessary work to be * done by bisection when computing the eigenvectors RTOL = LOG(REAL(IN)) * FOUR * EPS J = IBEGIN DO 140 I = 1, IN - 1 WORK( 2*I-1 ) = ABS( D( J ) ) WORK( 2*I ) = E( J )*E( J )*WORK( 2*I-1 ) J = J + 1 140 CONTINUE WORK( 2*IN-1 ) = ABS( D( IEND ) ) WORK( 2*IN ) = ZERO CALL SLASQ2( IN, WORK, IINFO ) IF( IINFO .NE. 0 ) THEN * If IINFO = -5 then an index is part of a tight cluster * and should be changed. The index is in IWORK(1) and the * gap is in WORK(N+1) INFO = -5 RETURN ELSE * Test that all eigenvalues are positive as expected DO 149 I = 1, IN IF( WORK( I ).LT.ZERO ) THEN INFO = -6 RETURN ENDIF 149 CONTINUE END IF IF( SGNDEF.GT.ZERO ) THEN DO 150 I = INDL, INDU M = M + 1 W( M ) = WORK( IN-I+1 ) IBLOCK( M ) = JBLK INDEXW( M ) = I 150 CONTINUE ELSE DO 160 I = INDL, INDU M = M + 1 W( M ) = -WORK( I ) IBLOCK( M ) = JBLK INDEXW( M ) = I 160 CONTINUE END IF DO 165 I = M - MB + 1, M * the value of RTOL below should be the tolerance in SLASQ2 WERR( I ) = RTOL * ABS( W(I) ) 165 CONTINUE DO 166 I = M - MB + 1, M - 1 * compute the right gap between the intervals WGAP( I ) = MAX( ZERO, $ W(I+1)-WERR(I+1) - (W(I)+WERR(I)) ) 166 CONTINUE WGAP( M ) = MAX( ZERO, $ ( VU-SIGMA ) - ( W( M ) + WERR( M ) ) ) END IF * proceed with next block IBEGIN = IEND + 1 WBEGIN = WEND + 1 170 CONTINUE * RETURN * * end of SLARRE * END
bsd-3-clause
lofar-astron/PyBDSF
src/port3/d7egr.f
2
4152
SUBROUTINE D7EGR(N,INDROW,JPNTR,INDCOL,IPNTR,NDEG,IWA,BWA) INTEGER N INTEGER INDROW(1),JPNTR(1),INDCOL(1),IPNTR(1),NDEG(N),IWA(N) LOGICAL BWA(N) C ********** C C SUBROUTINE D7EGR C C GIVEN THE SPARSITY PATTERN OF AN M BY N MATRIX A, C THIS SUBROUTINE DETERMINES THE DEGREE SEQUENCE FOR C THE INTERSECTION GRAPH OF THE COLUMNS OF A. C C IN GRAPH-THEORY TERMINOLOGY, THE INTERSECTION GRAPH OF C THE COLUMNS OF A IS THE LOOPLESS GRAPH G WITH VERTICES C A(J), J = 1,2,...,N WHERE A(J) IS THE J-TH COLUMN OF A C AND WITH EDGE (A(I),A(J)) IF AND ONLY IF COLUMNS I AND J C HAVE A NON-ZERO IN THE SAME ROW POSITION. C C NOTE THAT THE VALUE OF M IS NOT NEEDED BY D7EGR AND IS C THEREFORE NOT PRESENT IN THE SUBROUTINE STATEMENT. C C THE SUBROUTINE STATEMENT IS C C SUBROUTINE D7EGR(N,INDROW,JPNTR,INDCOL,IPNTR,NDEG,IWA,BWA) C C WHERE C C N IS A POSITIVE INTEGER INPUT VARIABLE SET TO THE NUMBER C OF COLUMNS OF A. C C INDROW IS AN INTEGER INPUT ARRAY WHICH CONTAINS THE ROW C INDICES FOR THE NON-ZEROES IN THE MATRIX A. C C JPNTR IS AN INTEGER INPUT ARRAY OF LENGTH N + 1 WHICH C SPECIFIES THE LOCATIONS OF THE ROW INDICES IN INDROW. C THE ROW INDICES FOR COLUMN J ARE C C INDROW(K), K = JPNTR(J),...,JPNTR(J+1)-1. C C NOTE THAT JPNTR(N+1)-1 IS THEN THE NUMBER OF NON-ZERO C ELEMENTS OF THE MATRIX A. C C INDCOL IS AN INTEGER INPUT ARRAY WHICH CONTAINS THE C COLUMN INDICES FOR THE NON-ZEROES IN THE MATRIX A. C C IPNTR IS AN INTEGER INPUT ARRAY OF LENGTH M + 1 WHICH C SPECIFIES THE LOCATIONS OF THE COLUMN INDICES IN INDCOL. C THE COLUMN INDICES FOR ROW I ARE C C INDCOL(K), K = IPNTR(I),...,IPNTR(I+1)-1. C C NOTE THAT IPNTR(M+1)-1 IS THEN THE NUMBER OF NON-ZERO C ELEMENTS OF THE MATRIX A. C C NDEG IS AN INTEGER OUTPUT ARRAY OF LENGTH N WHICH C SPECIFIES THE DEGREE SEQUENCE. THE DEGREE OF THE C J-TH COLUMN OF A IS NDEG(J). C C IWA IS AN INTEGER WORK ARRAY OF LENGTH N. C C BWA IS A LOGICAL WORK ARRAY OF LENGTH N. C C ARGONNE NATIONAL LABORATORY. MINPACK PROJECT. JUNE 1982. C THOMAS F. COLEMAN, BURTON S. GARBOW, JORGE J. MORE C C ********** INTEGER DEG,IC,IP,IPL,IPU,IR,JCOL,JP,JPL,JPU C C INITIALIZATION BLOCK. C DO 10 JP = 1, N NDEG(JP) = 0 BWA(JP) = .FALSE. 10 CONTINUE C C COMPUTE THE DEGREE SEQUENCE BY DETERMINING THE CONTRIBUTIONS C TO THE DEGREES FROM THE CURRENT(JCOL) COLUMN AND FURTHER C COLUMNS WHICH HAVE NOT YET BEEN CONSIDERED. C IF (N .LT. 2) GO TO 90 DO 80 JCOL = 2, N BWA(JCOL) = .TRUE. DEG = 0 C C DETERMINE ALL POSITIONS (IR,JCOL) WHICH CORRESPOND C TO NON-ZEROES IN THE MATRIX. C JPL = JPNTR(JCOL) JPU = JPNTR(JCOL+1) - 1 IF (JPU .LT. JPL) GO TO 50 DO 40 JP = JPL, JPU IR = INDROW(JP) C C FOR EACH ROW IR, DETERMINE ALL POSITIONS (IR,IC) C WHICH CORRESPOND TO NON-ZEROES IN THE MATRIX. C IPL = IPNTR(IR) IPU = IPNTR(IR+1) - 1 DO 30 IP = IPL, IPU IC = INDCOL(IP) C C ARRAY BWA MARKS COLUMNS WHICH HAVE CONTRIBUTED TO C THE DEGREE COUNT OF COLUMN JCOL. UPDATE THE DEGREE C COUNTS OF THESE COLUMNS. ARRAY IWA RECORDS THE C MARKED COLUMNS. C IF (BWA(IC)) GO TO 20 BWA(IC) = .TRUE. NDEG(IC) = NDEG(IC) + 1 DEG = DEG + 1 IWA(DEG) = IC 20 CONTINUE 30 CONTINUE 40 CONTINUE 50 CONTINUE C C UN-MARK THE COLUMNS RECORDED BY IWA AND FINALIZE THE C DEGREE COUNT OF COLUMN JCOL. C IF (DEG .LT. 1) GO TO 70 DO 60 JP = 1, DEG IC = IWA(JP) BWA(IC) = .FALSE. 60 CONTINUE NDEG(JCOL) = NDEG(JCOL) + DEG 70 CONTINUE 80 CONTINUE 90 CONTINUE RETURN C C LAST CARD OF SUBROUTINE D7EGR. C END
gpl-3.0
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/chptrf.f
29
20757
*> \brief \b CHPTRF * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download CHPTRF + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/chptrf.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/chptrf.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/chptrf.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE CHPTRF( UPLO, N, AP, IPIV, INFO ) * * .. Scalar Arguments .. * CHARACTER UPLO * INTEGER INFO, N * .. * .. Array Arguments .. * INTEGER IPIV( * ) * COMPLEX AP( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CHPTRF computes the factorization of a complex Hermitian packed *> matrix A using the Bunch-Kaufman diagonal pivoting method: *> *> A = U*D*U**H or A = L*D*L**H *> *> 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. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> = 'U': Upper triangle of A is stored; *> = 'L': Lower triangle of A is stored. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix A. N >= 0. *> \endverbatim *> *> \param[in,out] AP *> \verbatim *> AP is COMPLEX array, dimension (N*(N+1)/2) *> On entry, the upper or lower triangle of the Hermitian matrix *> A, packed columnwise in a linear array. The j-th column of A *> is stored in the array AP as follows: *> if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; *> if UPLO = 'L', AP(i + (j-1)*(2n-j)/2) = A(i,j) for j<=i<=n. *> *> On exit, the block diagonal matrix D and the multipliers used *> to obtain the factor U or L, stored as a packed triangular *> matrix overwriting A (see below for further details). *> \endverbatim *> *> \param[out] IPIV *> \verbatim *> IPIV is INTEGER array, dimension (N) *> Details of the interchanges and the block structure of D. *> If IPIV(k) > 0, then rows and columns k and IPIV(k) were *> interchanged and D(k,k) 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. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> > 0: if INFO = i, D(i,i) 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. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup complexOTHERcomputational * *> \par Further Details: * ===================== *> *> \verbatim *> *> If UPLO = 'U', then A = U*D*U**H, where *> U = P(n)*U(n)* ... *P(k)U(k)* ..., *> i.e., U is a product of terms P(k)*U(k), where k decreases from n to *> 1 in steps of 1 or 2, and D is a block diagonal matrix with 1-by-1 *> and 2-by-2 diagonal blocks D(k). P(k) is a permutation matrix as *> defined by IPIV(k), and U(k) is a unit upper triangular matrix, such *> that if the diagonal block D(k) is of order s (s = 1 or 2), then *> *> ( I v 0 ) k-s *> U(k) = ( 0 I 0 ) s *> ( 0 0 I ) n-k *> k-s s n-k *> *> If s = 1, D(k) overwrites A(k,k), and v overwrites A(1:k-1,k). *> If s = 2, the upper triangle of D(k) overwrites A(k-1,k-1), A(k-1,k), *> and A(k,k), and v overwrites A(1:k-2,k-1:k). *> *> If UPLO = 'L', then A = L*D*L**H, where *> L = P(1)*L(1)* ... *P(k)*L(k)* ..., *> i.e., L is a product of terms P(k)*L(k), where k increases from 1 to *> n in steps of 1 or 2, and D is a block diagonal matrix with 1-by-1 *> and 2-by-2 diagonal blocks D(k). P(k) is a permutation matrix as *> defined by IPIV(k), and L(k) is a unit lower triangular matrix, such *> that if the diagonal block D(k) is of order s (s = 1 or 2), then *> *> ( I 0 0 ) k-1 *> L(k) = ( 0 I 0 ) s *> ( 0 v I ) n-k-s+1 *> k-1 s n-k-s+1 *> *> If s = 1, D(k) overwrites A(k,k), and v overwrites A(k+1:n,k). *> If s = 2, the lower triangle of D(k) overwrites A(k,k), A(k+1,k), *> and A(k+1,k+1), and v overwrites A(k+2:n,k:k+1). *> \endverbatim * *> \par Contributors: * ================== *> *> J. Lewis, Boeing Computer Services Company *> * ===================================================================== SUBROUTINE CHPTRF( UPLO, N, AP, IPIV, INFO ) * * -- LAPACK computational routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER UPLO INTEGER INFO, N * .. * .. Array Arguments .. INTEGER IPIV( * ) COMPLEX AP( * ) * .. * * ===================================================================== * * .. Parameters .. REAL ZERO, ONE PARAMETER ( ZERO = 0.0E+0, ONE = 1.0E+0 ) REAL EIGHT, SEVTEN PARAMETER ( EIGHT = 8.0E+0, SEVTEN = 17.0E+0 ) * .. * .. Local Scalars .. LOGICAL UPPER INTEGER I, IMAX, J, JMAX, K, KC, KK, KNC, KP, KPC, $ KSTEP, KX, NPP REAL ABSAKK, ALPHA, COLMAX, D, D11, D22, R1, ROWMAX, $ TT COMPLEX D12, D21, T, WK, WKM1, WKP1, ZDUM * .. * .. External Functions .. LOGICAL LSAME INTEGER ICAMAX REAL SLAPY2 EXTERNAL LSAME, ICAMAX, SLAPY2 * .. * .. External Subroutines .. EXTERNAL CHPR, CSSCAL, CSWAP, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC ABS, AIMAG, CMPLX, CONJG, MAX, REAL, SQRT * .. * .. Statement Functions .. REAL CABS1 * .. * .. Statement Function definitions .. CABS1( ZDUM ) = ABS( REAL( ZDUM ) ) + ABS( AIMAG( ZDUM ) ) * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 UPPER = LSAME( UPLO, 'U' ) IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'CHPTRF', -INFO ) RETURN END IF * * Initialize ALPHA for use in choosing pivot block size. * ALPHA = ( ONE+SQRT( SEVTEN ) ) / EIGHT * IF( UPPER ) THEN * * Factorize A as U*D*U**H using the upper triangle of A * * K is the main loop index, decreasing from N to 1 in steps of * 1 or 2 * K = N KC = ( N-1 )*N / 2 + 1 10 CONTINUE KNC = KC * * If K < 1, exit from loop * IF( K.LT.1 ) $ GO TO 110 KSTEP = 1 * * Determine rows and columns to be interchanged and whether * a 1-by-1 or 2-by-2 pivot block will be used * ABSAKK = ABS( REAL( AP( KC+K-1 ) ) ) * * IMAX is the row-index of the largest off-diagonal element in * column K, and COLMAX is its absolute value * IF( K.GT.1 ) THEN IMAX = ICAMAX( K-1, AP( KC ), 1 ) COLMAX = CABS1( AP( KC+IMAX-1 ) ) ELSE COLMAX = ZERO END IF * IF( MAX( ABSAKK, COLMAX ).EQ.ZERO ) THEN * * Column K is zero: set INFO and continue * IF( INFO.EQ.0 ) $ INFO = K KP = K AP( KC+K-1 ) = REAL( AP( KC+K-1 ) ) ELSE IF( ABSAKK.GE.ALPHA*COLMAX ) THEN * * no interchange, use 1-by-1 pivot block * KP = K ELSE * * JMAX is the column-index of the largest off-diagonal * element in row IMAX, and ROWMAX is its absolute value * ROWMAX = ZERO JMAX = IMAX KX = IMAX*( IMAX+1 ) / 2 + IMAX DO 20 J = IMAX + 1, K IF( CABS1( AP( KX ) ).GT.ROWMAX ) THEN ROWMAX = CABS1( AP( KX ) ) JMAX = J END IF KX = KX + J 20 CONTINUE KPC = ( IMAX-1 )*IMAX / 2 + 1 IF( IMAX.GT.1 ) THEN JMAX = ICAMAX( IMAX-1, AP( KPC ), 1 ) ROWMAX = MAX( ROWMAX, CABS1( AP( KPC+JMAX-1 ) ) ) END IF * IF( ABSAKK.GE.ALPHA*COLMAX*( COLMAX / ROWMAX ) ) THEN * * no interchange, use 1-by-1 pivot block * KP = K ELSE IF( ABS( REAL( AP( KPC+IMAX-1 ) ) ).GE.ALPHA* $ ROWMAX ) THEN * * interchange rows and columns K and IMAX, use 1-by-1 * pivot block * KP = IMAX ELSE * * interchange rows and columns K-1 and IMAX, use 2-by-2 * pivot block * KP = IMAX KSTEP = 2 END IF END IF * KK = K - KSTEP + 1 IF( KSTEP.EQ.2 ) $ KNC = KNC - K + 1 IF( KP.NE.KK ) THEN * * Interchange rows and columns KK and KP in the leading * submatrix A(1:k,1:k) * CALL CSWAP( KP-1, AP( KNC ), 1, AP( KPC ), 1 ) KX = KPC + KP - 1 DO 30 J = KP + 1, KK - 1 KX = KX + J - 1 T = CONJG( AP( KNC+J-1 ) ) AP( KNC+J-1 ) = CONJG( AP( KX ) ) AP( KX ) = T 30 CONTINUE AP( KX+KK-1 ) = CONJG( AP( KX+KK-1 ) ) R1 = REAL( AP( KNC+KK-1 ) ) AP( KNC+KK-1 ) = REAL( AP( KPC+KP-1 ) ) AP( KPC+KP-1 ) = R1 IF( KSTEP.EQ.2 ) THEN AP( KC+K-1 ) = REAL( AP( KC+K-1 ) ) T = AP( KC+K-2 ) AP( KC+K-2 ) = AP( KC+KP-1 ) AP( KC+KP-1 ) = T END IF ELSE AP( KC+K-1 ) = REAL( AP( KC+K-1 ) ) IF( KSTEP.EQ.2 ) $ AP( KC-1 ) = REAL( AP( KC-1 ) ) END IF * * Update the leading submatrix * IF( KSTEP.EQ.1 ) THEN * * 1-by-1 pivot block D(k): column k now holds * * W(k) = U(k)*D(k) * * where U(k) is the k-th column of U * * Perform a rank-1 update of A(1:k-1,1:k-1) as * * A := A - U(k)*D(k)*U(k)**H = A - W(k)*1/D(k)*W(k)**H * R1 = ONE / REAL( AP( KC+K-1 ) ) CALL CHPR( UPLO, K-1, -R1, AP( KC ), 1, AP ) * * Store U(k) in column k * CALL CSSCAL( K-1, R1, AP( KC ), 1 ) ELSE * * 2-by-2 pivot block D(k): columns k and k-1 now hold * * ( W(k-1) W(k) ) = ( U(k-1) U(k) )*D(k) * * where U(k) and U(k-1) are the k-th and (k-1)-th columns * of U * * Perform a rank-2 update of A(1:k-2,1:k-2) as * * A := A - ( U(k-1) U(k) )*D(k)*( U(k-1) U(k) )**H * = A - ( W(k-1) W(k) )*inv(D(k))*( W(k-1) W(k) )**H * IF( K.GT.2 ) THEN * D = SLAPY2( REAL( AP( K-1+( K-1 )*K / 2 ) ), $ AIMAG( AP( K-1+( K-1 )*K / 2 ) ) ) D22 = REAL( AP( K-1+( K-2 )*( K-1 ) / 2 ) ) / D D11 = REAL( AP( K+( K-1 )*K / 2 ) ) / D TT = ONE / ( D11*D22-ONE ) D12 = AP( K-1+( K-1 )*K / 2 ) / D D = TT / D * DO 50 J = K - 2, 1, -1 WKM1 = D*( D11*AP( J+( K-2 )*( K-1 ) / 2 )- $ CONJG( D12 )*AP( J+( K-1 )*K / 2 ) ) WK = D*( D22*AP( J+( K-1 )*K / 2 )-D12* $ AP( J+( K-2 )*( K-1 ) / 2 ) ) DO 40 I = J, 1, -1 AP( I+( J-1 )*J / 2 ) = AP( I+( J-1 )*J / 2 ) - $ AP( I+( K-1 )*K / 2 )*CONJG( WK ) - $ AP( I+( K-2 )*( K-1 ) / 2 )*CONJG( WKM1 ) 40 CONTINUE AP( J+( K-1 )*K / 2 ) = WK AP( J+( K-2 )*( K-1 ) / 2 ) = WKM1 AP( J+( J-1 )*J / 2 ) = CMPLX( REAL( AP( J+( J-1 )* $ J / 2 ) ), 0.0E+0 ) 50 CONTINUE * END IF * END IF END IF * * Store details of the interchanges in IPIV * IF( KSTEP.EQ.1 ) THEN IPIV( K ) = KP ELSE IPIV( K ) = -KP IPIV( K-1 ) = -KP END IF * * Decrease K and return to the start of the main loop * K = K - KSTEP KC = KNC - K GO TO 10 * ELSE * * Factorize A as L*D*L**H using the lower triangle of A * * K is the main loop index, increasing from 1 to N in steps of * 1 or 2 * K = 1 KC = 1 NPP = N*( N+1 ) / 2 60 CONTINUE KNC = KC * * If K > N, exit from loop * IF( K.GT.N ) $ GO TO 110 KSTEP = 1 * * Determine rows and columns to be interchanged and whether * a 1-by-1 or 2-by-2 pivot block will be used * ABSAKK = ABS( REAL( AP( KC ) ) ) * * IMAX is the row-index of the largest off-diagonal element in * column K, and COLMAX is its absolute value * IF( K.LT.N ) THEN IMAX = K + ICAMAX( N-K, AP( KC+1 ), 1 ) COLMAX = CABS1( AP( KC+IMAX-K ) ) ELSE COLMAX = ZERO END IF * IF( MAX( ABSAKK, COLMAX ).EQ.ZERO ) THEN * * Column K is zero: set INFO and continue * IF( INFO.EQ.0 ) $ INFO = K KP = K AP( KC ) = REAL( AP( KC ) ) ELSE IF( ABSAKK.GE.ALPHA*COLMAX ) THEN * * no interchange, use 1-by-1 pivot block * KP = K ELSE * * JMAX is the column-index of the largest off-diagonal * element in row IMAX, and ROWMAX is its absolute value * ROWMAX = ZERO KX = KC + IMAX - K DO 70 J = K, IMAX - 1 IF( CABS1( AP( KX ) ).GT.ROWMAX ) THEN ROWMAX = CABS1( AP( KX ) ) JMAX = J END IF KX = KX + N - J 70 CONTINUE KPC = NPP - ( N-IMAX+1 )*( N-IMAX+2 ) / 2 + 1 IF( IMAX.LT.N ) THEN JMAX = IMAX + ICAMAX( N-IMAX, AP( KPC+1 ), 1 ) ROWMAX = MAX( ROWMAX, CABS1( AP( KPC+JMAX-IMAX ) ) ) END IF * IF( ABSAKK.GE.ALPHA*COLMAX*( COLMAX / ROWMAX ) ) THEN * * no interchange, use 1-by-1 pivot block * KP = K ELSE IF( ABS( REAL( AP( KPC ) ) ).GE.ALPHA*ROWMAX ) THEN * * interchange rows and columns K and IMAX, use 1-by-1 * pivot block * KP = IMAX ELSE * * interchange rows and columns K+1 and IMAX, use 2-by-2 * pivot block * KP = IMAX KSTEP = 2 END IF END IF * KK = K + KSTEP - 1 IF( KSTEP.EQ.2 ) $ KNC = KNC + N - K + 1 IF( KP.NE.KK ) THEN * * Interchange rows and columns KK and KP in the trailing * submatrix A(k:n,k:n) * IF( KP.LT.N ) $ CALL CSWAP( N-KP, AP( KNC+KP-KK+1 ), 1, AP( KPC+1 ), $ 1 ) KX = KNC + KP - KK DO 80 J = KK + 1, KP - 1 KX = KX + N - J + 1 T = CONJG( AP( KNC+J-KK ) ) AP( KNC+J-KK ) = CONJG( AP( KX ) ) AP( KX ) = T 80 CONTINUE AP( KNC+KP-KK ) = CONJG( AP( KNC+KP-KK ) ) R1 = REAL( AP( KNC ) ) AP( KNC ) = REAL( AP( KPC ) ) AP( KPC ) = R1 IF( KSTEP.EQ.2 ) THEN AP( KC ) = REAL( AP( KC ) ) T = AP( KC+1 ) AP( KC+1 ) = AP( KC+KP-K ) AP( KC+KP-K ) = T END IF ELSE AP( KC ) = REAL( AP( KC ) ) IF( KSTEP.EQ.2 ) $ AP( KNC ) = REAL( AP( KNC ) ) END IF * * Update the trailing submatrix * IF( KSTEP.EQ.1 ) THEN * * 1-by-1 pivot block D(k): column k now holds * * W(k) = L(k)*D(k) * * where L(k) is the k-th column of L * IF( K.LT.N ) THEN * * Perform a rank-1 update of A(k+1:n,k+1:n) as * * A := A - L(k)*D(k)*L(k)**H = A - W(k)*(1/D(k))*W(k)**H * R1 = ONE / REAL( AP( KC ) ) CALL CHPR( UPLO, N-K, -R1, AP( KC+1 ), 1, $ AP( KC+N-K+1 ) ) * * Store L(k) in column K * CALL CSSCAL( N-K, R1, AP( KC+1 ), 1 ) END IF ELSE * * 2-by-2 pivot block D(k): columns K and K+1 now hold * * ( W(k) W(k+1) ) = ( L(k) L(k+1) )*D(k) * * where L(k) and L(k+1) are the k-th and (k+1)-th columns * of L * IF( K.LT.N-1 ) THEN * * Perform a rank-2 update of A(k+2:n,k+2:n) as * * A := A - ( L(k) L(k+1) )*D(k)*( L(k) L(k+1) )**H * = A - ( W(k) W(k+1) )*inv(D(k))*( W(k) W(k+1) )**H * * where L(k) and L(k+1) are the k-th and (k+1)-th * columns of L * D = SLAPY2( REAL( AP( K+1+( K-1 )*( 2*N-K ) / 2 ) ), $ AIMAG( AP( K+1+( K-1 )*( 2*N-K ) / 2 ) ) ) D11 = REAL( AP( K+1+K*( 2*N-K-1 ) / 2 ) ) / D D22 = REAL( AP( K+( K-1 )*( 2*N-K ) / 2 ) ) / D TT = ONE / ( D11*D22-ONE ) D21 = AP( K+1+( K-1 )*( 2*N-K ) / 2 ) / D D = TT / D * DO 100 J = K + 2, N WK = D*( D11*AP( J+( K-1 )*( 2*N-K ) / 2 )-D21* $ AP( J+K*( 2*N-K-1 ) / 2 ) ) WKP1 = D*( D22*AP( J+K*( 2*N-K-1 ) / 2 )- $ CONJG( D21 )*AP( J+( K-1 )*( 2*N-K ) / 2 ) ) DO 90 I = J, N AP( I+( J-1 )*( 2*N-J ) / 2 ) = AP( I+( J-1 )* $ ( 2*N-J ) / 2 ) - AP( I+( K-1 )*( 2*N-K ) / $ 2 )*CONJG( WK ) - AP( I+K*( 2*N-K-1 ) / 2 )* $ CONJG( WKP1 ) 90 CONTINUE AP( J+( K-1 )*( 2*N-K ) / 2 ) = WK AP( J+K*( 2*N-K-1 ) / 2 ) = WKP1 AP( J+( J-1 )*( 2*N-J ) / 2 ) $ = CMPLX( REAL( AP( J+( J-1 )*( 2*N-J ) / 2 ) ), $ 0.0E+0 ) 100 CONTINUE END IF END IF END IF * * Store details of the interchanges in IPIV * IF( KSTEP.EQ.1 ) THEN IPIV( K ) = KP ELSE IPIV( K ) = -KP IPIV( K+1 ) = -KP END IF * * Increase K and return to the start of the main loop * K = K + KSTEP KC = KNC + N - K + 2 GO TO 60 * END IF * 110 CONTINUE RETURN * * End of CHPTRF * END
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/cgetri.f
29
7421
*> \brief \b CGETRI * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download CGETRI + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cgetri.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cgetri.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cgetri.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE CGETRI( N, A, LDA, IPIV, WORK, LWORK, INFO ) * * .. Scalar Arguments .. * INTEGER INFO, LDA, LWORK, N * .. * .. Array Arguments .. * INTEGER IPIV( * ) * COMPLEX A( LDA, * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> CGETRI computes the inverse of a matrix using the LU factorization *> computed by CGETRF. *> *> This method inverts U and then computes inv(A) by solving the system *> inv(A)*L = inv(U) for inv(A). *> \endverbatim * * Arguments: * ========== * *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix A. N >= 0. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX array, dimension (LDA,N) *> On entry, the factors L and U from the factorization *> A = P*L*U as computed by CGETRF. *> On exit, if INFO = 0, the inverse of the original matrix A. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,N). *> \endverbatim *> *> \param[in] IPIV *> \verbatim *> IPIV is INTEGER array, dimension (N) *> The pivot indices from CGETRF; for 1<=i<=N, row i of the *> matrix was interchanged with row IPIV(i). *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is COMPLEX array, dimension (MAX(1,LWORK)) *> On exit, if INFO=0, then WORK(1) returns the optimal LWORK. *> \endverbatim *> *> \param[in] LWORK *> \verbatim *> LWORK is INTEGER *> The dimension of the array WORK. LWORK >= max(1,N). *> For optimal performance LWORK >= N*NB, where NB is *> the optimal blocksize returned by ILAENV. *> *> If LWORK = -1, then 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 by XERBLA. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> > 0: if INFO = i, U(i,i) is exactly zero; the matrix is *> singular and its inverse could not be computed. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup complexGEcomputational * * ===================================================================== SUBROUTINE CGETRI( N, A, LDA, IPIV, WORK, LWORK, INFO ) * * -- LAPACK computational routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. INTEGER INFO, LDA, LWORK, N * .. * .. Array Arguments .. INTEGER IPIV( * ) COMPLEX A( LDA, * ), WORK( * ) * .. * * ===================================================================== * * .. Parameters .. COMPLEX ZERO, ONE PARAMETER ( ZERO = ( 0.0E+0, 0.0E+0 ), $ ONE = ( 1.0E+0, 0.0E+0 ) ) * .. * .. Local Scalars .. LOGICAL LQUERY INTEGER I, IWS, J, JB, JJ, JP, LDWORK, LWKOPT, NB, $ NBMIN, NN * .. * .. External Functions .. INTEGER ILAENV EXTERNAL ILAENV * .. * .. External Subroutines .. EXTERNAL CGEMM, CGEMV, CSWAP, CTRSM, CTRTRI, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX, MIN * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 NB = ILAENV( 1, 'CGETRI', ' ', N, -1, -1, -1 ) LWKOPT = N*NB WORK( 1 ) = LWKOPT LQUERY = ( LWORK.EQ.-1 ) IF( N.LT.0 ) THEN INFO = -1 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -3 ELSE IF( LWORK.LT.MAX( 1, N ) .AND. .NOT.LQUERY ) THEN INFO = -6 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'CGETRI', -INFO ) RETURN ELSE IF( LQUERY ) THEN RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * * Form inv(U). If INFO > 0 from CTRTRI, then U is singular, * and the inverse is not computed. * CALL CTRTRI( 'Upper', 'Non-unit', N, A, LDA, INFO ) IF( INFO.GT.0 ) $ RETURN * NBMIN = 2 LDWORK = N IF( NB.GT.1 .AND. NB.LT.N ) THEN IWS = MAX( LDWORK*NB, 1 ) IF( LWORK.LT.IWS ) THEN NB = LWORK / LDWORK NBMIN = MAX( 2, ILAENV( 2, 'CGETRI', ' ', N, -1, -1, -1 ) ) END IF ELSE IWS = N END IF * * Solve the equation inv(A)*L = inv(U) for inv(A). * IF( NB.LT.NBMIN .OR. NB.GE.N ) THEN * * Use unblocked code. * DO 20 J = N, 1, -1 * * Copy current column of L to WORK and replace with zeros. * DO 10 I = J + 1, N WORK( I ) = A( I, J ) A( I, J ) = ZERO 10 CONTINUE * * Compute current column of inv(A). * IF( J.LT.N ) $ CALL CGEMV( 'No transpose', N, N-J, -ONE, A( 1, J+1 ), $ LDA, WORK( J+1 ), 1, ONE, A( 1, J ), 1 ) 20 CONTINUE ELSE * * Use blocked code. * NN = ( ( N-1 ) / NB )*NB + 1 DO 50 J = NN, 1, -NB JB = MIN( NB, N-J+1 ) * * Copy current block column of L to WORK and replace with * zeros. * DO 40 JJ = J, J + JB - 1 DO 30 I = JJ + 1, N WORK( I+( JJ-J )*LDWORK ) = A( I, JJ ) A( I, JJ ) = ZERO 30 CONTINUE 40 CONTINUE * * Compute current block column of inv(A). * IF( J+JB.LE.N ) $ CALL CGEMM( 'No transpose', 'No transpose', N, JB, $ N-J-JB+1, -ONE, A( 1, J+JB ), LDA, $ WORK( J+JB ), LDWORK, ONE, A( 1, J ), LDA ) CALL CTRSM( 'Right', 'Lower', 'No transpose', 'Unit', N, JB, $ ONE, WORK( J ), LDWORK, A( 1, J ), LDA ) 50 CONTINUE END IF * * Apply column interchanges. * DO 60 J = N - 1, 1, -1 JP = IPIV( J ) IF( JP.NE.J ) $ CALL CSWAP( N, A( 1, J ), 1, A( 1, JP ), 1 ) 60 CONTINUE * WORK( 1 ) = IWS RETURN * * End of CGETRI * END
bsd-3-clause
nicjhan/MOM5
src/mom5/ocean_param/gotm-4.0/util/diff_face.F90
10
4290
#include"cppdefs.h" !----------------------------------------------------------------------- !BOP ! ! !ROUTINE: Diffusion schemes --- grid faces\label{sec:diffusionFace} ! ! !INTERFACE: subroutine diff_face(N,dt,cnpar,h,Bcup,Bcdw,Yup,Ydw,nuY,Lsour,Qsour,Y) ! ! !DESCRIPTION: ! ! !USES: use util, only : Dirichlet, Neumann use mtridiagonal IMPLICIT NONE ! ! !INPUT PARAMETERS: ! number of vertical layers integer, intent(in) :: N ! time step (s) REALTYPE, intent(in) :: dt ! "implicitness" parameter REALTYPE, intent(in) :: cnpar ! layer thickness (m) REALTYPE, intent(in) :: h(0:N) ! type of upper BC integer, intent(in) :: Bcup ! type of lower BC integer, intent(in) :: Bcdw ! value of upper BC REALTYPE, intent(in) :: Yup ! value of lower BC REALTYPE, intent(in) :: Ydw ! diffusivity of Y REALTYPE, intent(in) :: nuY(0:N) ! linear source term ! (treated implicitly) REALTYPE, intent(in) :: Lsour(0:N) ! constant source term ! (treated explicitly) REALTYPE, intent(in) :: Qsour(0:N) ! !INPUT/OUTPUT PARAMETERS: REALTYPE :: Y(0:N) ! ! !REVISION HISTORY: ! Original author(s): Lars Umlauf ! ! $Log: diff_face.F90,v $ ! Revision 20.0 2013/12/14 00:14:00 fms ! Merged revision 1.1.2.1 onto trunk ! ! Revision 1.1.2.1 2012/05/15 16:01:18 smg ! initial cvs ci to mom5 ! AUTHOR:Griffies ! REVIEWERS: ! TEST STATUS: ! CHANGES PUBLIC INTERFACES? ! CHANGES ANSWERS? ! ! Revision 1.1.2.1.390.1 2012/04/23 20:33:41 smg ! updated to gotm-2012.03.09 CVS tagged code. ! AUTHOR:Martin Schmidt ! REVIEWERS:Griffies ! TEST STATUS: ! CHANGES PUBLIC INTERFACES? ! CHANGES ANSWERS? ! ! Revision 1.3 2005-11-03 20:56:55 hb ! Source term linearisation now fully explicit again, reversion to old method ! ! Revision 1.2 2005/09/16 13:54:02 lars ! added missing IMPLICIT NONE ! ! Revision 1.1 2005/06/27 10:54:33 kbk ! new files needed ! ! !EOP ! ! !LOCAL VARIABLES: integer :: i REALTYPE :: a,c,l ! !----------------------------------------------------------------------- !BOC ! ! set up matrix do i=2,N-2 c = dt*( nuY(i+1) + nuY(i ) ) / ( h(i)+h(i+1) ) / h(i+1) a = dt*( nuY(i ) + nuY(i-1) ) / ( h(i)+h(i+1) ) / h(i ) l = dt*Lsour(i) cu(i) =-cnpar*c au(i) =-cnpar*a bu(i) = _ONE_ + cnpar*(a + c) - l du(i) = (_ONE_ - (_ONE_-cnpar)*(a + c))*Y(i) & + (_ONE_ - cnpar)*( a*Y(i-1) + c*Y(i+1) ) + dt*Qsour(i) end do ! set up upper boundary condition select case(Bcup) case(Neumann) a = dt*( nuY(N-1) + nuY(N-2) ) / ( h(N-1)+h(N) ) / h(N-1) l = dt*Lsour(N-1) au(N-1) =-cnpar*a bu(N-1) = _ONE_ + cnpar*a - l du(N-1) = (_ONE_ - (_ONE_-cnpar)*a)*Y(N-1) & + (_ONE_ - cnpar)*a*Y(N-2) + dt*Qsour(N-1) & + 2.0*dt*Yup/( h(N-1)+h(N) ) case(Dirichlet) au(N-1) = _ZERO_ bu(N-1) = _ONE_ du(N-1) = Yup case default FATAL 'invalid boundary condition type for upper boundary' stop 'diff_face.F90' end select ! set up lower boundary condition select case(Bcdw) case(Neumann) c = dt*( nuY(2) + nuY(1) ) / ( h(1)+h(2) ) / h(2) l = dt*Lsour(1) cu(1) =-cnpar*c bu(1) = _ONE_ + cnpar*c - l du(1) = (_ONE_ - (_ONE_-cnpar)*c)*Y(1) & + (_ONE_ - cnpar)*c*Y(2) + dt*Qsour(1) & + 2.0*dt*Ydw/( h(1)+h(2) ) case(Dirichlet) bu(1) = _ONE_ cu(1) = _ZERO_ du(1) = Ydw case default FATAL 'invalid boundary condition type for lower boundary' stop 'diff_face.F90' end select ! solve linear system call tridiagonal(N,1,N-1,Y) return end subroutine diff_face !EOC !----------------------------------------------------------------------- ! Copyright by the GOTM-team under the GNU Public License - www.gnu.org !-----------------------------------------------------------------------
gpl-2.0
pyramania/scipy
scipy/interpolate/fitpack/fpcuro.f
148
2492
subroutine fpcuro(a,b,c,d,x,n) c subroutine fpcuro finds the real zeros of a cubic polynomial c p(x) = a*x**3+b*x**2+c*x+d. c c calling sequence: c call fpcuro(a,b,c,d,x,n) c c input parameters: c a,b,c,d: real values, containing the coefficients of p(x). c c output parameters: c x : real array,length 3, which contains the real zeros of p(x) c n : integer, giving the number of real zeros of p(x). c .. c ..scalar arguments.. real*8 a,b,c,d integer n c ..array argument.. real*8 x(3) c ..local scalars.. integer i real*8 a1,b1,c1,df,disc,d1,e3,f,four,half,ovfl,pi3,p3,q,r, * step,tent,three,two,u,u1,u2,y c ..function references.. real*8 abs,max,datan,atan2,cos,sign,sqrt c set constants two = 0.2d+01 three = 0.3d+01 four = 0.4d+01 ovfl =0.1d+05 half = 0.5d+0 tent = 0.1d+0 e3 = tent/0.3d0 pi3 = datan(0.1d+01)/0.75d0 a1 = abs(a) b1 = abs(b) c1 = abs(c) d1 = abs(d) c test whether p(x) is a third degree polynomial. if(max(b1,c1,d1).lt.a1*ovfl) go to 300 c test whether p(x) is a second degree polynomial. if(max(c1,d1).lt.b1*ovfl) go to 200 c test whether p(x) is a first degree polynomial. if(d1.lt.c1*ovfl) go to 100 c p(x) is a constant function. n = 0 go to 800 c p(x) is a first degree polynomial. 100 n = 1 x(1) = -d/c go to 500 c p(x) is a second degree polynomial. 200 disc = c*c-four*b*d n = 0 if(disc.lt.0.) go to 800 n = 2 u = sqrt(disc) b1 = b+b x(1) = (-c+u)/b1 x(2) = (-c-u)/b1 go to 500 c p(x) is a third degree polynomial. 300 b1 = b/a*e3 c1 = c/a d1 = d/a q = c1*e3-b1*b1 r = b1*b1*b1+(d1-b1*c1)*half disc = q*q*q+r*r if(disc.gt.0.) go to 400 u = sqrt(abs(q)) if(r.lt.0.) u = -u p3 = atan2(sqrt(-disc),abs(r))*e3 u2 = u+u n = 3 x(1) = -u2*cos(p3)-b1 x(2) = u2*cos(pi3-p3)-b1 x(3) = u2*cos(pi3+p3)-b1 go to 500 400 u = sqrt(disc) u1 = -r+u u2 = -r-u n = 1 x(1) = sign(abs(u1)**e3,u1)+sign(abs(u2)**e3,u2)-b1 c apply a newton iteration to improve the accuracy of the roots. 500 do 700 i=1,n y = x(i) f = ((a*y+b)*y+c)*y+d df = (three*a*y+two*b)*y+c step = 0. if(abs(f).lt.abs(df)*tent) step = f/df x(i) = y-step 700 continue 800 return end
bsd-3-clause
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/dlaqsb.f
24
6377
*> \brief \b DLAQSB scales a symmetric/Hermitian band matrix, using scaling factors computed by spbequ. * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download DLAQSB + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dlaqsb.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dlaqsb.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dlaqsb.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE DLAQSB( UPLO, N, KD, AB, LDAB, S, SCOND, AMAX, EQUED ) * * .. Scalar Arguments .. * CHARACTER EQUED, UPLO * INTEGER KD, LDAB, N * DOUBLE PRECISION AMAX, SCOND * .. * .. Array Arguments .. * DOUBLE PRECISION AB( LDAB, * ), S( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DLAQSB equilibrates a symmetric band matrix A using the scaling *> factors in the vector S. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> Specifies whether the upper or lower triangular part of the *> symmetric matrix A is stored. *> = 'U': Upper triangular *> = 'L': Lower triangular *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix A. N >= 0. *> \endverbatim *> *> \param[in] KD *> \verbatim *> KD is INTEGER *> The number of super-diagonals of the matrix A if UPLO = 'U', *> or the number of sub-diagonals if UPLO = 'L'. KD >= 0. *> \endverbatim *> *> \param[in,out] AB *> \verbatim *> AB is DOUBLE PRECISION array, dimension (LDAB,N) *> On entry, the upper or lower triangle of the symmetric band *> matrix A, stored in the first KD+1 rows of the array. The *> j-th column of A is stored in the j-th column of the array AB *> as follows: *> if UPLO = 'U', AB(kd+1+i-j,j) = A(i,j) for max(1,j-kd)<=i<=j; *> if UPLO = 'L', AB(1+i-j,j) = A(i,j) for j<=i<=min(n,j+kd). *> *> On exit, if INFO = 0, the triangular factor U or L from the *> Cholesky factorization A = U**T*U or A = L*L**T of the band *> matrix A, in the same storage format as A. *> \endverbatim *> *> \param[in] LDAB *> \verbatim *> LDAB is INTEGER *> The leading dimension of the array AB. LDAB >= KD+1. *> \endverbatim *> *> \param[in] S *> \verbatim *> S is DOUBLE PRECISION array, dimension (N) *> The scale factors for A. *> \endverbatim *> *> \param[in] SCOND *> \verbatim *> SCOND is DOUBLE PRECISION *> Ratio of the smallest S(i) to the largest S(i). *> \endverbatim *> *> \param[in] AMAX *> \verbatim *> AMAX is DOUBLE PRECISION *> Absolute value of largest matrix entry. *> \endverbatim *> *> \param[out] EQUED *> \verbatim *> EQUED is CHARACTER*1 *> Specifies whether or not equilibration was done. *> = 'N': No equilibration. *> = 'Y': Equilibration was done, i.e., A has been replaced by *> diag(S) * A * diag(S). *> \endverbatim * *> \par Internal Parameters: * ========================= *> *> \verbatim *> THRESH is a threshold value used to decide if scaling should be done *> based on the ratio of the scaling factors. If SCOND < THRESH, *> scaling is done. *> *> LARGE and SMALL are threshold values used to decide if scaling should *> be done based on the absolute size of the largest matrix element. *> If AMAX > LARGE or AMAX < SMALL, scaling is done. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date September 2012 * *> \ingroup doubleOTHERauxiliary * * ===================================================================== SUBROUTINE DLAQSB( UPLO, N, KD, AB, LDAB, S, SCOND, AMAX, EQUED ) * * -- LAPACK auxiliary routine (version 3.4.2) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * September 2012 * * .. Scalar Arguments .. CHARACTER EQUED, UPLO INTEGER KD, LDAB, N DOUBLE PRECISION AMAX, SCOND * .. * .. Array Arguments .. DOUBLE PRECISION AB( LDAB, * ), S( * ) * .. * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ONE, THRESH PARAMETER ( ONE = 1.0D+0, THRESH = 0.1D+0 ) * .. * .. Local Scalars .. INTEGER I, J DOUBLE PRECISION CJ, LARGE, SMALL * .. * .. External Functions .. LOGICAL LSAME DOUBLE PRECISION DLAMCH EXTERNAL LSAME, DLAMCH * .. * .. Intrinsic Functions .. INTRINSIC MAX, MIN * .. * .. Executable Statements .. * * Quick return if possible * IF( N.LE.0 ) THEN EQUED = 'N' RETURN END IF * * Initialize LARGE and SMALL. * SMALL = DLAMCH( 'Safe minimum' ) / DLAMCH( 'Precision' ) LARGE = ONE / SMALL * IF( SCOND.GE.THRESH .AND. AMAX.GE.SMALL .AND. AMAX.LE.LARGE ) THEN * * No equilibration * EQUED = 'N' ELSE * * Replace A by diag(S) * A * diag(S). * IF( LSAME( UPLO, 'U' ) ) THEN * * Upper triangle of A is stored in band format. * DO 20 J = 1, N CJ = S( J ) DO 10 I = MAX( 1, J-KD ), J AB( KD+1+I-J, J ) = CJ*S( I )*AB( KD+1+I-J, J ) 10 CONTINUE 20 CONTINUE ELSE * * Lower triangle of A is stored. * DO 40 J = 1, N CJ = S( J ) DO 30 I = J, MIN( N, J+KD ) AB( 1+I-J, J ) = CJ*S( I )*AB( 1+I-J, J ) 30 CONTINUE 40 CONTINUE END IF EQUED = 'Y' END IF * RETURN * * End of DLAQSB * END
bsd-3-clause
shernshiou/CarND
Term3/01-CarND-Path-Planning-Project/src/Eigen-3.3/lapack/zlarf.f
281
6278
*> \brief \b ZLARF * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download ZLARF + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zlarf.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zlarf.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zlarf.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE ZLARF( SIDE, M, N, V, INCV, TAU, C, LDC, WORK ) * * .. Scalar Arguments .. * CHARACTER SIDE * INTEGER INCV, LDC, M, N * COMPLEX*16 TAU * .. * .. Array Arguments .. * COMPLEX*16 C( LDC, * ), V( * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> ZLARF applies a complex elementary reflector H to a complex M-by-N *> matrix C, from either the left or the right. H is represented in the *> form *> *> H = I - tau * v * v**H *> *> where tau is a complex scalar and v is a complex vector. *> *> If tau = 0, then H is taken to be the unit matrix. *> *> To apply H**H, supply conjg(tau) instead *> tau. *> \endverbatim * * Arguments: * ========== * *> \param[in] SIDE *> \verbatim *> SIDE is CHARACTER*1 *> = 'L': form H * C *> = 'R': form C * H *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> The number of rows of the matrix C. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of columns of the matrix C. *> \endverbatim *> *> \param[in] V *> \verbatim *> V is COMPLEX*16 array, dimension *> (1 + (M-1)*abs(INCV)) if SIDE = 'L' *> or (1 + (N-1)*abs(INCV)) if SIDE = 'R' *> The vector v in the representation of H. V is not used if *> TAU = 0. *> \endverbatim *> *> \param[in] INCV *> \verbatim *> INCV is INTEGER *> The increment between elements of v. INCV <> 0. *> \endverbatim *> *> \param[in] TAU *> \verbatim *> TAU is COMPLEX*16 *> The value tau in the representation of H. *> \endverbatim *> *> \param[in,out] C *> \verbatim *> C is COMPLEX*16 array, dimension (LDC,N) *> On entry, the M-by-N matrix C. *> On exit, C is overwritten by the matrix H * C if SIDE = 'L', *> or C * H if SIDE = 'R'. *> \endverbatim *> *> \param[in] LDC *> \verbatim *> LDC is INTEGER *> The leading dimension of the array C. LDC >= max(1,M). *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is COMPLEX*16 array, dimension *> (N) if SIDE = 'L' *> or (M) if SIDE = 'R' *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup complex16OTHERauxiliary * * ===================================================================== SUBROUTINE ZLARF( SIDE, M, N, V, INCV, TAU, C, LDC, WORK ) * * -- LAPACK auxiliary routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER SIDE INTEGER INCV, LDC, M, N COMPLEX*16 TAU * .. * .. Array Arguments .. COMPLEX*16 C( LDC, * ), V( * ), WORK( * ) * .. * * ===================================================================== * * .. Parameters .. COMPLEX*16 ONE, ZERO PARAMETER ( ONE = ( 1.0D+0, 0.0D+0 ), $ ZERO = ( 0.0D+0, 0.0D+0 ) ) * .. * .. Local Scalars .. LOGICAL APPLYLEFT INTEGER I, LASTV, LASTC * .. * .. External Subroutines .. EXTERNAL ZGEMV, ZGERC * .. * .. External Functions .. LOGICAL LSAME INTEGER ILAZLR, ILAZLC EXTERNAL LSAME, ILAZLR, ILAZLC * .. * .. Executable Statements .. * APPLYLEFT = LSAME( SIDE, 'L' ) LASTV = 0 LASTC = 0 IF( TAU.NE.ZERO ) THEN * Set up variables for scanning V. LASTV begins pointing to the end * of V. IF( APPLYLEFT ) THEN LASTV = M ELSE LASTV = N END IF IF( INCV.GT.0 ) THEN I = 1 + (LASTV-1) * INCV ELSE I = 1 END IF * Look for the last non-zero row in V. DO WHILE( LASTV.GT.0 .AND. V( I ).EQ.ZERO ) LASTV = LASTV - 1 I = I - INCV END DO IF( APPLYLEFT ) THEN * Scan for the last non-zero column in C(1:lastv,:). LASTC = ILAZLC(LASTV, N, C, LDC) ELSE * Scan for the last non-zero row in C(:,1:lastv). LASTC = ILAZLR(M, LASTV, C, LDC) END IF END IF * Note that lastc.eq.0 renders the BLAS operations null; no special * case is needed at this level. IF( APPLYLEFT ) THEN * * Form H * C * IF( LASTV.GT.0 ) THEN * * w(1:lastc,1) := C(1:lastv,1:lastc)**H * v(1:lastv,1) * CALL ZGEMV( 'Conjugate transpose', LASTV, LASTC, ONE, $ C, LDC, V, INCV, ZERO, WORK, 1 ) * * C(1:lastv,1:lastc) := C(...) - v(1:lastv,1) * w(1:lastc,1)**H * CALL ZGERC( LASTV, LASTC, -TAU, V, INCV, WORK, 1, C, LDC ) END IF ELSE * * Form C * H * IF( LASTV.GT.0 ) THEN * * w(1:lastc,1) := C(1:lastc,1:lastv) * v(1:lastv,1) * CALL ZGEMV( 'No transpose', LASTC, LASTV, ONE, C, LDC, $ V, INCV, ZERO, WORK, 1 ) * * C(1:lastc,1:lastv) := C(...) - w(1:lastc,1) * v(1:lastv,1)**H * CALL ZGERC( LASTC, LASTV, -TAU, WORK, 1, V, INCV, C, LDC ) END IF END IF RETURN * * End of ZLARF * END
mit
zakki/lsd_slam_windows
thirdparty/eigen-3.2.5/lapack/zlarf.f
281
6278
*> \brief \b ZLARF * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download ZLARF + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zlarf.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zlarf.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zlarf.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE ZLARF( SIDE, M, N, V, INCV, TAU, C, LDC, WORK ) * * .. Scalar Arguments .. * CHARACTER SIDE * INTEGER INCV, LDC, M, N * COMPLEX*16 TAU * .. * .. Array Arguments .. * COMPLEX*16 C( LDC, * ), V( * ), WORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> ZLARF applies a complex elementary reflector H to a complex M-by-N *> matrix C, from either the left or the right. H is represented in the *> form *> *> H = I - tau * v * v**H *> *> where tau is a complex scalar and v is a complex vector. *> *> If tau = 0, then H is taken to be the unit matrix. *> *> To apply H**H, supply conjg(tau) instead *> tau. *> \endverbatim * * Arguments: * ========== * *> \param[in] SIDE *> \verbatim *> SIDE is CHARACTER*1 *> = 'L': form H * C *> = 'R': form C * H *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> The number of rows of the matrix C. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of columns of the matrix C. *> \endverbatim *> *> \param[in] V *> \verbatim *> V is COMPLEX*16 array, dimension *> (1 + (M-1)*abs(INCV)) if SIDE = 'L' *> or (1 + (N-1)*abs(INCV)) if SIDE = 'R' *> The vector v in the representation of H. V is not used if *> TAU = 0. *> \endverbatim *> *> \param[in] INCV *> \verbatim *> INCV is INTEGER *> The increment between elements of v. INCV <> 0. *> \endverbatim *> *> \param[in] TAU *> \verbatim *> TAU is COMPLEX*16 *> The value tau in the representation of H. *> \endverbatim *> *> \param[in,out] C *> \verbatim *> C is COMPLEX*16 array, dimension (LDC,N) *> On entry, the M-by-N matrix C. *> On exit, C is overwritten by the matrix H * C if SIDE = 'L', *> or C * H if SIDE = 'R'. *> \endverbatim *> *> \param[in] LDC *> \verbatim *> LDC is INTEGER *> The leading dimension of the array C. LDC >= max(1,M). *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is COMPLEX*16 array, dimension *> (N) if SIDE = 'L' *> or (M) if SIDE = 'R' *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup complex16OTHERauxiliary * * ===================================================================== SUBROUTINE ZLARF( SIDE, M, N, V, INCV, TAU, C, LDC, WORK ) * * -- LAPACK auxiliary routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER SIDE INTEGER INCV, LDC, M, N COMPLEX*16 TAU * .. * .. Array Arguments .. COMPLEX*16 C( LDC, * ), V( * ), WORK( * ) * .. * * ===================================================================== * * .. Parameters .. COMPLEX*16 ONE, ZERO PARAMETER ( ONE = ( 1.0D+0, 0.0D+0 ), $ ZERO = ( 0.0D+0, 0.0D+0 ) ) * .. * .. Local Scalars .. LOGICAL APPLYLEFT INTEGER I, LASTV, LASTC * .. * .. External Subroutines .. EXTERNAL ZGEMV, ZGERC * .. * .. External Functions .. LOGICAL LSAME INTEGER ILAZLR, ILAZLC EXTERNAL LSAME, ILAZLR, ILAZLC * .. * .. Executable Statements .. * APPLYLEFT = LSAME( SIDE, 'L' ) LASTV = 0 LASTC = 0 IF( TAU.NE.ZERO ) THEN * Set up variables for scanning V. LASTV begins pointing to the end * of V. IF( APPLYLEFT ) THEN LASTV = M ELSE LASTV = N END IF IF( INCV.GT.0 ) THEN I = 1 + (LASTV-1) * INCV ELSE I = 1 END IF * Look for the last non-zero row in V. DO WHILE( LASTV.GT.0 .AND. V( I ).EQ.ZERO ) LASTV = LASTV - 1 I = I - INCV END DO IF( APPLYLEFT ) THEN * Scan for the last non-zero column in C(1:lastv,:). LASTC = ILAZLC(LASTV, N, C, LDC) ELSE * Scan for the last non-zero row in C(:,1:lastv). LASTC = ILAZLR(M, LASTV, C, LDC) END IF END IF * Note that lastc.eq.0 renders the BLAS operations null; no special * case is needed at this level. IF( APPLYLEFT ) THEN * * Form H * C * IF( LASTV.GT.0 ) THEN * * w(1:lastc,1) := C(1:lastv,1:lastc)**H * v(1:lastv,1) * CALL ZGEMV( 'Conjugate transpose', LASTV, LASTC, ONE, $ C, LDC, V, INCV, ZERO, WORK, 1 ) * * C(1:lastv,1:lastc) := C(...) - v(1:lastv,1) * w(1:lastc,1)**H * CALL ZGERC( LASTV, LASTC, -TAU, V, INCV, WORK, 1, C, LDC ) END IF ELSE * * Form C * H * IF( LASTV.GT.0 ) THEN * * w(1:lastc,1) := C(1:lastc,1:lastv) * v(1:lastv,1) * CALL ZGEMV( 'No transpose', LASTC, LASTV, ONE, C, LDC, $ V, INCV, ZERO, WORK, 1 ) * * C(1:lastc,1:lastv) := C(...) - w(1:lastc,1) * v(1:lastv,1)**H * CALL ZGERC( LASTC, LASTV, -TAU, WORK, 1, V, INCV, C, LDC ) END IF END IF RETURN * * End of ZLARF * END
gpl-3.0
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/SRC/dstevr.f
5
19011
*> \brief <b> DSTEVR computes the eigenvalues and, optionally, the left and/or right eigenvectors for OTHER matrices</b> * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download DSTEVR + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dstevr.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dstevr.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dstevr.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE DSTEVR( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, ABSTOL, * M, W, Z, LDZ, ISUPPZ, WORK, LWORK, IWORK, * LIWORK, INFO ) * * .. Scalar Arguments .. * CHARACTER JOBZ, RANGE * INTEGER IL, INFO, IU, LDZ, LIWORK, LWORK, M, N * DOUBLE PRECISION ABSTOL, VL, VU * .. * .. Array Arguments .. * INTEGER ISUPPZ( * ), IWORK( * ) * DOUBLE PRECISION D( * ), E( * ), W( * ), WORK( * ), Z( LDZ, * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DSTEVR computes selected eigenvalues and, optionally, eigenvectors *> of a real 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. *> *> Whenever possible, DSTEVR calls DSTEMR to compute the *> eigenspectrum using Relatively Robust Representations. DSTEMR *> computes eigenvalues by the dqds algorithm, while orthogonal *> eigenvectors are computed from various "good" L D L^T 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 i-th *> unreduced block of T, *> (a) Compute T - sigma_i = L_i D_i L_i^T, such that L_i D_i L_i^T *> is a relatively robust representation, *> (b) Compute the eigenvalues, lambda_j, of L_i D_i L_i^T to high *> relative accuracy by the dqds algorithm, *> (c) If there is a cluster of close eigenvalues, "choose" sigma_i *> close to the cluster, and go to step (a), *> (d) Given the approximate eigenvalue lambda_j of L_i D_i L_i^T, *> compute the corresponding eigenvector by forming a *> rank-revealing twisted factorization. *> The desired accuracy of the output can be specified by the input *> parameter ABSTOL. *> *> For more details, see "A new O(n^2) algorithm for the symmetric *> tridiagonal eigenvalue/eigenvector problem", by Inderjit Dhillon, *> Computer Science Division Technical Report No. UCB//CSD-97-971, *> UC Berkeley, May 1997. *> *> *> Note 1 : DSTEVR calls DSTEMR when the full spectrum is requested *> on machines which conform to the ieee-754 floating point standard. *> DSTEVR calls DSTEBZ and DSTEIN on non-ieee machines and *> when partial spectrum requests are made. *> *> Normal execution of DSTEMR may create NaNs and infinities and *> hence may abort due to a floating point exception in environments *> which do not handle NaNs and infinities in the ieee standard default *> manner. *> \endverbatim * * Arguments: * ========== * *> \param[in] JOBZ *> \verbatim *> JOBZ is CHARACTER*1 *> = 'N': Compute eigenvalues only; *> = 'V': Compute eigenvalues and eigenvectors. *> \endverbatim *> *> \param[in] RANGE *> \verbatim *> RANGE is CHARACTER*1 *> = 'A': all eigenvalues will be found. *> = 'V': all eigenvalues in the half-open interval (VL,VU] *> will be found. *> = 'I': the IL-th through IU-th eigenvalues will be found. *> For RANGE = 'V' or 'I' and IU - IL < N - 1, DSTEBZ and *> DSTEIN are called *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The order of the matrix. N >= 0. *> \endverbatim *> *> \param[in,out] D *> \verbatim *> D is DOUBLE PRECISION array, dimension (N) *> On entry, the n diagonal elements of the tridiagonal matrix *> A. *> On exit, D may be multiplied by a constant factor chosen *> to avoid over/underflow in computing the eigenvalues. *> \endverbatim *> *> \param[in,out] E *> \verbatim *> E is DOUBLE PRECISION array, dimension (max(1,N-1)) *> On entry, the (n-1) subdiagonal elements of the tridiagonal *> matrix A in elements 1 to N-1 of E. *> On exit, E may be multiplied by a constant factor chosen *> to avoid over/underflow in computing the eigenvalues. *> \endverbatim *> *> \param[in] VL *> \verbatim *> VL is DOUBLE PRECISION *> \endverbatim *> *> \param[in] VU *> \verbatim *> VU is DOUBLE PRECISION *> If RANGE='V', the lower and upper bounds of the interval to *> be searched for eigenvalues. VL < VU. *> Not referenced if RANGE = 'A' or 'I'. *> \endverbatim *> *> \param[in] IL *> \verbatim *> IL is INTEGER *> \endverbatim *> *> \param[in] IU *> \verbatim *> IU is INTEGER *> If RANGE='I', the indices (in ascending order) of the *> smallest and largest eigenvalues to be returned. *> 1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0. *> Not referenced if RANGE = 'A' or 'V'. *> \endverbatim *> *> \param[in] ABSTOL *> \verbatim *> ABSTOL is DOUBLE PRECISION *> 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 + EPS * max( |a|,|b| ) , *> *> where EPS is the machine precision. If ABSTOL is less than *> or equal to zero, then EPS*|T| will be used in its place, *> where |T| is the 1-norm of the tridiagonal matrix obtained *> by reducing A to tridiagonal form. *> *> See "Computing Small Singular Values of Bidiagonal Matrices *> with Guaranteed High Relative Accuracy," by Demmel and *> Kahan, LAPACK Working Note #3. *> *> If high relative accuracy is important, set ABSTOL to *> DLAMCH( 'Safe minimum' ). Doing so will guarantee that *> eigenvalues are computed to high relative accuracy when *> possible in future releases. The current code does not *> make any guarantees about high relative accuracy, but *> future releases will. See J. Barlow and J. Demmel, *> "Computing Accurate Eigensystems of Scaled Diagonally *> Dominant Matrices", LAPACK Working Note #7, for a discussion *> of which matrices define their eigenvalues to high relative *> accuracy. *> \endverbatim *> *> \param[out] M *> \verbatim *> M is INTEGER *> The total number of eigenvalues found. 0 <= M <= N. *> If RANGE = 'A', M = N, and if RANGE = 'I', M = IU-IL+1. *> \endverbatim *> *> \param[out] W *> \verbatim *> W is DOUBLE PRECISION array, dimension (N) *> The first M elements contain the selected eigenvalues in *> ascending order. *> \endverbatim *> *> \param[out] Z *> \verbatim *> Z is DOUBLE PRECISION array, dimension (LDZ, max(1,M) ) *> 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 i-th *> column of Z holding the eigenvector associated with W(i). *> Note: the user 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 must be used. *> \endverbatim *> *> \param[in] LDZ *> \verbatim *> LDZ is INTEGER *> The leading dimension of the array Z. LDZ >= 1, and if *> JOBZ = 'V', LDZ >= max(1,N). *> \endverbatim *> *> \param[out] ISUPPZ *> \verbatim *> ISUPPZ is INTEGER array, dimension ( 2*max(1,M) ) *> The support of the eigenvectors in Z, i.e., the indices *> indicating the nonzero elements in Z. The i-th 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 *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is DOUBLE PRECISION array, dimension (MAX(1,LWORK)) *> On exit, if INFO = 0, WORK(1) returns the optimal (and *> minimal) LWORK. *> \endverbatim *> *> \param[in] LWORK *> \verbatim *> LWORK is INTEGER *> The dimension of the array WORK. LWORK >= max(1,20*N). *> *> If LWORK = -1, then a workspace query is assumed; the routine *> only calculates 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 message related to LWORK or *> LIWORK is issued by XERBLA. *> \endverbatim *> *> \param[out] IWORK *> \verbatim *> IWORK is INTEGER array, dimension (MAX(1,LIWORK)) *> On exit, if INFO = 0, IWORK(1) returns the optimal (and *> minimal) LIWORK. *> \endverbatim *> *> \param[in] LIWORK *> \verbatim *> LIWORK is INTEGER *> The dimension of the array IWORK. LIWORK >= max(1,10*N). *> *> If LIWORK = -1, then a workspace query is assumed; the *> routine only calculates 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 message related to *> LWORK or LIWORK is issued by XERBLA. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> > 0: Internal error *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2015 * *> \ingroup doubleOTHEReigen * *> \par Contributors: * ================== *> *> Inderjit Dhillon, IBM Almaden, USA \n *> Osni Marques, LBNL/NERSC, USA \n *> Ken Stanley, Computer Science Division, University of *> California at Berkeley, USA \n *> * ===================================================================== SUBROUTINE DSTEVR( JOBZ, RANGE, N, D, E, VL, VU, IL, IU, ABSTOL, $ M, W, Z, LDZ, ISUPPZ, WORK, LWORK, IWORK, $ LIWORK, INFO ) * * -- LAPACK driver routine (version 3.6.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2015 * * .. Scalar Arguments .. CHARACTER JOBZ, RANGE INTEGER IL, INFO, IU, LDZ, LIWORK, LWORK, M, N DOUBLE PRECISION ABSTOL, VL, VU * .. * .. Array Arguments .. INTEGER ISUPPZ( * ), IWORK( * ) DOUBLE PRECISION D( * ), E( * ), W( * ), WORK( * ), Z( LDZ, * ) * .. * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ZERO, ONE, TWO PARAMETER ( ZERO = 0.0D+0, ONE = 1.0D+0, TWO = 2.0D+0 ) * .. * .. Local Scalars .. LOGICAL ALLEIG, INDEIG, TEST, LQUERY, VALEIG, WANTZ, $ TRYRAC CHARACTER ORDER INTEGER I, IEEEOK, IMAX, INDIBL, INDIFL, INDISP, $ INDIWO, ISCALE, ITMP1, J, JJ, LIWMIN, LWMIN, $ NSPLIT DOUBLE PRECISION BIGNUM, EPS, RMAX, RMIN, SAFMIN, SIGMA, SMLNUM, $ TMP1, TNRM, VLL, VUU * .. * .. External Functions .. LOGICAL LSAME INTEGER ILAENV DOUBLE PRECISION DLAMCH, DLANST EXTERNAL LSAME, ILAENV, DLAMCH, DLANST * .. * .. External Subroutines .. EXTERNAL DCOPY, DSCAL, DSTEBZ, DSTEMR, DSTEIN, DSTERF, $ DSWAP, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX, MIN, SQRT * .. * .. Executable Statements .. * * * Test the input parameters. * IEEEOK = ILAENV( 10, 'DSTEVR', 'N', 1, 2, 3, 4 ) * WANTZ = LSAME( JOBZ, 'V' ) ALLEIG = LSAME( RANGE, 'A' ) VALEIG = LSAME( RANGE, 'V' ) INDEIG = LSAME( RANGE, 'I' ) * LQUERY = ( ( LWORK.EQ.-1 ) .OR. ( LIWORK.EQ.-1 ) ) LWMIN = MAX( 1, 20*N ) LIWMIN = MAX( 1, 10*N ) * * INFO = 0 IF( .NOT.( WANTZ .OR. LSAME( JOBZ, 'N' ) ) ) THEN INFO = -1 ELSE IF( .NOT.( ALLEIG .OR. VALEIG .OR. INDEIG ) ) THEN INFO = -2 ELSE IF( N.LT.0 ) THEN INFO = -3 ELSE IF( VALEIG ) THEN IF( N.GT.0 .AND. VU.LE.VL ) $ INFO = -7 ELSE IF( INDEIG ) THEN IF( IL.LT.1 .OR. IL.GT.MAX( 1, N ) ) THEN INFO = -8 ELSE IF( IU.LT.MIN( N, IL ) .OR. IU.GT.N ) THEN INFO = -9 END IF END IF END IF IF( INFO.EQ.0 ) THEN IF( LDZ.LT.1 .OR. ( WANTZ .AND. LDZ.LT.N ) ) THEN INFO = -14 END IF END IF * IF( INFO.EQ.0 ) THEN WORK( 1 ) = LWMIN IWORK( 1 ) = LIWMIN * IF( LWORK.LT.LWMIN .AND. .NOT.LQUERY ) THEN INFO = -17 ELSE IF( LIWORK.LT.LIWMIN .AND. .NOT.LQUERY ) THEN INFO = -19 END IF END IF * IF( INFO.NE.0 ) THEN CALL XERBLA( 'DSTEVR', -INFO ) RETURN ELSE IF( LQUERY ) THEN RETURN END IF * * Quick return if possible * M = 0 IF( N.EQ.0 ) $ RETURN * IF( N.EQ.1 ) THEN IF( ALLEIG .OR. INDEIG ) THEN M = 1 W( 1 ) = D( 1 ) ELSE IF( VL.LT.D( 1 ) .AND. VU.GE.D( 1 ) ) THEN M = 1 W( 1 ) = D( 1 ) END IF END IF IF( WANTZ ) $ Z( 1, 1 ) = ONE RETURN END IF * * Get machine constants. * SAFMIN = DLAMCH( 'Safe minimum' ) EPS = DLAMCH( 'Precision' ) SMLNUM = SAFMIN / EPS BIGNUM = ONE / SMLNUM RMIN = SQRT( SMLNUM ) RMAX = MIN( SQRT( BIGNUM ), ONE / SQRT( SQRT( SAFMIN ) ) ) * * * Scale matrix to allowable range, if necessary. * ISCALE = 0 IF( VALEIG ) THEN VLL = VL VUU = VU END IF * TNRM = DLANST( 'M', N, D, E ) IF( TNRM.GT.ZERO .AND. TNRM.LT.RMIN ) THEN ISCALE = 1 SIGMA = RMIN / TNRM ELSE IF( TNRM.GT.RMAX ) THEN ISCALE = 1 SIGMA = RMAX / TNRM END IF IF( ISCALE.EQ.1 ) THEN CALL DSCAL( N, SIGMA, D, 1 ) CALL DSCAL( N-1, SIGMA, E( 1 ), 1 ) IF( VALEIG ) THEN VLL = VL*SIGMA VUU = VU*SIGMA END IF END IF * Initialize indices into workspaces. Note: These indices are used only * if DSTERF or DSTEMR fail. * IWORK(INDIBL:INDIBL+M-1) corresponds to IBLOCK in DSTEBZ and * stores the block indices of each of the M<=N eigenvalues. INDIBL = 1 * IWORK(INDISP:INDISP+NSPLIT-1) corresponds to ISPLIT in DSTEBZ and * stores the starting and finishing indices of each block. INDISP = INDIBL + N * IWORK(INDIFL:INDIFL+N-1) stores the indices of eigenvectors * that corresponding to eigenvectors that fail to converge in * DSTEIN. This information is discarded; if any fail, the driver * returns INFO > 0. INDIFL = INDISP + N * INDIWO is the offset of the remaining integer workspace. INDIWO = INDISP + N * * If all eigenvalues are desired, then * call DSTERF or DSTEMR. If this fails for some eigenvalue, then * try DSTEBZ. * * TEST = .FALSE. IF( INDEIG ) THEN IF( IL.EQ.1 .AND. IU.EQ.N ) THEN TEST = .TRUE. END IF END IF IF( ( ALLEIG .OR. TEST ) .AND. IEEEOK.EQ.1 ) THEN CALL DCOPY( N-1, E( 1 ), 1, WORK( 1 ), 1 ) IF( .NOT.WANTZ ) THEN CALL DCOPY( N, D, 1, W, 1 ) CALL DSTERF( N, W, WORK, INFO ) ELSE CALL DCOPY( N, D, 1, WORK( N+1 ), 1 ) IF (ABSTOL .LE. TWO*N*EPS) THEN TRYRAC = .TRUE. ELSE TRYRAC = .FALSE. END IF CALL DSTEMR( JOBZ, 'A', N, WORK( N+1 ), WORK, VL, VU, IL, $ IU, M, W, Z, LDZ, N, ISUPPZ, TRYRAC, $ WORK( 2*N+1 ), LWORK-2*N, IWORK, LIWORK, INFO ) * END IF IF( INFO.EQ.0 ) THEN M = N GO TO 10 END IF INFO = 0 END IF * * Otherwise, call DSTEBZ and, if eigenvectors are desired, DSTEIN. * IF( WANTZ ) THEN ORDER = 'B' ELSE ORDER = 'E' END IF CALL DSTEBZ( RANGE, ORDER, N, VLL, VUU, IL, IU, ABSTOL, D, E, M, $ NSPLIT, W, IWORK( INDIBL ), IWORK( INDISP ), WORK, $ IWORK( INDIWO ), INFO ) * IF( WANTZ ) THEN CALL DSTEIN( N, D, E, M, W, IWORK( INDIBL ), IWORK( INDISP ), $ Z, LDZ, WORK, IWORK( INDIWO ), IWORK( INDIFL ), $ INFO ) END IF * * If matrix was scaled, then rescale eigenvalues appropriately. * 10 CONTINUE IF( ISCALE.EQ.1 ) THEN IF( INFO.EQ.0 ) THEN IMAX = M ELSE IMAX = INFO - 1 END IF CALL DSCAL( IMAX, ONE / SIGMA, W, 1 ) END IF * * If eigenvalues are not in order, then sort them, along with * eigenvectors. * IF( WANTZ ) THEN DO 30 J = 1, M - 1 I = 0 TMP1 = W( J ) DO 20 JJ = J + 1, M IF( W( JJ ).LT.TMP1 ) THEN I = JJ TMP1 = W( JJ ) END IF 20 CONTINUE * IF( I.NE.0 ) THEN ITMP1 = IWORK( I ) W( I ) = W( J ) IWORK( I ) = IWORK( J ) W( J ) = TMP1 IWORK( J ) = ITMP1 CALL DSWAP( N, Z( 1, I ), 1, Z( 1, J ), 1 ) END IF 30 CONTINUE END IF * * Causes problems with tests 19 & 20: * IF (wantz .and. INDEIG ) Z( 1,1) = Z(1,1) / 1.002 + .002 * * WORK( 1 ) = LWMIN IWORK( 1 ) = LIWMIN RETURN * * End of DSTEVR * END
bsd-3-clause
scarrazza/apfel
src/DIS/integrandspDIS.f
1
2680
************************************************************************ * * integrandspDIS.f: * * This functions return the integrands need to compute the polarised DIS * structure functions. * In order to wrap it in a form that can be fed to the integration * function DGAUSS, it is an explicit function only of the integration * variable y while it depends on the other variables: * * 1) the perturbatibe order pt, * 2) the number of active flavours wnf, * 3) the grid indices walpha and wbeta, * 4) the particular plitting function denoted by k such that: * * k combination * -------------------------- * 1 gluon * 2 pure-singlet * 3 non-singlet-plus * 4 non-singlet-minus * * 5) the structure function index: * * sf Structure Function * -------------------------- * 1 g1 * 2 gL * 3 g4 * * that are contained in the common block wrapDIS.h * ************************************************************************ * * Zero Mass coefficient functions for polarised DIS * ************************************************************************ function integrandspDISzm(y) * implicit none * include "../commons/grid.h" include "../commons/wrapDIS.h" ** * Input Variables * double precision y ** * Internal Variables * double precision z,w_int,fR,fS,fL double precision CR,CS double precision G1G1PA, G1NS1PA, G1NS1PB double precision GLNS1PA double precision G4NS1PA, G4NS1PB ** * Output Variables * double precision integrandspDISzm * * Interpolant functions * z = xg(igrid,wbeta) / y * fL = 0d0 if(walpha.eq.wbeta) fL = 1d0 * fR = w_int(inter_degree(igrid),walpha,z) fS = fR - fL * * Contructing integrands order by order * CR = 0d0 CS = 0d0 * * NLO * if(wipt.eq.1)then * g4 if(sf.eq.3)then * Non-singlet-plus/minus if(k.eq.3.or.k.eq.4)then CR = G4NS1PA(y) CS = G4NS1PB(y) endif * gL elseif(sf.eq.2)then * Non-singlet-plus/minus if(k.eq.3.or.k.eq.4)then CR = GLNS1PA(y) endif * g1 elseif(sf.eq.1)then * Gluon if(k.eq.1)then CR = G1G1PA(y) * Non-singlet-plus/minus elseif(k.eq.3.or.k.eq.4)then CR = G1NS1PA(y) CS = G1NS1PB(y) endif endif endif * integrandspDISzm = CR * fR + CS * fS * return end
gpl-3.0
anshumang/lammps-analytics
lib/linalg/lsame.f
74
3146
*> \brief \b LSAME * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * LOGICAL FUNCTION LSAME(CA,CB) * * .. Scalar Arguments .. * CHARACTER CA,CB * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> LSAME returns .TRUE. if CA is the same letter as CB regardless of *> case. *> \endverbatim * * Arguments: * ========== * *> \param[in] CA *> \verbatim *> CA is CHARACTER*1 *> \endverbatim *> *> \param[in] CB *> \verbatim *> CB is CHARACTER*1 *> CA and CB specify the single characters to be compared. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup aux_blas * * ===================================================================== LOGICAL FUNCTION LSAME(CA,CB) * * -- Reference BLAS level1 routine (version 3.1) -- * -- Reference BLAS is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER CA,CB * .. * * ===================================================================== * * .. Intrinsic Functions .. INTRINSIC ICHAR * .. * .. Local Scalars .. INTEGER INTA,INTB,ZCODE * .. * * Test if the characters are equal * LSAME = CA .EQ. CB IF (LSAME) RETURN * * Now test for equivalence if both characters are alphabetic. * ZCODE = ICHAR('Z') * * Use 'Z' rather than 'A' so that ASCII can be detected on Prime * machines, on which ICHAR returns a value with bit 8 set. * ICHAR('A') on Prime machines returns 193 which is the same as * ICHAR('A') on an EBCDIC machine. * INTA = ICHAR(CA) INTB = ICHAR(CB) * IF (ZCODE.EQ.90 .OR. ZCODE.EQ.122) THEN * * ASCII is assumed - ZCODE is the ASCII code of either lower or * upper case 'Z'. * IF (INTA.GE.97 .AND. INTA.LE.122) INTA = INTA - 32 IF (INTB.GE.97 .AND. INTB.LE.122) INTB = INTB - 32 * ELSE IF (ZCODE.EQ.233 .OR. ZCODE.EQ.169) THEN * * EBCDIC is assumed - ZCODE is the EBCDIC code of either lower or * upper case 'Z'. * IF (INTA.GE.129 .AND. INTA.LE.137 .OR. + INTA.GE.145 .AND. INTA.LE.153 .OR. + INTA.GE.162 .AND. INTA.LE.169) INTA = INTA + 64 IF (INTB.GE.129 .AND. INTB.LE.137 .OR. + INTB.GE.145 .AND. INTB.LE.153 .OR. + INTB.GE.162 .AND. INTB.LE.169) INTB = INTB + 64 * ELSE IF (ZCODE.EQ.218 .OR. ZCODE.EQ.250) THEN * * ASCII is assumed, on Prime machines - ZCODE is the ASCII code * plus 128 of either lower or upper case 'Z'. * IF (INTA.GE.225 .AND. INTA.LE.250) INTA = INTA - 32 IF (INTB.GE.225 .AND. INTB.LE.250) INTB = INTB - 32 END IF LSAME = INTA .EQ. INTB * * RETURN * * End of LSAME * END
gpl-2.0
rgwan/gcc
gcc/testsuite/gfortran.dg/contained_3.f90
136
1216
! { dg-do run } ! Tests the fix for PR33897, in which gfortran missed that the ! declaration of 'setbd' in 'nxtstg2' made it external. Also ! the ENTRY 'setbd' would conflict with the external 'setbd'. ! ! Contributed by Michael Richmond <michael.a.richmond@nasa.gov> ! MODULE ksbin1_aux_mod CONTAINS SUBROUTINE nxtstg1() INTEGER :: i i = setbd() ! available by host association. if (setbd () .ne. 99 ) call abort () END SUBROUTINE nxtstg1 SUBROUTINE nxtstg2() INTEGER :: i integer :: setbd ! makes it external. i = setbd() ! this is the PR if (setbd () .ne. 42 ) call abort () END SUBROUTINE nxtstg2 FUNCTION binden() INTEGER :: binden INTEGER :: setbd binden = 0 ENTRY setbd() setbd = 99 END FUNCTION binden END MODULE ksbin1_aux_mod PROGRAM test USE ksbin1_aux_mod, only : nxtstg1, nxtstg2 integer setbd ! setbd is external, since not use assoc. CALL nxtstg1() CALL nxtstg2() if (setbd () .ne. 42 ) call abort () call foo contains subroutine foo USE ksbin1_aux_mod ! module setbd is available if (setbd () .ne. 99 ) call abort () end subroutine END PROGRAM test INTEGER FUNCTION setbd() setbd=42 END FUNCTION setbd
gpl-2.0
scarrazza/apfel
src/DIS/g1total.f
1
2851
************************************************************************ * * g1total.f: * * This function returns the value of the inclusive structure function * g1. * ************************************************************************ function g1total(x) * implicit none ** * Input Variables * double precision x ** * Internal Variables * double precision g1light,g1charm,g1bottom,g1top ** * Output Variables * double precision g1total * g1total = g1light(x) 1 + g1charm(x) 2 + g1bottom(x) 3 + g1top(x) * return end c$$$* c$$$************************************************************************ c$$$ function F3total(x) c$$$* c$$$ implicit none c$$$* c$$$ include "../commons/grid.h" c$$$ include "../commons/StructureFunctions.h" c$$$ include "../commons/TMC.h" c$$$ include "../commons/TimeLike.h" c$$$** c$$$* Input Variables c$$$* c$$$ double precision x c$$$** c$$$* Internal Variables c$$$* c$$$ integer n c$$$ integer alpha c$$$ double precision w_int_gen c$$$ double precision tau,xi c$$$ double precision c1,c2 c$$$ double precision tol c$$$ parameter(tol=1d-10) c$$$** c$$$* Output Variables c$$$* c$$$ double precision F3total c$$$* c$$$* c$$$ if(TMC)then c$$$ tau = 1d0 + 4d0 * rhop * x**2 c$$$ xi = 2d0 * x / ( 1d0 + dsqrt(tau) ) c$$$* c$$$ c1 = x**2 / xi**2 / tau c$$$ c2 = 4d0 * rhop * x**3 / tau**1.5d0 c$$$* c$$$ if(xi.lt.xmin(1)-tol.or.xi.gt.xmax+tol)then c$$$ write(6,*) "In F3total.f:" c$$$ write(6,*) "Invalid value of x =",xi c$$$ call exit(-10) c$$$ endif c$$$ if (xi.lt.xmin(1)) xi = xmin(1) c$$$ if (xi.gt.xmax) xi = 1d0 c$$$* c$$$* Interpolation c$$$* c$$$ F3total = 0d0 c$$$ n = inter_degree(0) c$$$ do alpha=0,nin(0) c$$$ F3total = F3total + w_int_gen(n,alpha,xi) c$$$ 1 * ( c1 * F3(7,0,alpha) + c2 * I3(7,0,alpha) ) c$$$ enddo c$$$ if(dabs(F3total).le.1d-14) F3total = 0d0 c$$$ else c$$$ if(x.lt.xmin(1)-tol.or.x.gt.xmax+tol)then c$$$ write(6,*) "In F3total.f:" c$$$ write(6,*) "Invalid value of x =",x c$$$ call exit(-10) c$$$ endif c$$$ if (x.lt.xmin(1)) x = xmin(1) c$$$ if (x.gt.xmax) x = 1d0 c$$$* c$$$* Interpolation c$$$* c$$$ F3total = 0d0 c$$$ n = inter_degree(0) c$$$ do alpha=0,nin(0) c$$$ F3total = F3total + w_int_gen(n,alpha,x) * F3(7,0,alpha) c$$$ enddo c$$$ if(dabs(F3total).le.1d-14) F3total = 0d0 c$$$ endif c$$$* c$$$ if(Timelike) F3total = F3total / x c$$$* c$$$ return c$$$ end
gpl-3.0
jrper/fluidity
femtools/Intersection_finder.F90
1
28108
#include "fdebug.h" module intersection_finder_module use fldebug use quadrature use elements use parallel_tools use data_structures use sparse_tools use fields_data_types use fields_base use adjacency_lists use linked_lists use fields_allocates use parallel_fields use transform_elements #ifdef HAVE_LIBSUPERMESH use libsupermesh, only : intersections, deallocate, & & rtree_intersection_finder_reset, & & rtree_intersection_finder_query_output, & & rtree_intersection_finder_get_output use libsupermesh, only : & & libsupermesh_advancing_front_intersection_finder => advancing_front_intersection_finder, & & libsupermesh_rtree_intersection_finder => rtree_intersection_finder, & & libsupermesh_rtree_intersection_finder_set_input => rtree_intersection_finder_set_input, & & libsupermesh_rtree_intersection_finder_find => rtree_intersection_finder_find #endif use supermesh_construction implicit none #ifndef HAVE_LIBSUPERMESH interface crtree_intersection_finder_set_input subroutine cintersection_finder_set_input(positions, enlist, ndim, loc, nnodes, nelements) implicit none integer, intent(in) :: ndim, loc, nnodes, nelements real, intent(in), dimension(nnodes * ndim) :: positions integer, intent(in), dimension(nelements * loc) :: enlist end subroutine cintersection_finder_set_input end interface crtree_intersection_finder_set_input interface crtree_intersection_finder_find subroutine cintersection_finder_find(positions, ndim, loc) implicit none integer, intent(in) :: ndim, loc real, dimension(ndim * loc) :: positions end subroutine cintersection_finder_find end interface crtree_intersection_finder_find interface rtree_intersection_finder_query_output subroutine cintersection_finder_query_output(nelems) implicit none integer, intent(out) :: nelems end subroutine cintersection_finder_query_output end interface rtree_intersection_finder_query_output interface rtree_intersection_finder_get_output subroutine cintersection_finder_get_output(id, nelem) implicit none integer, intent(out) :: id integer, intent(in) :: nelem end subroutine cintersection_finder_get_output end interface rtree_intersection_finder_get_output interface crtree_intersection_finder_reset subroutine cintersection_finder_reset(ntests) implicit none integer, intent(out) :: ntests end subroutine cintersection_finder_reset end interface crtree_intersection_finder_reset #endif private public :: rtree_intersection_finder_set_input, rtree_intersection_finder_find, & & rtree_intersection_finder_query_output, & & rtree_intersection_finder_get_output, rtree_intersection_finder_reset public :: tri_predicate, tet_predicate, bbox_predicate, intersection_finder, & & advancing_front_intersection_finder_seeds, & & advancing_front_intersection_finder, rtree_intersection_finder, & & brute_force_intersection_finder, verify_map contains function tri_predicate(posA, posB) result(intersects) ! dim x loc real, dimension(:, :), intent(in) :: posA, posB logical :: intersects interface function tri_tri_overlap_test_2d(p1, q1, r1, p2, q2, r2) result(f) real, dimension(2) :: p1, q1, r1, p2, q2, r2 integer :: f end function tri_tri_overlap_test_2d end interface real, dimension(2) :: p1, q1, r1, p2, q2, r2 integer :: f p1 = posA(:, 1); q1 = posA(:, 2); r1 = posA(:, 3) p2 = posB(:, 1); q2 = posB(:, 2); r2 = posB(:, 3) f = tri_tri_overlap_test_2d(p1, q1, r1, p2, q2, r2) intersects = (f == 1) end function tri_predicate function tet_predicate(posA, posB) result(intersects) ! dim x loc real, dimension(:, :), intent(in) :: posA, posB logical :: intersects interface function tet_a_tet(V1, V2) result(f) real, dimension(4, 3), intent(in) :: V1, V2 integer :: f end function tet_a_tet end interface integer :: f f = tet_a_tet(posA, posB) intersects = (f == 1) end function tet_predicate function bbox(pos) result(box) ! dim x loc real, dimension(:, :) :: pos real, dimension(size(pos, 1), 2) :: box integer :: dim, i, loc, j dim = size(pos, 1) loc = size(pos, 2) do i=1,dim box(i, 1) = pos(i, 1) box(i, 2) = pos(i, 1) do j=2,loc box(i, 1) = min(pos(i, j), box(i, 1)) box(i, 2) = max(pos(i, j), box(i, 2)) end do end do end function bbox function bbox_predicate(bboxA, bboxB) result(intersects) real, dimension(:, :), intent(in) :: bboxA, bboxB logical :: intersects integer :: dim, i intersects = .false. dim = size(bboxA, 1) do i=1,dim if (bboxA(i, 1) > bboxB(i, 2)) return if (bboxA(i, 2) < bboxB(i, 1)) return end do intersects = .true. end function bbox_predicate function intersection_finder(positionsA, positionsB) result(map_AB) !!< A simple wrapper to select an intersection finder ! The positions and meshes of A and B type(vector_field), intent(in), target :: positionsA, positionsB ! for each element in A, the intersecting elements in B type(ilist), dimension(ele_count(positionsA)) :: map_AB integer :: i #if HAVE_LIBSUPERMESH integer :: j type(intersections), dimension(:), allocatable :: lmap_AB ewrite(1, *) "In intersection_finder" allocate(lmap_AB(size(map_AB))) call libsupermesh_advancing_front_intersection_finder( & & positionsA%val, reshape(positionsA%mesh%ndglno, (/positionsA%mesh%shape%loc, ele_count(positionsA)/)), & & positionsB%val, reshape(positionsB%mesh%ndglno, (/positionsB%mesh%shape%loc, ele_count(positionsB)/)), lmap_AB) do i = 1, size(lmap_AB) do j = 1, lmap_AB(i)%n call insert(map_AB(i), lmap_AB(i)%v(j)) end do end do call deallocate(lmap_AB) deallocate(lmap_AB) ewrite(1, *) "Exiting intersection_finder" #else type(ilist) :: seeds type(inode), pointer :: node type(ilist), dimension(:), allocatable :: sub_map_AB ewrite(1, *) "In intersection_finder" ! We cannot assume connectedness, so we may have to run the ! advancing front more than once (once per connected sub-domain) seeds = advancing_front_intersection_finder_seeds(positionsA) allocate(sub_map_AB(size(map_AB))) node => seeds%firstnode do while(associated(node)) sub_map_AB = advancing_front_intersection_finder(positionsA, positionsB, seed = node%value) do i = 1, size(sub_map_AB) if(sub_map_AB(i)%length > 0) then assert(map_AB(i)%length == 0) map_AB(i) = sub_map_AB(i) end if end do node => node%next end do deallocate(sub_map_AB) call deallocate(seeds) ewrite(1, *) "Exiting intersection_finder" #endif end function intersection_finder function connected(positions) !!< Return whether the supplied coordinate field is connected. Uses a simple !!< element advancing front. type(vector_field), intent(in) :: positions logical :: connected integer :: ele, i type(csr_sparsity), pointer :: eelist logical, dimension(:), allocatable :: tested integer, dimension(:), pointer :: neigh type(ilist) :: next eelist => extract_eelist(positions) allocate(tested(ele_count(positions))) tested = .false. assert(ele_count(positions) > 0) ele = 1 tested(ele) = .true. neigh => row_m_ptr(eelist, ele) do i = 1, size(neigh) if(neigh(i) <= 0) cycle call insert(next, neigh(i)) end do do while(next%length > 0) ele = pop(next) if(tested(ele)) cycle tested(ele) = .true. neigh => row_m_ptr(eelist, ele) do i = 1, size(neigh) if(neigh(i) <= 0) cycle if(tested(neigh(i))) cycle ! Should check if neigh(i) is already in the list call insert(next, neigh(i)) end do end do ! The mesh is connected iff we see all elements in the advancing front connected = all(tested) deallocate(tested) end function connected function advancing_front_intersection_finder_seeds(positions) result(seeds) !!< Return a list of seeds for the advancing front intersection finder - one !!< seed per connected sub-domain. type(vector_field), intent(in) :: positions type(ilist) :: seeds integer :: ele, first_ele, i type(csr_sparsity), pointer :: eelist logical, dimension(:), allocatable :: tested integer, dimension(:), pointer :: neigh type(ilist) :: next eelist => extract_eelist(positions) allocate(tested(ele_count(positions))) tested = .false. first_ele = 1 do while(first_ele /= 0) ele = first_ele assert(ele > 0) assert(ele <= ele_count(positions)) assert(.not. tested(ele)) call insert(seeds, ele) tested(ele) = .true. neigh => row_m_ptr(eelist, ele) do i = 1, size(neigh) if(neigh(i) <= 0) cycle if(tested(neigh(i))) cycle call insert(next, neigh(i)) end do do while(next%length > 0) ele = pop(next) if(tested(ele)) cycle tested(ele) = .true. neigh => row_m_ptr(eelist, ele) do i = 1, size(neigh) if(neigh(i) <= 0) cycle if(tested(neigh(i))) cycle ! Should check if neigh(i) is already in the list call insert(next, neigh(i)) end do end do first_ele = next_false_loc(first_ele + 1, tested) end do assert(all(tested)) deallocate(tested) contains pure function next_false_loc(start_index, logical_vector) result(loc) integer, intent(in) :: start_index logical, dimension(:), intent(in) :: logical_vector integer :: loc integer :: i do i = start_index, size(logical_vector) if(.not. logical_vector(i)) then loc = i return end if end do loc = 0 end function next_false_loc end function advancing_front_intersection_finder_seeds #ifdef HAVE_LIBSUPERMESH function advancing_front_intersection_finder(positionsA, positionsB) result(map_AB) ! The positions and meshes of A and B type(vector_field), intent(in) :: positionsA type(vector_field), intent(in) :: positionsB ! for each element in A, the intersecting elements in B type(ilist), dimension(ele_count(positionsA)) :: map_AB integer :: i, j type(intersections), dimension(:), allocatable :: lmap_AB ewrite(1, *) "In advancing_front_intersection_finder" allocate(lmap_AB(size(map_AB))) call libsupermesh_advancing_front_intersection_finder( & & positionsA%val, reshape(positionsA%mesh%ndglno, (/positionsA%mesh%shape%loc, ele_count(positionsA)/)), & & positionsB%val, reshape(positionsB%mesh%ndglno, (/positionsB%mesh%shape%loc, ele_count(positionsB)/)), lmap_AB) do i = 1, size(lmap_AB) do j = 1, lmap_AB(i)%n call insert(map_AB(i), lmap_AB(i)%v(j)) end do end do call deallocate(lmap_AB) ewrite(1, *) "Exiting advancing_front_intersection_finder" end function advancing_front_intersection_finder #else function advancing_front_intersection_finder(positionsA, positionsB, seed) result(map_AB) ! The positions and meshes of A and B type(vector_field), intent(in), target :: positionsA, positionsB ! for each element in A, the intersecting elements in B type(ilist), dimension(ele_count(positionsA)) :: map_AB integer, optional, intent(in) :: seed ! processed_neighbour maps an element to a neighbour that has already been processed (i.e. its clue) type(integer_hash_table) :: processed_neighbour ! we also need to keep a set of the elements we've seen: this is different to ! the elements that have map_AB(ele)%length > 0 in the case where the domain ! is not simply connected! type(integer_set) :: seen_elements integer :: ele_A type(mesh_type), pointer :: mesh_A, mesh_B integer :: i, neighbour real, dimension(ele_count(positionsB), positionsB%dim, 2) :: bboxes_B integer, dimension(:), pointer :: neigh_A type(csr_sparsity), pointer :: eelist_A, eelist_B type(ilist) :: clues ewrite(1, *) "In advancing_front_intersection_finder" mesh_A => positionsA%mesh mesh_B => positionsB%mesh eelist_A => extract_eelist(mesh_A) eelist_B => extract_eelist(mesh_B) call compute_bboxes(positionsB, bboxes_B) if(present(seed)) then assert(seed > 0) assert(seed <= ele_count(positionsA)) ele_A = seed else ele_A = 1 end if map_AB(ele_A) = brute_force_search(ele_val(positionsA, ele_A), positionsB, bboxes_B) call allocate(processed_neighbour) call allocate(seen_elements) neigh_A => row_m_ptr(eelist_A, ele_A) do i=1,size(neigh_A) neighbour = neigh_A(i) if (neighbour <= 0) cycle call insert(processed_neighbour, neighbour, ele_A) end do call insert(seen_elements, ele_A) do while (key_count(processed_neighbour) > 0) call fetch_pair(processed_neighbour, 1, ele_A, neighbour) ! try to keep our memory footprint low call remove(processed_neighbour, ele_A) call insert(seen_elements, ele_A) assert(map_AB(ele_A)%length == 0) ! we haven't seen it yet clues = clueful_search(ele_val(positionsA, ele_A), map_AB(neighbour), & & bboxes_B, ele_A, neighbour) map_AB(ele_A) = advance_front(ele_val(positionsA, ele_A), positionsB, clues, bboxes_B, eelist_B) call deallocate(clues) ! Now that ele_A has been computed, make its clues available to anyone who needs them neigh_A => row_m_ptr(eelist_A, ele_A) do i=1,size(neigh_A) neighbour = neigh_A(i) if (neighbour <= 0) cycle if (has_value(seen_elements, neighbour)) then ! We've already seen it cycle end if call insert(processed_neighbour, neighbour, ele_A) end do end do assert(key_count(processed_neighbour) == 0) call deallocate(processed_neighbour) call deallocate(seen_elements) ewrite(1, *) "Exiting advancing_front_intersection_finder" contains function advance_front(posA, positionsB, clues, bboxes_B, eelist_B) result(map) real, dimension(:, :), intent(in) :: posA type(vector_field), intent(in), target :: positionsB type(ilist), intent(inout) :: clues real, dimension(:, :, :), intent(in) :: bboxes_B type(csr_sparsity), intent(in) :: eelist_B type(ilist) :: map integer, dimension(:), pointer :: neigh_B integer :: i, possible, neighbour, j logical :: intersects type(mesh_type), pointer :: mesh_B real, dimension(size(posA, 1), 2) :: bboxA integer :: ele_B type(integer_set) :: in_list type(integer_hash_table) :: possibles_tbl integer :: possible_size bboxA = bbox(posA) call allocate(in_list) call allocate(possibles_tbl) possible_size = 0 mesh_B => positionsB%mesh do while (clues%length /= 0) ele_B = pop(clues) if (.not. has_value(in_list, ele_B)) then call insert(map, ele_B) call insert(in_list, ele_B) end if ! Append all the neighbours of ele_B to possibles. neigh_B => row_m_ptr(eelist_B, ele_B) do i=1,size(neigh_B) neighbour = neigh_B(i) if (neighbour <= 0) cycle if (.not. has_value(in_list, neighbour)) then possible_size = possible_size + 1 call insert(possibles_tbl, possible_size, neighbour) call insert(in_list, neighbour) end if end do end do ! while len(possibles) != 0: ! If predicate(ele_A, ele_B) is false: remove it from possibles and add it to rejects. ! If true: add it to map and add all its neighbours not in map or rejects to map. j = 1 do while (j <= possible_size) possible = fetch(possibles_tbl, j) intersects = bbox_predicate(bboxA, bboxes_B(possible, :, :)) if (intersects) then call insert(map, possible) neigh_B => row_m_ptr(eelist_B, possible) do i=1,size(neigh_B) neighbour = neigh_B(i) if (neighbour <= 0) cycle if (.not. has_value(in_list, neighbour)) then possible_size = possible_size + 1 call insert(possibles_tbl, possible_size, neighbour) call insert(in_list, neighbour) end if end do end if j = j + 1 end do call deallocate(in_list) call deallocate(possibles_tbl) possible_size = 0 end function advance_front end function advancing_front_intersection_finder #endif function brute_force_intersection_finder(positions_a, positions_b) result(map_ab) !!< As advancing_front_intersection_finder, but uses a brute force !!< algorithm. For testing *only*. For practical applications, use the !!< linear algorithm. ! The positions and meshes of A and B type(vector_field), intent(in), target :: positions_a, positions_b ! for each element in A, the intersecting elements in B type(ilist), dimension(ele_count(positions_a)) :: map_ab integer :: i, j ewrite(1, *) "In brute_force_intersection_finder" do i = 1, ele_count(positions_a) do j = 1, ele_count(positions_b) if(bbox_predicate(bbox(ele_val(positions_a, i)), bbox(ele_val(positions_b, j)))) then call insert(map_ab(i), j) end if end do end do ewrite(1, *) "Exiting brute_force_intersection_finder" end function brute_force_intersection_finder #ifndef HAVE_LIBSUPERMESH subroutine rtree_intersection_finder_reset() integer :: ntests call crtree_intersection_finder_reset(ntests) end subroutine rtree_intersection_finder_reset #endif subroutine rtree_intersection_finder_set_input(old_positions) type(vector_field), intent(in) :: old_positions #ifdef HAVE_LIBSUPERMESH call libsupermesh_rtree_intersection_finder_set_input( & & old_positions%val, & & reshape(old_positions%mesh%ndglno, (/old_positions%mesh%shape%loc, ele_count(old_positions)/))) #else real, dimension(node_count(old_positions) * old_positions%dim) :: tmp_positions integer :: node, dim dim = old_positions%dim ! Ugh. We have to copy the memory because old_positions ! stores it as 2 or 3 separate vectors do node=1,node_count(old_positions) tmp_positions((node-1)*dim+1:node*dim) = node_val(old_positions, node) end do call crtree_intersection_finder_set_input(tmp_positions, old_positions%mesh%ndglno, dim, & & ele_loc(old_positions, 1), node_count(old_positions), & & ele_count(old_positions)) #endif end subroutine rtree_intersection_finder_set_input subroutine rtree_intersection_finder_find(new_positions, ele_B) type(vector_field), intent(in) :: new_positions integer, intent(in) :: ele_B #ifdef HAVE_LIBSUPERMESH call libsupermesh_rtree_intersection_finder_find(ele_val(new_positions, ele_B)) #else integer :: dim, loc dim = new_positions%dim loc = ele_loc(new_positions, 1) call crtree_intersection_finder_find(reshape(ele_val(new_positions, ele_B), (/dim*loc/)), dim, loc) #endif end subroutine rtree_intersection_finder_find function rtree_intersection_finder(positions_a, positions_b) result(map_ab) !!< As advancing_front_intersection_finder, but uses an rtree algorithm. For !!< testing *only*. For practical applications, use the linear algorithm. ! The positions and meshes of A and B type(vector_field), intent(in), target :: positions_a, positions_b ! for each element in A, the intersecting elements in B type(ilist), dimension(ele_count(positions_a)) :: map_ab integer :: i, j, id, nelms ewrite(1, *) "In rtree_intersection_finder" call rtree_intersection_finder_set_input(positions_b) do i = 1, ele_count(positions_a) call rtree_intersection_finder_find(positions_a, i) call rtree_intersection_finder_query_output(nelms) do j = 1, nelms call rtree_intersection_finder_get_output(id, j) call insert(map_ab(i), id) end do end do call rtree_intersection_finder_reset() ewrite(1, *) "Exiting rtree_intersection_finder" end function rtree_intersection_finder subroutine verify_map(mesh_field_a, mesh_field_b, map_ab, map_ab_reference) !!< Verify the given intersection map against a reference map. type(vector_field), intent(in) :: mesh_field_a type(vector_field), intent(in) :: mesh_field_b type(ilist), dimension(:), intent(in) :: map_ab type(ilist), dimension(:), intent(in) :: map_ab_reference integer :: dim, i, j, loc real :: reference_intersection_volume, intersection_volume real, dimension(:), allocatable :: detwei real, parameter :: relative_tolerance = 1.0e-8 type(element_type):: shape type(quadrature_type) :: quad type(inode), pointer :: node type(vector_field) :: intersection logical :: empty_intersection ewrite(1, *) "Entering verify_map" assert(mesh_field_a%dim == mesh_field_b%dim) dim = mesh_field_a%dim select case(dim) case(2) loc = 3 case(3) loc = 4 case default FLAbort("Can only verify intersection maps for dimension 2 or 3") end select quad = make_quadrature(loc, mesh_field_a%dim ,degree = mesh_field_a%mesh%shape%quadrature%degree) shape = make_element_shape(loc, mesh_field_a%dim, mesh_field_a%mesh%shape%degree, quad) call deallocate(quad) call intersector_set_dimension(mesh_field_a%dim) do i = 1, ele_count(mesh_field_a) if(map_ab(i)%length /= map_ab_reference(i)%length) then ewrite(0, "(a,i0)") "For element ", i ewrite(0, "(a,i0)") "Test number of intersections: ", map_ab(i)%length ewrite(0, "(a,i0)") "Reference number of intersections: ", map_ab_reference(i)%length ewrite(0, *) "Warning: Number of intersection elements differs" end if intersection_volume = 0.0 node => map_ab(i)%firstnode do while(associated(node)) intersection = intersect_elements(mesh_field_a, i, ele_val(mesh_field_b, node%value), shape, empty_intersection) if (empty_intersection) then node => node%next cycle end if do j = 1, ele_count(intersection) allocate(detwei(shape%ngi)) call transform_to_physical(intersection, j, detwei = detwei) intersection_volume = intersection_volume + sum(detwei) deallocate(detwei) end do call deallocate(intersection) node => node%next end do reference_intersection_volume = 0.0 node => map_ab_reference(i)%firstnode do while(associated(node)) intersection = intersect_elements(mesh_field_a, i, ele_val(mesh_field_b, node%value), shape, empty_intersection) if (empty_intersection) then node => node%next cycle end if do j = 1, ele_count(intersection) allocate(detwei(shape%ngi)) call transform_to_physical(intersection, j, detwei = detwei) reference_intersection_volume = reference_intersection_volume + sum(detwei) deallocate(detwei) end do call deallocate(intersection) node => node%next end do if(abs(intersection_volume - reference_intersection_volume) > abs(max(relative_tolerance, relative_tolerance * intersection_volume))) then ewrite(-1, "(a,i0)") "For element ", i ewrite(-1, *) "Volume of test intersection: ", intersection_volume ewrite(-1, *) "Volume of reference intersection: ", reference_intersection_volume FLAbort("Intersection volumes do not match") end if end do call deallocate(shape) ewrite(2, *) "Verification successful" ewrite(1, *) "Exiting verify_map" end subroutine verify_map #ifndef HAVE_LIBSUPERMESH subroutine compute_bboxes(positionsB, bboxes_B) type(vector_field), intent(in) :: positionsB real, dimension(:, :, :), intent(out) :: bboxes_B integer :: ele_B do ele_B=1,ele_count(positionsB) bboxes_B(ele_B, :, :) = bbox(ele_val(positionsB, ele_B)) end do end subroutine compute_bboxes function brute_force_search(posA, positionsB, bboxes_B) result(map) real, dimension(:, :), intent(in) :: posA type(vector_field), intent(in) :: positionsB real, dimension(:, :, :), intent(in) :: bboxes_B type(ilist) :: map integer :: ele_B real, dimension(size(posA, 1), 2) :: bboxA bboxA = bbox(posA) do ele_B=1,ele_count(positionsB) if (bbox_predicate(bboxA, bboxes_B(ele_B, :, :))) then call insert(map, ele_B) end if end do if (map%length == 0) then FLAbort("Should never get here -- it has to intersect /something/!") end if end function brute_force_search function clueful_search(posA, possibles, bboxes_B, ele_A, neighbour) result(clues) real, dimension(:, :), intent(in) :: posA type(ilist), intent(in) :: possibles real, dimension(:, :, :), intent(in) :: bboxes_B integer, intent(in) :: ele_A, neighbour type(inode), pointer :: node type(ilist) :: clues real, dimension(size(posA, 1), 2) :: bboxA integer :: ele_B bboxA = bbox(posA) node => possibles%firstnode do while (associated(node)) ele_B = node%value if (bbox_predicate(bboxA, bboxes_B(ele_B, :, :))) then call insert(clues, ele_B) end if node => node%next end do ! if (clues%length == 0) then ! ewrite(-1,*) "It seems something has gone rather badly wrong." ! ewrite(-1,*) "Element in A we are searching for: ", ele_A ! ewrite(-1,*) "Neighbour element we are looking for a clue from: ", neighbour ! ewrite(-1,*) "Recorded list of neighbour's intersections: " ! call print_list(possibles, -1) ! ewrite(-1,*) "I will not crash as this MIGHT happen legitimately if your" ! ewrite(-1,*) "source domain is not connected, but your target domain is connected" ! ewrite(-1,*) "across the disconnection." !! subpos = extract_elements(positionsB, list2vector(possibles)) !! call vtk_write_fields("intersection_failure", 0, subpos, subpos%mesh) !! call deallocate(subpos) !! ewrite(-1,*) "Brute forcing to find intersections of neighbour: " !! clues = brute_force_search(neighbour_posA, positionsB, bboxes_B) !! call print_list(clues, -1) !! subpos = extract_elements(positionsB, list2vector(clues)) !! call vtk_write_fields("intersection_failure", 1, subpos, subpos%mesh) !! call deallocate(subpos) !! ewrite(-1,*) "Brute forcing to find intersections of ele_A: " !! clues = brute_force_search(posA, positionsB, bboxes_B) !! call print_list(clues, -1) !! subpos = extract_elements(positionsB, list2vector(clues)) !! call vtk_write_fields("intersection_failure", 2, subpos, subpos%mesh) !! call deallocate(subpos) !! subpos = extract_elements(positionsA, (/ele_A, neighbour/)) !! call vtk_write_fields("intersection_failure", 3, subpos, subpos%mesh) !! call deallocate(subpos) !! FLAbort("Should never get here -- it has to intersect /something/!") ! end if end function clueful_search #endif end module
lgpl-2.1
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/typebound_operator_15.f90
141
1943
! { dg-do run } ! ! PR fortran/53255 ! ! Contributed by Reinhold Bader. ! ! Before TYPE(ext)'s .tr. wrongly called the base type's trace ! instead of ext's trace_ext. ! module mod_base implicit none private integer, public :: base_cnt = 0 type, public :: base private real :: r(2,2) = reshape( (/ 1.0, 2.0, 3.0, 4.0 /), (/ 2, 2 /)) contains procedure, private :: trace generic :: operator(.tr.) => trace end type base contains complex function trace(this) class(base), intent(in) :: this base_cnt = base_cnt + 1 ! write(*,*) 'executing base' trace = this%r(1,1) + this%r(2,2) end function trace end module mod_base module mod_ext use mod_base implicit none private integer, public :: ext_cnt = 0 public :: base, base_cnt type, public, extends(base) :: ext private real :: i(2,2) = reshape( (/ 1.0, 1.0, 1.0, 1.5 /), (/ 2, 2 /)) contains procedure, private :: trace => trace_ext end type ext contains complex function trace_ext(this) class(ext), intent(in) :: this ! the following should be executed through invoking .tr. p below ! write(*,*) 'executing override' ext_cnt = ext_cnt + 1 trace_ext = .tr. this%base + (0.0, 1.0) * ( this%i(1,1) + this%i(2,2) ) end function trace_ext end module mod_ext program test_override use mod_ext implicit none type(base) :: o type(ext) :: p real :: r ! Note: ext's ".tr." (trace_ext) calls also base's "trace" ! write(*,*) .tr. o ! write(*,*) .tr. p if (base_cnt /= 0 .or. ext_cnt /= 0) call abort () r = .tr. o if (base_cnt /= 1 .or. ext_cnt /= 0) call abort () r = .tr. p if (base_cnt /= 2 .or. ext_cnt /= 1) call abort () if (abs(.tr. o - 5.0 ) < 1.0e-6 .and. abs( .tr. p - (5.0,2.5)) < 1.0e-6) & then if (base_cnt /= 4 .or. ext_cnt /= 2) call abort () ! write(*,*) 'OK' else call abort() ! write(*,*) 'FAIL' end if end program test_override
gpl-2.0
rgwan/gcc
gcc/testsuite/gfortran.dg/gomp/pr29759.f90
179
1030
! PR fortran/29759 ! { dg-do compile } PROGRAM test_omp !$OMP PARALLEL & !$OMP NUM_THREADS(2) !$OMP END PARALLEL !$OMP PARALLEL & !$OMP & NUM_THREADS(2) !$OMP END PARALLEL !$OMP PARALLEL & ! !$OMP NUM_THREADS(2) !$OMP END PARALLEL !$OMP PARALLEL & ! !$OMP & NUM_THREADS(2) !$OMP END PARALLEL !$OMP PARALLEL & ! { dg-error "Unclassifiable OpenMP" } !$ NUM_THREADS(2) ! { dg-error "Unclassifiable|Invalid character" } !$OMP END PARALLEL ! { dg-error "Unexpected" } !$OMP PARALLEL & ! { dg-error "Unclassifiable OpenMP" } !$ & NUM_THREADS(2) ! { dg-error "Unclassifiable|Invalid character" } !$OMP END PARALLEL ! { dg-error "Unexpected" } !$OMP PARALLEL & ! { dg-error "Unclassifiable OpenMP" } ! !$ NUM_THREADS(2) ! { dg-error "Unclassifiable|Invalid character" } !$OMP END PARALLEL ! { dg-error "Unexpected" } !$OMP PARALLEL & ! { dg-error "Unclassifiable OpenMP" } ! !$ & NUM_THREADS(2) ! { dg-error "Unclassifiable|Invalid character" } !$OMP END PARALLEL ! { dg-error "Unexpected" } END PROGRAM
gpl-2.0
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/elemental_optional_args_6.f90
9
1652
! { dg-do run } ! { dg-options "-Wpedantic" } ! ! PR fortran/53692 ! ! Check that the nonabsent arrary is used for scalarization: ! Either the NONOPTIONAL one or, if there are none, any array. ! ! Based on a program by Daniel C Chen ! Program main implicit none integer :: arr1(2), arr2(2) arr1 = [ 1, 2 ] arr2 = [ 1, 2 ] call sub1 (arg2=arr2) call two () contains subroutine sub1 (arg1, arg2) integer, optional :: arg1(:) integer :: arg2(:) ! print *, fun1 (arg1, arg2) if (size (fun1 (arg1, arg2)) /= 2) call abort() ! { dg-warning "is an array and OPTIONAL" } if (any (fun1 (arg1, arg2) /= [1,2])) call abort() ! { dg-warning "is an array and OPTIONAL" } end subroutine elemental function fun1 (arg1, arg2) integer,intent(in), optional :: arg1 integer,intent(in) :: arg2 integer :: fun1 fun1 = arg2 end function end program subroutine two () implicit none integer :: arr1(2), arr2(2) arr1 = [ 1, 2 ] arr2 = [ 1, 2 ] call sub2 (arr1, arg2=arr2) contains subroutine sub2 (arg1, arg2) integer, optional :: arg1(:) integer, optional :: arg2(:) ! print *, fun2 (arg1, arg2) if (size (fun2 (arg1, arg2)) /= 2) call abort() ! { dg-warning "is an array and OPTIONAL" } if (any (fun2 (arg1, arg2) /= [1,2])) call abort() ! { dg-warning "is an array and OPTIONAL" } end subroutine elemental function fun2 (arg1,arg2) integer,intent(in), optional :: arg1 integer,intent(in), optional :: arg2 integer :: fun2 fun2 = arg2 end function end subroutine two
gpl-2.0
CapeDrew/DITK
Modules/ThirdParty/Netlib/src/netlib/slatec/d9gmit.f
48
2597
*DECK D9GMIT DOUBLE PRECISION FUNCTION D9GMIT (A, X, ALGAP1, SGNGAM, ALX) C***BEGIN PROLOGUE D9GMIT C***SUBSIDIARY C***PURPOSE Compute Tricomi's incomplete Gamma function for small C arguments. C***LIBRARY SLATEC (FNLIB) C***CATEGORY C7E C***TYPE DOUBLE PRECISION (R9GMIT-S, D9GMIT-D) C***KEYWORDS COMPLEMENTARY INCOMPLETE GAMMA FUNCTION, FNLIB, SMALL X, C SPECIAL FUNCTIONS, TRICOMI C***AUTHOR Fullerton, W., (LANL) C***DESCRIPTION C C Compute Tricomi's incomplete gamma function for small X. C C***REFERENCES (NONE) C***ROUTINES CALLED D1MACH, DLNGAM, XERMSG C***REVISION HISTORY (YYMMDD) C 770701 DATE WRITTEN C 890531 Changed all specific intrinsics to generic. (WRB) C 890911 Removed unnecessary intrinsics. (WRB) C 890911 REVISION DATE from Version 3.2 C 891214 Prologue converted to Version 4.0 format. (BAB) C 900315 CALLs to XERROR changed to CALLs to XERMSG. (THJ) C 900720 Routine changed from user-callable to subsidiary. (WRB) C***END PROLOGUE D9GMIT DOUBLE PRECISION A, X, ALGAP1, SGNGAM, ALX, AE, AEPS, ALGS, ALG2, 1 BOT, EPS, FK, S, SGNG2, T, TE, D1MACH, DLNGAM LOGICAL FIRST SAVE EPS, BOT, FIRST DATA FIRST /.TRUE./ C***FIRST EXECUTABLE STATEMENT D9GMIT IF (FIRST) THEN EPS = 0.5D0*D1MACH(3) BOT = LOG (D1MACH(1)) ENDIF FIRST = .FALSE. C IF (X .LE. 0.D0) CALL XERMSG ('SLATEC', 'D9GMIT', + 'X SHOULD BE GT 0', 1, 2) C MA = A + 0.5D0 IF (A.LT.0.D0) MA = A - 0.5D0 AEPS = A - MA C AE = A IF (A.LT.(-0.5D0)) AE = AEPS C T = 1.D0 TE = AE S = T DO 20 K=1,200 FK = K TE = -X*TE/FK T = TE/(AE+FK) S = S + T IF (ABS(T).LT.EPS*ABS(S)) GO TO 30 20 CONTINUE CALL XERMSG ('SLATEC', 'D9GMIT', + 'NO CONVERGENCE IN 200 TERMS OF TAYLOR-S SERIES', 2, 2) C 30 IF (A.GE.(-0.5D0)) ALGS = -ALGAP1 + LOG(S) IF (A.GE.(-0.5D0)) GO TO 60 C ALGS = -DLNGAM(1.D0+AEPS) + LOG(S) S = 1.0D0 M = -MA - 1 IF (M.EQ.0) GO TO 50 T = 1.0D0 DO 40 K=1,M T = X*T/(AEPS-(M+1-K)) S = S + T IF (ABS(T).LT.EPS*ABS(S)) GO TO 50 40 CONTINUE C 50 D9GMIT = 0.0D0 ALGS = -MA*LOG(X) + ALGS IF (S.EQ.0.D0 .OR. AEPS.EQ.0.D0) GO TO 60 C SGNG2 = SGNGAM * SIGN (1.0D0, S) ALG2 = -X - ALGAP1 + LOG(ABS(S)) C IF (ALG2.GT.BOT) D9GMIT = SGNG2 * EXP(ALG2) IF (ALGS.GT.BOT) D9GMIT = D9GMIT + EXP(ALGS) RETURN C 60 D9GMIT = EXP (ALGS) RETURN C END
apache-2.0
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/char_result_8.f90
188
1068
! Related to PR 15326. Compare functions that return string pointers with ! functions that return strings. ! { dg-do run } program main implicit none character (len = 30), target :: string call test (f1 (), 30) call test (f2 (50), 50) call test (f3 (), 30) call test (f4 (70), 70) call indirect (100) contains function f1 () character (len = 30) :: f1 f1 = '' end function f1 function f2 (i) integer :: i character (len = i) :: f2 f2 = '' end function f2 function f3 () character (len = 30), pointer :: f3 f3 => string end function f3 function f4 (i) integer :: i character (len = i), pointer :: f4 f4 => string end function f4 subroutine indirect (i) integer :: i call test (f1 (), 30) call test (f2 (i), i) call test (f3 (), 30) call test (f4 (i), i) end subroutine indirect subroutine test (string, length) character (len = *) :: string integer, intent (in) :: length if (len (string) .ne. length) call abort end subroutine test end program main
gpl-2.0
sriki18/scipy
scipy/linalg/src/id_dist/src/idd_house.f
100
6886
c this file contains the following user-callable routines: c c c routine idd_house calculates the vector and scalar c needed to apply the Householder tranformation reflecting c a given vector into its first component. c c routine idd_houseapp applies a Householder matrix to a vector. c c ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c c c c subroutine idd_houseapp(n,vn,u,ifrescal,scal,v) c c applies the Householder matrix c identity_matrix - scal * vn * transpose(vn) c to the vector u, yielding the vector v; c c scal = 2/(1 + vn(2)^2 + ... + vn(n)^2) c when vn(2), ..., vn(n) don't all vanish; c c scal = 0 c when vn(2), ..., vn(n) do all vanish c (including when n = 1). c c input: c n -- size of vn, u, and v, though the indexing on vn goes c from 2 to n c vn -- components 2 to n of the Householder vector vn; c vn(1) is assumed to be 1 c u -- vector to be transformed c ifrescal -- set to 1 to recompute scal from vn(2), ..., vn(n); c set to 0 to use scal as input c scal -- see the entry for ifrescal in the decription c of the input c c output: c scal -- see the entry for ifrescal in the decription c of the input c v -- result of applying the Householder matrix to u; c it's O.K. to have v be the same as u c in order to apply the matrix to the vector in place c c reference: c Golub and Van Loan, "Matrix Computations," 3rd edition, c Johns Hopkins University Press, 1996, Chapter 5. c implicit none save integer n,k,ifrescal real*8 vn(2:*),scal,u(n),v(n),fact,sum c c c Get out of this routine if n = 1. c if(n .eq. 1) then v(1) = u(1) return endif c c if(ifrescal .eq. 1) then c c c Calculate (vn(2))^2 + ... + (vn(n))^2. c sum = 0 do k = 2,n sum = sum+vn(k)**2 enddo ! k c c c Calculate scal. c if(sum .eq. 0) scal = 0 if(sum .ne. 0) scal = 2/(1+sum) c c endif c c c Calculate fact = scal * transpose(vn) * u. c fact = u(1) c do k = 2,n fact = fact+vn(k)*u(k) enddo ! k c fact = fact*scal c c c Subtract fact*vn from u, yielding v. c v(1) = u(1) - fact c do k = 2,n v(k) = u(k) - fact*vn(k) enddo ! k c c return end c c c c subroutine idd_house(n,x,rss,vn,scal) c c constructs the vector vn with vn(1) = 1 c and the scalar scal such that c H := identity_matrix - scal * vn * transpose(vn) is orthogonal c and Hx = +/- e_1 * the root-sum-square of the entries of x c (H is the Householder matrix corresponding to x). c c input: c n -- size of x and vn, though the indexing on vn goes c from 2 to n c x -- vector to reflect into its first component c c output: c rss -- first entry of the vector resulting from the application c of the Householder matrix to x; c its absolute value is the root-sum-square c of the entries of x c vn -- entries 2 to n of the Householder vector vn; c vn(1) is assumed to be 1 c scal -- scalar multiplying vn * transpose(vn); c c scal = 2/(1 + vn(2)^2 + ... + vn(n)^2) c when vn(2), ..., vn(n) don't all vanish; c c scal = 0 c when vn(2), ..., vn(n) do all vanish c (including when n = 1) c c reference: c Golub and Van Loan, "Matrix Computations," 3rd edition, c Johns Hopkins University Press, 1996, Chapter 5. c implicit none save integer n,k real*8 x(n),rss,sum,v1,scal,vn(2:*),x1 c c x1 = x(1) c c c Get out of this routine if n = 1. c if(n .eq. 1) then rss = x1 scal = 0 return endif c c c Calculate (x(2))^2 + ... (x(n))^2 c and the root-sum-square value of the entries in x. c c sum = 0 do k = 2,n sum = sum+x(k)**2 enddo ! k c c c Get out of this routine if sum = 0; c flag this case as such by setting v(2), ..., v(n) all to 0. c if(sum .eq. 0) then c rss = x1 do k = 2,n vn(k) = 0 enddo ! k scal = 0 c return c endif c c rss = x1**2 + sum rss = sqrt(rss) c c c Determine the first component v1 c of the unnormalized Householder vector c v = x - rss * (1 0 0 ... 0 0)^T. c c If x1 <= 0, then form x1-rss directly, c since that expression cannot involve any cancellation. c if(x1 .le. 0) v1 = x1-rss c c If x1 > 0, then use the fact that c x1-rss = -sum / (x1+rss), c in order to avoid potential cancellation. c if(x1 .gt. 0) v1 = -sum / (x1+rss) c c c Compute the vector vn and the scalar scal such that vn(1) = 1 c in the Householder transformation c identity_matrix - scal * vn * transpose(vn). c do k = 2,n vn(k) = x(k)/v1 enddo ! k c c scal = 2 c / ( vn(1)^2 + vn(2)^2 + ... + vn(n)^2 ) c c = 2 c / ( 1 + vn(2)^2 + ... + vn(n)^2 ) c c = 2*v(1)^2 c / ( v(1)^2 + (v(1)*vn(2))^2 + ... + (v(1)*vn(n))^2 ) c c = 2*v(1)^2 c / ( v(1)^2 + (v(2)^2 + ... + v(n)^2) ) c scal = 2*v1**2 / (v1**2+sum) c c return end c c c c subroutine idd_housemat(n,vn,scal,h) c c fills h with the Householder matrix c identity_matrix - scal * vn * transpose(vn). c c input: c n -- size of vn and h, though the indexing of vn goes c from 2 to n c vn -- entries 2 to n of the vector vn; c vn(1) is assumed to be 1 c scal -- scalar multiplying vn * transpose(vn) c c output: c h -- identity_matrix - scal * vn * transpose(vn) c implicit none save integer n,j,k real*8 vn(2:*),h(n,n),scal,factor1,factor2 c c c Fill h with the identity matrix. c do j = 1,n do k = 1,n c if(j .eq. k) h(k,j) = 1 if(j .ne. k) h(k,j) = 0 c enddo ! k enddo ! j c c c Subtract from h the matrix scal*vn*transpose(vn). c do j = 1,n do k = 1,n c if(j .eq. 1) factor1 = 1 if(j .ne. 1) factor1 = vn(j) c if(k .eq. 1) factor2 = 1 if(k .ne. 1) factor2 = vn(k) c h(k,j) = h(k,j) - scal*factor1*factor2 c enddo ! k enddo ! j c c return end
bsd-3-clause
rgwan/gcc
libgfortran/generated/_exp_r10.F90
47
1474
! Copyright (C) 2002-2015 Free Software Foundation, Inc. ! Contributed by Paul Brook <paul@nowt.org> ! !This file is part of the GNU Fortran 95 runtime library (libgfortran). ! !GNU libgfortran 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 3 of the License, or (at your option) any later version. !GNU libgfortran 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. ! !Under Section 7 of GPL version 3, you are granted additional !permissions described in the GCC Runtime Library Exception, version !3.1, as published by the Free Software Foundation. ! !You should have received a copy of the GNU General Public License and !a copy of the GCC Runtime Library Exception along with this program; !see the files COPYING3 and COPYING.RUNTIME respectively. If not, see !<http://www.gnu.org/licenses/>. ! !This file is machine generated. #include "config.h" #include "kinds.inc" #include "c99_protos.inc" #if defined (HAVE_GFC_REAL_10) #ifdef HAVE_EXPL elemental function _gfortran_specific__exp_r10 (parm) real (kind=10), intent (in) :: parm real (kind=10) :: _gfortran_specific__exp_r10 _gfortran_specific__exp_r10 = exp (parm) end function #endif #endif
gpl-2.0
Gd58/gcc
gcc/testsuite/gfortran.dg/g77/f77-edit-t-in.f
166
1151
C Test Fortran 77 T edit descriptor for input C (ANSI X3.9-1978 Section 13.5.3.2) C C Origin: David Billinghurst <David.Billinghurst@riotinto.com> C C { dg-do run } C { dg-options "-std=legacy" } C integer i,j real a,b,c,d,e character*32 in in = '1234 8' read(in,'(T3,I1)') i if ( i.ne.3 ) call abort() read(in,'(5X,TL4,I2)') i if ( i.ne.23 ) call abort() read(in,'(3X,I1,TR3,I1)') i,j if ( i.ne.4 ) call abort() if ( j.ne.8 ) call abort() in = ' 1.5 -12.62 348.75 1.0E-6' 100 format(F6.0,TL6,I4,1X,I1,8X,I5,F3.0,T10,F5.0,T17,F6.0,TR2,F6.0) read(in,100) a,i,j,k,b,c,d,e if ( abs(a-1.5).gt.1.0e-5 ) call abort() if ( i.ne.1 ) call abort() if ( j.ne.5 ) call abort() if ( k.ne.348 ) call abort() if ( abs(b-0.75).gt.1.0e-5 ) call abort() if ( abs(c-12.62).gt.1.0e-5 ) call abort() if ( abs(d-348.75).gt.1.0e-4 ) call abort() if ( abs(e-1.0e-6).gt.1.0e-11 ) call abort() end
gpl-2.0
rgwan/gcc
gcc/testsuite/gfortran.dg/g77/f77-edit-t-in.f
166
1151
C Test Fortran 77 T edit descriptor for input C (ANSI X3.9-1978 Section 13.5.3.2) C C Origin: David Billinghurst <David.Billinghurst@riotinto.com> C C { dg-do run } C { dg-options "-std=legacy" } C integer i,j real a,b,c,d,e character*32 in in = '1234 8' read(in,'(T3,I1)') i if ( i.ne.3 ) call abort() read(in,'(5X,TL4,I2)') i if ( i.ne.23 ) call abort() read(in,'(3X,I1,TR3,I1)') i,j if ( i.ne.4 ) call abort() if ( j.ne.8 ) call abort() in = ' 1.5 -12.62 348.75 1.0E-6' 100 format(F6.0,TL6,I4,1X,I1,8X,I5,F3.0,T10,F5.0,T17,F6.0,TR2,F6.0) read(in,100) a,i,j,k,b,c,d,e if ( abs(a-1.5).gt.1.0e-5 ) call abort() if ( i.ne.1 ) call abort() if ( j.ne.5 ) call abort() if ( k.ne.348 ) call abort() if ( abs(b-0.75).gt.1.0e-5 ) call abort() if ( abs(c-12.62).gt.1.0e-5 ) call abort() if ( abs(d-348.75).gt.1.0e-4 ) call abort() if ( abs(e-1.0e-6).gt.1.0e-11 ) call abort() end
gpl-2.0
rgwan/gcc
libgfortran/generated/_sqrt_r10.F90
47
1479
! Copyright (C) 2002-2015 Free Software Foundation, Inc. ! Contributed by Paul Brook <paul@nowt.org> ! !This file is part of the GNU Fortran 95 runtime library (libgfortran). ! !GNU libgfortran 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 3 of the License, or (at your option) any later version. !GNU libgfortran 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. ! !Under Section 7 of GPL version 3, you are granted additional !permissions described in the GCC Runtime Library Exception, version !3.1, as published by the Free Software Foundation. ! !You should have received a copy of the GNU General Public License and !a copy of the GCC Runtime Library Exception along with this program; !see the files COPYING3 and COPYING.RUNTIME respectively. If not, see !<http://www.gnu.org/licenses/>. ! !This file is machine generated. #include "config.h" #include "kinds.inc" #include "c99_protos.inc" #if defined (HAVE_GFC_REAL_10) #ifdef HAVE_SQRTL elemental function _gfortran_specific__sqrt_r10 (parm) real (kind=10), intent (in) :: parm real (kind=10) :: _gfortran_specific__sqrt_r10 _gfortran_specific__sqrt_r10 = sqrt (parm) end function #endif #endif
gpl-2.0
Gd58/gcc
gcc/testsuite/gfortran.dg/ieee/large_3.F90
46
3667
! { dg-do run } ! { dg-additional-options "-ffree-line-length-none" } ! { dg-additional-options "-mfp-trap-mode=sui" { target alpha*-*-* } } ! ! Use dg-additional-options rather than dg-options to avoid overwriting the ! default IEEE options which are passed by ieee.exp and necessary. use ieee_features use ieee_exceptions use ieee_arithmetic implicit none ! k1 and k2 will be large real kinds, if supported, and single/double ! otherwise integer, parameter :: k1 = & max(ieee_selected_real_kind(precision(0.d0) + 1), kind(0.)) integer, parameter :: k2 = & max(ieee_selected_real_kind(precision(0._k1) + 1), kind(0.d0)) type(ieee_flag_type), parameter :: x(5) = & [ IEEE_INVALID, IEEE_OVERFLOW, IEEE_DIVIDE_BY_ZERO, & IEEE_UNDERFLOW, IEEE_INEXACT ] logical :: l(5) = .false. character(len=5) :: s #define FLAGS_STRING(S) \ call ieee_get_flag(x, l) ; \ write(S,"(5(A1))") merge(["I","O","Z","U","P"],[" "," "," "," "," "],l) #define CHECK_FLAGS(expected) \ FLAGS_STRING(s) ; \ if (s /= expected) then ; \ write (*,"(A,I0,A,A)") "Flags at line ", __LINE__, ": ", s ; \ call abort ; \ end if ; \ call check_flag_sub real(kind=k1), volatile :: sx real(kind=k2), volatile :: dx ! This file tests IEEE_SET_FLAG and IEEE_GET_FLAG !!!! Large kind 1 ! Initial flags are all off CHECK_FLAGS(" ") ! Check we can clear them call ieee_set_flag(ieee_all, .false.) CHECK_FLAGS(" ") ! Raise invalid, then clear sx = -1 sx = sqrt(sx) CHECK_FLAGS("I ") call ieee_set_flag(ieee_all, .false.) CHECK_FLAGS(" ") ! Raise overflow and precision sx = huge(sx) CHECK_FLAGS(" ") sx = sx*sx CHECK_FLAGS(" O P") ! Also raise divide-by-zero sx = 0 sx = 1 / sx CHECK_FLAGS(" OZ P") ! Clear them call ieee_set_flag([ieee_overflow,ieee_inexact,& ieee_divide_by_zero],[.false.,.false.,.true.]) CHECK_FLAGS(" Z ") call ieee_set_flag(ieee_divide_by_zero, .false.) CHECK_FLAGS(" ") ! Raise underflow sx = tiny(sx) CHECK_FLAGS(" ") sx = sx / 10 CHECK_FLAGS(" UP") ! Raise everything call ieee_set_flag(ieee_all, .true.) CHECK_FLAGS("IOZUP") ! And clear call ieee_set_flag(ieee_all, .false.) CHECK_FLAGS(" ") !!!! Large kind 2 ! Initial flags are all off CHECK_FLAGS(" ") ! Check we can clear them call ieee_set_flag(ieee_all, .false.) CHECK_FLAGS(" ") ! Raise invalid, then clear dx = -1 dx = sqrt(dx) CHECK_FLAGS("I ") call ieee_set_flag(ieee_all, .false.) CHECK_FLAGS(" ") ! Raise overflow and precision dx = huge(dx) CHECK_FLAGS(" ") dx = dx*dx CHECK_FLAGS(" O P") ! Also raise divide-by-zero dx = 0 dx = 1 / dx CHECK_FLAGS(" OZ P") ! Clear them call ieee_set_flag([ieee_overflow,ieee_inexact,& ieee_divide_by_zero],[.false.,.false.,.true.]) CHECK_FLAGS(" Z ") call ieee_set_flag(ieee_divide_by_zero, .false.) CHECK_FLAGS(" ") ! Raise underflow dx = tiny(dx) CHECK_FLAGS(" ") dx = dx / 10 CHECK_FLAGS(" UP") ! Raise everything call ieee_set_flag(ieee_all, .true.) CHECK_FLAGS("IOZUP") ! And clear call ieee_set_flag(ieee_all, .false.) CHECK_FLAGS(" ") contains subroutine check_flag_sub use ieee_exceptions logical :: l(5) = .false. type(ieee_flag_type), parameter :: x(5) = & [ IEEE_INVALID, IEEE_OVERFLOW, IEEE_DIVIDE_BY_ZERO, & IEEE_UNDERFLOW, IEEE_INEXACT ] call ieee_get_flag(x, l) if (any(l)) then print *, "Flags not cleared in subroutine" call abort end if end subroutine end
gpl-2.0
sriki18/scipy
scipy/special/cdflib/cdfchi.f
109
6534
SUBROUTINE cdfchi(which,p,q,x,df,status,bound) C********************************************************************** C C SUBROUTINE CDFCHI( WHICH, P, Q, X, DF, STATUS, BOUND ) C Cumulative Distribution Function C CHI-Square distribution C C C Function C C C Calculates any one parameter of the chi-square C distribution given values for the others. C C C Arguments C C C WHICH --> Integer indicating which of the next three argument C values is to be calculated from the others. C Legal range: 1..3 C iwhich = 1 : Calculate P and Q from X and DF C iwhich = 2 : Calculate X from P,Q and DF C iwhich = 3 : Calculate DF from P,Q and X C INTEGER WHICH C C P <--> The integral from 0 to X of the chi-square C distribution. C Input range: [0, 1]. C DOUBLE PRECISION P C C Q <--> 1-P. C Input range: (0, 1]. C P + Q = 1.0. C DOUBLE PRECISION Q C C X <--> Upper limit of integration of the non-central C chi-square distribution. C Input range: [0, +infinity). C Search range: [0,1E100] C DOUBLE PRECISION X C C DF <--> Degrees of freedom of the C chi-square distribution. C Input range: (0, +infinity). C Search range: [ 1E-100, 1E100] C DOUBLE PRECISION DF C C STATUS <-- 0 if calculation completed correctly C -I if input parameter number I is out of range C 1 if answer appears to be lower than lowest C search bound C 2 if answer appears to be higher than greatest C search bound C 3 if P + Q .ne. 1 C 10 indicates error returned from cumgam. See C references in cdfgam C INTEGER STATUS C C BOUND <-- Undefined if STATUS is 0 C C Bound exceeded by parameter number I if STATUS C is negative. C C Lower search bound if STATUS is 1. C C Upper search bound if STATUS is 2. C C C Method C C C Formula 26.4.19 of Abramowitz and Stegun, Handbook of C Mathematical Functions (1966) is used to reduce the chisqure C distribution to the incomplete distribution. C C Computation of other parameters involve a seach for a value that C produces the desired value of P. The search relies on the C monotinicity of P with the other parameter. C C********************************************************************** C .. Parameters .. DOUBLE PRECISION tol PARAMETER (tol=1.0D-8) DOUBLE PRECISION atol PARAMETER (atol=1.0D-50) DOUBLE PRECISION zero,inf PARAMETER (zero=1.0D-100,inf=1.0D100) C .. C .. Scalar Arguments .. DOUBLE PRECISION bound,df,p,q,x INTEGER status,which C .. C .. Local Scalars .. DOUBLE PRECISION ccum,cum,fx,porq,pq LOGICAL qhi,qleft,qporq C .. C .. External Functions .. DOUBLE PRECISION spmpar EXTERNAL spmpar C .. C .. External Subroutines .. EXTERNAL cumchi,dinvr,dstinv C .. C .. Intrinsic Functions .. INTRINSIC abs C .. IF (.NOT. ((which.LT.1).OR. (which.GT.3))) GO TO 30 IF (.NOT. (which.LT.1)) GO TO 10 bound = 1.0D0 GO TO 20 10 bound = 3.0D0 20 status = -1 RETURN 30 IF (which.EQ.1) GO TO 70 IF (.NOT. ((p.LT.0.0D0).OR. (p.GT.1.0D0))) GO TO 60 IF (.NOT. (p.LT.0.0D0)) GO TO 40 bound = 0.0D0 GO TO 50 40 bound = 1.0D0 50 status = -2 RETURN 60 CONTINUE 70 IF (which.EQ.1) GO TO 110 IF (.NOT. ((q.LE.0.0D0).OR. (q.GT.1.0D0))) GO TO 100 IF (.NOT. (q.LE.0.0D0)) GO TO 80 bound = 0.0D0 GO TO 90 80 bound = 1.0D0 90 status = -3 RETURN 100 CONTINUE 110 IF (which.EQ.2) GO TO 130 IF (.NOT. (x.LT.0.0D0)) GO TO 120 bound = 0.0D0 status = -4 RETURN 120 CONTINUE 130 IF (which.EQ.3) GO TO 150 IF (.NOT. (df.LE.0.0D0)) GO TO 140 bound = 0.0D0 status = -5 RETURN 140 CONTINUE 150 IF (which.EQ.1) GO TO 190 pq = p + q IF (.NOT. (abs(((pq)-0.5D0)-0.5D0).GT. + (3.0D0*spmpar(1)))) GO TO 180 IF (.NOT. (pq.LT.0.0D0)) GO TO 160 bound = 0.0D0 GO TO 170 160 bound = 1.0D0 170 status = 3 RETURN 180 CONTINUE 190 IF (which.EQ.1) GO TO 220 qporq = p .LE. q IF (.NOT. (qporq)) GO TO 200 porq = p GO TO 210 200 porq = q 210 CONTINUE 220 IF ((1).EQ. (which)) THEN status = 0 CALL cumchi(x,df,p,q) IF (porq.GT.1.5D0) THEN status = 10 RETURN END IF ELSE IF ((2).EQ. (which)) THEN x = 5.0D0 CALL dstinv(0.0D0,inf,0.5D0,0.5D0,5.0D0,atol,tol) status = 0 CALL dinvr(status,x,fx,qleft,qhi) 230 IF (.NOT. (status.EQ.1)) GO TO 270 CALL cumchi(x,df,cum,ccum) IF (.NOT. (qporq)) GO TO 240 fx = cum - p GO TO 250 240 fx = ccum - q 250 IF (.NOT. ((fx+porq).GT.1.5D0)) GO TO 260 status = 10 RETURN 260 CALL dinvr(status,x,fx,qleft,qhi) GO TO 230 270 IF (.NOT. (status.EQ.-1)) GO TO 300 IF (.NOT. (qleft)) GO TO 280 status = 1 bound = 0.0D0 GO TO 290 280 status = 2 bound = inf 290 CONTINUE 300 CONTINUE ELSE IF ((3).EQ. (which)) THEN df = 5.0D0 CALL dstinv(zero,inf,0.5D0,0.5D0,5.0D0,atol,tol) status = 0 CALL dinvr(status,df,fx,qleft,qhi) 310 IF (.NOT. (status.EQ.1)) GO TO 350 CALL cumchi(x,df,cum,ccum) IF (.NOT. (qporq)) GO TO 320 fx = cum - p GO TO 330 320 fx = ccum - q 330 IF (.NOT. ((fx+porq).GT.1.5D0)) GO TO 340 status = 10 RETURN 340 CALL dinvr(status,df,fx,qleft,qhi) GO TO 310 350 IF (.NOT. (status.EQ.-1)) GO TO 380 IF (.NOT. (qleft)) GO TO 360 status = 1 bound = zero GO TO 370 360 status = 2 bound = inf 370 CONTINUE 380 END IF RETURN END
bsd-3-clause
mingwpy/scipy
scipy/special/cdflib/cdfchi.f
109
6534
SUBROUTINE cdfchi(which,p,q,x,df,status,bound) C********************************************************************** C C SUBROUTINE CDFCHI( WHICH, P, Q, X, DF, STATUS, BOUND ) C Cumulative Distribution Function C CHI-Square distribution C C C Function C C C Calculates any one parameter of the chi-square C distribution given values for the others. C C C Arguments C C C WHICH --> Integer indicating which of the next three argument C values is to be calculated from the others. C Legal range: 1..3 C iwhich = 1 : Calculate P and Q from X and DF C iwhich = 2 : Calculate X from P,Q and DF C iwhich = 3 : Calculate DF from P,Q and X C INTEGER WHICH C C P <--> The integral from 0 to X of the chi-square C distribution. C Input range: [0, 1]. C DOUBLE PRECISION P C C Q <--> 1-P. C Input range: (0, 1]. C P + Q = 1.0. C DOUBLE PRECISION Q C C X <--> Upper limit of integration of the non-central C chi-square distribution. C Input range: [0, +infinity). C Search range: [0,1E100] C DOUBLE PRECISION X C C DF <--> Degrees of freedom of the C chi-square distribution. C Input range: (0, +infinity). C Search range: [ 1E-100, 1E100] C DOUBLE PRECISION DF C C STATUS <-- 0 if calculation completed correctly C -I if input parameter number I is out of range C 1 if answer appears to be lower than lowest C search bound C 2 if answer appears to be higher than greatest C search bound C 3 if P + Q .ne. 1 C 10 indicates error returned from cumgam. See C references in cdfgam C INTEGER STATUS C C BOUND <-- Undefined if STATUS is 0 C C Bound exceeded by parameter number I if STATUS C is negative. C C Lower search bound if STATUS is 1. C C Upper search bound if STATUS is 2. C C C Method C C C Formula 26.4.19 of Abramowitz and Stegun, Handbook of C Mathematical Functions (1966) is used to reduce the chisqure C distribution to the incomplete distribution. C C Computation of other parameters involve a seach for a value that C produces the desired value of P. The search relies on the C monotinicity of P with the other parameter. C C********************************************************************** C .. Parameters .. DOUBLE PRECISION tol PARAMETER (tol=1.0D-8) DOUBLE PRECISION atol PARAMETER (atol=1.0D-50) DOUBLE PRECISION zero,inf PARAMETER (zero=1.0D-100,inf=1.0D100) C .. C .. Scalar Arguments .. DOUBLE PRECISION bound,df,p,q,x INTEGER status,which C .. C .. Local Scalars .. DOUBLE PRECISION ccum,cum,fx,porq,pq LOGICAL qhi,qleft,qporq C .. C .. External Functions .. DOUBLE PRECISION spmpar EXTERNAL spmpar C .. C .. External Subroutines .. EXTERNAL cumchi,dinvr,dstinv C .. C .. Intrinsic Functions .. INTRINSIC abs C .. IF (.NOT. ((which.LT.1).OR. (which.GT.3))) GO TO 30 IF (.NOT. (which.LT.1)) GO TO 10 bound = 1.0D0 GO TO 20 10 bound = 3.0D0 20 status = -1 RETURN 30 IF (which.EQ.1) GO TO 70 IF (.NOT. ((p.LT.0.0D0).OR. (p.GT.1.0D0))) GO TO 60 IF (.NOT. (p.LT.0.0D0)) GO TO 40 bound = 0.0D0 GO TO 50 40 bound = 1.0D0 50 status = -2 RETURN 60 CONTINUE 70 IF (which.EQ.1) GO TO 110 IF (.NOT. ((q.LE.0.0D0).OR. (q.GT.1.0D0))) GO TO 100 IF (.NOT. (q.LE.0.0D0)) GO TO 80 bound = 0.0D0 GO TO 90 80 bound = 1.0D0 90 status = -3 RETURN 100 CONTINUE 110 IF (which.EQ.2) GO TO 130 IF (.NOT. (x.LT.0.0D0)) GO TO 120 bound = 0.0D0 status = -4 RETURN 120 CONTINUE 130 IF (which.EQ.3) GO TO 150 IF (.NOT. (df.LE.0.0D0)) GO TO 140 bound = 0.0D0 status = -5 RETURN 140 CONTINUE 150 IF (which.EQ.1) GO TO 190 pq = p + q IF (.NOT. (abs(((pq)-0.5D0)-0.5D0).GT. + (3.0D0*spmpar(1)))) GO TO 180 IF (.NOT. (pq.LT.0.0D0)) GO TO 160 bound = 0.0D0 GO TO 170 160 bound = 1.0D0 170 status = 3 RETURN 180 CONTINUE 190 IF (which.EQ.1) GO TO 220 qporq = p .LE. q IF (.NOT. (qporq)) GO TO 200 porq = p GO TO 210 200 porq = q 210 CONTINUE 220 IF ((1).EQ. (which)) THEN status = 0 CALL cumchi(x,df,p,q) IF (porq.GT.1.5D0) THEN status = 10 RETURN END IF ELSE IF ((2).EQ. (which)) THEN x = 5.0D0 CALL dstinv(0.0D0,inf,0.5D0,0.5D0,5.0D0,atol,tol) status = 0 CALL dinvr(status,x,fx,qleft,qhi) 230 IF (.NOT. (status.EQ.1)) GO TO 270 CALL cumchi(x,df,cum,ccum) IF (.NOT. (qporq)) GO TO 240 fx = cum - p GO TO 250 240 fx = ccum - q 250 IF (.NOT. ((fx+porq).GT.1.5D0)) GO TO 260 status = 10 RETURN 260 CALL dinvr(status,x,fx,qleft,qhi) GO TO 230 270 IF (.NOT. (status.EQ.-1)) GO TO 300 IF (.NOT. (qleft)) GO TO 280 status = 1 bound = 0.0D0 GO TO 290 280 status = 2 bound = inf 290 CONTINUE 300 CONTINUE ELSE IF ((3).EQ. (which)) THEN df = 5.0D0 CALL dstinv(zero,inf,0.5D0,0.5D0,5.0D0,atol,tol) status = 0 CALL dinvr(status,df,fx,qleft,qhi) 310 IF (.NOT. (status.EQ.1)) GO TO 350 CALL cumchi(x,df,cum,ccum) IF (.NOT. (qporq)) GO TO 320 fx = cum - p GO TO 330 320 fx = ccum - q 330 IF (.NOT. ((fx+porq).GT.1.5D0)) GO TO 340 status = 10 RETURN 340 CALL dinvr(status,df,fx,qleft,qhi) GO TO 310 350 IF (.NOT. (status.EQ.-1)) GO TO 380 IF (.NOT. (qleft)) GO TO 360 status = 1 bound = zero GO TO 370 360 status = 2 bound = inf 370 CONTINUE 380 END IF RETURN END
bsd-3-clause
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/where_operator_assign_1.f90
136
2356
! { dg-do compile } ! Tests the fix for PR30407, in which operator assignments did not work ! in WHERE blocks or simple WHERE statements. This is the test provided ! by the reporter. ! ! Contributed by Dominique d'Humieres <dominiq@lps.ens.fr> !============================================================================== MODULE kind_mod IMPLICIT NONE PRIVATE INTEGER, PUBLIC, PARAMETER :: I4=SELECTED_INT_KIND(9) INTEGER, PUBLIC, PARAMETER :: TF=KIND(.TRUE._I4) END MODULE kind_mod !============================================================================== MODULE pointer_mod USE kind_mod, ONLY : I4 IMPLICIT NONE PRIVATE TYPE, PUBLIC :: pvt INTEGER(I4), POINTER, DIMENSION(:) :: vect END TYPE pvt INTERFACE ASSIGNMENT(=) MODULE PROCEDURE p_to_p END INTERFACE PUBLIC :: ASSIGNMENT(=) CONTAINS !--------------------------------------------------------------------------- PURE ELEMENTAL SUBROUTINE p_to_p(a1, a2) IMPLICIT NONE TYPE(pvt), INTENT(OUT) :: a1 TYPE(pvt), INTENT(IN) :: a2 a1%vect = a2%vect END SUBROUTINE p_to_p !--------------------------------------------------------------------------- END MODULE pointer_mod !============================================================================== PROGRAM test_prog USE pointer_mod, ONLY : pvt, ASSIGNMENT(=) USE kind_mod, ONLY : I4, TF IMPLICIT NONE INTEGER(I4), DIMENSION(12_I4), TARGET :: ia LOGICAL(TF), DIMENSION(2_I4,3_I4) :: la TYPE(pvt), DIMENSION(6_I4) :: pv INTEGER(I4) :: i ! Initialisation... la(:,1_I4:3_I4:2_I4)=.TRUE._TF la(:,2_I4)=.FALSE._TF DO i=1_I4,6_I4 pv(i)%vect => ia((2_I4*i-1_I4):(2_I4*i)) END DO ia=0_I4 DO i=1_I4,3_I4 WHERE(la((/1_I4,2_I4/),i)) pv((2_I4*i-1_I4):(2_I4*i))= iaef((/(2_I4*i-1_I4),(2_I4*i)/)) ELSEWHERE pv((2_I4*i-1_I4):(2_I4*i))= iaef((/0_I4,0_I4/)) END WHERE END DO if (any (ia .ne. (/1,-1,2,-2,0,0,0,0,5,-5,6,-6/))) call abort () CONTAINS TYPE(pvt) ELEMENTAL FUNCTION iaef(index) RESULT(ans) USE kind_mod, ONLY : I4 USE pointer_mod, ONLY : pvt, ASSIGNMENT(=) IMPLICIT NONE INTEGER(I4), INTENT(IN) :: index ALLOCATE(ans%vect(2_I4)) ans%vect=(/index,-index/) END FUNCTION iaef END PROGRAM test_prog
gpl-2.0
rgwan/gcc
gcc/testsuite/gfortran.dg/pr58968.f
113
3439
C PR rtl-optimization/58968.f C { dg-do compile { target powerpc*-*-*} } C { dg-options "-mcpu=power7 -O3 -w -ffast-math -funroll-loops" } SUBROUTINE MAKTABS(IW,SOME,LBOX1,LBOX2,LBOX3,NSPACE,NA,NB, * LBST,X, * NX,IAMA,IAMI,IBMA,IBMI,MNUM,IDIM,MSTA,IBO, * IDSYM,ISYM1,NSYM, * NACT,LWRK,KTAB,LGMUL, * LCON,LCOA,LCOB, * LANDET,LBNDET,NAST,NBST,LSYMA,LSYMB,LGCOM, * MINI,MAXI,LSPA,LSPB,LDISB, * LSAS,LSBS,LSAC,LSBC, * ITGA,ITGB,IAST,IBST,NCI,NA1EX,NB1EX,FDIRCT) IMPLICIT DOUBLE PRECISION(A-H,O-Z) LOGICAL SOME DIMENSION LBOX1(NSPACE),LBOX2(NSPACE),LBOX3(NSPACE),LBST(NSPACE) DIMENSION X(NX) DIMENSION IAMA(NSPACE),IAMI(NSPACE),IBMA(NSPACE),IBMI(NSPACE) DIMENSION MNUM(NSPACE),IDIM(NSPACE),MSTA(NSPACE+1),IBO(NACT) DIMENSION LWRK(43),KTAB(NSYM),LGMUL(NSYM,NSYM) DIMENSION LCON(NA) DIMENSION LCOA(NSYM,ITGA),LCOB(NSYM,ITGB) DIMENSION LANDET(NSPACE,ITGA),LBNDET(NSPACE,ITGB) DIMENSION NAST(ITGA+1),NBST(ITGB+1) DIMENSION LSYMA(IAST),LSYMB(IBST) DIMENSION LGCOM(ITGB,ITGA) DIMENSION MINI(NSPACE),MAXI(NSPACE) DIMENSION LSPA(IAST),LSPB(IBST) DIMENSION LDISB(NSYM,ITGB,ITGA) DIMENSION LSAS(NSYM+1,ITGA),LSBS(NSYM+1,ITGB) DIMENSION LSAC(IAST),LSBC(IBST) LOGICAL FDIRCT LCOA = 0 LCOB = 0 ISTA1 = LBST(1) CALL RESETCO(LBOX1,NSPACE,NB,IBMA,IBMI,LBOX2) NAST(1) = 0 NBST(1) = 0 DO II=1,ITGA ITOT = 1 DO JJ=1,NSPACE ITOT = ITOT * LANDET(JJ,II) ENDDO NAST(II+1) = NAST(II) + ITOT ENDDO DO II=1,ITGB ITOT = 1 DO JJ=1,NSPACE ITOT = ITOT * LBNDET(JJ,II) ENDDO NBST(II+1) = NBST(II) + ITOT ENDDO ICOMP = 0 CALL RESETCO(LBOX1,NSPACE,NA,IAMA,IAMI,LBOX3) NA1EX = 0 NB1EX = 0 CALL RESETCO(LBOX1,NSPACE,NB,IBMA,IBMI,LBOX3) DO IIB = 1,ITGB CALL RESETDE(LBOX1,NSPACE,NB,MSTA,LCON) DO KKB=NBST(IIB)+1,NBST(IIB+1) DO II=1,NSPACE LBOX2(II) = LBOX1(II) ENDDO IEBS = NB+1 DO ISPB1=NSPACE,1,-1 IOC1 = LBOX1(ISPB1) IEBE = IEBS - 1 IEBS = IEBS - IOC1 LBOX2(ISPB1) = LBOX2(ISPB1)-1 DO IB1=IEBE,IEBS,-1 IO1 = LCON(IB1) IGBE = IEBE - LBOX1(ISPB1) DO ISPB2=ISPB1,NSPACE IGBS = IGBE + 1 IGBE = IGBE + LBOX1(ISPB2) LBOX2(ISPB2) = LBOX2(ISPB2) + 1 IGBA = MAX(IB1+1,IGBS) DO IGAP=IGBA,IGBE+1 DO JJ=ISTA,IEND NB1EX = NB1EX + 1 ENDDO ISTA = LCON(IGAP)+1 IEND = LCON(IGAP+1)-1 IF (IGAP.EQ.IGBE) IEND=MSTA(ISPB2+1)-1 ENDDO LBOX2(ISPB2) = LBOX2(ISPB2) - 1 ENDDO ENDDO LBOX2(ISPB1) = LBOX2(ISPB1) + 1 ENDDO CALL MOVEUP2(LBOX1,NSPACE,NB,MSTA,LCON) ENDDO CALL PUSHCO(LBOX1,NSPACE,NB,IBMA,IBMI,LBOX3,IEND) ENDDO RETURN END
gpl-2.0
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/pr58968.f
113
3439
C PR rtl-optimization/58968.f C { dg-do compile { target powerpc*-*-*} } C { dg-options "-mcpu=power7 -O3 -w -ffast-math -funroll-loops" } SUBROUTINE MAKTABS(IW,SOME,LBOX1,LBOX2,LBOX3,NSPACE,NA,NB, * LBST,X, * NX,IAMA,IAMI,IBMA,IBMI,MNUM,IDIM,MSTA,IBO, * IDSYM,ISYM1,NSYM, * NACT,LWRK,KTAB,LGMUL, * LCON,LCOA,LCOB, * LANDET,LBNDET,NAST,NBST,LSYMA,LSYMB,LGCOM, * MINI,MAXI,LSPA,LSPB,LDISB, * LSAS,LSBS,LSAC,LSBC, * ITGA,ITGB,IAST,IBST,NCI,NA1EX,NB1EX,FDIRCT) IMPLICIT DOUBLE PRECISION(A-H,O-Z) LOGICAL SOME DIMENSION LBOX1(NSPACE),LBOX2(NSPACE),LBOX3(NSPACE),LBST(NSPACE) DIMENSION X(NX) DIMENSION IAMA(NSPACE),IAMI(NSPACE),IBMA(NSPACE),IBMI(NSPACE) DIMENSION MNUM(NSPACE),IDIM(NSPACE),MSTA(NSPACE+1),IBO(NACT) DIMENSION LWRK(43),KTAB(NSYM),LGMUL(NSYM,NSYM) DIMENSION LCON(NA) DIMENSION LCOA(NSYM,ITGA),LCOB(NSYM,ITGB) DIMENSION LANDET(NSPACE,ITGA),LBNDET(NSPACE,ITGB) DIMENSION NAST(ITGA+1),NBST(ITGB+1) DIMENSION LSYMA(IAST),LSYMB(IBST) DIMENSION LGCOM(ITGB,ITGA) DIMENSION MINI(NSPACE),MAXI(NSPACE) DIMENSION LSPA(IAST),LSPB(IBST) DIMENSION LDISB(NSYM,ITGB,ITGA) DIMENSION LSAS(NSYM+1,ITGA),LSBS(NSYM+1,ITGB) DIMENSION LSAC(IAST),LSBC(IBST) LOGICAL FDIRCT LCOA = 0 LCOB = 0 ISTA1 = LBST(1) CALL RESETCO(LBOX1,NSPACE,NB,IBMA,IBMI,LBOX2) NAST(1) = 0 NBST(1) = 0 DO II=1,ITGA ITOT = 1 DO JJ=1,NSPACE ITOT = ITOT * LANDET(JJ,II) ENDDO NAST(II+1) = NAST(II) + ITOT ENDDO DO II=1,ITGB ITOT = 1 DO JJ=1,NSPACE ITOT = ITOT * LBNDET(JJ,II) ENDDO NBST(II+1) = NBST(II) + ITOT ENDDO ICOMP = 0 CALL RESETCO(LBOX1,NSPACE,NA,IAMA,IAMI,LBOX3) NA1EX = 0 NB1EX = 0 CALL RESETCO(LBOX1,NSPACE,NB,IBMA,IBMI,LBOX3) DO IIB = 1,ITGB CALL RESETDE(LBOX1,NSPACE,NB,MSTA,LCON) DO KKB=NBST(IIB)+1,NBST(IIB+1) DO II=1,NSPACE LBOX2(II) = LBOX1(II) ENDDO IEBS = NB+1 DO ISPB1=NSPACE,1,-1 IOC1 = LBOX1(ISPB1) IEBE = IEBS - 1 IEBS = IEBS - IOC1 LBOX2(ISPB1) = LBOX2(ISPB1)-1 DO IB1=IEBE,IEBS,-1 IO1 = LCON(IB1) IGBE = IEBE - LBOX1(ISPB1) DO ISPB2=ISPB1,NSPACE IGBS = IGBE + 1 IGBE = IGBE + LBOX1(ISPB2) LBOX2(ISPB2) = LBOX2(ISPB2) + 1 IGBA = MAX(IB1+1,IGBS) DO IGAP=IGBA,IGBE+1 DO JJ=ISTA,IEND NB1EX = NB1EX + 1 ENDDO ISTA = LCON(IGAP)+1 IEND = LCON(IGAP+1)-1 IF (IGAP.EQ.IGBE) IEND=MSTA(ISPB2+1)-1 ENDDO LBOX2(ISPB2) = LBOX2(ISPB2) - 1 ENDDO ENDDO LBOX2(ISPB1) = LBOX2(ISPB1) + 1 ENDDO CALL MOVEUP2(LBOX1,NSPACE,NB,MSTA,LCON) ENDDO CALL PUSHCO(LBOX1,NSPACE,NB,IBMA,IBMI,LBOX3,IEND) ENDDO RETURN END
gpl-2.0
PHASTA/phasta
phSolver/incompressible/e3ql.f
5
9269
subroutine e3ql (yl, dwl, shp, shgl, & xl, ql, xmudmi, & sgn ) c c---------------------------------------------------------------------- c c This routine computes the local diffusive flux vector using a c local projection algorithm c c input: c yl (npro,nshl,ndof) : Y variables c shp (nen,ngauss) : element shape-functions c shgl (nsd,nen,ngauss) : element local-grad-shape-functions c xl (npro,nshape,nsd) : nodal coordinates at current step c sgn (npro,nshl) : signs for reversed shape functions c c output: c ql (npro,nshl,nsd*nsd) : element RHS diffusion residual c c---------------------------------------------------------------------- c use local_mass include "common.h" c dimension yl(npro,nshl,ndof), dwl(npro,nshl), & shp(nshl,ngauss), shgl(nsd,nshl,ngauss), & xl(npro,nenl,nsd), sgn(npro,nshl), & ql(npro,nshl,idflx), xmudmi(npro,ngauss) c c local arrays c dimension g1yi(npro,ndof), g2yi(npro,ndof), & g3yi(npro,ndof), shg(npro,nshl,nsd), & dxidx(npro,nsd,nsd), WdetJ(npro), & rmu(npro), & rminv(npro,nshl,nshl), & qrl(npro,nshl,nsd*nsd) c dimension qdi(npro,nsd*nsd), shape(npro,nshl), & shdrv(npro,nsd,nshl), indx(nshl), & rmass(npro,nshl,nshl) real*8 tmp(npro) c c.... loop through the integration points c rminv = zero rmass = zero qrl = zero do intp = 1, ngauss call getshp(shp, shgl, sgn, shape, shdrv) qdi = zero c c.... calculate the integration variables c c call e3qvar (yl, shdrv, & xl, g1yi, & g2yi, g3yi, shg, & dxidx, WdetJ ) call getdiff(dwl, yl, shape, xmudmi, xl,rmu, tmp) c c.... diffusive flux in x1-direction c qdi(:,1) = two * rmu * g1yi(:,2) qdi(:,4) = rmu * (g1yi(:,3) + g2yi(:,2)) qdi(:,7) = rmu * (g1yi(:,4) + g3yi(:,2)) c c.... diffusive flux in x2-direction c qdi(:,2) = rmu * (g1yi(:,3) + g2yi(:,2)) qdi(:,5) = two * rmu * g2yi(:,3) qdi(:,8) = rmu * (g2yi(:,4) + g3yi(:,3)) c c.... diffusive flux in x3-direction c qdi(:,3) = rmu * (g1yi(:,4) + g3yi(:,2)) qdi(:,6)= rmu * (g2yi(:,4) + g3yi(:,3)) qdi(:,9)= two * rmu * g3yi(:,4) c c c.... assemble contribution of qdi to qrl,i.e., contribution to c each element shape function c tmp = Qwt(lcsyst,intp) if (lcsyst .eq. 1) then tmp = tmp*(three/four) endif c c reconsider this when hierarchic wedges come into code WDGCHECK c do i=1,nshl qrl(:,i,1 ) = qrl(:,i,1 )+ shape(:,i)*tmp*qdi(:,1 ) qrl(:,i,2 ) = qrl(:,i,2 )+ shape(:,i)*tmp*qdi(:,2 ) qrl(:,i,3 ) = qrl(:,i,3 )+ shape(:,i)*tmp*qdi(:,3 ) qrl(:,i,4 ) = qrl(:,i,4 )+ shape(:,i)*tmp*qdi(:,4 ) qrl(:,i,5 ) = qrl(:,i,5 )+ shape(:,i)*tmp*qdi(:,5 ) qrl(:,i,6 ) = qrl(:,i,6 )+ shape(:,i)*tmp*qdi(:,6 ) qrl(:,i,7 ) = qrl(:,i,7 )+ shape(:,i)*tmp*qdi(:,7 ) qrl(:,i,8 ) = qrl(:,i,8 )+ shape(:,i)*tmp*qdi(:,8 ) qrl(:,i,9 ) = qrl(:,i,9 )+ shape(:,i)*tmp*qdi(:,9 ) enddo c c.... add contribution to local mass matrix c if (have_local_mass .eq. 0) then do i=1,nshl do j=1,nshl rmass(:,i,j) = rmass(:,i,j)+shape(:,i)*shape(:,j)*tmp enddo enddo endif c c.... end of the loop over integration points c enddo c c.... find the inverse of the local mass matrix for each element if (have_local_mass .eq. 0) then allocate (lmassinv(iblock)%p(npro,nshl,nshl)) do iel=1,npro do i=1,nshl ! form the identy matrix do j=1,nshl lmassinv(iblock)%p(iel,i,j) = 0.0 enddo lmassinv(iblock)%p(iel,i,i)=1.0 enddo c c.... LU factor the mass matrix c call ludcmp(rmass(iel,:,:),nshl,nshl,indx,d) c c.... back substitute with the identy matrix to find the c matrix inverse c do j=1,nshl call lubksb(rmass(iel,:,:),nshl,nshl,indx, & lmassinv(iblock)%p(iel,:,j)) enddo enddo rminv(:,:,:) = lmassinv(iblock)%p(:,:,:) else rminv(:,:,:) = lmassinv(iblock)%p(:,:,:) endif c c.... find the modal coefficients of ql by multiplying by the inverse of c the local mass matrix c do iel=1,npro do j=1,9 c do j=1, 3*nsd ql(iel,:,j) = matmul( rminv(iel,:,:),qrl(iel,:,j) ) enddo enddo c c.... return c return end subroutine e3qlSclr (yl, dwl, shp, shgl, & xl, ql, sgn ) c c---------------------------------------------------------------------- c c This routine computes the local diffusive flux vector using a c local projection algorithm: c diffus * phi,i c c---------------------------------------------------------------------- c use local_mass include "common.h" c dimension yl(npro,nshl,ndof), dwl(npro,nshl), & shp(nshl,ngauss), shgl(nsd,nshl,ngauss), & xl(npro,nenl,nsd), sgn(npro,nshl), & ql(npro,nshl,nsd) c c local arrays c dimension dxidx(npro,nsd,nsd), WdetJ(npro), & diffus(npro), & rminv(npro,nshl,nshl), & qrl(npro,nshl,nsd) c dimension qdi(npro,nsd), shape(npro,nshl), & shdrv(npro,nsd,nshl), indx(nshl), & rmass(npro,nshl,nshl), gradT(npro,nsd), & eviscv(npro) c c.... loop through the integration points c rminv = zero rmass = zero qrl = zero do intp = 1, ngauss call getshp(shp, shgl, sgn, shape, shdrv) qdi = zero c c.... calculate the integration variables c c call e3qvarSclr (yl, shdrv, xl, & gradT, dxidx, WdetJ ) c c.... call function to sort out diffusivity (at end of this file) c call getdiffsclr(dwl,shape,yl, diffus) c c.... diffusive flux in x1-direction c qdi(:,1) = diffus * gradT(:,1) qdi(:,2) = diffus * gradT(:,2) qdi(:,3) = diffus * gradT(:,3) c c.... assemble contribution of qdi to qrl,i.e., contribution to c each element shape function c tmp = Qwt(lcsyst,intp) if (lcsyst .eq. 1) then tmp = tmp*(three/four) endif do i=1,nshl qrl(:,i,1 ) = qrl(:,i,1 )+ shape(:,i)*tmp*qdi(:,1 ) qrl(:,i,2 ) = qrl(:,i,2 )+ shape(:,i)*tmp*qdi(:,2 ) qrl(:,i,3 ) = qrl(:,i,3 )+ shape(:,i)*tmp*qdi(:,3 ) enddo c c.... add contribution to local mass matrix c if (have_local_mass .eq. 0) then do i=1,nshl do j=1,nshl rmass(:,i,j)=rmass(:,i,j)+shape(:,i)*shape(:,j)*tmp enddo enddo endif c.... end of the loop over integration points c enddo c c.... find the inverse of the local mass matrix for each element c qrl = qrl/6.d0 c c.... Assuming that lmassinv was already computed for flow equations c rmass = rmass/6.0 c c.... for cubics, it cannot be precomputed, so compute and c save it the first time it is needed c if (have_local_mass .eq. 0) then allocate (lmassinv(iblock)%p(npro,nshl,nshl)) do iel=1,npro do i=1,nshl ! form the identy matrix do j=1,nshl lmassinv(iblock)%p(iel,i,j) = 0.0 enddo lmassinv(iblock)%p(iel,i,i)=1.0 enddo c c.... LU factor the mass matrix c call ludcmp(rmass(iel,:,:),nshl,nshl,indx,d) c c.... back substitute with the identy matrix to find the c matrix inverse c do j=1,nshl call lubksb(rmass(iel,:,:),nshl,nshl,indx, & lmassinv(iblock)%p(iel,:,j)) enddo enddo rminv(:,:,:) = lmassinv(iblock)%p(:,:,:) else rminv(:,:,:) = lmassinv(iblock)%p(:,:,:) endif c c.... find the modal coefficients of ql by multiplying by the inverse of c the local mass matrix c do iel=1,npro do j=1,nsd ql(iel,:,j) = matmul( rminv(iel,:,:),qrl(iel,:,j) ) enddo enddo c c.... return c return end
bsd-3-clause
PHASTA/phasta
phSolver/AMG/ramg_control.f
5
10834
!********************************************************* ! ramg control ! Control AMG preparation/solve process ! will have dynamic control (based on solver vecters) !********************************************************* subroutine ramg_control(colm,rowp,lhsK,lhsP, & ilwork,BC,iBC,iper) use ramg_data include "common.h" integer,intent(in),dimension(nshg+1) :: colm integer,intent(in),dimension(nnz_tot) :: rowp real(kind=8),intent(in),dimension(9,nnz_tot) :: lhsK real(kind=8),intent(in),dimension(4,nnz_tot) :: lhsP ! the boundary info integer, intent(in), dimension(nlwork) :: ilwork integer, intent(in),dimension(nshg) :: iBC,iper real(kind=8),intent(in),dimension(nshg,ndofBC) :: BC integer i if (iamg_init .eq. 0 ) then ! The overall initialization ! do init ramg_winct = 0 ramg_setup_flag = 0 iamg_init = 1 ramg_time = 0 else ramg_setup_flag = mod(ramg_setup_flag+1 ,iamg_setup_frez) end if ! Extract PPE call ramg_extract_ppe(colm,rowp,lhsK,lhsP, & ilwork,BC,iBC,iper) ! Coarsening call ramg_prep(ilwork,BC,iBC,iper) call ramg_init_ilwork(ilwork,BC,iBC,iper) ! Prepare for MLS smoothing if (iamg_smoother.eq.2) then call ramg_cheby_setup(colm,rowp,lhsK,lhsP, & ilwork,BC,iBC,iper) else call ramg_mls_setup(colm,rowp,lhsK,lhsP, & ilwork,BC,iBC,iper) endif if (iamg_c_solver.eq.2) then ! Setup Coarsest Direct solver call ramg_direct_LU(amg_A_colm(ramg_levelx)%p, & amg_A_rowp(ramg_levelx)%p, & amg_A_lhs(ramg_levelx)%p,amg_nshg(ramg_levelx), & amg_nnz(ramg_levelx)) endif if (maxnev.gt.0) then ! Setup GGB call ramg_ggb_setup(colm,rowp,lhsK,lhsP,ilwork,BC,iBC,iper) endif end subroutine !ramg_control !********************************************************* ! Ramg preparation !********************************************************* subroutine ramg_prep(ilwork,BC,iBC,iper) use ramg_data include "common.h" include "mpif.h" include "auxmpi.h" integer,intent(in),dimension(nlwork) :: ilwork integer,intent(in),dimension(nshg) :: iBC,iper real(kind=8),intent(in),dimension(nshg,ndofBC) :: BC logical :: maxstopsign,mxs2 integer :: i,p,p2 if (ramg_setup_flag.ne.0) return maxstopsign = .false. i = 1 do while ((i+1.le.iamg_nlevel) .and. (.not.maxstopsign)) if (amg_nshg(i+1).ne.0) then call ramg_deallocate(i+1) end if call ramg_coarse_setup(i,i+1,strong_eps,iamg_interp, & ramg_trunc, & ilwork,BC,iBC,iper,nshg,nlwork,ndofBC) call ramg_calcITAI(i,i+1,maxstopsign) if ((iamg_verb.gt.2).and.(myrank.eq.master)) then write(*,*)'COARSEN: level:',i+1,' nshg:',amg_nshg(i+1), & ' nnz:',amg_nnz(i+1) endif i = i+1 call MPI_Barrier(MPI_COMM_WORLD,ierr) maxstopsign = (amg_nshg(i).eq.amg_nshg(i-1)) IF (.true.) THEN !call ramg_checkcoarse(i,ilwork,BC,iBC,iper,maxstopsign) p = 1 if (maxstopsign) p = 0 call MPI_AllReduce(p,p2,1,MPI_INTEGER,MPI_SUM, & MPI_COMM_WORLD,ierr) if (p2.eq.0) then maxstopsign = .true. !write(*,*)'mcheck stopped' else maxstopsign = .false. endif ENDIF enddo ramg_levelx=i if (maxstopsign) then ramg_levelx = ramg_levelx-1 endif ! if ( (irun_amg_prec.eq.1).and.(mlsDeg.gt.0) ) then if (.false.) then deallocate(amg_A_colm(1)%p) deallocate(amg_A_rowp(1)%p) deallocate(amg_A_lhs(1)%p) endif allocate(CF_map(ramg_levelx)%p(amg_nshg(ramg_levelx))) allocate(CF_revmap(ramg_levelx)%p(amg_nshg(ramg_levelx))) do i=1,amg_nshg(ramg_levelx) CF_map(ramg_levelx)%p(i) = i CF_revmap(ramg_levelx)%p(i) = i enddo !call ramg_output_coarsening end subroutine !ramg_prep subroutine ramg_checkcoarse(level1,ilwork,BC,iBC,iper, & cfstop) use ramg_data include "common.h" include "mpif.h" include "auxmpi.h" integer,intent(in) :: level1 integer,intent(in),dimension(nlwork) :: ilwork integer,intent(in),dimension(nshg) :: iBC,iper real(kind=8),intent(in),dimension(nshg,ndofBC) :: BC logical,intent(inout) :: cfstop integer :: i,numtask,itkbeg,numseg,iacc integer :: j,k,p integer,allocatable,dimension(:) & :: subcfstop,subnnz,subcf,subcfrev,subnei real(kind=8) :: rhoratio logical :: subneireduce IF (( iamg_reduce.le.1).or.(numpe.gt.1)) THEN ! IF (.TRUE.) THEN if (numpe.ge.2) then numtask = ilwork(1)+1 else numtask = 1 endif allocate(subcfrev(numpe)) subcfrev = 0 allocate(subnei(numtask)) subnei = 0 subnei(1) = myrank+1 subcfrev(subnei(1))=1 itkbeg = 1 do i=2,numtask subnei(i)=ilwork(itkbeg+3)+1 subcfrev(subnei(i)) = i itkbeg = itkbeg + 4 + 2*ilwork(itkbeg+4) enddo ELSE !reduced numtask = rmapmax-1 allocate(subcfrev(numtask)) allocate(subnei(numtask)) do i=1,numtask subcfrev(i) = i enddo ENDIF allocate(subcfstop(numtask)) allocate(subcf(numtask)) allocate(subnnz(numtask)) subcfstop = 0 subcf = 0 subnnz = 0 do i = 1,amg_nnz(level1) k = amg_A_rowp(level1)%p(i) p = iabs(amg_paramap(level1)%p(k)) ! if (iamg_reduce.gt.1) then ! p = 1 ! for reduced only ! endif p = subcfrev(p) subnnz(p) = subnnz(p) + 1 enddo do i = 1,amg_nshg(level1) p = iabs(amg_paramap(level1)%p(i)) ! if (iamg_reduce.gt.1) then ! p = 1 ! for reduced only ! endif p = subcfrev(p) subcf(p) = subcf(p) + 1 enddo do i=1,numtask IF ((iamg_reduce.le.1).or.(numpe.gt.1)) THEN ! IF (.TRUE.) THEN p = subnei(i) subneireduce = (p.ne.(myrank+1)) ELSE !reduced subneireduce = (i.gt.iamg_reduce) END IF if ((subcf(i).lt.30).and.subneireduce) then subcfstop(i) = 1 endif if (.not.subneireduce) then if (subcf(i).lt.200) then subcfstop(i) = 1 endif if ((subnnz(i)/(subcf(i)**2)).gt.0.6) then subcfstop(i) = 1 endif end if enddo cfstop = .true. do i=1,numtask if (subcfstop(i).eq.0) then cfstop = .false. exit endif enddo IF ((iamg_reduce.le.1).or.(numpe.gt.1)) THEN ! if interior is coarsened, boundary should be fixed whatever if (subcfstop(1).eq.1) then cfstop = .true. endif ENDIF if (.not.cfstop) then do i=1,amg_nshg(level1) p = iabs(amg_paramap(level1)%p(i)) ! if (iamg_reduce.gt.1) then ! p = 1 ! reduced only ! endif p = subcfrev(p) if (subcfstop(p).eq.1) then amg_paramap(level1)%p(i) = -iabs(amg_paramap(level1)%p(i)) endif enddo endif deallocate(subcfrev) deallocate(subnei) deallocate(subcfstop) deallocate(subcf) deallocate(subnnz) end subroutine ! ramg_checkcoarse !****************************************************************** ! A bunch of code that hook to leslib's cg solve ! Force it to restart with AMG if meets plateau !****************************************************************** !******** ! sc writes: ! irun_amg_prec is a variable controling how to use AMG wisely. ! 0 : no run ! 1 : always use AMG prec'd CG ! 2 : restart CG a ( if plain CG hits plateau, do again with AMG ) ! 3 : restart CG b ( if plain exceeds maxiter, do again with AMG ) ! also refer to input.config for a detailed description. !******** subroutine ramg_normcheck(tmpnorm) use ramg_data include "common.h" include "mpif.h" real(kind=8),intent(inout) :: tmpnorm real(kind=8) :: sqnorm !write(*,*)myrank,' winct:',ramg_winct,sqrt(tmpnorm) !return if (irun_amg_prec.ne.2) return ! No control at all if (ramg_winct.eq.0) then !ramg_window = sqrt(tmpnorm) return ! Not relevant endif ramg_winct=0 if (ramg_flag.gt.1) return ! Second run does not need control ! Following are for the first run !write(*,*)'normcheck: ',sqnorm !return; if (ramg_redo.ge.100) then ! The rest of GMRES should be terminated if (ramg_redo.lt.104) then ramg_winct = 1 ramg_redo=ramg_redo+1 ! write(*,*)'***' else ramg_redo = 0 tmpnorm = 0 endif return endif sqnorm = sqrt(tmpnorm) if (ramg_redo.le.7) then ramg_redo = ramg_redo + 1 call ramg_winpushin(sqnorm) return endif call ramg_winpushin(sqnorm) if (ramg_window(7).gt.ramg_window(1)) then ! Stop point ! write(*,*)'myrank:',myrank,ramg_window(7),ramg_window(1) ! if (ramg_window(7).lt.1e-3) then ! stop point in cg if (myrank.eq.master) then write(*,*)"Prepare to restart CG" endif tmpnorm = 0 ramg_redo = 100 ramg_winct = 1 ramg_flag = ramg_flag -1 endif end subroutine ! ramg_normcheck subroutine ramg_winpushin(sqnorm) use ramg_data include "common.h" include "mpif.h" real(kind=8),intent(in) :: sqnorm integer i integer totlen totlen = 7 do i=1,totlen-1 ramg_window(i)=ramg_window(i+1) enddo ramg_window(totlen) = sqnorm end subroutine ! ramg_winpushin !********************************************************* ! <EOF> RAMG Control !*********************************************************
bsd-3-clause
itsimbal/gcc.cet
gcc/testsuite/gfortran.fortran-torture/compile/pr39937.f
181
1152
SUBROUTINE DTREVC( SIDE, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR, $ LDVR, MM, M, WORK, INFO ) DOUBLE PRECISION T( LDT, * ), VL( LDVL, * ), VR( LDVR, * ), $ WORK( * ) DOUBLE PRECISION X( 2, 2 ) CALL DLALN2( .FALSE., 1, 1, SMIN, ONE, T( J, J ), $ ZERO, X, 2, SCALE, XNORM, IERR ) CALL DSCAL( KI, SCALE, WORK( 1+N ), 1 ) DO 90 J = KI - 2, 1, -1 IF( J.GT.JNXT ) $ GO TO 90 JNXT = J - 1 IF( J.GT.1 ) THEN IF( T( J, J-1 ).NE.ZERO ) THEN IF( WORK( J ).GT.BIGNUM / XNORM ) THEN X( 1, 1 ) = X( 1, 1 ) / XNORM END IF END IF CALL DLALN2( .FALSE., 2, 2, SMIN, ONE, $ T( J-1, J-1 ), LDT, ONE, ONE, $ XNORM, IERR ) CALL DAXPY( J-2, -X( 1, 1 ), T( 1, J-1 ), 1, $ WORK( 1+N ), 1 ) CALL DAXPY( J-2, -X( 2, 2 ), T( 1, J ), 1, $ WORK( 1+N2 ), 1 ) END IF 90 CONTINUE END
gpl-2.0
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/graphite/pr38953.f90
159
6495
! { dg-options "-O3 -fgraphite-identity" } MODULE MAIN1 INTEGER , PARAMETER :: IFMAX = 40 , IKN = 85 , ISTRG = 132 , & & IERRN = 170 , ILEN_FLD = 80 CHARACTER PATH*2 , PPATH*2 , KEYWRD*8 , PKEYWD*8 , KEYWD*8 , & & KTYPE*5 , RUNST*1 DIMENSION FIELD(IFMAX) , KEYWD(IKN) , RUNST(ISTRG) LOGICAL :: DFAULT , CONC , DEPOS , DDEP , WDEP , RURAL , URBAN , & & GRDRIS , NOSTD , NOBID , CLMPRO , MSGPRO , PERIOD , & & OLM=.FALSE. INTEGER :: NSRC , NREC , NGRP , NQF, & & NARC , NOLM CHARACTER NETID*8 , NETIDT*8 , PNETID*8 , NTID*8 , NTTYP*8 , & & RECTYP*2 , PXSOID*8 , PESOID*8 , ARCID*8 ALLOCATABLE ::NETID(:) , RECTYP(:) , NTID(:) , NTTYP(:) , ARCID(:) DATA (KEYWD(I),I=1,IKN)/'STARTING' , 'FINISHED' , 'TITLEONE' , & & 'TITLETWO' , 'MODELOPT' , 'AVERTIME' , 'POLLUTID' , & & 'HALFLIFE' , 'DCAYCOEF' , 'DEBUGOPT' , 'ELEVUNIT' , & & 'FLAGPOLE' , 'RUNORNOT' , 'EVENTFIL' , 'SAVEFILE' , & & 'INITFILE' , 'MULTYEAR' , 'ERRORFIL' , 'GASDEPDF' , & & 'GDSEASON' , 'GASDEPVD' , 'GDLANUSE' , 'EVENTFIL' , & & 'URBANOPT' , 'METHOD_2' , 'LOCATION' , 'SRCPARAM' , & & 'BUILDHGT' , 'BUILDWID' , 'BUILDLEN' , 'XBADJ ' , & & 'YBADJ ' , 'EMISFACT' , 'EMISUNIT' , 'PARTDIAM' , & & 'MASSFRAX' , 'PARTDENS' , ' ' , ' ' , & & ' ' , 'CONCUNIT' , 'DEPOUNIT' , 'HOUREMIS' , & & 'GASDEPOS' , 'URBANSRC' , 'EVENTPER' , 'EVENTLOC' , & & 'SRCGROUP' , 'GRIDCART' , 'GRIDPOLR' , 'DISCCART' , & & 'DISCPOLR' , 'SURFFILE' , 'PROFFILE' , 'PROFBASE' , & & ' ' , 'SURFDATA' , 'UAIRDATA' , 'SITEDATA' , & & 'STARTEND' , 'DAYRANGE' , 'WDROTATE' , 'DTHETADZ' , & & 'WINDCATS' , 'RECTABLE' , 'MAXTABLE' , 'DAYTABLE' , & & 'MAXIFILE' , 'POSTFILE' , 'PLOTFILE' , 'TOXXFILE' , & & 'EVENTOUT' , 'INCLUDED' , 'SCIMBYHR' , 'SEASONHR' , & & 'AREAVERT' , 'PARTSIZE' , 'RANKFILE' , 'EVALCART' , & & 'EVALFILE' , 'NO2EQUIL' , 'OZONEVAL' , 'OZONEFIL' , & & 'NO2RATIO' , 'OLMGROUP'/ DIMENSION RESTAB(9,6,5) , STAB(9) DATA (((RESTAB(I,J,K),I=1,9),J=1,6),K=1,5)/1.E07 , 60. , 120. , & & 100. , 200. , 150. , 1.E07 , 1.E07 , 80. , 1.E07 , 2000. , & & 2000. , 2000. , 2000. , 2000. , 1.E07 , 1.E07 , 2500. , & & 1.E07 , 1000. , 1000. , 1000. , 2000. , 2000. , 1.E07 , & & 1.E07 , 1000. , 100. , 200. , 100. , 2000. , 100. , 1500. , & & 0. , 0. , 300. , 400. , 150. , 350. , 300. , 500. , 450. , & & 0. , 1000. , 0. , 300. , 150. , 200. , 200. , 300. , 300. , & & 2000. , 400. , 1000. , 1.E07 , 1.E07 , 1.E07 , 350. , & & 1.E07 , 700. , 1.E07 , 1.E07 , 1.E07 , 1.E07 , 6500. , & & 6500. , 3000. , 2000. , 2000. , 1.E07 , 1.E07 , 6500. , & & 1.E07 , 400. , 300. , 500. , 600. , 1000. , 1.E07 , 1.E07 , & & 300. , 100. , 150. , 100. , 1700. , 100. , 1200. , 0. , 0. ,& & 200. , 400. , 200. , 350. , 300. , 500. , 450. , 0. , & & 1000. , 0. , 300. , 150. , 200. , 200. , 300. , 300. , & & 2000. , 400. , 800. , 1.E07 , 1.E07 , 1.E07 , 500. , 1.E07 ,& & 1000. , 1.E07 , 1.E07 , 1.E07 , 1.E07 , 1.E07 , 9000. , & & 6000. , 2000. , 2000. , 1.E07 , 1.E07 , 9000. , 1.E07 , & & 1.E07 , 400. , 600. , 800. , 1600. , 1.E07 , 1.E07 , 800. , & & 100. , 0. , 100. , 1500. , 100. , 1000. , 0. , 0. , 100. , & & 400. , 150. , 350. , 300. , 500. , 450. , 0. , 0. , 1000. , & & 300. , 150. , 200. , 200. , 300. , 300. , 2000. , 400. , & & 1000. , 1.E07 , 1.E07 , 1.E07 , 800. , 1.E07 , 1600. , & & 1.E07 , 1.E07 , 1.E07 , 1.E07 , 1.E07 , 1.E07 , 400. , & & 1.E07 , 800. , 1.E07 , 1.E07 , 9000. , 1.E07 , 2000. , & & 1000. , 600. , 2000. , 1200. , 1.E07 , 1.E07 , 800. , 100. ,& & 0. , 10. , 1500. , 100. , 1000. , 0. , 0. , 50. , 100. , & & 100. , 100. , 100. , 200. , 200. , 0. , 1000. , 100. , & & 600. , 3500. , 3500. , 3500. , 500. , 500. , 2000. , 400. , & & 3500. , 1.E07 , 100. , 120. , 100. , 200. , 150. , 1.E07 , & & 1.E07 , 80. , 1.E07 , 2000. , 2000. , 1500. , 2000. , & & 2000. , 1.E07 , 1.E07 , 2000. , 1.E07 , 1000. , 250. , & & 350. , 500. , 700. , 1.E07 , 1.E07 , 300. , 100. , 50. , & & 80. , 1500. , 100. , 1000. , 0. , 0. , 200. , 500. , 150. , & & 350. , 300. , 500. , 450. , 0. , 1000. , 0. , 300. , 150. , & & 200. , 200. , 300. , 300. , 2000. , 400. , 1000./ END SUBROUTINE SHAVE USE MAIN1 IF ( PERIOD ) THEN 9020 FORMAT ('(''*'',8X,''X'',13X,''Y'',4X,',I1, & &'(2X,3A4),4X,''ZELEV'', 4X,''ZHILL'',4X,''ZFLAG'',4X,''AVE'',5X,& &_______ ________ ________'')') ENDIF DO IGRP = 1 , NUMGRP IF ( IANPST(IGRP).EQ.1 ) THEN IF ( IANFRM(IGRP).EQ.0 ) THEN DO IREC = 1 , NUMREC ENDDO ENDIF DO IREC = 1 , NUMREC IF ( RECTYP(IREC).EQ.'DC' ) THEN WRITE (IOUNIT,9082) SRCID(ISRF) , SRCTYP(ISRF) , & & AXS(ISRF) , AYS(ISRF) , AZS(ISRF) & & , (J,AXR(IREC+J-1),AYR(IREC+J-1), & & HCLMSG(IREC+J-1,IHNUM,IGRP,IAVE, & & ITYP),J=1,36) 9082 FORMAT (' BOUNDARY RECEPTOR NETWORK OF SOURCE ID: ', & & 18(2(1X,I4,3X,F10.2,', ',F10.2,',',F13.5,A1, & & '(',I8.8,')',7X),/),/) ENDIF ENDDO ENDIF ENDDO END USE MAIN1 IF ( ICOUNT.NE.0 .AND. JCOUNT.NE.0 ) THEN DO J = 1 , JCOUNT DO I = 1 , ICOUNT IF ( ISET.GT.NREC ) THEN GOTO 999 ENDIF ENDDO ENDDO ENDIF 999 CONTINUE END
gpl-2.0
itsimbal/gcc.cet
libgomp/testsuite/libgomp.fortran/lastprivate2.f90
182
3274
program lastprivate integer :: i, k common /c/ i, k !$omp parallel num_threads (4) call test1 !$omp end parallel if (i .ne. 21 .or. k .ne. 20) call abort !$omp parallel num_threads (4) call test2 !$omp end parallel if (i .ne. 64 .or. k .ne. 61) call abort !$omp parallel num_threads (4) call test3 !$omp end parallel if (i .ne. 14 .or. k .ne. 11) call abort call test4 call test5 call test6 call test7 call test8 call test9 call test10 call test11 call test12 contains subroutine test1 integer :: i, k common /c/ i, k !$omp do lastprivate (i, k) do i = 1, 20 k = i end do end subroutine test1 subroutine test2 integer :: i, k common /c/ i, k !$omp do lastprivate (i, k) do i = 7, 61, 3 k = i end do end subroutine test2 function ret3 () integer :: ret3 ret3 = 3 end function ret3 subroutine test3 integer :: i, k common /c/ i, k !$omp do lastprivate (i, k) do i = -10, 11, ret3 () k = i end do end subroutine test3 subroutine test4 integer :: j, l !$omp parallel do lastprivate (j, l) num_threads (4) do j = 1, 20 l = j end do if (j .ne. 21 .or. l .ne. 20) call abort end subroutine test4 subroutine test5 integer :: j, l l = 77 !$omp parallel do lastprivate (j, l) num_threads (4) firstprivate (l) do j = 7, 61, 3 l = j end do if (j .ne. 64 .or. l .ne. 61) call abort end subroutine test5 subroutine test6 integer :: j, l !$omp parallel do lastprivate (j, l) num_threads (4) do j = -10, 11, ret3 () l = j end do if (j .ne. 14 .or. l .ne. 11) call abort end subroutine test6 subroutine test7 integer :: i, k common /c/ i, k !$omp parallel do lastprivate (i, k) num_threads (4) do i = 1, 20 k = i end do if (i .ne. 21 .or. k .ne. 20) call abort end subroutine test7 subroutine test8 integer :: i, k common /c/ i, k !$omp parallel do lastprivate (i, k) num_threads (4) do i = 7, 61, 3 k = i end do if (i .ne. 64 .or. k .ne. 61) call abort end subroutine test8 subroutine test9 integer :: i, k common /c/ i, k k = 77 !$omp parallel do lastprivate (i, k) num_threads (4) firstprivate (k) do i = -10, 11, ret3 () k = i end do if (i .ne. 14 .or. k .ne. 11) call abort end subroutine test9 subroutine test10 integer :: i, k common /c/ i, k !$omp parallel num_threads (4) !$omp do lastprivate (i, k) do i = 1, 20 k = i end do !$omp end parallel if (i .ne. 21 .or. k .ne. 20) call abort end subroutine test10 subroutine test11 integer :: i, k common /c/ i, k !$omp parallel num_threads (4) !$omp do lastprivate (i, k) do i = 7, 61, 3 k = i end do !$omp end parallel if (i .ne. 64 .or. k .ne. 61) call abort end subroutine test11 subroutine test12 integer :: i, k common /c/ i, k k = 77 !$omp parallel num_threads (4) !$omp do lastprivate (i, k) firstprivate (k) do i = -10, 11, ret3 () k = i end do !$omp end parallel if (i .ne. 14 .or. k .ne. 11) call abort end subroutine test12 end program lastprivate
gpl-2.0
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/assumed_rank_7.f90
135
1674
! { dg-do run } ! ! PR fortran/48820 ! ! Handle type/class for assumed-rank arrays ! ! FIXME: Passing a CLASS to a CLASS has to be re-enabled. implicit none type t integer :: i end type class(T), allocatable :: ac(:,:) type(T), allocatable :: at(:,:) integer :: i allocate(ac(2:3,2:4)) allocate(at(2:3,2:4)) i = 0 call foo(ac) call foo(at) call bar(ac) call bar(at) if (i /= 12) call abort() contains subroutine bar(x) type(t) :: x(..) if (lbound(x,1) /= 1 .or. lbound(x,2) /= 1) call abort() if (size(x) /= 6) call abort() if (size(x,1) /= 2 .or. size(x,2) /= 3) call abort() if (ubound(x,1) /= 2 .or. ubound(x,2) /= 3) call abort() i = i + 1 call foo(x) call bar2(x) end subroutine subroutine bar2(x) type(t) :: x(..) if (lbound(x,1) /= 1 .or. lbound(x,2) /= 1) call abort() if (size(x) /= 6) call abort() if (size(x,1) /= 2 .or. size(x,2) /= 3) call abort() if (ubound(x,1) /= 2 .or. ubound(x,2) /= 3) call abort() i = i + 1 end subroutine subroutine foo(x) class(t) :: x(..) if (lbound(x,1) /= 1 .or. lbound(x,2) /= 1) call abort() if (size(x) /= 6) call abort() if (size(x,1) /= 2 .or. size(x,2) /= 3) call abort() if (ubound(x,1) /= 2 .or. ubound(x,2) /= 3) call abort() i = i + 1 call foo2(x) ! call bar2(x) ! Passing a CLASS to a TYPE does not yet work end subroutine subroutine foo2(x) class(t) :: x(..) if (lbound(x,1) /= 1 .or. lbound(x,2) /= 1) call abort() if (size(x) /= 6) call abort() if (size(x,1) /= 2 .or. size(x,2) /= 3) call abort() if (ubound(x,1) /= 2 .or. ubound(x,2) /= 3) call abort() i = i + 1 end subroutine end
gpl-2.0
jrper/fluidity
femtools/tests/test_supermesh_shapes_ac.F90
4
6107
! Copyright (C) 2006 Imperial College London and others. ! ! Please see the AUTHORS file in the main source directory for a full list ! of copyright holders. ! ! Prof. C Pain ! Applied Modelling and Computation Group ! Department of Earth Science and Engineeringp ! Imperial College London ! ! amcgsoftware@imperial.ac.uk ! ! 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, ! version 2.1 of the License. ! ! 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ! USA #include "fdebug.h" subroutine test_supermesh_shapes_ac use quadrature use elements use fetools use fields use fldebug use supermesh_assembly use unittest_tools implicit none integer :: degree, i real, dimension(:), allocatable :: shape_rhs_integral_a, shape_rhs_integral_c real, dimension(:, :), allocatable :: dshape_dot_dshape_integral_a, dshape_dot_dshape_integral_c type(element_type) :: shape_a, shape_c type(element_type), dimension(:), allocatable :: shapes_c type(mesh_type) :: mesh_a, mesh_c, shape_mesh type(quadrature_type) :: quad type(vector_field) :: positions_a, positions_c do degree = 0, 4 print *, "Degree = ", degree quad = make_quadrature(vertices = 3, dim = 2, degree = max(degree * 2, 1)) shape_a = make_element_shape(vertices = 3, dim = 2, degree = 1, quad = quad) shape_c = make_element_shape(vertices = 3, dim = 2, degree = degree, quad = quad) call deallocate(quad) call allocate(mesh_a, nodes = 3, elements = 1, shape = shape_a, name = "TargetMesh") call set_ele_nodes(mesh_a, 1, (/1, 2, 3/)) call allocate(positions_a, dim = 2, mesh = mesh_a, name = "TargetCoordinate") call deallocate(mesh_a) call set(positions_a, 1, (/0.0, 0.0/)) call set(positions_a, 2, (/1.0, 0.0/)) call set(positions_a, 3, (/0.0, 1.0/)) call allocate(mesh_c, nodes = 4, elements = 3, shape = shape_a, name = "Supermesh") call deallocate(shape_a) call set_ele_nodes(mesh_c, 1, (/1, 2, 4/)) call set_ele_nodes(mesh_c, 2, (/4, 2, 3/)) call set_ele_nodes(mesh_c, 3, (/3, 1, 4/)) allocate(mesh_c%region_ids(3)) mesh_c%region_ids = (/1, 1, 1/) call allocate(positions_c, dim = 2, mesh = mesh_c, name = "SupermeshCoordinate") call deallocate(mesh_c) call set(positions_c, 1, (/0.0, 0.0/)) call set(positions_c, 2, (/1.0, 0.0/)) call set(positions_c, 3, (/0.0, 1.0/)) call set(positions_c, 4, (/0.25, 0.25/)) shape_mesh = make_mesh(positions_a%mesh, shape = shape_c, continuity = -1, name = "ShapeMesh") call deallocate(shape_c) call project_donor_shape_to_supermesh(positions_a, shape_mesh, positions_c, & & shapes_c, form_dn = .true.) allocate(shape_rhs_integral_a(ele_loc(shape_mesh, 1))) shape_rhs_integral_a = shape_rhs_integral_ele(1, positions_a, ele_shape(shape_mesh, 1)) allocate(shape_rhs_integral_c(ele_loc(shape_mesh, 1))) shape_rhs_integral_c = 0.0 do i = 1, ele_count(positions_c) shape_rhs_integral_c = shape_rhs_integral_c + shape_rhs_integral_ele(i, positions_c, shapes_c(i)) end do call report_test("[shape_rhs on supermesh]", shape_rhs_integral_a .fne. shape_rhs_integral_c, .false., "Incorrect integral") deallocate(shape_rhs_integral_a) deallocate(shape_rhs_integral_c) allocate(dshape_dot_dshape_integral_a(ele_loc(shape_mesh, 1), ele_loc(shape_mesh, 1))) dshape_dot_dshape_integral_a = dshape_dot_dshape_integral_ele(1, positions_a, ele_shape(shape_mesh, 1)) allocate(dshape_dot_dshape_integral_c(ele_loc(shape_mesh, 1), ele_loc(shape_mesh, 1))) dshape_dot_dshape_integral_c = 0.0 do i = 1, ele_count(positions_c) dshape_dot_dshape_integral_c = dshape_dot_dshape_integral_c + dshape_dot_dshape_integral_ele(i, positions_c, shapes_c(i)) end do call report_test("[dshape_dot_dshape on supermesh]", fnequals(dshape_dot_dshape_integral_a, dshape_dot_dshape_integral_c, tol = 1.0e3 * epsilon(0.0)), .false., "Incorrect integral") deallocate(dshape_dot_dshape_integral_a) deallocate(dshape_dot_dshape_integral_c) do i = 1, size(shapes_c) call deallocate(shapes_c(i)) end do deallocate(shapes_c) call deallocate(positions_a) call deallocate(positions_c) call deallocate(shape_mesh) call report_test_no_references() end do contains function shape_rhs_integral_ele(ele, positions, shape) result(integral) integer, intent(in) :: ele type(vector_field), intent(in) :: positions type(element_type), intent(in) :: shape real, dimension(shape%loc) :: integral real, dimension(ele_ngi(positions, ele)) :: detwei call transform_to_physical(positions, ele, detwei = detwei) integral = shape_rhs(shape, detwei) end function shape_rhs_integral_ele function dshape_dot_dshape_integral_ele(ele, positions, shape) result(integral) integer, intent(in) :: ele type(vector_field), intent(in) :: positions type(element_type), intent(in) :: shape real, dimension(shape%loc, shape%loc) :: integral real, dimension(ele_ngi(positions, ele)) :: detwei real, dimension(shape%loc, ele_ngi(positions, ele), positions%dim) :: dn call transform_to_physical(positions, ele, shape, & & dshape = dn, detwei = detwei) integral = dshape_dot_dshape(dn, dn, detwei) end function dshape_dot_dshape_integral_ele end subroutine test_supermesh_shapes_ac
lgpl-2.1
Gd58/gcc
gcc/testsuite/gfortran.dg/interface_3.f90
155
1587
! { dg-do compile } ! Tests the fix for PR20880, which was due to failure to the failure ! to detect the USE association of a nameless interface for a ! procedure with the same name as the encompassing scope. ! ! Contributed by Joost VandeVondele <jv244@cam.ac.uk> ! ! Modified for PR fortran/34657 ! module test_mod interface subroutine my_sub (a) real a end subroutine end interface interface function my_fun (a) real a, my_fun end function end interface end module module test_mod2 interface function my_fun (a) real a, my_fun end function end interface end module ! This is the original PR, excepting that the error requires the symbol ! to be referenced. subroutine my_sub (a) use test_mod ! { dg-error "is also the name of the current program unit" } real a call my_sub (a) ! { dg-error "ambiguous reference" } print *, a end subroutine integer function my_fun (a) use test_mod ! { dg-error "is also the name of the current program unit" } real a print *, a my_fun = 1 ! { dg-error "ambiguous reference" } end function ! This was found whilst investigating => segfault subroutine thy_sub (a) interface subroutine thy_sub (a) ! { dg-error "enclosing procedure" } real a end subroutine end interface real a print *, a end subroutine subroutine thy_fun (a) use test_mod use test_mod2 ! OK because there is no reference to my_fun print *, a end subroutine thy_fun subroutine his_fun (a) use test_mod use test_mod2 print *, my_fun (a) ! { dg-error "ambiguous reference" } end subroutine his_fun
gpl-2.0
jrper/fluidity
libmba2d/minim.f
7
4425
C************************************************************* C MINIMIZATION OF THE NONLINEAR FUNCTIONAL FUNC(U) C IN GIVEN DIRECTION ZZ C************************************************************* Subroutine minim( C group(F) & nU, U, ZZ, Lamda1, Lamda2, fMin, U1, & icnt, rMove, flagResult, C group (ANI) & XYP, IPE, IEE, HesP, hStar, status, & lE, iEs, XYPs, IPEs, detGs, HesPs, qEs, & nPw, nEw, XYPw, HesPw, IPEw, & MetricFunction, flagAnalytic, & iSE, rSE, iP1, iFNCs, calCrv, & L1Et, L2Et, tE, & nL2t, nStept, nEt, nCrvFnc, LFnc, ILt, C group (Tangle) & flagTM, nBad) C =========================================================== include 'makS.fd' include 'status.fd' C =========================================================== C group (F) real U(*), ZZ(*), U1(*) real Lamda1, Lamda2, fMin, rMove Logical flagResult C group (ANI) Integer IPE(3, *), IEE(3, *) Integer iEs(*), IPEs(3, *), IPEw(3, *), iSE(*), status real XYP(2, *), HesP(3, *), hStar real XYPs(2, *), HesPs(*), detGs, qEs(*) real XYPw(2, *), HesPw(3, *), rSE(*) real tE(*) EXTERNAL calCrv Integer L1Et(2, *), L2Et(*) Integer nL2t(*), nStept(4, *), nEt(*) Integer LFnc(*), ILt(*) Logical flagAnalytic Integer MetricFunction EXTERNAL MetricFunction C group (Tangle) Logical flagTM Integer nBad C group (Local variables) real NLnFnc real Lamda, dLamda, step, x, f0, f1 real aStep real qEt(MaxS), XYPt(2), HesPt(3), detGt real XYPu(2) Integer iOs(MaxS) Logical flagOrient C =========================================================== flagResult = .FALSE. x = 0D0 Do i = 1, nU x = x + ZZ(i) ** 2 End do x = sqrt(x) Do i = 1, nU ZZ(i) = ZZ(i) / x End do x=Lamda1 Lamda1 = min(x, Lamda2) Lamda2 = max(x, Lamda2) icnt = 0 step = 5D-3 aStep = 0D0 dLamda = Lamda2 - Lamda1 f0 = fMin Call copySQ(lE, qEs, XYPs, HesPs, detGs, & qEt, XYPt, HesPt, detGt) 10 Lamda = step * dLamda If(Lamda.GT.(1D0 - aStep - step) * dLamda) Then f1 = f0 + 1D0 Else Do i = 1, nU U1(i) = U(i) + Lamda * ZZ(i) End do icnt = icnt + 1 f1 = NLnFnc(nU, U1, C group (ANI) & XYP, IPE, IEE, HesP, hStar, status, & lE, iEs, XYPs, IPEs, HesPs, detGs, qEs, & nPw, nEw, XYPw, HesPw, IPEw, & MetricFunction, flagAnalytic, & iSE, rSE, iP1, iFNCs, calCrv, & L1Et, L2Et, tE, & nL2t, nStept, nEt, nCrvFnc, LFnc, ILt) c ... checking for inverted elements If(flagTM) Then Do i = 1, 2 XYPu(i) = XYP(i, iP1) XYP(i, iP1) = XYPs(i, 1) End do Do n = 1, lE If(qEs(n).GT.0D0) Then Call updQb(n, lE, iEs, XYP, IPEs, qEs) End if End do Do i = 1, 2 XYP(i, iP1) = XYPu(i) End do mBad = 0 Do n = 1, lE If(qEs(n).LE.0D0) Then mBad = mBad + 1 f1 = max(f1, 1D0 - qEs(n)) End if End do If(mBad.GT.nBad) f1 = f0 + 1D0 c ... checking orientation of triangles Else Call calSO(XYP, IPE, lE, iEs, iOs) Call chkSO(iP1, iP1, XYPs, XYP, IPE, lE, iEs, iOs, & flagOrient) If(.NOT.flagOrient) f1 = f0 + 1D0 End if End if If(f1.LT.f0) Then f0 = f1 Do i = 1, nU U(i) = U1(i) End do flagResult = .TRUE. Call copySQ(lE, qEs, XYPs, HesPs, detGs, & qEt, XYPt, HesPt, detGt) aStep = aStep + step step = 4D0 * step Else step = step / 4D0 If(step.LT.1D-5) Then fMin = f0 rMove = aStep * dLamda goto 1000 End if End if goto 10 1000 Call copySQ(lE, qEt, XYPt, HesPt, detGt, & qEs, XYPs, HesPs, detGs) 9000 Return End
lgpl-2.1
Gd58/gcc
gcc/testsuite/gfortran.dg/vect/fast-math-vect-8.f90
56
2073
! { dg-do compile } ! { dg-require-effective-target vect_float } ! { dg-require-visibility "" } module solv_cap implicit none public :: init_solve integer, parameter, public :: dp = 4 real(kind=dp), private :: Pi, Mu0, c0, eps0 logical, private :: UseFFT, UsePreco real(kind=dp), private :: D1, D2 integer, private, save :: Ng1=0, Ng2=0 integer, private, pointer, dimension(:,:) :: Grid real(kind=dp), private, allocatable, dimension(:,:) :: G contains subroutine init_solve(Grid_in, GrSize1, GrSize2, UseFFT_in, UsePreco_in) integer, intent(in), target, dimension(:,:) :: Grid_in real(kind=dp), intent(in) :: GrSize1, GrSize2 logical, intent(in) :: UseFFT_in, UsePreco_in integer :: i, j Pi = acos(-1.0_dp) Mu0 = 4e-7_dp * Pi c0 = 299792458 eps0 = 1 / (Mu0 * c0**2) UseFFT = UseFFT_in UsePreco = UsePreco_in if(Ng1 /= 0 .and. allocated(G) ) then deallocate( G ) end if Grid => Grid_in Ng1 = size(Grid, 1) Ng2 = size(Grid, 2) D1 = GrSize1/Ng1 D2 = GrSize2/Ng2 allocate( G(0:Ng1,0:Ng2) ) write(unit=*, fmt=*) "Calculating G" do i=0,Ng1 do j=0,Ng2 G(j,i) = Ginteg( -D1/2,-D2/2, D1/2,D2/2, i*D1,j*D2 ) end do end do if(UseFFT) then write(unit=*, fmt=*) "Transforming G" call FourirG(G,1) end if return contains function Ginteg(xq1,yq1, xq2,yq2, xp,yp) result(G) real(kind=dp), intent(in) :: xq1,yq1, xq2,yq2, xp,yp real(kind=dp) :: G real(kind=dp) :: x1,x2,y1,y2,t x1 = xq1-xp x2 = xq2-xp y1 = yq1-yp y2 = yq2-yp if (x1+x2 < 0) then t = -x1 x1 = -x2 x2 = t end if if (y1+y2 < 0) then t = -y1 y1 = -y2 y2 = t end if G = (x2*y2)-(x1*y2)-(x2*y1)+(x1*y1) return end function Ginteg end subroutine init_solve end module solv_cap ! { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { target vect_intfloat_cvt } } }
gpl-2.0
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/operator_4.f90
155
2879
! PR 17711 : Verify error message text meets operator in source ! { dg-do compile } MODULE mod_t type :: t integer :: x end type INTERFACE OPERATOR(==) MODULE PROCEDURE t_eq END INTERFACE INTERFACE OPERATOR(/=) MODULE PROCEDURE t_ne END INTERFACE INTERFACE OPERATOR(>) MODULE PROCEDURE t_gt END INTERFACE INTERFACE OPERATOR(>=) MODULE PROCEDURE t_ge END INTERFACE INTERFACE OPERATOR(<) MODULE PROCEDURE t_lt END INTERFACE INTERFACE OPERATOR(<=) MODULE PROCEDURE t_le END INTERFACE CONTAINS LOGICAL FUNCTION t_eq(this, other) TYPE(t), INTENT(in) :: this, other t_eq = (this%x == other%x) END FUNCTION LOGICAL FUNCTION t_ne(this, other) TYPE(t), INTENT(in) :: this, other t_ne = (this%x /= other%x) END FUNCTION LOGICAL FUNCTION t_gt(this, other) TYPE(t), INTENT(in) :: this, other t_gt = (this%x > other%x) END FUNCTION LOGICAL FUNCTION t_ge(this, other) TYPE(t), INTENT(in) :: this, other t_ge = (this%x >= other%x) END FUNCTION LOGICAL FUNCTION t_lt(this, other) TYPE(t), INTENT(in) :: this, other t_lt = (this%x < other%x) END FUNCTION LOGICAL FUNCTION t_le(this, other) TYPE(t), INTENT(in) :: this, other t_le = (this%x <= other%x) END FUNCTION END MODULE PROGRAM pr17711 USE mod_t LOGICAL :: A INTEGER :: B TYPE(t) :: C A = (A == B) ! { dg-error "comparison operator '=='" } A = (A.EQ.B) ! { dg-error "comparison operator '.eq.'" } A = (A /= B) ! { dg-error "comparison operator '/='" } A = (A.NE.B) ! { dg-error "comparison operator '.ne.'" } A = (A <= B) ! { dg-error "comparison operator '<='" } A = (A.LE.B) ! { dg-error "comparison operator '.le.'" } A = (A < B) ! { dg-error "comparison operator '<'" } A = (A.LT.B) ! { dg-error "comparison operator '.lt.'" } A = (A >= B) ! { dg-error "comparison operator '>='" } A = (A.GE.B) ! { dg-error "comparison operator '.ge.'" } A = (A > B) ! { dg-error "comparison operator '>'" } A = (A.GT.B) ! { dg-error "comparison operator '.gt.'" } ! this should also work with user defined operators A = (A == C) ! { dg-error "comparison operator '=='" } A = (A.EQ.C) ! { dg-error "comparison operator '.eq.'" } A = (A /= C) ! { dg-error "comparison operator '/='" } A = (A.NE.C) ! { dg-error "comparison operator '.ne.'" } A = (A <= C) ! { dg-error "comparison operator '<='" } A = (A.LE.C) ! { dg-error "comparison operator '.le.'" } A = (A < C) ! { dg-error "comparison operator '<'" } A = (A.LT.C) ! { dg-error "comparison operator '.lt.'" } A = (A >= C) ! { dg-error "comparison operator '>='" } A = (A.GE.C) ! { dg-error "comparison operator '.ge.'" } A = (A > C) ! { dg-error "comparison operator '>'" } A = (A.GT.C) ! { dg-error "comparison operator '.gt.'" } END PROGRAM
gpl-2.0
PHASTA/phasta
phSolver/incompressible/asbflx.f
5
3233
subroutine AsBFlx (u, y, ac, & x, shpb, & shglb, ienb, iBCB, & BCB, invflx, flxres, & flxLHS, flxnrm, xKebe ) c c---------------------------------------------------------------------- c c This routine computes and assembles the data corresponding to the c boundary elements. c c Zdenek Johan, Winter 1991. (Fortran 90) c---------------------------------------------------------------------- c use turbSA ! access to d2wall include "common.h" c dimension y(nshg,ndofl), x(numnp,nsd), & ac(nshg,ndofl), u(nshg,nsd), & shpb(nshl,ngaussb), & shglb(nsd,nshl,ngaussb), & ienb(npro,nshl), & iBCB(npro,ndiBCB), BCB(npro,nshlb,ndBCB), & invflx(nshg), flxres(nshg,nflow), & flxLHS(nshg,1), flxnrm(nshg,nsd) c dimension yl(npro,nshl,ndofl), xlb(npro,nenl,nsd), & rl(npro,nshl,nflow), sgn(npro,nshl), & flhsl(npro,nshl,1), fnrml(npro,nshl,nsd), & lnflx(npro), lnode(27), & ul(npro,nshl,nsd), acl(npro,nshl,ndofl) real*8 dwl(npro,nshl) dimension xKebe(npro,9,nshl,nshl) c c.... compute the nodes which lie on the boundary (hierarchic) c call getbnodes(lnode) c c.... get the matrix of mode signs for the hierarchic basis functions c if (ipord .gt. 1) then call getsgn(ienb,sgn) endif c c.... gather the variables c call localy(y, yl, ienb, ndofl, 'gather ') call localy(ac, acl, ienb, ndofl, 'gather ') call localx(x, xlb, ienb, nsd, 'gather ') call localx(u, ul, ienb, nsd, 'gather ') if(iRANS.eq.-2) then call local(d2wall, dwl, ienb, 1, 'gather ') endif rl = zero flhsl = zero fnrml = zero c ires = 2 call e3b (ul, yl, acl, iBCB, BCB, & shpb, shglb, & xlb, rl, sgn, dwl, xKebe) ires = 1 c c.... assemble the residuals c call local (flxres, rl, ienb, nflow, 'scatter ') c c.... compute the LHS for the flux computation (should only be done c once) c call f3lhs (shpb, shglb, xlb, & flhsl, fnrml, sgn ) c c.... reset the non-contributing element values c lnflx = 0 do n = 1, nshlb lnflx = lnflx + min(1, invflx(ienb(:,lnode(n)))) enddo c do n = 1, nshl where (lnflx .ne. nshlb) flhsl(:,n,1) = zero do i = 1, nsd where (lnflx .ne. nshlb) fnrml(:,n,i) = zero enddo enddo c c.... assemble the boundary LHS and normal c call local (flxLHS, flhsl, ienb, 1, 'scatter ') call local (flxnrm, fnrml, ienb, nsd, 'scatter ') c c.... end c return end
bsd-3-clause
CapeDrew/DITK
Modules/ThirdParty/VNL/src/vxl/v3p/netlib/lapack/complex16/zgebal.f
44
9063
SUBROUTINE ZGEBAL( JOB, N, A, LDA, ILO, IHI, SCALE, INFO ) * * -- LAPACK routine (version 3.0) -- * Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., * Courant Institute, Argonne National Lab, and Rice University * June 30, 1999 * * .. Scalar Arguments .. CHARACTER JOB INTEGER IHI, ILO, INFO, LDA, N * .. * .. Array Arguments .. DOUBLE PRECISION SCALE( * ) COMPLEX*16 A( LDA, * ) * .. * * Purpose * ======= * * ZGEBAL balances a general complex matrix A. This involves, first, * permuting A by a similarity transformation to isolate eigenvalues * in the first 1 to ILO-1 and last IHI+1 to N elements on the * diagonal; and second, applying a diagonal similarity transformation * to rows and columns ILO to IHI to make the rows and columns as * close in norm as possible. Both steps are optional. * * Balancing may reduce the 1-norm of the matrix, and improve the * accuracy of the computed eigenvalues and/or eigenvectors. * * Arguments * ========= * * JOB (input) CHARACTER*1 * Specifies the operations to be performed on A: * = 'N': none: simply set ILO = 1, IHI = N, SCALE(I) = 1.0 * for i = 1,...,N; * = 'P': permute only; * = 'S': scale only; * = 'B': both permute and scale. * * N (input) INTEGER * The order of the matrix A. N >= 0. * * A (input/output) COMPLEX*16 array, dimension (LDA,N) * On entry, the input matrix A. * On exit, A is overwritten by the balanced matrix. * If JOB = 'N', A is not referenced. * See Further Details. * * LDA (input) INTEGER * The leading dimension of the array A. LDA >= max(1,N). * * ILO (output) INTEGER * IHI (output) INTEGER * ILO and IHI are set to integers such that on exit * A(i,j) = 0 if i > j and j = 1,...,ILO-1 or I = IHI+1,...,N. * If JOB = 'N' or 'S', ILO = 1 and IHI = N. * * SCALE (output) DOUBLE PRECISION array, dimension (N) * Details of the permutations and scaling factors applied to * A. If P(j) is the index of the row and column interchanged * with row and column j and D(j) is the scaling factor * applied to row and column j, then * SCALE(j) = P(j) for j = 1,...,ILO-1 * = D(j) for j = ILO,...,IHI * = P(j) for j = IHI+1,...,N. * The order in which the interchanges are made is N to IHI+1, * then 1 to ILO-1. * * INFO (output) INTEGER * = 0: successful exit. * < 0: if INFO = -i, the i-th argument had an illegal value. * * Further Details * =============== * * The permutations consist of row and column interchanges which put * the matrix in the form * * ( T1 X Y ) * P A P = ( 0 B Z ) * ( 0 0 T2 ) * * where T1 and T2 are upper triangular matrices whose eigenvalues lie * along the diagonal. The column indices ILO and IHI mark the starting * and ending columns of the submatrix B. Balancing consists of applying * a diagonal similarity transformation inv(D) * B * D to make the * 1-norms of each row of B and its corresponding column nearly equal. * The output matrix is * * ( T1 X*D Y ) * ( 0 inv(D)*B*D inv(D)*Z ). * ( 0 0 T2 ) * * Information about the permutations P and the diagonal matrix D is * returned in the vector SCALE. * * This subroutine is based on the EISPACK routine CBAL. * * Modified by Tzu-Yi Chen, Computer Science Division, University of * California at Berkeley, USA * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ZERO, ONE PARAMETER ( ZERO = 0.0D+0, ONE = 1.0D+0 ) DOUBLE PRECISION SCLFAC PARAMETER ( SCLFAC = 0.8D+1 ) DOUBLE PRECISION FACTOR PARAMETER ( FACTOR = 0.95D+0 ) * .. * .. Local Scalars .. LOGICAL NOCONV INTEGER I, ICA, IEXC, IRA, J, K, L, M DOUBLE PRECISION C, CA, F, G, R, RA, S, SFMAX1, SFMAX2, SFMIN1, $ SFMIN2 COMPLEX*16 CDUM * .. * .. External Functions .. LOGICAL LSAME INTEGER IZAMAX DOUBLE PRECISION DLAMCH EXTERNAL LSAME, IZAMAX, DLAMCH * .. * .. External Subroutines .. EXTERNAL XERBLA, ZDSCAL, ZSWAP * .. * .. Intrinsic Functions .. INTRINSIC ABS, DBLE, DIMAG, MAX, MIN * .. * .. Statement Functions .. DOUBLE PRECISION CABS1 * .. * .. Statement Function definitions .. CABS1( CDUM ) = ABS( DBLE( CDUM ) ) + ABS( DIMAG( CDUM ) ) * .. * .. Executable Statements .. * * Test the input parameters * INFO = 0 IF( .NOT.LSAME( JOB, 'N' ) .AND. .NOT.LSAME( JOB, 'P' ) .AND. $ .NOT.LSAME( JOB, 'S' ) .AND. .NOT.LSAME( JOB, 'B' ) ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -4 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'ZGEBAL', -INFO ) RETURN END IF * K = 1 L = N * IF( N.EQ.0 ) $ GO TO 210 * IF( LSAME( JOB, 'N' ) ) THEN DO 10 I = 1, N SCALE( I ) = ONE 10 CONTINUE GO TO 210 END IF * IF( LSAME( JOB, 'S' ) ) $ GO TO 120 * * Permutation to isolate eigenvalues if possible * GO TO 50 * * Row and column exchange. * 20 CONTINUE SCALE( M ) = J IF( J.EQ.M ) $ GO TO 30 * CALL ZSWAP( L, A( 1, J ), 1, A( 1, M ), 1 ) CALL ZSWAP( N-K+1, A( J, K ), LDA, A( M, K ), LDA ) * 30 CONTINUE GO TO ( 40, 80 )IEXC * * Search for rows isolating an eigenvalue and push them down. * 40 CONTINUE IF( L.EQ.1 ) $ GO TO 210 L = L - 1 * 50 CONTINUE DO 70 J = L, 1, -1 * DO 60 I = 1, L IF( I.EQ.J ) $ GO TO 60 IF( DBLE( A( J, I ) ).NE.ZERO .OR. DIMAG( A( J, I ) ).NE. $ ZERO )GO TO 70 60 CONTINUE * M = L IEXC = 1 GO TO 20 70 CONTINUE * GO TO 90 * * Search for columns isolating an eigenvalue and push them left. * 80 CONTINUE K = K + 1 * 90 CONTINUE DO 110 J = K, L * DO 100 I = K, L IF( I.EQ.J ) $ GO TO 100 IF( DBLE( A( I, J ) ).NE.ZERO .OR. DIMAG( A( I, J ) ).NE. $ ZERO )GO TO 110 100 CONTINUE * M = K IEXC = 2 GO TO 20 110 CONTINUE * 120 CONTINUE DO 130 I = K, L SCALE( I ) = ONE 130 CONTINUE * IF( LSAME( JOB, 'P' ) ) $ GO TO 210 * * Balance the submatrix in rows K to L. * * Iterative loop for norm reduction * SFMIN1 = DLAMCH( 'S' ) / DLAMCH( 'P' ) SFMAX1 = ONE / SFMIN1 SFMIN2 = SFMIN1*SCLFAC SFMAX2 = ONE / SFMIN2 140 CONTINUE NOCONV = .FALSE. * DO 200 I = K, L C = ZERO R = ZERO * DO 150 J = K, L IF( J.EQ.I ) $ GO TO 150 C = C + CABS1( A( J, I ) ) R = R + CABS1( A( I, J ) ) 150 CONTINUE ICA = IZAMAX( L, A( 1, I ), 1 ) CA = ABS( A( ICA, I ) ) IRA = IZAMAX( N-K+1, A( I, K ), LDA ) RA = ABS( A( I, IRA+K-1 ) ) * * Guard against zero C or R due to underflow. * IF( C.EQ.ZERO .OR. R.EQ.ZERO ) $ GO TO 200 G = R / SCLFAC F = ONE S = C + R 160 CONTINUE IF( C.GE.G .OR. MAX( F, C, CA ).GE.SFMAX2 .OR. $ MIN( R, G, RA ).LE.SFMIN2 )GO TO 170 F = F*SCLFAC C = C*SCLFAC CA = CA*SCLFAC R = R / SCLFAC G = G / SCLFAC RA = RA / SCLFAC GO TO 160 * 170 CONTINUE G = C / SCLFAC 180 CONTINUE IF( G.LT.R .OR. MAX( R, RA ).GE.SFMAX2 .OR. $ MIN( F, C, G, CA ).LE.SFMIN2 )GO TO 190 F = F / SCLFAC C = C / SCLFAC G = G / SCLFAC CA = CA / SCLFAC R = R*SCLFAC RA = RA*SCLFAC GO TO 180 * * Now balance. * 190 CONTINUE IF( ( C+R ).GE.FACTOR*S ) $ GO TO 200 IF( F.LT.ONE .AND. SCALE( I ).LT.ONE ) THEN IF( F*SCALE( I ).LE.SFMIN1 ) $ GO TO 200 END IF IF( F.GT.ONE .AND. SCALE( I ).GT.ONE ) THEN IF( SCALE( I ).GE.SFMAX1 / F ) $ GO TO 200 END IF G = ONE / F SCALE( I ) = SCALE( I )*F NOCONV = .TRUE. * CALL ZDSCAL( N-K+1, G, A( I, K ), LDA ) CALL ZDSCAL( L, F, A( 1, I ), 1 ) * 200 CONTINUE * IF( NOCONV ) $ GO TO 140 * 210 CONTINUE ILO = K IHI = L * RETURN * * End of ZGEBAL * END
apache-2.0
mingwpy/scipy
scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/snaupd.f
103
29700
c\BeginDoc c c\Name: snaupd c c\Description: c Reverse communication interface for the Implicitly Restarted Arnoldi c iteration. This subroutine computes approximations to a few eigenpairs c of a linear operator "OP" with respect to a semi-inner product defined by c a symmetric positive semi-definite real matrix B. B may be the identity c matrix. NOTE: If the linear operator "OP" is real and symmetric c with respect to the real positive semi-definite symmetric matrix B, c i.e. B*OP = (OP`)*B, then subroutine ssaupd should be used instead. c c The computed approximate eigenvalues are called Ritz values and c the corresponding approximate eigenvectors are called Ritz vectors. c c snaupd is usually called iteratively to solve one of the c following problems: c c Mode 1: A*x = lambda*x. c ===> OP = A and B = I. c c Mode 2: A*x = lambda*M*x, M symmetric positive definite c ===> OP = inv[M]*A and B = M. c ===> (If M can be factored see remark 3 below) c c Mode 3: A*x = lambda*M*x, M symmetric semi-definite c ===> OP = Real_Part{ inv[A - sigma*M]*M } and B = M. c ===> shift-and-invert mode (in real arithmetic) c If OP*x = amu*x, then c amu = 1/2 * [ 1/(lambda-sigma) + 1/(lambda-conjg(sigma)) ]. c Note: If sigma is real, i.e. imaginary part of sigma is zero; c Real_Part{ inv[A - sigma*M]*M } == inv[A - sigma*M]*M c amu == 1/(lambda-sigma). c c Mode 4: A*x = lambda*M*x, M symmetric semi-definite c ===> OP = Imaginary_Part{ inv[A - sigma*M]*M } and B = M. c ===> shift-and-invert mode (in real arithmetic) c If OP*x = amu*x, then c amu = 1/2i * [ 1/(lambda-sigma) - 1/(lambda-conjg(sigma)) ]. c c Both mode 3 and 4 give the same enhancement to eigenvalues close to c the (complex) shift sigma. However, as lambda goes to infinity, c the operator OP in mode 4 dampens the eigenvalues more strongly than c does OP defined in mode 3. c c NOTE: The action of w <- inv[A - sigma*M]*v or w <- inv[M]*v c should be accomplished either by a direct method c using a sparse matrix factorization and solving c c [A - sigma*M]*w = v or M*w = v, c c or through an iterative method for solving these c systems. If an iterative method is used, the c convergence test must be more stringent than c the accuracy requirements for the eigenvalue c approximations. c c\Usage: c call snaupd c ( IDO, BMAT, N, WHICH, NEV, TOL, RESID, NCV, V, LDV, IPARAM, c IPNTR, WORKD, WORKL, LWORKL, INFO ) c c\Arguments c IDO Integer. (INPUT/OUTPUT) c Reverse communication flag. IDO must be zero on the first c call to snaupd. IDO will be set internally to c indicate the type of operation to be performed. Control is c then given back to the calling routine which has the c responsibility to carry out the requested operation and call c snaupd with the result. The operand is given in c WORKD(IPNTR(1)), the result must be put in WORKD(IPNTR(2)). c ------------------------------------------------------------- c IDO = 0: first call to the reverse communication interface c IDO = -1: compute Y = OP * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c This is for the initialization phase to force the c starting vector into the range of OP. c IDO = 1: compute Y = OP * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c In mode 3 and 4, the vector B * X is already c available in WORKD(ipntr(3)). It does not c need to be recomputed in forming OP * X. c IDO = 2: compute Y = B * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c IDO = 3: compute the IPARAM(8) real and imaginary parts c of the shifts where INPTR(14) is the pointer c into WORKL for placing the shifts. See Remark c 5 below. c IDO = 99: done c ------------------------------------------------------------- c c BMAT Character*1. (INPUT) c BMAT specifies the type of the matrix B that defines the c semi-inner product for the operator OP. c BMAT = 'I' -> standard eigenvalue problem A*x = lambda*x c BMAT = 'G' -> generalized eigenvalue problem A*x = lambda*B*x c c N Integer. (INPUT) c Dimension of the eigenproblem. c c WHICH Character*2. (INPUT) c 'LM' -> want the NEV eigenvalues of largest magnitude. c 'SM' -> want the NEV eigenvalues of smallest magnitude. c 'LR' -> want the NEV eigenvalues of largest real part. c 'SR' -> want the NEV eigenvalues of smallest real part. c 'LI' -> want the NEV eigenvalues of largest imaginary part. c 'SI' -> want the NEV eigenvalues of smallest imaginary part. c c NEV Integer. (INPUT) c Number of eigenvalues of OP to be computed. 0 < NEV < N-1. c c TOL Real scalar. (INPUT) c Stopping criterion: the relative accuracy of the Ritz value c is considered acceptable if BOUNDS(I) .LE. TOL*ABS(RITZ(I)) c where ABS(RITZ(I)) is the magnitude when RITZ(I) is complex. c DEFAULT = wslamch('EPS') (machine precision as computed c by the LAPACK auxiliary subroutine wslamch). c c RESID Real array of length N. (INPUT/OUTPUT) c On INPUT: c If INFO .EQ. 0, a random initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c On OUTPUT: c RESID contains the final residual vector. c c NCV Integer. (INPUT) c Number of columns of the matrix V. NCV must satisfy the two c inequalities 2 <= NCV-NEV and NCV <= N. c This will indicate how many Arnoldi vectors are generated c at each iteration. After the startup phase in which NEV c Arnoldi vectors are generated, the algorithm generates c approximately NCV-NEV Arnoldi vectors at each subsequent update c iteration. Most of the cost in generating each Arnoldi vector is c in the matrix-vector operation OP*x. c NOTE: 2 <= NCV-NEV in order that complex conjugate pairs of Ritz c values are kept together. (See remark 4 below) c c V Real array N by NCV. (OUTPUT) c Contains the final set of Arnoldi basis vectors. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling program. c c IPARAM Integer array of length 11. (INPUT/OUTPUT) c IPARAM(1) = ISHIFT: method for selecting the implicit shifts. c The shifts selected at each iteration are used to restart c the Arnoldi iteration in an implicit fashion. c ------------------------------------------------------------- c ISHIFT = 0: the shifts are provided by the user via c reverse communication. The real and imaginary c parts of the NCV eigenvalues of the Hessenberg c matrix H are returned in the part of the WORKL c array corresponding to RITZR and RITZI. See remark c 5 below. c ISHIFT = 1: exact shifts with respect to the current c Hessenberg matrix H. This is equivalent to c restarting the iteration with a starting vector c that is a linear combination of approximate Schur c vectors associated with the "wanted" Ritz values. c ------------------------------------------------------------- c c IPARAM(2) = No longer referenced. c c IPARAM(3) = MXITER c On INPUT: maximum number of Arnoldi update iterations allowed. c On OUTPUT: actual number of Arnoldi update iterations taken. c c IPARAM(4) = NB: blocksize to be used in the recurrence. c The code currently works only for NB = 1. c c IPARAM(5) = NCONV: number of "converged" Ritz values. c This represents the number of Ritz values that satisfy c the convergence criterion. c c IPARAM(6) = IUPD c No longer referenced. Implicit restarting is ALWAYS used. c c IPARAM(7) = MODE c On INPUT determines what type of eigenproblem is being solved. c Must be 1,2,3,4; See under \Description of snaupd for the c four modes available. c c IPARAM(8) = NP c When ido = 3 and the user provides shifts through reverse c communication (IPARAM(1)=0), snaupd returns NP, the number c of shifts the user is to provide. 0 < NP <=NCV-NEV. See Remark c 5 below. c c IPARAM(9) = NUMOP, IPARAM(10) = NUMOPB, IPARAM(11) = NUMREO, c OUTPUT: NUMOP = total number of OP*x operations, c NUMOPB = total number of B*x operations if BMAT='G', c NUMREO = total number of steps of re-orthogonalization. c c IPNTR Integer array of length 14. (OUTPUT) c Pointer to mark the starting locations in the WORKD and WORKL c arrays for matrices/vectors used by the Arnoldi iteration. c ------------------------------------------------------------- c IPNTR(1): pointer to the current operand vector X in WORKD. c IPNTR(2): pointer to the current result vector Y in WORKD. c IPNTR(3): pointer to the vector B * X in WORKD when used in c the shift-and-invert mode. c IPNTR(4): pointer to the next available location in WORKL c that is untouched by the program. c IPNTR(5): pointer to the NCV by NCV upper Hessenberg matrix c H in WORKL. c IPNTR(6): pointer to the real part of the ritz value array c RITZR in WORKL. c IPNTR(7): pointer to the imaginary part of the ritz value array c RITZI in WORKL. c IPNTR(8): pointer to the Ritz estimates in array WORKL associated c with the Ritz values located in RITZR and RITZI in WORKL. c c IPNTR(14): pointer to the NP shifts in WORKL. See Remark 5 below. c c Note: IPNTR(9:13) is only referenced by sneupd. See Remark 2 below. c c IPNTR(9): pointer to the real part of the NCV RITZ values of the c original system. c IPNTR(10): pointer to the imaginary part of the NCV RITZ values of c the original system. c IPNTR(11): pointer to the NCV corresponding error bounds. c IPNTR(12): pointer to the NCV by NCV upper quasi-triangular c Schur matrix for H. c IPNTR(13): pointer to the NCV by NCV matrix of eigenvectors c of the upper Hessenberg matrix H. Only referenced by c sneupd if RVEC = .TRUE. See Remark 2 below. c ------------------------------------------------------------- c c WORKD Real work array of length 3*N. (REVERSE COMMUNICATION) c Distributed array to be used in the basic Arnoldi iteration c for reverse communication. The user should not use WORKD c as temporary workspace during the iteration. Upon termination c WORKD(1:N) contains B*RESID(1:N). If an invariant subspace c associated with the converged Ritz values is desired, see remark c 2 below, subroutine sneupd uses this output. c See Data Distribution Note below. c c WORKL Real work array of length LWORKL. (OUTPUT/WORKSPACE) c Private (replicated) array on each PE or array allocated on c the front end. See Data Distribution Note below. c c LWORKL Integer. (INPUT) c LWORKL must be at least 3*NCV**2 + 6*NCV. c c INFO Integer. (INPUT/OUTPUT) c If INFO .EQ. 0, a randomly initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c Error flag on output. c = 0: Normal exit. c = 1: Maximum number of iterations taken. c All possible eigenvalues of OP has been found. IPARAM(5) c returns the number of wanted converged Ritz values. c = 2: No longer an informational error. Deprecated starting c with release 2 of ARPACK. c = 3: No shifts could be applied during a cycle of the c Implicitly restarted Arnoldi iteration. One possibility c is to increase the size of NCV relative to NEV. c See remark 4 below. c = -1: N must be positive. c = -2: NEV must be positive. c = -3: NCV-NEV >= 2 and less than or equal to N. c = -4: The maximum number of Arnoldi update iteration c must be greater than zero. c = -5: WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI' c = -6: BMAT must be one of 'I' or 'G'. c = -7: Length of private work array is not sufficient. c = -8: Error return from LAPACK eigenvalue calculation; c = -9: Starting vector is zero. c = -10: IPARAM(7) must be 1,2,3,4. c = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatable. c = -12: IPARAM(1) must be equal to 0 or 1. c = -9999: Could not build an Arnoldi factorization. c IPARAM(5) returns the size of the current Arnoldi c factorization. c c\Remarks c 1. The computed Ritz values are approximate eigenvalues of OP. The c selection of WHICH should be made with this in mind when c Mode = 3 and 4. After convergence, approximate eigenvalues of the c original problem may be obtained with the ARPACK subroutine sneupd. c c 2. If a basis for the invariant subspace corresponding to the converged Ritz c values is needed, the user must call sneupd immediately following c completion of snaupd. This is new starting with release 2 of ARPACK. c c 3. If M can be factored into a Cholesky factorization M = LL` c then Mode = 2 should not be selected. Instead one should use c Mode = 1 with OP = inv(L)*A*inv(L`). Appropriate triangular c linear systems should be solved with L and L` rather c than computing inverses. After convergence, an approximate c eigenvector z of the original problem is recovered by solving c L`z = x where x is a Ritz vector of OP. c c 4. At present there is no a-priori analysis to guide the selection c of NCV relative to NEV. The only formal requrement is that NCV > NEV + 2. c However, it is recommended that NCV .ge. 2*NEV+1. If many problems of c the same type are to be solved, one should experiment with increasing c NCV while keeping NEV fixed for a given test problem. This will c usually decrease the required number of OP*x operations but it c also increases the work and storage required to maintain the orthogonal c basis vectors. The optimal "cross-over" with respect to CPU time c is problem dependent and must be determined empirically. c See Chapter 8 of Reference 2 for further information. c c 5. When IPARAM(1) = 0, and IDO = 3, the user needs to provide the c NP = IPARAM(8) real and imaginary parts of the shifts in locations c real part imaginary part c ----------------------- -------------- c 1 WORKL(IPNTR(14)) WORKL(IPNTR(14)+NP) c 2 WORKL(IPNTR(14)+1) WORKL(IPNTR(14)+NP+1) c . . c . . c . . c NP WORKL(IPNTR(14)+NP-1) WORKL(IPNTR(14)+2*NP-1). c c Only complex conjugate pairs of shifts may be applied and the pairs c must be placed in consecutive locations. The real part of the c eigenvalues of the current upper Hessenberg matrix are located in c WORKL(IPNTR(6)) through WORKL(IPNTR(6)+NCV-1) and the imaginary part c in WORKL(IPNTR(7)) through WORKL(IPNTR(7)+NCV-1). They are ordered c according to the order defined by WHICH. The complex conjugate c pairs are kept together and the associated Ritz estimates are located in c WORKL(IPNTR(8)), WORKL(IPNTR(8)+1), ... , WORKL(IPNTR(8)+NCV-1). c c----------------------------------------------------------------------- c c\Data Distribution Note: c c Fortran-D syntax: c ================ c Real resid(n), v(ldv,ncv), workd(3*n), workl(lworkl) c decompose d1(n), d2(n,ncv) c align resid(i) with d1(i) c align v(i,j) with d2(i,j) c align workd(i) with d1(i) range (1:n) c align workd(i) with d1(i-n) range (n+1:2*n) c align workd(i) with d1(i-2*n) range (2*n+1:3*n) c distribute d1(block), d2(block,:) c replicated workl(lworkl) c c Cray MPP syntax: c =============== c Real resid(n), v(ldv,ncv), workd(n,3), workl(lworkl) c shared resid(block), v(block,:), workd(block,:) c replicated workl(lworkl) c c CM2/CM5 syntax: c ============== c c----------------------------------------------------------------------- c c include 'ex-nonsym.doc' c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c 3. B.N. Parlett & Y. Saad, "Complex Shift and Invert Strategies for c Real Matrices", Linear Algebra and its Applications, vol 88/89, c pp 575-595, (1987). c c\Routines called: c snaup2 ARPACK routine that implements the Implicitly Restarted c Arnoldi Iteration. c ivout ARPACK utility routine that prints integers. c arscnd ARPACK utility routine for timing. c svout ARPACK utility routine that prints vectors. c wslamch LAPACK routine that determines machine constants. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/16/93: Version '1.1' c c\SCCS Information: @(#) c FILE: naupd.F SID: 2.8 DATE OF SID: 04/10/01 RELEASE: 2 c c\Remarks c c\EndLib c c----------------------------------------------------------------------- c subroutine snaupd & ( ido, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, & ipntr, workd, workl, lworkl, info ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1, which*2 integer ido, info, ldv, lworkl, n, ncv, nev Real & tol c c %-----------------% c | Array Arguments | c %-----------------% c integer iparam(11), ipntr(14) Real & resid(n), v(ldv,ncv), workd(3*n), workl(lworkl) c c %------------% c | Parameters | c %------------% c Real & one, zero parameter (one = 1.0E+0 , zero = 0.0E+0 ) c c %---------------% c | Local Scalars | c %---------------% c integer bounds, ierr, ih, iq, ishift, iupd, iw, & ldh, ldq, levec, mode, msglvl, mxiter, nb, & nev0, next, np, ritzi, ritzr, j save bounds, ih, iq, ishift, iupd, iw, ldh, ldq, & levec, mode, msglvl, mxiter, nb, nev0, next, & np, ritzi, ritzr c c %----------------------% c | External Subroutines | c %----------------------% c external snaup2, svout, ivout, arscnd, sstatn c c %--------------------% c | External Functions | c %--------------------% c Real & wslamch external wslamch c c %-----------------------% c | Executable Statements | c %-----------------------% c if (ido .eq. 0) then c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call sstatn call arscnd (t0) msglvl = mnaupd c c %----------------% c | Error checking | c %----------------% c ierr = 0 ishift = iparam(1) c levec = iparam(2) mxiter = iparam(3) c nb = iparam(4) nb = 1 c c %--------------------------------------------% c | Revision 2 performs only implicit restart. | c %--------------------------------------------% c iupd = 1 mode = iparam(7) c if (n .le. 0) then ierr = -1 else if (nev .le. 0) then ierr = -2 else if (ncv .le. nev+1 .or. ncv .gt. n) then ierr = -3 else if (mxiter .le. 0) then ierr = -4 else if (which .ne. 'LM' .and. & which .ne. 'SM' .and. & which .ne. 'LR' .and. & which .ne. 'SR' .and. & which .ne. 'LI' .and. & which .ne. 'SI') then ierr = -5 else if (bmat .ne. 'I' .and. bmat .ne. 'G') then ierr = -6 else if (lworkl .lt. 3*ncv**2 + 6*ncv) then ierr = -7 else if (mode .lt. 1 .or. mode .gt. 4) then ierr = -10 else if (mode .eq. 1 .and. bmat .eq. 'G') then ierr = -11 else if (ishift .lt. 0 .or. ishift .gt. 1) then ierr = -12 end if c c %------------% c | Error Exit | c %------------% c if (ierr .ne. 0) then info = ierr ido = 99 go to 9000 end if c c %------------------------% c | Set default parameters | c %------------------------% c if (nb .le. 0) nb = 1 if (tol .le. zero) tol = wslamch('EpsMach') c c %----------------------------------------------% c | NP is the number of additional steps to | c | extend the length NEV Lanczos factorization. | c | NEV0 is the local variable designating the | c | size of the invariant subspace desired. | c %----------------------------------------------% c np = ncv - nev nev0 = nev c c %-----------------------------% c | Zero out internal workspace | c %-----------------------------% c do 10 j = 1, 3*ncv**2 + 6*ncv workl(j) = zero 10 continue c c %-------------------------------------------------------------% c | Pointer into WORKL for address of H, RITZ, BOUNDS, Q | c | etc... and the remaining workspace. | c | Also update pointer to be used on output. | c | Memory is laid out as follows: | c | workl(1:ncv*ncv) := generated Hessenberg matrix | c | workl(ncv*ncv+1:ncv*ncv+2*ncv) := real and imaginary | c | parts of ritz values | c | workl(ncv*ncv+2*ncv+1:ncv*ncv+3*ncv) := error bounds | c | workl(ncv*ncv+3*ncv+1:2*ncv*ncv+3*ncv) := rotation matrix Q | c | workl(2*ncv*ncv+3*ncv+1:3*ncv*ncv+6*ncv) := workspace | c | The final workspace is needed by subroutine sneigh called | c | by snaup2. Subroutine sneigh calls LAPACK routines for | c | calculating eigenvalues and the last row of the eigenvector | c | matrix. | c %-------------------------------------------------------------% c ldh = ncv ldq = ncv ih = 1 ritzr = ih + ldh*ncv ritzi = ritzr + ncv bounds = ritzi + ncv iq = bounds + ncv iw = iq + ldq*ncv next = iw + ncv**2 + 3*ncv c ipntr(4) = next ipntr(5) = ih ipntr(6) = ritzr ipntr(7) = ritzi ipntr(8) = bounds ipntr(14) = iw c end if c c %-------------------------------------------------------% c | Carry out the Implicitly restarted Arnoldi Iteration. | c %-------------------------------------------------------% c call snaup2 & ( ido, bmat, n, which, nev0, np, tol, resid, mode, iupd, & ishift, mxiter, v, ldv, workl(ih), ldh, workl(ritzr), & workl(ritzi), workl(bounds), workl(iq), ldq, workl(iw), & ipntr, workd, info ) c c %--------------------------------------------------% c | ido .ne. 99 implies use of reverse communication | c | to compute operations involving OP or shifts. | c %--------------------------------------------------% c if (ido .eq. 3) iparam(8) = np if (ido .ne. 99) go to 9000 c iparam(3) = mxiter iparam(5) = np iparam(9) = nopx iparam(10) = nbx iparam(11) = nrorth c c %------------------------------------% c | Exit if there was an informational | c | error within snaup2. | c %------------------------------------% c if (info .lt. 0) go to 9000 if (info .eq. 2) info = 3 c if (msglvl .gt. 0) then call ivout (logfil, 1, mxiter, ndigit, & '_naupd: Number of update iterations taken') call ivout (logfil, 1, np, ndigit, & '_naupd: Number of wanted "converged" Ritz values') call svout (logfil, np, workl(ritzr), ndigit, & '_naupd: Real part of the final Ritz values') call svout (logfil, np, workl(ritzi), ndigit, & '_naupd: Imaginary part of the final Ritz values') call svout (logfil, np, workl(bounds), ndigit, & '_naupd: Associated Ritz estimates') end if c call arscnd (t1) tnaupd = t1 - t0 c if (msglvl .gt. 0) then c c %--------------------------------------------------------% c | Version Number & Version Date are defined in version.h | c %--------------------------------------------------------% c write (6,1000) write (6,1100) mxiter, nopx, nbx, nrorth, nitref, nrstrt, & tmvopx, tmvbx, tnaupd, tnaup2, tnaitr, titref, & tgetv0, tneigh, tngets, tnapps, tnconv, trvec 1000 format (//, & 5x, '=============================================',/ & 5x, '= Nonsymmetric implicit Arnoldi update code =',/ & 5x, '= Version Number: ', ' 2.4' , 21x, ' =',/ & 5x, '= Version Date: ', ' 07/31/96' , 16x, ' =',/ & 5x, '=============================================',/ & 5x, '= Summary of timing statistics =',/ & 5x, '=============================================',//) 1100 format ( & 5x, 'Total number update iterations = ', i5,/ & 5x, 'Total number of OP*x operations = ', i5,/ & 5x, 'Total number of B*x operations = ', i5,/ & 5x, 'Total number of reorthogonalization steps = ', i5,/ & 5x, 'Total number of iterative refinement steps = ', i5,/ & 5x, 'Total number of restart steps = ', i5,/ & 5x, 'Total time in user OP*x operation = ', f12.6,/ & 5x, 'Total time in user B*x operation = ', f12.6,/ & 5x, 'Total time in Arnoldi update routine = ', f12.6,/ & 5x, 'Total time in naup2 routine = ', f12.6,/ & 5x, 'Total time in basic Arnoldi iteration loop = ', f12.6,/ & 5x, 'Total time in reorthogonalization phase = ', f12.6,/ & 5x, 'Total time in (re)start vector generation = ', f12.6,/ & 5x, 'Total time in Hessenberg eig. subproblem = ', f12.6,/ & 5x, 'Total time in getting the shifts = ', f12.6,/ & 5x, 'Total time in applying the shifts = ', f12.6,/ & 5x, 'Total time in convergence testing = ', f12.6,/ & 5x, 'Total time in computing final Ritz vectors = ', f12.6/) end if c 9000 continue c return c c %---------------% c | End of snaupd | c %---------------% c end
bsd-3-clause
Gd58/gcc
gcc/testsuite/gfortran.dg/array_function_3.f90
155
1631
! { dg-do compile } ! PR fortran/36167 ! This used to cause an ICE because of a missing array spec after interface ! mapping. ! Contributed by Frank Muldoon <fmuldoo@me.lsu.edu> module communication_tools contains !******************************************************************************* function overlap_1(u,lbound_u,ubound_u) !******************************************************************************* integer, intent(in), dimension(:) :: lbound_u,ubound_u real, intent(in), dimension(lbound_u(1):ubound_u(1),lbound_u(2):ubound_u(2),& lbound_u(3):ubound_u(3)) :: u real, dimension(& lbound(u,1):ubound(u,1),& lbound(u,2):ubound(u,2),& lbound(u,3):ubound(u,3)) :: overlap_1 return end function overlap_1 end module communication_tools !******************************************************************************* subroutine write_out_particles !******************************************************************************* use communication_tools real, dimension(1:5, 2:4, 3:10) :: vorticityMag real, allocatable, dimension(:,:,:) :: temp3d allocate(temp3d( & lbound(overlap_1(vorticityMag,lbound(vorticityMag),ubound(vorticityMag)),1):& ubound(overlap_1(vorticityMag,lbound(vorticityMag),ubound(vorticityMag)),1),& lbound(overlap_1(vorticityMag,lbound(vorticityMag),ubound(vorticityMag)),2):& ubound(overlap_1(vorticityMag,lbound(vorticityMag),ubound(vorticityMag)),2),& lbound(overlap_1(vorticityMag,lbound(vorticityMag),ubound(vorticityMag)),3):& ubound(overlap_1(vorticityMag,lbound(vorticityMag),ubound(vorticityMag)),3))) return end subroutine write_out_particles
gpl-2.0
sriki18/scipy
scipy/interpolate/fitpack/fppogr.f
148
14234
subroutine fppogr(iopt,ider,u,mu,v,mv,z,mz,z0,r,s,nuest,nvest, * tol,maxit,nc,nu,tu,nv,tv,c,fp,fp0,fpold,reducu,reducv,fpintu, * fpintv,dz,step,lastdi,nplusu,nplusv,lasttu,nru,nrv,nrdatu, * nrdatv,wrk,lwrk,ier) c .. c ..scalar arguments.. integer mu,mv,mz,nuest,nvest,maxit,nc,nu,nv,lastdi,nplusu,nplusv, * lasttu,lwrk,ier real*8 z0,r,s,tol,fp,fp0,fpold,reducu,reducv,step c ..array arguments.. integer iopt(3),ider(2),nrdatu(nuest),nrdatv(nvest),nru(mu), * nrv(mv) real*8 u(mu),v(mv),z(mz),tu(nuest),tv(nvest),c(nc),fpintu(nuest), * fpintv(nvest),dz(3),wrk(lwrk) c ..local scalars.. real*8 acc,fpms,f1,f2,f3,p,per,pi,p1,p2,p3,vb,ve,zmax,zmin,rn,one, * * con1,con4,con9 integer i,ich1,ich3,ifbu,ifbv,ifsu,ifsv,istart,iter,i1,i2,j,ju, * ktu,l,l1,l2,l3,l4,mpm,mumin,mu0,mu1,nn,nplu,nplv,npl1,nrintu, * nrintv,nue,numax,nve,nvmax c ..local arrays.. integer idd(2) real*8 dzz(3) c ..function references.. real*8 abs,datan2,fprati integer max0,min0 c ..subroutine references.. c fpknot,fpopdi c .. c set constants one = 1d0 con1 = 0.1e0 con9 = 0.9e0 con4 = 0.4e-01 c initialization ifsu = 0 ifsv = 0 ifbu = 0 ifbv = 0 p = -one mumin = 4-iopt(3) if(ider(1).ge.0) mumin = mumin-1 if(iopt(2).eq.1 .and. ider(2).eq.1) mumin = mumin-1 pi = datan2(0d0,-one) per = pi+pi vb = v(1) ve = vb+per cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c part 1: determination of the number of knots and their position. c c **************************************************************** c c given a set of knots we compute the least-squares spline sinf(u,v) c c and the corresponding sum of squared residuals fp = f(p=inf). c c if iopt(1)=-1 sinf(u,v) is the requested approximation. c c if iopt(1)>=0 we check whether we can accept the knots: c c if fp <= s we will continue with the current set of knots. c c if fp > s we will increase the number of knots and compute the c c corresponding least-squares spline until finally fp <= s. c c the initial choice of knots depends on the value of s and iopt. c c if s=0 we have spline interpolation; in that case the number of c c knots in the u-direction equals nu=numax=mu+5+iopt(2)+iopt(3) c c and in the v-direction nv=nvmax=mv+7. c c if s>0 and c c iopt(1)=0 we first compute the least-squares polynomial,i.e. a c c spline without interior knots : nu=8 ; nv=8. c c iopt(1)=1 we start with the set of knots found at the last call c c of the routine, except for the case that s > fp0; then we c c compute the least-squares polynomial directly. c cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc if(iopt(1).lt.0) go to 120 c acc denotes the absolute tolerance for the root of f(p)=s. acc = tol*s c numax and nvmax denote the number of knots needed for interpolation. numax = mu+5+iopt(2)+iopt(3) nvmax = mv+7 nue = min0(numax,nuest) nve = min0(nvmax,nvest) if(s.gt.0.) go to 100 c if s = 0, s(u,v) is an interpolating spline. nu = numax nv = nvmax c test whether the required storage space exceeds the available one. if(nu.gt.nuest .or. nv.gt.nvest) go to 420 c find the position of the knots in the v-direction. do 10 l=1,mv tv(l+3) = v(l) 10 continue tv(mv+4) = ve l1 = mv-2 l2 = mv+5 do 20 i=1,3 tv(i) = v(l1)-per tv(l2) = v(i+1)+per l1 = l1+1 l2 = l2+1 20 continue c if not all the derivative values g(i,j) are given, we will first c estimate these values by computing a least-squares spline idd(1) = ider(1) if(idd(1).eq.0) idd(1) = 1 if(idd(1).gt.0) dz(1) = z0 idd(2) = ider(2) if(ider(1).lt.0) go to 30 if(iopt(2).eq.0 .or. ider(2).ne.0) go to 70 c we set up the knots in the u-direction for computing the least-squares c spline. 30 i1 = 3 i2 = mu-2 nu = 4 do 40 i=1,mu if(i1.gt.i2) go to 50 nu = nu+1 tu(nu) = u(i1) i1 = i1+2 40 continue 50 do 60 i=1,4 tu(i) = 0. nu = nu+1 tu(nu) = r 60 continue c we compute the least-squares spline for estimating the derivatives. call fpopdi(ifsu,ifsv,ifbu,ifbv,u,mu,v,mv,z,mz,z0,dz,iopt,idd, * tu,nu,tv,nv,nuest,nvest,p,step,c,nc,fp,fpintu,fpintv,nru,nrv, * wrk,lwrk) ifsu = 0 c if all the derivatives at the origin are known, we compute the c interpolating spline. c we set up the knots in the u-direction, needed for interpolation. 70 nn = numax-8 if(nn.eq.0) go to 95 ju = 2-iopt(2) do 80 l=1,nn tu(l+4) = u(ju) ju = ju+1 80 continue nu = numax l = nu do 90 i=1,4 tu(i) = 0. tu(l) = r l = l-1 90 continue c we compute the interpolating spline. 95 call fpopdi(ifsu,ifsv,ifbu,ifbv,u,mu,v,mv,z,mz,z0,dz,iopt,idd, * tu,nu,tv,nv,nuest,nvest,p,step,c,nc,fp,fpintu,fpintv,nru,nrv, * wrk,lwrk) go to 430 c if s>0 our initial choice of knots depends on the value of iopt(1). 100 ier = 0 if(iopt(1).eq.0) go to 115 step = -step if(fp0.le.s) go to 115 c if iopt(1)=1 and fp0 > s we start computing the least-squares spline c according to the set of knots found at the last call of the routine. c we determine the number of grid coordinates u(i) inside each knot c interval (tu(l),tu(l+1)). l = 5 j = 1 nrdatu(1) = 0 mu0 = 2-iopt(2) mu1 = mu-2+iopt(3) do 105 i=mu0,mu1 nrdatu(j) = nrdatu(j)+1 if(u(i).lt.tu(l)) go to 105 nrdatu(j) = nrdatu(j)-1 l = l+1 j = j+1 nrdatu(j) = 0 105 continue c we determine the number of grid coordinates v(i) inside each knot c interval (tv(l),tv(l+1)). l = 5 j = 1 nrdatv(1) = 0 do 110 i=2,mv nrdatv(j) = nrdatv(j)+1 if(v(i).lt.tv(l)) go to 110 nrdatv(j) = nrdatv(j)-1 l = l+1 j = j+1 nrdatv(j) = 0 110 continue idd(1) = ider(1) idd(2) = ider(2) go to 120 c if iopt(1)=0 or iopt(1)=1 and s >= fp0,we start computing the least- c squares polynomial (which is a spline without interior knots). 115 ier = -2 idd(1) = ider(1) idd(2) = 1 nu = 8 nv = 8 nrdatu(1) = mu-3+iopt(2)+iopt(3) nrdatv(1) = mv-1 lastdi = 0 nplusu = 0 nplusv = 0 fp0 = 0. fpold = 0. reducu = 0. reducv = 0. c main loop for the different sets of knots.mpm=mu+mv is a save upper c bound for the number of trials. 120 mpm = mu+mv do 270 iter=1,mpm c find nrintu (nrintv) which is the number of knot intervals in the c u-direction (v-direction). nrintu = nu-7 nrintv = nv-7 c find the position of the additional knots which are needed for the c b-spline representation of s(u,v). i = nu do 130 j=1,4 tu(j) = 0. tu(i) = r i = i-1 130 continue l1 = 4 l2 = l1 l3 = nv-3 l4 = l3 tv(l2) = vb tv(l3) = ve do 140 j=1,3 l1 = l1+1 l2 = l2-1 l3 = l3+1 l4 = l4-1 tv(l2) = tv(l4)-per tv(l3) = tv(l1)+per 140 continue c find an estimate of the range of possible values for the optimal c derivatives at the origin. ktu = nrdatu(1)+2-iopt(2) if(nrintu.eq.1) ktu = mu if(ktu.lt.mumin) ktu = mumin if(ktu.eq.lasttu) go to 150 zmin = z0 zmax = z0 l = mv*ktu do 145 i=1,l if(z(i).lt.zmin) zmin = z(i) if(z(i).gt.zmax) zmax = z(i) 145 continue step = zmax-zmin lasttu = ktu c find the least-squares spline sinf(u,v). 150 call fpopdi(ifsu,ifsv,ifbu,ifbv,u,mu,v,mv,z,mz,z0,dz,iopt,idd, * tu,nu,tv,nv,nuest,nvest,p,step,c,nc,fp,fpintu,fpintv,nru,nrv, * wrk,lwrk) if(step.lt.0.) step = -step if(ier.eq.(-2)) fp0 = fp c test whether the least-squares spline is an acceptable solution. if(iopt(1).lt.0) go to 440 fpms = fp-s if(abs(fpms) .lt. acc) go to 440 c if f(p=inf) < s, we accept the choice of knots. if(fpms.lt.0.) go to 300 c if nu=numax and nv=nvmax, sinf(u,v) is an interpolating spline if(nu.eq.numax .and. nv.eq.nvmax) go to 430 c increase the number of knots. c if nu=nue and nv=nve we cannot further increase the number of knots c because of the storage capacity limitation. if(nu.eq.nue .and. nv.eq.nve) go to 420 if(ider(1).eq.0) fpintu(1) = fpintu(1)+(z0-c(1))**2 ier = 0 c adjust the parameter reducu or reducv according to the direction c in which the last added knots were located. if (lastdi.lt.0) go to 160 if (lastdi.eq.0) go to 155 go to 170 155 nplv = 3 idd(2) = ider(2) fpold = fp go to 230 160 reducu = fpold-fp go to 175 170 reducv = fpold-fp c store the sum of squared residuals for the current set of knots. 175 fpold = fp c find nplu, the number of knots we should add in the u-direction. nplu = 1 if(nu.eq.8) go to 180 npl1 = nplusu*2 rn = nplusu if(reducu.gt.acc) npl1 = rn*fpms/reducu nplu = min0(nplusu*2,max0(npl1,nplusu/2,1)) c find nplv, the number of knots we should add in the v-direction. 180 nplv = 3 if(nv.eq.8) go to 190 npl1 = nplusv*2 rn = nplusv if(reducv.gt.acc) npl1 = rn*fpms/reducv nplv = min0(nplusv*2,max0(npl1,nplusv/2,1)) c test whether we are going to add knots in the u- or v-direction. 190 if (nplu.lt.nplv) go to 210 if (nplu.eq.nplv) go to 200 go to 230 200 if(lastdi.lt.0) go to 230 210 if(nu.eq.nue) go to 230 c addition in the u-direction. lastdi = -1 nplusu = nplu ifsu = 0 istart = 0 if(iopt(2).eq.0) istart = 1 do 220 l=1,nplusu c add a new knot in the u-direction call fpknot(u,mu,tu,nu,fpintu,nrdatu,nrintu,nuest,istart) c test whether we cannot further increase the number of knots in the c u-direction. if(nu.eq.nue) go to 270 220 continue go to 270 230 if(nv.eq.nve) go to 210 c addition in the v-direction. lastdi = 1 nplusv = nplv ifsv = 0 do 240 l=1,nplusv c add a new knot in the v-direction. call fpknot(v,mv,tv,nv,fpintv,nrdatv,nrintv,nvest,1) c test whether we cannot further increase the number of knots in the c v-direction. if(nv.eq.nve) go to 270 240 continue c restart the computations with the new set of knots. 270 continue c test whether the least-squares polynomial is a solution of our c approximation problem. 300 if(ier.eq.(-2)) go to 440 cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c part 2: determination of the smoothing spline sp(u,v) c c ***************************************************** c c we have determined the number of knots and their position. we now c c compute the b-spline coefficients of the smoothing spline sp(u,v). c c this smoothing spline depends on the parameter p in such a way that c c f(p) = sumi=1,mu(sumj=1,mv((z(i,j)-sp(u(i),v(j)))**2) c c is a continuous, strictly decreasing function of p. moreover the c c least-squares polynomial corresponds to p=0 and the least-squares c c spline to p=infinity. then iteratively we have to determine the c c positive value of p such that f(p)=s. the process which is proposed c c here makes use of rational interpolation. f(p) is approximated by a c c rational function r(p)=(u*p+v)/(p+w); three values of p (p1,p2,p3) c c with corresponding values of f(p) (f1=f(p1)-s,f2=f(p2)-s,f3=f(p3)-s)c c are used to calculate the new value of p such that r(p)=s. c c convergence is guaranteed by taking f1 > 0 and f3 < 0. c cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c initial value for p. p1 = 0. f1 = fp0-s p3 = -one f3 = fpms p = one dzz(1) = dz(1) dzz(2) = dz(2) dzz(3) = dz(3) ich1 = 0 ich3 = 0 c iteration process to find the root of f(p)=s. do 350 iter = 1,maxit c find the smoothing spline sp(u,v) and the corresponding sum f(p). call fpopdi(ifsu,ifsv,ifbu,ifbv,u,mu,v,mv,z,mz,z0,dzz,iopt,idd, * tu,nu,tv,nv,nuest,nvest,p,step,c,nc,fp,fpintu,fpintv,nru,nrv, * wrk,lwrk) c test whether the approximation sp(u,v) is an acceptable solution. fpms = fp-s if(abs(fpms).lt.acc) go to 440 c test whether the maximum allowable number of iterations has been c reached. if(iter.eq.maxit) go to 400 c carry out one more step of the iteration process. p2 = p f2 = fpms if(ich3.ne.0) go to 320 if((f2-f3).gt.acc) go to 310 c our initial choice of p is too large. p3 = p2 f3 = f2 p = p*con4 if(p.le.p1) p = p1*con9 + p2*con1 go to 350 310 if(f2.lt.0.) ich3 = 1 320 if(ich1.ne.0) go to 340 if((f1-f2).gt.acc) go to 330 c our initial choice of p is too small p1 = p2 f1 = f2 p = p/con4 if(p3.lt.0.) go to 350 if(p.ge.p3) p = p2*con1 + p3*con9 go to 350 c test whether the iteration process proceeds as theoretically c expected. 330 if(f2.gt.0.) ich1 = 1 340 if(f2.ge.f1 .or. f2.le.f3) go to 410 c find the new value of p. p = fprati(p1,f1,p2,f2,p3,f3) 350 continue c error codes and messages. 400 ier = 3 go to 440 410 ier = 2 go to 440 420 ier = 1 go to 440 430 ier = -1 fp = 0. 440 return end
bsd-3-clause
jrper/fluidity
femtools/Streamfunction.F90
4
10968
! Copyright (C) 2010 Imperial College London and others. ! ! Please see the AUTHORS file in the main source directory for a full list ! of copyright holders. ! ! Prof. C Pain ! Applied Modelling and Computation Group ! Department of Earth Science and Engineering ! Imperial College London ! ! amcgsoftware@imperial.ac.uk ! ! 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, ! version 2.1 of the License. ! ! 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ! USA #include "fdebug.h" module streamfunction use spud use fldebug use global_parameters, only: OPTION_PATH_LEN use futils, only: present_and_nonzero, nullify use parallel_tools use sparse_tools use vector_tools use eventcounter use elements use transform_elements use linked_lists use parallel_fields use fetools, only: dshape_dot_dshape, shape_curl_shape_2d use fields use state_module use sparsity_patterns use solvers use boundary_conditions use sparsity_patterns_meshes implicit none private public :: calculate_stream_function_multipath_2d type(integer_vector), dimension(:), allocatable, save :: flux_face_list real, dimension(:,:), allocatable, save :: flux_normal integer, save :: last_adapt=-1 contains subroutine find_stream_paths(X, streamfunc) !!< Find the paths through the mesh over which the velocity will be !!< integrated to calculate the flux. type(vector_field), intent(in) :: X type(scalar_field), intent(inout) :: streamfunc type(ilist) :: tmp_face_list integer :: bc_count character(len=OPTION_PATH_LEN) :: option_path real, dimension(2) :: start, end, dx, face_c integer, dimension(:), pointer :: neigh integer :: face, p, ele1, ele2, e2, i real :: dx2, c1, c2 bc_count=get_boundary_condition_count(streamfunc) if(.not.(allocated(flux_face_list))) then allocate(flux_face_list(bc_count)) CALL nullify(flux_face_list) allocate(flux_normal(2, bc_count)) end if bc_loop: do i=1, bc_count call get_boundary_condition(streamfunc, i, option_path=option_path) if (have_option(trim(option_path)//"/primary_boundary")) then ! No path on the primary boundary. if (associated(flux_face_list(i)%ptr)) then deallocate(flux_face_list(i)%ptr) end if allocate(flux_face_list(i)%ptr(0)) cycle bc_loop end if ! We must be on a secondary boundary. call get_option(trim(option_path)//"/secondary_boundary/primary_point"& &, start) call get_option(trim(option_path)//"/secondary_boundary/secondary_point"& &, end) dx=-abs(start-end) dx2=dot_product(dx,dx) do ele1=1, element_count(streamfunc) neigh=>ele_neigh(X, ele1) do e2=1,size(neigh) ele2=neigh(e2) ! Don't do boundaries if (ele2<=0) cycle ! Do each edge only once if (ele1>ele2) cycle !for parallel check that we own the node if (.not.element_owned(streamfunc, ele1)) cycle face=ele_face(streamfunc, ele1, ele2) face_c=sum(face_val(X,face),2)/face_loc(X,face) p=dot_product(face_c,dx)/dx2 ! If the face is not within the limits of the line, don't do it. if (p<0.or.p>1) cycle c1=cross_product2(sum(ele_val(X,ele1),2)/ele_loc(X,ele1)-start, dx) c2=cross_product2(sum(ele_val(X,ele2),2)/ele_loc(X,ele2)-start, dx) if(C1<0 .and. C2>=0) then continue else if (C1>=0 .and. C2<0) then continue else cycle end if call insert(tmp_face_list, face) end do end do if (associated(flux_face_list(i)%ptr)) then deallocate(flux_face_list(i)%ptr) end if allocate(flux_face_list(i)%ptr(tmp_face_list%length)) flux_face_list(i)%ptr=list2vector(tmp_face_list) call flush_list(tmp_face_list) ! Work out the orthonormal to the line. dx=start-end dx=dx/sqrt(dx2) flux_normal(:,i)=(/-dx(2), dx(1)/) end do bc_loop end subroutine find_stream_paths function boundary_value(X, U, bc_num) !!< Calculate the value of the streamfunction on the boundary provided !!< by integrating the velocity flux across a line between this !!< boundary and the primary boundary. real :: boundary_value type(vector_field), intent(in) :: X, U integer, intent(in) :: bc_num integer :: face, i boundary_value=0.0 do i=1, size(flux_face_list(bc_num)%ptr) face=flux_face_list(bc_num)%ptr(i) boundary_value=boundary_value + face_flux(face, X, U, bc_num) end do ! for parallel so each partitition calculates the bit of the flux that it owns and they sum along the boundary so they all have the correct bd. condition call allsum(boundary_value) contains function face_flux(face, X, U, bc_num) real :: face_flux integer, intent(in) :: face, bc_num type(vector_field), intent(in) :: X, U real, dimension(face_ngi(U, face)) :: detwei real, dimension(U%dim,face_ngi(U, face)) :: normal, U_quad integer :: gi call transform_facet_to_physical(X, face, detwei_f=detwei, normal=normal) U_quad=face_val_at_quad(U,face) face_flux=0.0 do gi=1, size(detwei) face_flux=face_flux+abs(dot_product(flux_normal(:,bc_num),normal(:,gi)))& * dot_product(U_quad(:,gi),flux_normal(:,bc_num))& * detwei(gi) end do end function face_flux end function boundary_value subroutine calculate_stream_function_multipath_2d(state, streamfunc) !!< Calculate the stream function for a type(state_type), intent(inout) :: state type(scalar_field), intent(inout) :: streamfunc integer :: i, ele, stat type(vector_field), pointer :: X, U type(csr_sparsity), pointer :: psi_sparsity type(csr_matrix) :: psi_mat type(scalar_field) :: rhs real :: flux_val type(scalar_field), pointer :: surface_field integer :: mesh_movement integer, save :: last_mesh_movement = -1 X => extract_vector_field(state, "Coordinate", stat) if(present_and_nonzero(stat)) return U => extract_vector_field(state, "Velocity", stat) if(present_and_nonzero(stat)) return if (X%dim/=2) then FLExit("Streamfunction is only valid in 2d") end if ! No discontinuous stream functions. if (continuity(streamfunc)<0) then FLExit("Streamfunction must be a continuous field") end if if (last_adapt<eventcount(EVENT_ADAPTIVITY)) then last_adapt=eventcount(EVENT_ADAPTIVITY) call find_stream_paths(X, streamfunc) end if psi_mat = extract_csr_matrix(state, "StreamFunctionMatrix", stat = stat) if(stat == 0) then mesh_movement = eventcount(EVENT_MESH_MOVEMENT) if(mesh_movement /= last_mesh_movement) then stat = 1 end if end if if(stat /= 0) then psi_sparsity => get_csr_sparsity_firstorder(state, streamfunc%mesh, streamfunc%mesh) call allocate(psi_mat, psi_sparsity, name="StreamFunctionMatrix") call zero(psi_mat) call allocate(rhs, streamfunc%mesh, "StreamFunctionRHS") call zero(rhs) do ele=1, element_count(streamfunc) call calculate_streamfunc_ele(rhs, ele, X, U, psi_mat = psi_mat) end do call insert(state, psi_mat, psi_mat%name) else call incref(psi_mat) call allocate(rhs, streamfunc%mesh, "StreamFunctionRHS") call zero(rhs) do ele=1, element_count(streamfunc) call calculate_streamfunc_ele(rhs, ele, X, U) end do end if last_mesh_movement = eventcount(EVENT_MESH_MOVEMENT) do i = 1, get_boundary_condition_count(streamfunc) surface_field=>extract_surface_field(streamfunc, i, "value") flux_val=boundary_value(X,U,i) call set(surface_field, flux_val) end do call zero(streamfunc) call apply_dirichlet_conditions(psi_mat, rhs, streamfunc) call petsc_solve(streamfunc, psi_mat, rhs) call deallocate(rhs) call deallocate(psi_mat) contains subroutine calculate_streamfunc_ele(rhs, ele, X, U, psi_mat) type(scalar_field), intent(inout) :: rhs type(vector_field), intent(in) :: X,U integer, intent(in) :: ele type(csr_matrix), optional, intent(inout) :: psi_mat ! Transformed gradient function for velocity. real, dimension(ele_loc(U, ele), ele_ngi(U, ele), mesh_dim(U)) :: du_t ! Ditto for the stream function, psi real, dimension(ele_loc(rhs, ele), ele_ngi(rhs, ele), mesh_dim(rhs))& & :: dpsi_t ! Local vorticity_matrix real, dimension(2, ele_loc(rhs, ele), ele_loc(U, ele)) ::& & lvorticity_mat ! Local vorticity real, dimension(ele_loc(rhs, ele)) :: lvorticity ! Variable transform times quadrature weights. real, dimension(ele_ngi(U,ele)) :: detwei type(element_type), pointer :: U_shape, psi_shape integer, dimension(:), pointer :: psi_ele integer :: i U_shape=> ele_shape(U, ele) psi_shape=> ele_shape(rhs, ele) psi_ele=>ele_nodes(rhs, ele) ! Transform U derivatives and weights into physical space. call transform_to_physical(X, ele, U_shape, dshape=du_t, detwei=detwei) ! Ditto psi. call transform_to_physical(X, ele, psi_shape, dshape=dpsi_t) if(present(psi_mat)) then call addto(psi_mat, psi_ele, psi_ele, & dshape_dot_dshape(dpsi_t, dpsi_t, detwei)) end if lvorticity_mat=shape_curl_shape_2d(psi_shape, du_t, detwei) lvorticity=0.0 do i=1,2 lvorticity=lvorticity & +matmul(lvorticity_mat(i,:,:), ele_val(U, i, ele)) end do call addto(rhs, psi_ele, -lvorticity) end subroutine calculate_streamfunc_ele end subroutine calculate_stream_function_multipath_2d end module streamfunction
lgpl-2.1
jrper/fluidity
assemble/Advection_Diffusion_CG.F90
2
66149
! Copyright (C) 2006 Imperial College London and others. ! ! Please see the AUTHORS file in the main source directory for a full list ! of copyright holders. ! ! Prof. C Pain ! Applied Modelling and Computation Group ! Department of Earth Science and Engineering ! Imperial College London ! ! amcgsoftware@imperial.ac.uk ! ! 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, ! version 2.1 of the License. ! ! 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ! USA #include "fdebug.h" module advection_diffusion_cg use fldebug use global_parameters, only : FIELD_NAME_LEN, OPTION_PATH_LEN, COLOURING_CG1 use futils, only: int2str use quadrature use elements use spud use integer_set_module #ifdef _OPENMP use omp_lib #endif use sparse_tools use transform_elements use fetools use fields use profiler use sparse_tools_petsc use state_module use boundary_conditions use field_options use sparsity_patterns_meshes use boundary_conditions_from_options use petsc_solve_state_module use upwind_stabilisation use porous_media use multiphase_module use colouring implicit none private public :: solve_field_equation_cg, advection_diffusion_cg_check_options character(len = *), parameter, public :: advdif_cg_m_name = "AdvectionDiffusionCGMatrix" character(len = *), parameter, public :: advdif_cg_rhs_name = "AdvectionDiffusionCGRHS" character(len = *), parameter, public :: advdif_cg_delta_t_name = "AdvectionDiffusionCGChange" character(len = *), parameter, public :: advdif_cg_velocity_name = "AdvectionDiffusionCGVelocity" ! Stabilisation schemes integer, parameter :: STABILISATION_NONE = 0, & & STABILISATION_STREAMLINE_UPWIND = 1, STABILISATION_SUPG = 2 ! Boundary condition types integer, parameter :: BC_TYPE_NEUMANN = 1, BC_TYPE_WEAKDIRICHLET = 2, BC_TYPE_INTERNAL = 3, & BC_TYPE_ROBIN = 4 ! Global variables, set by assemble_advection_diffusion_cg for use by ! assemble_advection_diffusion_element_cg and ! assemble_advection_diffusion_face_cg ! Local timestep real :: local_dt ! Implicitness/explicitness factor * timestep real :: dt_theta ! Implicitness/explicitness factor real :: theta ! Conservative/non-conservative discretisation factor real :: beta ! Stabilisation scheme integer :: stabilisation_scheme integer :: nu_bar_scheme real :: nu_bar_scale ! equation type integer :: equation_type ! Implicitness/explicitness factor for density real :: density_theta ! Which terms do we have? ! Mass term? logical :: have_mass ! Lump mass? logical :: lump_mass ! Advection? logical :: have_advection ! Integrate advection by parts? logical :: integrate_advection_by_parts ! Source? logical :: have_source ! Add source directly to the right hand side? logical :: add_src_directly_to_rhs ! Absorption? logical :: have_absorption ! Diffusivity? logical :: have_diffusivity ! Isotropic diffusivity? logical :: isotropic_diffusivity ! Is the mesh moving? logical :: move_mesh ! Include porosity? logical :: include_porosity ! Is this material_phase compressible? logical :: compressible = .false. ! Are we running a multiphase flow simulation? logical :: multiphase contains subroutine solve_field_equation_cg(field_name, state, istate, dt, velocity_name, iterations_taken) !!< Construct and solve the advection-diffusion equation for the given !!< field using a continuous Galerkin discretisation. Based on !!< Advection_Diffusion_DG and Momentum_CG. character(len = *), intent(in) :: field_name type(state_type), dimension(:), intent(inout) :: state integer, intent(in) :: istate real, intent(in) :: dt character(len = *), optional, intent(in) :: velocity_name integer, intent(out), optional :: iterations_taken type(csr_matrix) :: matrix type(scalar_field) :: delta_t, rhs type(scalar_field), pointer :: t ewrite(1, *) "In solve_field_equation_cg" ewrite(2, *) "Solving advection-diffusion equation for field " // & & trim(field_name) // " in state " // trim(state(istate)%name) call initialise_advection_diffusion_cg(field_name, t, delta_t, matrix, rhs, state(istate)) call profiler_tic(t, "assembly") call assemble_advection_diffusion_cg(t, matrix, rhs, state(istate), dt, velocity_name = velocity_name) ! Note: the assembly of the heat transfer term is done here to avoid ! passing in the whole state array to assemble_advection_diffusion_cg. if(have_option("/multiphase_interaction/heat_transfer") .and. & equation_type_index(trim(t%option_path)) == FIELD_EQUATION_INTERNALENERGY) then call add_heat_transfer(state, istate, t, matrix, rhs) end if call profiler_toc(t, "assembly") call profiler_tic(t, "solve_total") call solve_advection_diffusion_cg(t, delta_t, matrix, rhs, state(istate), & iterations_taken = iterations_taken) call profiler_toc(t, "solve_total") call profiler_tic(t, "assembly") call apply_advection_diffusion_cg_change(t, delta_t, dt) call finalise_advection_diffusion_cg(delta_t, matrix, rhs) call profiler_toc(t, "assembly") ewrite(1, *) "Exiting solve_field_equation_cg" end subroutine solve_field_equation_cg subroutine initialise_advection_diffusion_cg(field_name, t, delta_t, matrix, rhs, state) character(len = *), intent(in) :: field_name type(scalar_field), pointer :: t type(scalar_field), intent(out) :: delta_t type(csr_matrix), intent(out) :: matrix type(scalar_field), intent(out) :: rhs type(state_type), intent(inout) :: state integer :: stat type(csr_sparsity), pointer :: sparsity type(scalar_field), pointer :: t_old t => extract_scalar_field(state, field_name) if(t%mesh%continuity /= 0) then FLExit("CG advection-diffusion requires a continuous mesh") end if t_old => extract_scalar_field(state, "Old" // field_name, stat = stat) if(stat == 0) then assert(t_old%mesh == t%mesh) ! Reset t to value at the beginning of the timestep call set(t, t_old) end if sparsity => get_csr_sparsity_firstorder(state, t%mesh, t%mesh) call allocate(matrix, sparsity, name = advdif_cg_m_name) call allocate(rhs, t%mesh, name = advdif_cg_rhs_name) call allocate(delta_t, t%mesh, name = trim(field_name)//advdif_cg_delta_t_name) call set_advection_diffusion_cg_initial_guess(delta_t) end subroutine initialise_advection_diffusion_cg subroutine finalise_advection_diffusion_cg(delta_t, matrix, rhs) type(scalar_field), intent(inout) :: delta_t type(csr_matrix), intent(inout) :: matrix type(scalar_field), intent(inout) :: rhs call deallocate(matrix) call deallocate(rhs) call deallocate(delta_t) end subroutine finalise_advection_diffusion_cg subroutine set_advection_diffusion_cg_initial_guess(delta_t) type(scalar_field), intent(inout) :: delta_t call zero(delta_t) end subroutine set_advection_diffusion_cg_initial_guess subroutine assemble_advection_diffusion_cg(t, matrix, rhs, state, dt, velocity_name) type(scalar_field), intent(inout) :: t type(csr_matrix), intent(inout) :: matrix type(scalar_field), intent(inout) :: rhs type(state_type), intent(inout) :: state real, intent(in) :: dt character(len = *), optional, intent(in) :: velocity_name character(len = FIELD_NAME_LEN) :: lvelocity_name, velocity_equation_type integer :: i, j, stat integer, dimension(:), allocatable :: t_bc_types type(scalar_field) :: t_bc, t_bc_2 type(scalar_field), pointer :: absorption, sinking_velocity, source type(tensor_field), pointer :: diffusivity type(vector_field) :: velocity type(vector_field), pointer :: gravity_direction, temp_velocity_ptr, velocity_ptr, grid_velocity type(vector_field), pointer :: positions, old_positions, new_positions type(scalar_field), target :: dummydensity type(scalar_field), pointer :: density, olddensity character(len = FIELD_NAME_LEN) :: density_name type(scalar_field), pointer :: pressure ! Volume fraction fields for multiphase flow simulation type(scalar_field), pointer :: vfrac type(scalar_field) :: nvfrac ! Non-linear version ! Porosity field type(scalar_field) :: porosity_theta !! Coloring data structures for OpenMP parallization type(integer_set), dimension(:), pointer :: colours integer :: clr, nnid, len, ele integer :: num_threads, thread_num !! Did we successfully prepopulate the transform_to_physical_cache? logical :: cache_valid type(element_type), dimension(:), allocatable :: supg_element ewrite(1, *) "In assemble_advection_diffusion_cg" assert(mesh_dim(rhs) == mesh_dim(t)) assert(ele_count(rhs) == ele_count(t)) if(present(velocity_name)) then lvelocity_name = velocity_name else lvelocity_name = "NonlinearVelocity" end if #ifdef _OPENMP num_threads = omp_get_max_threads() #else num_threads = 1 #endif ! Step 1: Pull fields out of state ! Coordinate positions => extract_vector_field(state, "Coordinate") ewrite_minmax(positions) assert(positions%dim == mesh_dim(t)) assert(ele_count(positions) == ele_count(t)) ! Velocity velocity_ptr => extract_vector_field(state, lvelocity_name, stat = stat) if(stat == 0) then assert(velocity_ptr%dim == mesh_dim(t)) assert(ele_count(velocity_ptr) == ele_count(t)) ewrite(2, *) "Velocity:" ewrite_minmax(velocity_ptr) if (have_option(trim(t%option_path) // & "/prognostic/spatial_discretisation/continuous_galerkin/advection_terms/only_sinking_velocity")) then ewrite(2, *) "No advection set for field" call allocate(velocity, mesh_dim(t), t%mesh, name = advdif_cg_velocity_name) call zero(velocity) else call allocate(velocity, velocity_ptr%dim, velocity_ptr%mesh, name = advdif_cg_velocity_name) call set(velocity, velocity_ptr) end if else ewrite(2, *) "No velocity" call allocate(velocity, mesh_dim(t), t%mesh, name = advdif_cg_velocity_name) call zero(velocity) end if ! Source source => extract_scalar_field(state, trim(t%name) // "Source", stat = stat) have_source = stat == 0 if(have_source) then assert(mesh_dim(source) == mesh_dim(t)) assert(ele_count(source) == ele_count(t)) add_src_directly_to_rhs = have_option(trim(source%option_path)//'/diagnostic/add_directly_to_rhs') if (add_src_directly_to_rhs) then ewrite(2, *) "Adding Source field directly to the right hand side" assert(node_count(source) == node_count(t)) end if ewrite_minmax(source) else ewrite(2, *) "No source" add_src_directly_to_rhs = .false. end if ! Absorption absorption => extract_scalar_field(state, trim(t%name) // "Absorption", stat = stat) have_absorption = stat == 0 if(have_absorption) then assert(mesh_dim(absorption) == mesh_dim(t)) assert(ele_count(absorption) == ele_count(t)) ewrite_minmax(absorption) else ewrite(2, *) "No absorption" end if ! Sinking velocity sinking_velocity => extract_scalar_field(state, trim(t%name) // "SinkingVelocity", stat = stat) if(stat == 0) then ewrite_minmax(sinking_velocity) gravity_direction => extract_vector_field(state, "GravityDirection") ! this may perform a "remap" internally from CoordinateMesh to VelocitMesh call addto(velocity, gravity_direction, scale = sinking_velocity) ewrite_minmax(velocity) else ewrite(2, *) "No sinking velocity" end if ! Diffusivity diffusivity => extract_tensor_field(state, trim(t%name) // "Diffusivity", stat = stat) have_diffusivity = stat == 0 if(have_diffusivity) then assert(all(diffusivity%dim == mesh_dim(t))) assert(ele_count(diffusivity) == ele_count(t)) isotropic_diffusivity = option_count(complete_field_path(diffusivity%option_path)) & & == option_count(trim(complete_field_path(diffusivity%option_path)) // "/value/isotropic") if(isotropic_diffusivity) then ewrite(2, *) "Isotropic diffusivity" assert(all(diffusivity%dim > 0)) ewrite_minmax(diffusivity%val(1, 1, :)) else ewrite_minmax(diffusivity) end if else isotropic_diffusivity = .false. ewrite(2, *) "No diffusivity" end if ! Porosity if (have_option(trim(complete_field_path(t%option_path))//'/porosity')) then include_porosity = .true. ! get the porosity theta averaged field - this will allocate it call form_porosity_theta(porosity_theta, state, option_path = trim(complete_field_path(t%option_path))//'/porosity') else include_porosity = .false. call allocate(porosity_theta, t%mesh, field_type=FIELD_TYPE_CONSTANT) call set(porosity_theta, 1.0) end if ! Step 2: Pull options out of the options tree call get_option(trim(t%option_path) // "/prognostic/temporal_discretisation/theta", theta) assert(theta >= 0.0 .and. theta <= 1.0) ewrite(2, *) "Theta = ", theta dt_theta = dt * theta local_dt = dt call get_option(trim(t%option_path) // "/prognostic/spatial_discretisation/conservative_advection", beta) assert(beta >= 0.0 .and. beta <= 1.0) ewrite(2, *) "Beta = ", beta have_advection = .not. have_option(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/advection_terms/exclude_advection_terms") if(have_advection) then ewrite(2, *) "Including advection" integrate_advection_by_parts = have_option(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/advection_terms/integrate_advection_by_parts") if(integrate_advection_by_parts) then ewrite(2, *) "Integrating advection terms by parts" end if else integrate_advection_by_parts = .false. ewrite(2, *) "Excluding advection" end if have_mass = .not. have_option(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/mass_terms/exclude_mass_terms") if(have_mass) then ewrite(2, *) "Including mass" lump_mass = have_option(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/mass_terms/lump_mass_matrix") if(lump_mass) then ewrite(2, *) "Lumping mass" end if else lump_mass = .false. ewrite(2, *) "Excluding mass" end if ! are we moving the mesh? move_mesh = (have_option("/mesh_adaptivity/mesh_movement") .and. have_mass) if(move_mesh) then if (include_porosity) then FLExit('Cannot include porosity in CG advection diffusion of a field with a moving mesh') end if ewrite(2,*) "Moving the mesh" old_positions => extract_vector_field(state, "OldCoordinate") ewrite_minmax(old_positions) new_positions => extract_vector_field(state, "IteratedCoordinate") ewrite_minmax(new_positions) ! Grid velocity grid_velocity => extract_vector_field(state, "GridVelocity") assert(grid_velocity%dim == mesh_dim(t)) assert(ele_count(grid_velocity) == ele_count(t)) ewrite(2, *) "Grid velocity:" ewrite_minmax(grid_velocity) else ewrite(2,*) "Not moving the mesh" end if allocate(supg_element(num_threads)) if(have_option(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/stabilisation/streamline_upwind")) then ewrite(2, *) "Streamline upwind stabilisation" stabilisation_scheme = STABILISATION_STREAMLINE_UPWIND call get_upwind_options(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/stabilisation/streamline_upwind", & & nu_bar_scheme, nu_bar_scale) if(move_mesh) then FLExit("Haven't thought about how mesh movement works with stabilisation yet.") end if else if(have_option(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/stabilisation/streamline_upwind_petrov_galerkin")) then ewrite(2, *) "SUPG stabilisation" stabilisation_scheme = STABILISATION_SUPG call get_upwind_options(trim(t%option_path) // "/prognostic/spatial_discretisation/continuous_galerkin/stabilisation/streamline_upwind_petrov_galerkin", & & nu_bar_scheme, nu_bar_scale) ! Note this is not mixed mesh safe (but then nothing really is) ! You need 1 supg_element per thread. do i = 1, num_threads supg_element(i)=make_supg_element(ele_shape(t,1)) end do if(move_mesh) then FLExit("Haven't thought about how mesh movement works with stabilisation yet.") end if else ewrite(2, *) "No stabilisation" stabilisation_scheme = STABILISATION_NONE end if ! PhaseVolumeFraction for multiphase flow simulations if(option_count("/material_phase/vector_field::Velocity/prognostic") > 1) then multiphase = .true. vfrac => extract_scalar_field(state, "PhaseVolumeFraction") call allocate(nvfrac, vfrac%mesh, "NonlinearPhaseVolumeFraction") call zero(nvfrac) call get_nonlinear_volume_fraction(state, nvfrac) ewrite_minmax(nvfrac) else multiphase = .false. call allocate(nvfrac, t%mesh, "DummyNonlinearPhaseVolumeFraction", field_type=FIELD_TYPE_CONSTANT) call set(nvfrac, 1.0) end if call allocate(dummydensity, t%mesh, "DummyDensity", field_type=FIELD_TYPE_CONSTANT) call set(dummydensity, 1.0) ! find out equation type and hence if density is needed or not equation_type=equation_type_index(trim(t%option_path)) select case(equation_type) case(FIELD_EQUATION_ADVECTIONDIFFUSION) ewrite(2,*) "Solving advection-diffusion equation" ! density not needed so use a constant field for assembly density => dummydensity olddensity => dummydensity density_theta = 1.0 pressure => dummydensity case(FIELD_EQUATION_INTERNALENERGY) ewrite(2,*) "Solving internal energy equation" if(move_mesh) then FLExit("Haven't implemented a moving mesh energy equation yet.") end if ! Get old and current densities call get_option(trim(t%option_path)//'/prognostic/equation[0]/density[0]/name', & density_name) density=>extract_scalar_field(state, trim(density_name)) ewrite_minmax(density) olddensity=>extract_scalar_field(state, "Old"//trim(density_name)) ewrite_minmax(olddensity) if(have_option(trim(state%option_path)//'/equation_of_state/compressible')) then call get_option(trim(density%option_path)//"/prognostic/temporal_discretisation/theta", density_theta) compressible = .true. ! We always include the p*div(u) term if this is the compressible phase. pressure=>extract_scalar_field(state, "Pressure") ewrite_minmax(pressure) else ! Since the particle phase is always incompressible then its Density ! will not be prognostic. Just use a fixed theta value of 1.0. density_theta = 1.0 compressible = .false. ! Don't include the p*div(u) term if this is the incompressible particle phase. pressure => dummydensity end if case(FIELD_EQUATION_KEPSILON) ewrite(2,*) "Solving k-epsilon equation" if(move_mesh) then FLExit("Haven't implemented a moving mesh k-epsilon equation yet.") end if ! Depending on the equation type, extract the density or set it to some dummy field allocated above temp_velocity_ptr => extract_vector_field(state, "Velocity") call get_option(trim(temp_velocity_ptr%option_path)//"/prognostic/equation[0]/name", velocity_equation_type) select case(velocity_equation_type) case("LinearMomentum") density=>extract_scalar_field(state, "Density") olddensity => dummydensity density_theta = 1.0 case("Boussinesq") density=>dummydensity olddensity => dummydensity density_theta = 1.0 case("Drainage") density=>dummydensity olddensity => dummydensity density_theta = 1.0 case default ! developer error... out of sync options input and code FLAbort("Unknown equation type for velocity") end select ewrite_minmax(density) case default FLExit("Unknown field equation type for cg advection diffusion.") end select ! Step 3: Assembly call zero(matrix) call zero(rhs) call profiler_tic(t, "advection_diffusion_loop_overhead") #ifdef _OPENMP cache_valid = prepopulate_transform_cache(positions) #endif call get_mesh_colouring(state, t%mesh, COLOURING_CG1, colours) call profiler_toc(t, "advection_diffusion_loop_overhead") call profiler_tic(t, "advection_diffusion_loop") !$OMP PARALLEL DEFAULT(SHARED) & !$OMP PRIVATE(clr, len, nnid, ele, thread_num) #ifdef _OPENMP thread_num = omp_get_thread_num() #else thread_num=0 #endif colour_loop: do clr = 1, size(colours) len = key_count(colours(clr)) !$OMP DO SCHEDULE(STATIC) element_loop: do nnid = 1, len ele = fetch(colours(clr), nnid) call assemble_advection_diffusion_element_cg(ele, t, matrix, rhs, & positions, old_positions, new_positions, & velocity, grid_velocity, & source, absorption, diffusivity, & density, olddensity, pressure, porosity_theta, nvfrac, & supg_element(thread_num+1)) end do element_loop !$OMP END DO end do colour_loop !$OMP END PARALLEL call profiler_toc(t, "advection_diffusion_loop") ! Add the source directly to the rhs if required ! which must be included before dirichlet BC's. if (add_src_directly_to_rhs) call addto(rhs, source) ! Step 4: Boundary conditions if( & & (integrate_advection_by_parts .and. have_advection) & & .or. have_diffusivity & & ) then allocate(t_bc_types(surface_element_count(t))) call get_entire_boundary_condition(t, & (/ "neumann ", & "weakdirichlet", & "internal ", & "robin "/), & t_bc, & t_bc_types, & boundary_second_value = t_bc_2) if(any(t_bc_types /= 0)) then call ewrite_bc_counts(2, t_bc_types) end if do i = 1, surface_element_count(t) if(t_bc_types(i)==BC_TYPE_INTERNAL) cycle call assemble_advection_diffusion_face_cg(i, t_bc_types(i), t, t_bc, t_bc_2, & matrix, rhs, & positions, velocity, grid_velocity, & density, olddensity, nvfrac) end do call deallocate(t_bc) call deallocate(t_bc_2) deallocate(t_bc_types) end if ewrite(2, *) "Applying strong Dirichlet boundary conditions" call apply_dirichlet_conditions(matrix, rhs, t, dt) ewrite_minmax(rhs) call deallocate(velocity) call deallocate(nvfrac) call deallocate(dummydensity) if (stabilisation_scheme == STABILISATION_SUPG) then do i = 1, num_threads call deallocate(supg_element(i)) end do end if deallocate(supg_element) call deallocate(porosity_theta) ewrite(1, *) "Exiting assemble_advection_diffusion_cg" end subroutine assemble_advection_diffusion_cg subroutine ewrite_bc_counts(debug_level, bc_types) !!< A simple subroutine to count and output the number of elements with !!< each boundary conditions (combines counts into a single surface !!< element loop). integer, intent(in) :: debug_level integer, dimension(:), intent(in) :: bc_types integer :: i, nneumann, nweak_dirichlet, ninternal, nrobin if(debug_level > current_debug_level) return nneumann = 0 nweak_dirichlet = 0 ninternal = 0 nrobin = 0 do i = 1, size(bc_types) select case(bc_types(i)) case(BC_TYPE_NEUMANN) nneumann = nneumann + 1 case(BC_TYPE_WEAKDIRICHLET) nweak_dirichlet = nweak_dirichlet + 1 case(BC_TYPE_INTERNAL) ninternal = ninternal + 1 case(BC_TYPE_ROBIN) nrobin = nrobin + 1 case(0) case default ! this is a code error ewrite(-1, *) "For boundary condition type: ", bc_types(i) FLAbort("Unrecognised boundary condition type") end select end do ewrite(debug_level, *) "Surface elements with Neumann boundary condition: ", nneumann ewrite(debug_level, *) "Surface elements with weak Dirichlet boundary condition: ", nweak_dirichlet ewrite(debug_level, *) "Surface elements with internal or periodic boundary condition: ", ninternal ewrite(debug_level, *) "Surface elements with Robin boundary condition: ", nrobin end subroutine ewrite_bc_counts subroutine assemble_advection_diffusion_element_cg(ele, t, matrix, rhs, & positions, old_positions, new_positions, & velocity, grid_velocity, & source, absorption, diffusivity, & density, olddensity, pressure, porosity_theta, nvfrac, supg_shape) integer, intent(in) :: ele type(scalar_field), intent(in) :: t type(csr_matrix), intent(inout) :: matrix type(scalar_field), intent(inout) :: rhs type(vector_field), intent(in) :: positions type(vector_field), pointer :: old_positions, new_positions type(vector_field), intent(in) :: velocity type(vector_field), pointer :: grid_velocity type(scalar_field), intent(in) :: source type(scalar_field), intent(in) :: absorption type(tensor_field), intent(in) :: diffusivity type(scalar_field), intent(in) :: density type(scalar_field), intent(in) :: olddensity type(scalar_field), intent(in) :: pressure type(scalar_field), intent(in) :: porosity_theta type(scalar_field), intent(in) :: nvfrac type(element_type), intent(inout) :: supg_shape integer, dimension(:), pointer :: element_nodes real, dimension(ele_ngi(t, ele)) :: detwei, detwei_old, detwei_new real, dimension(ele_loc(t, ele), ele_ngi(t, ele), mesh_dim(t)) :: dt_t real, dimension(ele_loc(density, ele), ele_ngi(density, ele), mesh_dim(density)) :: drho_t real, dimension(ele_loc(velocity, ele), ele_ngi(velocity, ele), mesh_dim(t)) :: du_t real, dimension(ele_loc(positions, ele), ele_ngi(velocity, ele), mesh_dim(t)) :: dug_t ! Derivative of shape function for nvfrac field real, dimension(ele_loc(nvfrac, ele), ele_ngi(nvfrac, ele), mesh_dim(nvfrac)) :: dnvfrac_t real, dimension(mesh_dim(t), mesh_dim(t), ele_ngi(t, ele)) :: j_mat type(element_type) :: test_function type(element_type), pointer :: t_shape ! What we will be adding to the matrix and RHS - assemble these as we ! go, so that we only do the calculations we really need real, dimension(ele_loc(t, ele)) :: rhs_addto real, dimension(ele_loc(t, ele), ele_loc(t, ele)) :: matrix_addto #ifdef DDEBUG assert(ele_ngi(positions, ele) == ele_ngi(t, ele)) assert(ele_ngi(velocity, ele) == ele_ngi(t, ele)) if(have_diffusivity) then assert(ele_ngi(diffusivity, ele) == ele_ngi(t, ele)) end if if(have_source) then assert(ele_ngi(source, ele) == ele_ngi(t, ele)) end if if(have_absorption) then assert(ele_ngi(absorption, ele) == ele_ngi(t, ele)) end if if(move_mesh) then ! the following has been assumed in the declarations above assert(ele_loc(grid_velocity, ele) == ele_loc(positions, ele)) assert(ele_ngi(grid_velocity, ele) == ele_ngi(velocity, ele)) end if if (include_porosity) then assert(ele_ngi(porosity_theta, ele) == ele_ngi(t, ele)) end if #endif matrix_addto = 0.0 rhs_addto = 0.0 t_shape => ele_shape(t, ele) ! Step 1: Transform if(.not. have_advection .and. .not. have_diffusivity) then call transform_to_physical(positions, ele, detwei = detwei) else if(any(stabilisation_scheme == (/STABILISATION_STREAMLINE_UPWIND, STABILISATION_SUPG/))) then call transform_to_physical(positions, ele, t_shape, & & dshape = dt_t, detwei = detwei, j = j_mat) else call transform_to_physical(positions, ele, t_shape, & & dshape = dt_t, detwei = detwei) end if if(have_advection.or.(equation_type==FIELD_EQUATION_INTERNALENERGY).or.equation_type==FIELD_EQUATION_KEPSILON) then call transform_to_physical(positions, ele, & & ele_shape(velocity, ele), dshape = du_t) end if if(have_advection.and.move_mesh.and..not.integrate_advection_by_parts) then call transform_to_physical(positions, ele, & & ele_shape(grid_velocity, ele), dshape = dug_t) end if if(move_mesh) then call transform_to_physical(old_positions, ele, detwei=detwei_old) call transform_to_physical(new_positions, ele, detwei=detwei_new) end if if(have_advection.and.(equation_type==FIELD_EQUATION_INTERNALENERGY .or. equation_type==FIELD_EQUATION_KEPSILON)) then if(ele_shape(density, ele)==t_shape) then drho_t = dt_t else call transform_to_physical(positions, ele, & & ele_shape(density, ele), dshape = drho_t) end if end if if(have_advection .and. multiphase .and. (equation_type==FIELD_EQUATION_INTERNALENERGY)) then ! If the field and nvfrac meshes are different, then we need to ! compute the derivatives of the nvfrac shape functions. if(ele_shape(nvfrac, ele) == t_shape) then dnvfrac_t = dt_t else call transform_to_physical(positions, ele, ele_shape(nvfrac, ele), dshape=dnvfrac_t) end if end if ! Step 2: Set up test function select case(stabilisation_scheme) case(STABILISATION_SUPG) if(have_diffusivity) then call supg_test_function(supg_shape, t_shape, dt_t, ele_val_at_quad(velocity, ele), j_mat, diff_q = ele_val_at_quad(diffusivity, ele), & & nu_bar_scheme = nu_bar_scheme, nu_bar_scale = nu_bar_scale) else call supg_test_function(supg_shape, t_shape, dt_t, ele_val_at_quad(velocity, ele), j_mat, & & nu_bar_scheme = nu_bar_scheme, nu_bar_scale = nu_bar_scale) end if test_function = supg_shape case default test_function = t_shape end select ! Important note: with SUPG the test function derivatives have not been ! modified - i.e. dt_t is currently used everywhere. This is fine for P1, ! but is not consistent for P>1. ! Step 3: Assemble contributions ! Mass if(have_mass) call add_mass_element_cg(ele, test_function, t, density, olddensity, porosity_theta, nvfrac, detwei, detwei_old, detwei_new, matrix_addto, rhs_addto) ! Advection if(have_advection) call add_advection_element_cg(ele, test_function, t, & velocity, grid_velocity, diffusivity, & density, olddensity, nvfrac, & dt_t, du_t, dug_t, drho_t, dnvfrac_t, detwei, j_mat, matrix_addto, rhs_addto) ! Absorption if(have_absorption) call add_absorption_element_cg(ele, test_function, t, absorption, detwei, matrix_addto, rhs_addto) ! Diffusivity if(have_diffusivity) call add_diffusivity_element_cg(ele, t, diffusivity, dt_t, nvfrac, detwei, matrix_addto, rhs_addto) ! Source if(have_source .and. (.not. add_src_directly_to_rhs)) then call add_source_element_cg(ele, test_function, t, source, detwei, rhs_addto) end if ! Pressure if(equation_type==FIELD_EQUATION_INTERNALENERGY .and. compressible) then call add_pressurediv_element_cg(ele, test_function, t, velocity, pressure, nvfrac, du_t, detwei, rhs_addto) end if ! Step 4: Insertion element_nodes => ele_nodes(t, ele) call addto(matrix, element_nodes, element_nodes, matrix_addto) call addto(rhs, element_nodes, rhs_addto) end subroutine assemble_advection_diffusion_element_cg subroutine add_mass_element_cg(ele, test_function, t, density, olddensity, porosity_theta, nvfrac, detwei, detwei_old, detwei_new, matrix_addto, rhs_addto) integer, intent(in) :: ele type(element_type), intent(in) :: test_function type(scalar_field), intent(in) :: t type(scalar_field), intent(in) :: density, olddensity type(scalar_field), intent(in) :: porosity_theta type(scalar_field), intent(in) :: nvfrac real, dimension(ele_ngi(t, ele)), intent(in) :: detwei, detwei_old, detwei_new real, dimension(ele_loc(t, ele), ele_loc(t, ele)), intent(inout) :: matrix_addto real, dimension(ele_loc(t, ele)), intent(inout) :: rhs_addto integer :: i real, dimension(ele_loc(t, ele), ele_loc(t, ele)) :: mass_matrix real, dimension(ele_ngi(density,ele)) :: density_at_quad real, dimension(ele_ngi(porosity_theta,ele)) :: porosity_theta_at_quad assert(have_mass) if (include_porosity) porosity_theta_at_quad = ele_val_at_quad(porosity_theta, ele) select case(equation_type) case(FIELD_EQUATION_INTERNALENERGY) assert(ele_ngi(density, ele)==ele_ngi(olddensity, ele)) density_at_quad = ele_val_at_quad(olddensity, ele) if(move_mesh) then ! needs to be evaluated at t+dt mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei_new*density_at_quad) else if (include_porosity) then mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei*density_at_quad*porosity_theta_at_quad) else if(multiphase) then mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei*density_at_quad*ele_val_at_quad(nvfrac, ele)) else mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei*density_at_quad) end if end if case(FIELD_EQUATION_KEPSILON) density_at_quad = ele_val_at_quad(density, ele) mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei*density_at_quad) case default if(move_mesh) then ! needs to be evaluated at t+dt mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei_new) else if (include_porosity) then mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei*porosity_theta_at_quad) else mass_matrix = shape_shape(test_function, ele_shape(t, ele), detwei) end if end if end select if(lump_mass) then do i = 1, size(matrix_addto, 1) matrix_addto(i, i) = matrix_addto(i, i) + sum(mass_matrix(i, :)) end do else matrix_addto = matrix_addto + mass_matrix end if if(move_mesh) then ! In the unaccelerated form we solve: ! / ! | N^{n+1} T^{n+1}/dt - N^{n} T^n/dt + ... = f ! / ! so in accelerated form: ! / ! | N^{n+1} dT + (N^{n+1}- N^{n}) T^n/dt + ... = f ! / ! where dT=(T^{n+1}-T^{n})/dt is the acceleration. ! Put the (N^{n+1}-N^{n}) T^n term on the rhs mass_matrix = shape_shape(test_function, ele_shape(t, ele), (detwei_new-detwei_old)) if(lump_mass) then rhs_addto = rhs_addto - sum(mass_matrix, 2)*ele_val(t, ele)/local_dt else rhs_addto = rhs_addto - matmul(mass_matrix, ele_val(t, ele))/local_dt end if end if end subroutine add_mass_element_cg subroutine add_advection_element_cg(ele, test_function, t, & velocity, grid_velocity, diffusivity, & density, olddensity, nvfrac, & dt_t, du_t, dug_t, drho_t, dnvfrac_t, detwei, j_mat, matrix_addto, rhs_addto) integer, intent(in) :: ele type(element_type), intent(in) :: test_function type(scalar_field), intent(in) :: t type(vector_field), intent(in) :: velocity type(vector_field), pointer :: grid_velocity type(tensor_field), intent(in) :: diffusivity type(scalar_field), intent(in) :: density, olddensity type(scalar_field), intent(in) :: nvfrac real, dimension(ele_loc(t, ele), ele_ngi(t, ele), mesh_dim(t)), intent(in) :: dt_t real, dimension(ele_loc(velocity, ele), ele_ngi(velocity, ele), mesh_dim(t)) :: du_t real, dimension(:, :, :) :: dug_t real, dimension(ele_loc(density, ele), ele_ngi(density, ele), mesh_dim(density)), intent(in) :: drho_t real, dimension(:, :, :), intent(in) :: dnvfrac_t real, dimension(ele_ngi(t, ele)), intent(in) :: detwei real, dimension(mesh_dim(t), mesh_dim(t), ele_ngi(t, ele)), intent(in) :: j_mat real, dimension(ele_loc(t, ele), ele_loc(t, ele)), intent(inout) :: matrix_addto real, dimension(ele_loc(t, ele)), intent(inout) :: rhs_addto real, dimension(ele_loc(t, ele), ele_loc(t,ele)) :: advection_mat real, dimension(velocity%dim, ele_ngi(velocity, ele)) :: velocity_at_quad real, dimension(ele_ngi(velocity, ele)) :: velocity_div_at_quad type(element_type), pointer :: t_shape real, dimension(ele_ngi(density, ele)) :: density_at_quad real, dimension(velocity%dim, ele_ngi(density, ele)) :: densitygrad_at_quad real, dimension(ele_ngi(density, ele)) :: udotgradrho_at_quad real, dimension(ele_ngi(t, ele)) :: nvfrac_at_quad real, dimension(velocity%dim, ele_ngi(t, ele)) :: nvfracgrad_at_quad real, dimension(ele_ngi(t, ele)) :: udotgradnvfrac_at_quad assert(have_advection) t_shape => ele_shape(t, ele) velocity_at_quad = ele_val_at_quad(velocity, ele) if(move_mesh) then velocity_at_quad = velocity_at_quad - ele_val_at_quad(grid_velocity, ele) end if select case(equation_type) case(FIELD_EQUATION_INTERNALENERGY) assert(ele_ngi(density, ele)==ele_ngi(olddensity, ele)) density_at_quad = density_theta*ele_val_at_quad(density, ele)& +(1.-density_theta)*ele_val_at_quad(olddensity, ele) densitygrad_at_quad = density_theta*ele_grad_at_quad(density, ele, drho_t) & +(1.-density_theta)*ele_grad_at_quad(olddensity, ele, drho_t) udotgradrho_at_quad = sum(densitygrad_at_quad*velocity_at_quad, 1) if(multiphase) then nvfrac_at_quad = ele_val_at_quad(nvfrac, ele) end if case(FIELD_EQUATION_KEPSILON) density_at_quad = ele_val_at_quad(density, ele) densitygrad_at_quad = ele_grad_at_quad(density, ele, drho_t) udotgradrho_at_quad = sum(densitygrad_at_quad*velocity_at_quad, 1) end select if(integrate_advection_by_parts) then ! element advection matrix ! / / ! - | (grad N_A dot nu) N_B dV - (1. - beta) | N_A ( div nu ) N_B dV ! / / select case(equation_type) case(FIELD_EQUATION_INTERNALENERGY) if(multiphase) then advection_mat = -dshape_dot_vector_shape(dt_t, velocity_at_quad, t_shape, detwei*density_at_quad*nvfrac_at_quad) else advection_mat = -dshape_dot_vector_shape(dt_t, velocity_at_quad, t_shape, detwei*density_at_quad) end if if(abs(1.0 - beta) > epsilon(0.0)) then velocity_div_at_quad = ele_div_at_quad(velocity, ele, du_t) if(multiphase) then nvfracgrad_at_quad = ele_grad_at_quad(nvfrac, ele, dnvfrac_t) udotgradnvfrac_at_quad = sum(nvfracgrad_at_quad*velocity_at_quad, 1) advection_mat = advection_mat - (1.0-beta) * ( shape_shape(test_function, t_shape, detwei*velocity_div_at_quad*density_at_quad*nvfrac_at_quad) & + shape_shape(test_function, t_shape, detwei*nvfrac_at_quad*udotgradrho_at_quad) & + shape_shape(test_function, t_shape, detwei*density_at_quad*udotgradnvfrac_at_quad) ) else advection_mat = advection_mat - (1.0-beta) * shape_shape(test_function, t_shape, (velocity_div_at_quad*density_at_quad + udotgradrho_at_quad)*detwei) end if end if case(FIELD_EQUATION_KEPSILON) advection_mat = -dshape_dot_vector_shape(dt_t, velocity_at_quad, t_shape, detwei*density_at_quad) if(abs(1.0 - beta) > epsilon(0.0)) then velocity_div_at_quad = ele_div_at_quad(velocity, ele, du_t) advection_mat = advection_mat & - (1.0-beta) * shape_shape(test_function, t_shape, (velocity_div_at_quad*density_at_quad & +udotgradrho_at_quad)* detwei) end if case default advection_mat = -dshape_dot_vector_shape(dt_t, velocity_at_quad, t_shape, detwei) if(abs(1.0 - beta) > epsilon(0.0)) then velocity_div_at_quad = ele_div_at_quad(velocity, ele, du_t) advection_mat = advection_mat & - (1.0-beta)*shape_shape(test_function, t_shape, velocity_div_at_quad*detwei) end if end select else ! element advection matrix ! / / ! | N_A (nu dot grad N_B) dV + beta | N_A ( div nu ) N_B dV ! / / select case(equation_type) case(FIELD_EQUATION_INTERNALENERGY) if(multiphase) then ! vfrac*rho*nu*grad(internalenergy) advection_mat = shape_vector_dot_dshape(test_function, velocity_at_quad, dt_t, detwei*density_at_quad*nvfrac_at_quad) else advection_mat = shape_vector_dot_dshape(test_function, velocity_at_quad, dt_t, detwei*density_at_quad) end if if(abs(beta) > epsilon(0.0)) then velocity_div_at_quad = ele_div_at_quad(velocity, ele, du_t) if(multiphase) then ! advection_mat + internalenergy*div(vfrac*rho*nu) ! Split up div(vfrac*rho*nu) = vfrac*rho*div(nu) + nu*grad(vfrac*rho) = vfrac*rho*div(nu) + nu*(vfrac*grad(rho) + rho*grad(nvfrac)) nvfracgrad_at_quad = ele_grad_at_quad(nvfrac, ele, dnvfrac_t) udotgradnvfrac_at_quad = sum(nvfracgrad_at_quad*velocity_at_quad, 1) advection_mat = advection_mat + beta * ( shape_shape(test_function, t_shape, detwei*velocity_div_at_quad*density_at_quad*nvfrac_at_quad) & + shape_shape(test_function, t_shape, detwei*nvfrac_at_quad*udotgradrho_at_quad) & + shape_shape(test_function, t_shape, detwei*density_at_quad*udotgradnvfrac_at_quad) ) else advection_mat = advection_mat + beta*shape_shape(test_function, t_shape, (velocity_div_at_quad*density_at_quad & +udotgradrho_at_quad)*detwei) end if end if case(FIELD_EQUATION_KEPSILON) advection_mat = shape_vector_dot_dshape(test_function, velocity_at_quad, dt_t, detwei*density_at_quad) if(abs(beta) > epsilon(0.0)) then velocity_div_at_quad = ele_div_at_quad(velocity, ele, du_t) advection_mat = advection_mat & + beta*shape_shape(test_function, t_shape, (velocity_div_at_quad*density_at_quad & +udotgradrho_at_quad)*detwei) end if case default advection_mat = shape_vector_dot_dshape(test_function, velocity_at_quad, dt_t, detwei) if(abs(beta) > epsilon(0.0)) then velocity_div_at_quad = ele_div_at_quad(velocity, ele, du_t) advection_mat = advection_mat & + beta*shape_shape(test_function, t_shape, velocity_div_at_quad*detwei) end if if(move_mesh) then advection_mat = advection_mat & - shape_shape(test_function, t_shape, ele_div_at_quad(grid_velocity, ele, dug_t)*detwei) end if end select end if ! Stabilisation select case(stabilisation_scheme) case(STABILISATION_STREAMLINE_UPWIND) if(have_diffusivity) then advection_mat = advection_mat + & & element_upwind_stabilisation(t_shape, dt_t, velocity_at_quad, j_mat, detwei, & & diff_q = ele_val_at_quad(diffusivity, ele), nu_bar_scheme = nu_bar_scheme, nu_bar_scale = nu_bar_scale) else advection_mat = advection_mat + & & element_upwind_stabilisation(t_shape, dt_t, velocity_at_quad, j_mat, detwei, & & nu_bar_scheme = nu_bar_scheme, nu_bar_scale = nu_bar_scale) end if case default end select if(abs(dt_theta) > epsilon(0.0)) then matrix_addto = matrix_addto + dt_theta * advection_mat end if rhs_addto = rhs_addto - matmul(advection_mat, ele_val(t, ele)) end subroutine add_advection_element_cg subroutine add_source_element_cg(ele, test_function, t, source, detwei, rhs_addto) integer, intent(in) :: ele type(element_type), intent(in) :: test_function type(scalar_field), intent(in) :: t type(scalar_field), intent(in) :: source real, dimension(ele_ngi(t, ele)), intent(in) :: detwei real, dimension(ele_loc(t, ele)), intent(inout) :: rhs_addto assert(have_source) rhs_addto = rhs_addto + shape_rhs(test_function, detwei * ele_val_at_quad(source, ele)) end subroutine add_source_element_cg subroutine add_absorption_element_cg(ele, test_function, t, absorption, detwei, matrix_addto, rhs_addto) integer, intent(in) :: ele type(element_type), intent(in) :: test_function type(scalar_field), intent(in) :: t type(scalar_field), intent(in) :: absorption real, dimension(ele_ngi(t, ele)), intent(in) :: detwei real, dimension(ele_loc(t, ele), ele_loc(t, ele)), intent(inout) :: matrix_addto real, dimension(ele_loc(t, ele)), intent(inout) :: rhs_addto real, dimension(ele_loc(t, ele), ele_loc(t, ele)) :: absorption_mat assert(have_absorption) absorption_mat = shape_shape(test_function, ele_shape(t, ele), detwei * ele_val_at_quad(absorption, ele)) if(abs(dt_theta) > epsilon(0.0)) matrix_addto = matrix_addto + dt_theta * absorption_mat rhs_addto = rhs_addto - matmul(absorption_mat, ele_val(t, ele)) end subroutine add_absorption_element_cg subroutine add_diffusivity_element_cg(ele, t, diffusivity, dt_t, nvfrac, detwei, matrix_addto, rhs_addto) integer, intent(in) :: ele type(scalar_field), intent(in) :: t, nvfrac type(tensor_field), intent(in) :: diffusivity real, dimension(ele_loc(t, ele), ele_ngi(t, ele), mesh_dim(t)), intent(in) :: dt_t real, dimension(ele_ngi(t, ele)), intent(in) :: detwei real, dimension(ele_loc(t, ele), ele_loc(t, ele)), intent(inout) :: matrix_addto real, dimension(ele_loc(t, ele)), intent(inout) :: rhs_addto real, dimension(diffusivity%dim(1), diffusivity%dim(2), ele_ngi(diffusivity, ele)) :: diffusivity_gi real, dimension(ele_loc(t, ele), ele_loc(t, ele)) :: diffusivity_mat assert(have_diffusivity) diffusivity_gi = ele_val_at_quad(diffusivity, ele) if(isotropic_diffusivity) then assert(size(diffusivity_gi, 1) > 0) if(multiphase .and. equation_type==FIELD_EQUATION_INTERNALENERGY) then ! This allows us to use the Diffusivity term as the heat flux term ! in the multiphase InternalEnergy equation: div( (k/Cv) * vfrac * grad(ie) ). ! The user needs to input k/Cv for the prescribed diffusivity, ! where k is the effective conductivity and Cv is the specific heat ! at constant volume. We've assumed this will always be isotropic here. ! The division by Cv is needed because the heat flux ! is defined in terms of temperature T = ie/Cv. diffusivity_mat = dshape_dot_dshape(dt_t, dt_t, detwei * diffusivity_gi(1, 1, :) * ele_val_at_quad(nvfrac, ele)) else diffusivity_mat = dshape_dot_dshape(dt_t, dt_t, detwei * diffusivity_gi(1, 1, :)) end if else diffusivity_mat = dshape_tensor_dshape(dt_t, diffusivity_gi, dt_t, detwei) end if if(abs(dt_theta) > epsilon(0.0)) matrix_addto = matrix_addto + dt_theta * diffusivity_mat rhs_addto = rhs_addto - matmul(diffusivity_mat, ele_val(t, ele)) end subroutine add_diffusivity_element_cg subroutine add_pressurediv_element_cg(ele, test_function, t, velocity, pressure, nvfrac, du_t, detwei, rhs_addto) integer, intent(in) :: ele type(element_type), intent(in) :: test_function type(scalar_field), intent(in) :: t type(vector_field), intent(in) :: velocity type(scalar_field), intent(in) :: pressure type(scalar_field), intent(in) :: nvfrac real, dimension(ele_loc(velocity, ele), ele_ngi(velocity, ele), mesh_dim(t)), intent(in) :: du_t real, dimension(ele_ngi(t, ele)), intent(in) :: detwei real, dimension(ele_loc(t, ele)), intent(inout) :: rhs_addto assert(equation_type==FIELD_EQUATION_INTERNALENERGY) assert(ele_ngi(pressure, ele)==ele_ngi(t, ele)) if(multiphase) then ! -p * vfrac * div(nu) rhs_addto = rhs_addto - shape_rhs(test_function, ele_div_at_quad(velocity, ele, du_t) * ele_val_at_quad(pressure, ele) * detwei * ele_val_at_quad(nvfrac, ele)) else rhs_addto = rhs_addto - shape_rhs(test_function, ele_div_at_quad(velocity, ele, du_t) * ele_val_at_quad(pressure, ele) * detwei) end if end subroutine add_pressurediv_element_cg subroutine assemble_advection_diffusion_face_cg(face, bc_type, t, t_bc, t_bc_2, matrix, rhs, positions, velocity, grid_velocity, density, olddensity, nvfrac) integer, intent(in) :: face integer, intent(in) :: bc_type type(scalar_field), intent(in) :: t type(scalar_field), intent(in) :: t_bc type(scalar_field), intent(in) :: t_bc_2 type(csr_matrix), intent(inout) :: matrix type(scalar_field), intent(inout) :: rhs type(vector_field), intent(in) :: positions type(vector_field), intent(in) :: velocity type(vector_field), pointer :: grid_velocity type(scalar_field), intent(in) :: density type(scalar_field), intent(in) :: olddensity type(scalar_field), intent(in) :: nvfrac integer, dimension(face_loc(t, face)) :: face_nodes real, dimension(face_ngi(t, face)) :: detwei real, dimension(mesh_dim(t), face_ngi(t, face)) :: normal ! What we will be adding to the matrix and RHS - assemble these as we ! go, so that we only do the calculations we really need real, dimension(face_loc(t, face)) :: rhs_addto real, dimension(face_loc(t, face), face_loc(t, face)) :: matrix_addto assert(any(bc_type == (/0, BC_TYPE_NEUMANN, BC_TYPE_WEAKDIRICHLET, BC_TYPE_ROBIN/))) assert(face_ngi(positions, face) == face_ngi(t, face)) assert(face_ngi(velocity, face) == face_ngi(t, face)) matrix_addto = 0.0 rhs_addto = 0.0 ! Step 1: Transform if(have_advection .and. integrate_advection_by_parts) then call transform_facet_to_physical(positions, face, & & detwei_f = detwei, normal = normal) else if(have_diffusivity.and.((bc_type == BC_TYPE_NEUMANN).or.(bc_type == BC_TYPE_ROBIN))) then call transform_facet_to_physical(positions, face, & & detwei_f = detwei) end if ! Note that with SUPG the surface element test function is not modified ! Step 2: Assemble contributions ! Advection if(have_advection .and. integrate_advection_by_parts) & call add_advection_face_cg(face, bc_type, t, t_bc, velocity, grid_velocity, density, olddensity, nvfrac, detwei, normal, matrix_addto, rhs_addto) ! Diffusivity if(have_diffusivity) call add_diffusivity_face_cg(face, bc_type, t, t_bc, t_bc_2, detwei, matrix_addto, rhs_addto) ! Step 3: Insertion face_nodes = face_global_nodes(t, face) call addto(matrix, face_nodes, face_nodes, matrix_addto) call addto(rhs, face_nodes, rhs_addto) end subroutine assemble_advection_diffusion_face_cg subroutine add_advection_face_cg(face, bc_type, t, t_bc, velocity, grid_velocity, density, olddensity, nvfrac, detwei, normal, matrix_addto, rhs_addto) integer, intent(in) :: face integer, intent(in) :: bc_type type(scalar_field), intent(in) :: t type(scalar_field), intent(in) :: t_bc type(vector_field), intent(in) :: velocity type(vector_field), pointer :: grid_velocity type(scalar_field), intent(in) :: density type(scalar_field), intent(in) :: olddensity type(scalar_field), intent(in) :: nvfrac real, dimension(face_ngi(t, face)), intent(in) :: detwei real, dimension(mesh_dim(t), face_ngi(t, face)), intent(in) :: normal real, dimension(face_loc(t, face), face_loc(t, face)), intent(inout) :: matrix_addto real, dimension(face_loc(t, face)), intent(inout) :: rhs_addto real, dimension(velocity%dim, face_ngi(velocity, face)) :: velocity_at_quad real, dimension(face_loc(t, face), face_loc(t,face)) :: advection_mat type(element_type), pointer :: t_shape real, dimension(face_ngi(density, face)) :: density_at_quad assert(have_advection) assert(integrate_advection_by_parts) t_shape => face_shape(t, face) velocity_at_quad = face_val_at_quad(velocity, face) if(move_mesh) then velocity_at_quad = velocity_at_quad - face_val_at_quad(grid_velocity, face) end if select case(equation_type) case(FIELD_EQUATION_INTERNALENERGY) density_at_quad = density_theta*face_val_at_quad(density, face) & +(1.0-density_theta)*face_val_at_quad(olddensity, face) if(multiphase) then advection_mat = shape_shape(t_shape, t_shape, detwei * sum(velocity_at_quad * normal, 1) * density_at_quad * face_val_at_quad(nvfrac, face)) else advection_mat = shape_shape(t_shape, t_shape, detwei * sum(velocity_at_quad * normal, 1) * density_at_quad) end if case default advection_mat = shape_shape(t_shape, t_shape, detwei * sum(velocity_at_quad * normal, 1)) end select if(abs(dt_theta) > epsilon(0.0)) then if(bc_type == BC_TYPE_WEAKDIRICHLET) then rhs_addto = rhs_addto - theta * matmul(advection_mat, ele_val(t_bc, face) - face_val(t, face)) else matrix_addto = matrix_addto + dt_theta * advection_mat end if end if rhs_addto = rhs_addto - matmul(advection_mat, face_val(t, face)) end subroutine add_advection_face_cg subroutine add_diffusivity_face_cg(face, bc_type, t, t_bc, t_bc_2, detwei, matrix_addto, rhs_addto) integer, intent(in) :: face integer, intent(in) :: bc_type type(scalar_field), intent(in) :: t type(scalar_field), intent(in) :: t_bc type(scalar_field), intent(in) :: t_bc_2 real, dimension(face_ngi(t, face)), intent(in) :: detwei real, dimension(face_loc(t, face), face_loc(t, face)), intent(inout) :: matrix_addto real, dimension(face_loc(t, face)), intent(inout) :: rhs_addto real, dimension(face_loc(t, face), face_loc(t,face)) :: robin_mat type(element_type), pointer :: t_shape assert(have_diffusivity) t_shape => face_shape(t, face) if(bc_type == BC_TYPE_NEUMANN) then rhs_addto = rhs_addto + shape_rhs(t_shape, detwei * ele_val_at_quad(t_bc, face)) else if(bc_type == BC_TYPE_ROBIN) then rhs_addto = rhs_addto + shape_rhs(t_shape, detwei * ele_val_at_quad(t_bc, face)) robin_mat = shape_shape(t_shape, t_shape, detwei * ele_val_at_quad(t_bc_2, face)) if (abs(dt_theta) > epsilon(0.0)) then matrix_addto = matrix_addto + dt_theta * robin_mat end if ! this next term is due to solving the acceleration form of the equation rhs_addto = rhs_addto - matmul(robin_mat, face_val(t, face)) else if(bc_type == BC_TYPE_WEAKDIRICHLET) then ! Need to add stuff here once transform_to_physical can supply gradients ! on faces to ensure that weak bcs work FLExit("Weak Dirichlet boundary conditions with diffusivity are not supported by CG advection-diffusion") end if end subroutine add_diffusivity_face_cg subroutine solve_advection_diffusion_cg(t, delta_t, matrix, rhs, state, iterations_taken) type(scalar_field), intent(in) :: t type(scalar_field), intent(inout) :: delta_t type(csr_matrix), intent(in) :: matrix type(scalar_field), intent(in) :: rhs type(state_type), intent(in) :: state integer, intent(out), optional :: iterations_taken call petsc_solve(delta_t, matrix, rhs, state, option_path = t%option_path, & iterations_taken = iterations_taken) ewrite_minmax(delta_t) end subroutine solve_advection_diffusion_cg subroutine apply_advection_diffusion_cg_change(t, delta_t, dt) type(scalar_field), intent(inout) :: t type(scalar_field), intent(in) :: delta_t real, intent(in) :: dt ewrite_minmax(t) call addto(t, delta_t, dt) ewrite_minmax(t) end subroutine apply_advection_diffusion_cg_change subroutine advection_diffusion_cg_check_options !!< Check CG advection-diffusion specific options character(len = FIELD_NAME_LEN) :: field_name, state_name, mesh_0, mesh_1 character(len = OPTION_PATH_LEN) :: path integer :: i, j, stat real :: beta, l_theta if(option_count("/material_phase/scalar_field/prognostic/spatial_discretisation/continuous_galerkin") == 0) then ! Nothing to check return end if ewrite(2, *) "Checking CG advection-diffusion options" if(option_count("/material_phase/scalar_field::" // advdif_cg_rhs_name) > 0) then FLExit("The scalar field name " // advdif_cg_rhs_name // " is reserved") end if if(option_count("/material_phase/scalar_field::" // advdif_cg_delta_t_name) > 0) then FLExit("The scalar field name " // advdif_cg_delta_t_name // " is reserved") end if do i = 0, option_count("/material_phase") - 1 path = "/material_phase[" // int2str(i) // "]" call get_option(trim(path) // "/name", state_name) do j = 0, option_count(trim(path) // "/scalar_field") - 1 path = "/material_phase[" // int2str(i) // "]/scalar_field[" // int2str(j) // "]" call get_option(trim(path) // "/name", field_name) if(field_name /= "Pressure") then path = trim(path) // "/prognostic" if(have_option(trim(path) // "/spatial_discretisation/continuous_galerkin").and.& have_option(trim(path) // "/equation[0]")) then call get_option(trim(path) // "/spatial_discretisation/conservative_advection", beta, stat) if(stat == SPUD_NO_ERROR) then if(beta < 0.0 .or. beta > 1.0) then call field_error(state_name, field_name, & & "Conservative advection factor (beta) must be >= 0.0 and <= 1.0") end if else call field_error(state_name, field_name, & & "Conservative advection factor (beta) required") end if call get_option(trim(path) // "/temporal_discretisation/theta", l_theta, stat) if(stat == SPUD_NO_ERROR) then if(l_theta < 0. .or. l_theta > 1.0) then call field_error(state_name, field_name, & &"Implicitness factor (theta) must be >= 0.0 and <= 1.0") end if else call field_error(state_name, field_name, & & "Implicitness factor (theta) required") end if if(have_option(trim(path) // "/spatial_discretisation/continuous_galerkin/mass_terms/exclude_mass_terms") .and. & & abs(l_theta - 1.0) > epsilon(0.0)) then call field_warning(state_name, field_name, & & "Implicitness factor (theta) should = 1.0 when excluding mass") end if if(have_option(trim(path) // "/spatial_discretisation/continuous_galerkin/stabilisation/streamline_upwind_petrov_galerkin") .and. & & have_option(trim(path) // "/spatial_discretisation/continuous_galerkin/advection_terms/integrate_advection_by_parts")) then call field_warning(state_name, field_name, & & "SUPG stabilisation should only be used with advection not integrated by parts") end if if(option_count(trim(path) // "/boundary_conditions/type::dirichlet/apply_weakly") > 0 & & .and. have_option(trim(path) // "/tensor_field::Diffusivity")) then call field_error(state_name, field_name, & & "Weak Dirichlet boundary conditions with diffusivity are not supported by CG advection-diffusion") end if if (have_option(trim(path) // "/scalar_field::SinkingVelocity")) then call get_option(trim(complete_field_path(trim(path) // & "/scalar_field::SinkingVelocity"))//"/mesh[0]/name", & mesh_0, stat) if(stat == SPUD_NO_ERROR) then call get_option(trim(complete_field_path("/material_phase[" // int2str(i) // & "]/vector_field::Velocity")) // "/mesh[0]/name", mesh_1) if(trim(mesh_0) /= trim(mesh_1)) then call field_warning(state_name, field_name, & & "SinkingVelocity is on a different mesh to the Velocity field. This could cause problems") end if end if end if if(have_option(trim(path) // "/spatial_discretisation/continuous_galerkin/advection_terms/exclude_advection_terms")) then if(have_option(trim(path) // "/scalar_field::SinkingVelocity")) then call field_warning(state_name, field_name, & & "SinkingVelocity set, but advection terms have been excluded - SinkingVelocity will have no effect") end if end if if(option_count(trim(path) // "/boundary_conditions/type::neumann") > 0 & & .and. .not. (have_option(trim(path) // "/tensor_field::Diffusivity") & & .or. have_option(trim(path) // "/subgridscale_parameterisation::k-epsilon") & & .or. have_option(trim(path) // "/subgridscale_parameterisation::GLS"))) then call field_warning(state_name, field_name, & & "Neumann boundary condition set, but have no diffusivity - boundary condition will not be applied") end if end if end if end do end do ewrite(2, *) "Finished checking CG advection-diffusion options" contains subroutine field_warning(state_name, field_name, msg) character(len = *), intent(in) :: state_name character(len = *), intent(in) :: field_name character(len = *), intent(in) :: msg ewrite(0, *) "Warning: For field " // trim(field_name) // " in state " // trim(state_name) ewrite(0, *) trim(msg) end subroutine field_warning subroutine field_error(state_name, field_name, msg) character(len = *), intent(in) :: state_name character(len = *), intent(in) :: field_name character(len = *), intent(in) :: msg ewrite(-1, *) "For field " // trim(field_name) // " in state " // trim(state_name) FLExit(trim(msg)) end subroutine field_error end subroutine advection_diffusion_cg_check_options end module advection_diffusion_cg
lgpl-2.1
jrper/fluidity
tools/fldiagnostics.F90
5
3179
! Offline vtu diagnostics tools ! ! James Maddison #include "fdebug.h" subroutine fldiag_add_diag(input_name_, input_name_len, & & output_name_, output_name_len, & & outfield_name_, outfield_name_len, & & meshfield_name_, meshfield_name_len, & & state_name_, state_name_len, outfield_rank) bind(c) !!< Read data from the vtu with name input_name, add a specified diagnostic !!< field with name outfield_name, and write the new data to a vtu with name !!< output_name. See fldiagnostics help for more information. use diagnostic_fields use fields_data_types use fields use fldebug use spud use state_module use vtk_interfaces use iso_c_binding implicit none integer(kind=c_size_t), value :: input_name_len, output_name_len, outfield_name_len, & & meshfield_name_len, state_name_len integer(kind=c_int32_t), value :: outfield_rank character(kind=c_char, len=1) :: input_name_(*), output_name_(*), outfield_name_(*), & & meshfield_name_(*), state_name_(*) character(len = input_name_len) :: input_name character(len = output_name_len) :: output_name character(len = outfield_name_len) :: outfield_name character(len = meshfield_name_len):: meshfield_name character(len = state_name_len) :: state_name integer :: i, rank, stat type(mesh_type), pointer :: mesh type(state_type), dimension(1) :: state do i=1, input_name_len input_name(i:i)=input_name_(i) end do do i=1, output_name_len output_name(i:i)=output_name_(i) end do do i=1, outfield_name_len outfield_name(i:i)=outfield_name_(i) end do do i=1, meshfield_name_len meshfield_name(i:i)=meshfield_name_(i) end do do i=1, state_name_len state_name(i:i)=state_name_(i) end do if(.not. have_option("/simulation_name")) then ewrite(0, *) "Warning: No options file supplied to fldiag_add_diag" end if call vtk_read_state(trim(input_name), state(1)) if(state_name_len > 0) then state(1)%name = state_name else call get_option("/material_phase[0]/name", state(1)%name, stat) end if mesh => extract_field_mesh(state(1), meshfield_name) rank = field_rank(state(1), outfield_name) if(outfield_rank .ne. 0) then if(rank > 0 .and. rank /= outfield_rank) then FLExit("Requested diagnostic field rank and rank of existing field in input file do not match") end if call insert_diagnostic_field(state(1), outfield_name, mesh, outfield_rank) else do i = 0, 3 call insert_diagnostic_field(state(1), outfield_name, mesh, i, stat) if(stat == 0) then if(rank >= 0 .and. rank /= i) then FLExit("Rank of calculated diagnostic field and existing field in input file do not match") end if exit else if(i == 3) then FLExit("Failed to calculate diagnostic variable - try specifying the rank") end if end do end if call vtk_write_state(trim(output_name), state = state) call deallocate(state(1)) end subroutine fldiag_add_diag !subroutine fldiag_add_presc !end subroutine fldiag_add_presc
lgpl-2.1
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/argument_checking_5.f90
174
1121
! { dg-do compile } ! ! PR fortran/30940 program test implicit none interface subroutine foobar(x) integer,dimension(4) :: x end subroutine foobar subroutine arr(y) integer,dimension(1,2,1,2) :: y end subroutine arr end interface integer a(3), b(5) call foobar(a) ! { dg-warning "contains too few elements" } call foobar(b) call foobar(b(1:3)) ! { dg-warning "contains too few elements" } call foobar(b(1:5)) call foobar(b(1:5:2)) ! { dg-warning "contains too few elements" } call foobar(b(2)) call foobar(b(3)) ! { dg-warning "Actual argument contains too few elements" } call foobar(reshape(a(1:3),[2,1])) ! { dg-warning "contains too few elements" } call foobar(reshape(b(2:5),[2,2])) call arr(a) ! { dg-warning "contains too few elements" } call arr(b) call arr(b(1:3)) ! { dg-warning "contains too few elements" } call arr(b(1:5)) call arr(b(1:5:2)) ! { dg-warning "contains too few elements" } call arr(b(2)) call arr(b(3)) ! { dg-warning "contains too few elements" } call arr(reshape(a(1:3),[2,1])) ! { dg-warning "contains too few elements" } call arr(reshape(b(2:5),[2,2])) end program test
gpl-2.0
davidinouye/lpmrf
mexcode/eigen/lapack/zladiv.f
280
2364
*> \brief \b ZLADIV * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download ZLADIV + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zladiv.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zladiv.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zladiv.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * COMPLEX*16 FUNCTION ZLADIV( X, Y ) * * .. Scalar Arguments .. * COMPLEX*16 X, Y * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> ZLADIV := X / Y, where X and Y are complex. The computation of X / Y *> will not overflow on an intermediary step unless the results *> overflows. *> \endverbatim * * Arguments: * ========== * *> \param[in] X *> \verbatim *> X is COMPLEX*16 *> \endverbatim *> *> \param[in] Y *> \verbatim *> Y is COMPLEX*16 *> The complex scalars X and Y. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup complex16OTHERauxiliary * * ===================================================================== COMPLEX*16 FUNCTION ZLADIV( X, Y ) * * -- LAPACK auxiliary routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. COMPLEX*16 X, Y * .. * * ===================================================================== * * .. Local Scalars .. DOUBLE PRECISION ZI, ZR * .. * .. External Subroutines .. EXTERNAL DLADIV * .. * .. Intrinsic Functions .. INTRINSIC DBLE, DCMPLX, DIMAG * .. * .. Executable Statements .. * CALL DLADIV( DBLE( X ), DIMAG( X ), DBLE( Y ), DIMAG( Y ), ZR, $ ZI ) ZLADIV = DCMPLX( ZR, ZI ) * RETURN * * End of ZLADIV * END
mit
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/dummy_procedure_7.f90
136
1291
! { dg-do run } ! ! PR fortran/52022 ! module check integer, save :: icheck = 0 end module check module t implicit none contains subroutine sol(cost) use check interface function cost(p) result(y) double precision,dimension(:) :: p double precision,dimension(:),allocatable :: y end function cost end interface if (any (cost([1d0,2d0]) /= [2.d0, 4.d0])) call abort () icheck = icheck + 1 end subroutine end module t module tt procedure(cost1),pointer :: pcost contains subroutine init() pcost=>cost1 end subroutine function cost1(x) result(y) double precision,dimension(:) :: x double precision,dimension(:),allocatable :: y allocate(y(2)) y=2d0*x end function cost1 function cost(x) result(y) double precision,dimension(:) :: x double precision,dimension(:),allocatable :: y allocate(y(2)) y=pcost(x) end function cost end module program test use tt use t use check implicit none call init() if (any (cost([3.d0,7.d0]) /= [6.d0, 14.d0])) call abort () if (icheck /= 0) call abort () call sol(cost) if (icheck /= 1) call abort () end program test
gpl-2.0
rgwan/gcc
gcc/testsuite/gfortran.dg/bound_simplification_5.f90
48
2258
! { dg-do run } ! { dg-additional-options "-fcoarray=single -fdump-tree-original" } ! ! Check that {L,U}{,CO}BOUND intrinsics are properly simplified. ! implicit none type :: t integer :: c end type t type(t) :: d(3:8) = t(7) type(t) :: e[5:9,-1:*] type(t) :: h(3), j(4), k(0) !Test full arrays vs subarrays if (lbound(d, 1) /= 3) call abort if (lbound(d(3:5), 1) /= 1) call abort if (lbound(d%c, 1) /= 1) call abort if (ubound(d, 1) /= 8) call abort if (ubound(d(3:5), 1) /= 3) call abort if (ubound(d%c, 1) /= 6) call abort if (lcobound(e, 1) /= 5) call abort if (lcobound(e%c, 1) /= 5) call abort if (lcobound(e, 2) /= -1) call abort if (lcobound(e%c, 2) /= -1) call abort if (ucobound(e, 1) /= 9) call abort if (ucobound(e%c, 1) /= 9) call abort ! no simplification for ucobound(e{,%c}, dim=2) if (any(lbound(d ) /= [3])) call abort if (any(lbound(d(3:5)) /= [1])) call abort if (any(lbound(d%c ) /= [1])) call abort if (any(ubound(d ) /= [8])) call abort if (any(ubound(d(3:5)) /= [3])) call abort if (any(ubound(d%c ) /= [6])) call abort if (any(lcobound(e ) /= [5, -1])) call abort if (any(lcobound(e%c) /= [5, -1])) call abort ! no simplification for ucobound(e{,%c}) call test_empty_arrays(h, j, k) contains subroutine test_empty_arrays(a, c, d) type(t) :: a(:), c(-3:0), d(3:1) type(t) :: f(4:2), g(0:6) if (lbound(a, 1) /= 1) call abort if (lbound(c, 1) /= -3) call abort if (lbound(d, 1) /= 1) call abort if (lbound(f, 1) /= 1) call abort if (lbound(g, 1) /= 0) call abort if (ubound(c, 1) /= 0) call abort if (ubound(d, 1) /= 0) call abort if (ubound(f, 1) /= 0) call abort if (ubound(g, 1) /= 6) call abort if (any(lbound(a) /= [ 1])) call abort if (any(lbound(c) /= [-3])) call abort if (any(lbound(d) /= [ 1])) call abort if (any(lbound(f) /= [ 1])) call abort if (any(lbound(g) /= [ 0])) call abort if (any(ubound(c) /= [0])) call abort if (any(ubound(d) /= [0])) call abort if (any(ubound(f) /= [0])) call abort if (any(ubound(g) /= [6])) call abort end subroutine end ! { dg-final { scan-tree-dump-not "abort" "original" } }
gpl-2.0
Gd58/gcc
gcc/testsuite/gfortran.dg/pr66311.f90
54
2211
! { dg-do run } ! { dg-additional-options "-fno-range-check -w" } ! ! Check that we can print large constants ! ! "-fno-range-check -w" is used so the testcase compiles even with targets ! that don't support large integer kinds. program test use iso_fortran_env, only : ikinds => integer_kinds implicit none ! Largest integer kind integer, parameter :: k = ikinds(size(ikinds)) integer, parameter :: hk = k / 2 if (k <= 8) stop call check(9000000000000000000_k, "9000000000000000000") call check(90000000000000000000_k, "90000000000000000000") call check(int(huge(1_hk), kind=k), "9223372036854775807") call check(2_k**63, "9223372036854775808") call check(10000000000000000000_k, "10000000000000000000") call check(18446744065119617024_k, "18446744065119617024") call check(2_k**64 - 1, "18446744073709551615") call check(2_k**64, "18446744073709551616") call check(20000000000000000000_k, "20000000000000000000") call check(huge(0_k), "170141183460469231731687303715884105727") call check(huge(0_k)-1, "170141183460469231731687303715884105726") call check(-9000000000000000000_k, "-9000000000000000000") call check(-90000000000000000000_k, "-90000000000000000000") call check(-int(huge(1_hk), kind=k), "-9223372036854775807") call check(-2_k**63, "-9223372036854775808") call check(-10000000000000000000_k, "-10000000000000000000") call check(-18446744065119617024_k, "-18446744065119617024") call check(-(2_k**64 - 1), "-18446744073709551615") call check(-2_k**64, "-18446744073709551616") call check(-20000000000000000000_k, "-20000000000000000000") call check(-huge(0_k), "-170141183460469231731687303715884105727") call check(-(huge(0_k)-1), "-170141183460469231731687303715884105726") call check(-huge(0_k)-1, "-170141183460469231731687303715884105728") call check(2_k * huge(1_hk), "18446744073709551614") call check((-2_k) * huge(1_hk), "-18446744073709551614") contains subroutine check (i, str) implicit none integer(kind=k), intent(in), value :: i character(len=*), intent(in) :: str character(len=100) :: buffer write(buffer,*) i if (adjustl(buffer) /= adjustl(str)) call abort end subroutine end
gpl-2.0
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/defined_operators_1.f90
34
1995
! { dg-do compile } ! { dg-options "-std=legacy" } ! Tests the fix for PR27122, in which the requirements of 12.3.2.1.1 ! for defined operators were not enforced. ! ! Based on PR test by Thomas Koenig <tkoenig@gcc.gnu.org> ! module mymod interface operator (.foo.) module procedure foo_0 module procedure foo_1 module procedure foo_2 module procedure foo_3 module procedure foo_1_OK module procedure foo_2_OK function foo_chr (chr) ! { dg-error "cannot be assumed character length" } character(*) :: foo_chr character(*), intent(in) :: chr end function foo_chr end interface ! ! PR fortran/33117 ! PR fortran/46478 ! Mixing FUNCTIONs and SUBROUTINEs in an INTERFACE hides the ! errors that should be tested here. Hence split out subroutine ! to test separately. ! interface operator (.bar.) subroutine bad_foo (chr) ! { dg-error "must be a FUNCTION" } character(*), intent(in) :: chr end subroutine bad_foo end interface contains function foo_0 () ! { dg-error "must have at least one argument" } integer :: foo_1 foo_0 = 1 end function foo_0 function foo_1 (a) ! { dg-error "Ambiguous interfaces" } integer :: foo_1 integer, intent(in) :: a foo_1 = 1 end function foo_1 function foo_1_OK (a) ! { dg-error "Ambiguous interfaces" } integer :: foo_1_OK integer, intent (in) :: a foo_1_OK = 1 end function foo_1_OK function foo_2 (a, b) ! { dg-error "cannot be optional" } integer :: foo_2 integer, intent(in) :: a integer, intent(in), optional :: b foo_2 = 2 * a + b end function foo_2 function foo_2_OK (a, b) real :: foo_2_OK real, intent(in) :: a real, intent(in) :: b foo_2_OK = 2.0 * a + b end function foo_2_OK function foo_3 (a, b, c) ! { dg-error "must have, at most, two arguments" } integer :: foo_3 integer, intent(in) :: a, b, c foo_3 = a + 3 * b - c end function foo_3 end module mymod
gpl-2.0
emb-team/loongson-gccgo
libgomp/testsuite/libgomp.fortran/allocatable12.f90
102
2433
! { dg-do run } integer, allocatable :: a, b(:), c(:,:) logical :: l if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort !$omp parallel private (a, b, c, l) l = .false. if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort !$omp single allocate (a, b(6:9), c(3, 8:9)) a = 4 b = 5 c = 6 !$omp end single copyprivate (a, b, c) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 4) call abort if (lbound (b, 1) /= 6 .or. ubound (b, 1) /= 9) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 8 .or. ubound (c, 2) /= 9) call abort if (a /= 4 .or. any (b /= 5) .or. any (c /= 6)) call abort !$omp single deallocate (a, b, c) if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort allocate (a, b(0:4), c(3, 2:7)) a = 1 b = 2 c = 3 !$omp end single copyprivate (a, b, c) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 5) call abort if (lbound (b, 1) /= 0 .or. ubound (b, 1) /= 4) call abort if (.not.allocated (c) .or. size (c) /= 18) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 6) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 2 .or. ubound (c, 2) /= 7) call abort if (a /= 1 .or. any (b /= 2) .or. any (c /= 3)) call abort !$omp single l = .true. deallocate (a, b, c) if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort allocate (a, b(2:6), c(3:5, 3:8)) a = 7 b = 8 c = 9 !$omp end single copyprivate (a, b, c) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 5) call abort if (l) then if (lbound (b, 1) /= 2 .or. ubound (b, 1) /= 6) call abort else if (lbound (b, 1) /= 0 .or. ubound (b, 1) /= 4) call abort end if if (.not.allocated (c) .or. size (c) /= 18) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 6) call abort if (l) then if (lbound (c, 1) /= 3 .or. ubound (c, 1) /= 5) call abort if (lbound (c, 2) /= 3 .or. ubound (c, 2) /= 8) call abort else if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 2 .or. ubound (c, 2) /= 7) call abort end if if (a /= 7 .or. any (b /= 8) .or. any (c /= 9)) call abort !$omp end parallel end
gpl-2.0
sriki18/scipy
scipy/special/cdflib/alngam.f
133
3399
DOUBLE PRECISION FUNCTION alngam(x) C********************************************************************** C C DOUBLE PRECISION FUNCTION ALNGAM(X) C double precision LN of the GAMma function C C C Function C C C Returns the natural logarithm of GAMMA(X). C C C Arguments C C C X --> value at which scaled log gamma is to be returned C X is DOUBLE PRECISION C C C Method C C C If X .le. 6.0, then use recursion to get X below 3 C then apply rational approximation number 5236 of C Hart et al, Computer Approximations, John Wiley and C Sons, NY, 1968. C C If X .gt. 6.0, then use recursion to get X to at least 12 and C then use formula 5423 of the same source. C C********************************************************************** C C .. Parameters .. DOUBLE PRECISION hln2pi PARAMETER (hln2pi=0.91893853320467274178D0) C .. C .. Scalar Arguments .. DOUBLE PRECISION x C .. C .. Local Scalars .. DOUBLE PRECISION offset,prod,xx INTEGER i,n C .. C .. Local Arrays .. DOUBLE PRECISION coef(5),scoefd(4),scoefn(9) C .. C .. External Functions .. DOUBLE PRECISION devlpl EXTERNAL devlpl C .. C .. Intrinsic Functions .. INTRINSIC log,dble,int C .. C .. Data statements .. DATA scoefn(1)/0.62003838007127258804D2/, + scoefn(2)/0.36036772530024836321D2/, + scoefn(3)/0.20782472531792126786D2/, + scoefn(4)/0.6338067999387272343D1/, + scoefn(5)/0.215994312846059073D1/, + scoefn(6)/0.3980671310203570498D0/, + scoefn(7)/0.1093115956710439502D0/, + scoefn(8)/0.92381945590275995D-2/, + scoefn(9)/0.29737866448101651D-2/ DATA scoefd(1)/0.62003838007126989331D2/, + scoefd(2)/0.9822521104713994894D1/, + scoefd(3)/-0.8906016659497461257D1/, + scoefd(4)/0.1000000000000000000D1/ DATA coef(1)/0.83333333333333023564D-1/, + coef(2)/-0.27777777768818808D-2/, + coef(3)/0.79365006754279D-3/,coef(4)/-0.594997310889D-3/, + coef(5)/0.8065880899D-3/ C .. C .. Executable Statements .. IF (.NOT. (x.LE.6.0D0)) GO TO 70 prod = 1.0D0 xx = x IF (.NOT. (x.GT.3.0D0)) GO TO 30 10 IF (.NOT. (xx.GT.3.0D0)) GO TO 20 xx = xx - 1.0D0 prod = prod*xx GO TO 10 20 CONTINUE 30 IF (.NOT. (x.LT.2.0D0)) GO TO 60 40 IF (.NOT. (xx.LT.2.0D0)) GO TO 50 prod = prod/xx xx = xx + 1.0D0 GO TO 40 50 CONTINUE 60 alngam = devlpl(scoefn,9,xx-2.0D0)/devlpl(scoefd,4,xx-2.0D0) C C C COMPUTE RATIONAL APPROXIMATION TO GAMMA(X) C C alngam = alngam*prod alngam = log(alngam) GO TO 110 70 offset = hln2pi C C C IF NECESSARY MAKE X AT LEAST 12 AND CARRY CORRECTION IN OFFSET C C IF ((x.GT.12.0D0)) GO TO 90 n = int(12.0D0-x) IF (.NOT. (n.GT.0)) GO TO 90 prod = 1.0D0 DO 80,i = 1,n prod = prod* (x+dble(i-1)) 80 CONTINUE offset = offset - log(prod) xx = x + dble(n) GO TO 100 90 xx = x C C C COMPUTE POWER SERIES C C 100 alngam = devlpl(coef,5,1.0D0/ (xx**2))/xx alngam = alngam + offset + (xx-0.5D0)*log(xx) - xx 110 RETURN END
bsd-3-clause
jrper/fluidity
error_measures/tests/test_match_up_ellipsoids.F90
6
1338
subroutine test_match_up_ellipsoids use gradation_metric use unittest_tools implicit none real, dimension(3, 3) :: vec_P, vec_Q real, dimension(3) :: val_P, val_Q integer, dimension(3) :: perm_P, perm_Q logical :: fail vec_P(1, :) = (/0.00000000000000000000E+00, 0.36972895530693085375E-01, -0.99931626875382983943E+00/) vec_P(2, :) = (/0.00000000000000000000E+00, -0.99931626875382983943E+00, -0.36972895530693078436E-01/) vec_P(3, :) = (/0.10000000000000000000E+01, 0.00000000000000000000E+00, 0.00000000000000000000E+00/) vec_Q(1, :) = (/0.36972895530693432320E-01, 0.00000000000000000000E+00, -0.99931626875382983943E+00/) vec_Q(2, :) = (/-0.99931626875382972841E+00, 0.00000000000000000000E+00, -0.36972895530693432320E-01/) vec_Q(3, :) = (/0.00000000000000000000E+00, 0.10000000000000000000E+01, 0.00000000000000000000E+00/) val_P = (/0.16000000000000000000E+02, 0.16000000000000003553E+02, 0.10000000000000000000E+03/) val_Q = (/0.15999999999999998224E+02, 0.16000000000000000000E+02, 0.10000000000000000000E+03/) call match_up_ellipsoids(vec_P, val_P, perm_P, vec_Q, val_Q, perm_Q) fail = .false. if (perm_Q(2) == perm_Q(3)) fail = .true. call report_test("[match up ellipsoids]", fail, .false., & "Previous bugs should not happen again.") end subroutine test_match_up_ellipsoids
lgpl-2.1
fabm-model/code
src/models/aed/aed_zoop_utils.F90
3
5432
!############################################################################### !# # !# aed_zoop_utils.F90 # !# # !# Developed by : # !# AquaticEcoDynamics (AED) Group # !# School of Earth & Environment # !# (C) The University of Western Australia # !# # !# Copyright by the AED-team @ UWA under the GNU Public License - www.gnu.org # !# # !# ----------------------------------------------------------------------- # !# # !# Created October 2011 # !# # !############################################################################### #include "aed.h" MODULE aed_zoop_utils !------------------------------------------------------------------------------- USE aed_core IMPLICIT NONE ! PRIVATE ! By default make everything private ! TYPE type_zoop_prey !State variable name for zooplankton prey CHARACTER(64) :: zoop_prey !Preference factors for zooplankton predators grazing on prey AED_REAL :: Pzoo_prey END TYPE type_zoop_prey TYPE type_zoop_params ! General Attributes CHARACTER(64) :: zoop_name AED_REAL :: zoop_initial, min_zoo ! Growth rate parameters AED_REAL :: Rgrz_zoo, fassim_zoo, Kgrz_zoo, theta_grz_zoo ! Respiration, mortaility and excretion parameters AED_REAL :: Rresp_zoo, Rmort_zoo, ffecal_zoo, fexcr_zoo, ffecal_sed ! Temperature limitation on zooplankton loss terms AED_REAL :: theta_resp_zoo, Tstd_zoo, Topt_zoo, Tmax_zoo ! Salinity parameters INTEGER :: saltfunc_zoo AED_REAL :: Smin_zoo, Smax_zoo, Sint_zoo ! Nutrient parameters AED_REAL :: INC_zoo, IPC_zoo ! Dissolved oxygen parameters AED_REAL :: DOmin_zoo ! Minumum prey concentration parameters AED_REAL :: Cmin_grz_zoo ! Prey information INTEGER :: num_prey TYPE(type_zoop_prey) :: prey(MAX_ZOOP_PREY) INTEGER :: simDOlim ! Temperature limitation derived terms AED_REAL :: kTn, aTn, bTn END TYPE TYPE,extends(type_zoop_params) :: type_zoop_data TYPE (type_state_variable_id) :: id_prey(MAX_ZOOP_PREY) TYPE (type_state_variable_id) :: id_phyIN(MAX_ZOOP_PREY),id_phyIP(MAX_ZOOP_PREY) END TYPE CONTAINS !=============================================================================== !############################################################################### FUNCTION fPrey_Limitation(zoops,group,C) RESULT(fPlim) !----------------------------------------------------------------------------! ! Michaelis-Menten formulation for zooplankton grazing on available ! prey is applied. !----------------------------------------------------------------------------! !ARGUMENTS TYPE(type_zoop_data),DIMENSION(:),INTENT(in) :: zoops INTEGER :: group AED_REAL,INTENT(in) :: C !total concentration of available prey ! !LOCALS ! Returns the M-M limitation function AED_REAL :: fPlim ! !------------------------------------------------------------------------------- !BEGIN fPlim = 1.0 fPlim = C/(zoops(group)%Kgrz_zoo+C) IF( fPlim<zero_ ) fPlim=zero_ END FUNCTION fPrey_Limitation !+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ !############################################################################### FUNCTION fSalinity_Limitation(zoops,group,S) RESULT(fSal) !----------------------------------------------------------------------------! ! Salinity tolerance of zooplankton ! !----------------------------------------------------------------------------! !ARGUMENTS TYPE(type_zoop_data),DIMENSION(:),INTENT(in) :: zoops INTEGER :: group AED_REAL,INTENT(in) :: S ! !LOCALS AED_REAL :: fSal ! Returns the salinity function AED_REAL :: Smin,Smax,Sint ! !------------------------------------------------------------------------------- !BEGIN Smin = zoops(group)%Smin_zoo Smax = zoops(group)%Smax_zoo Sint = zoops(group)%Sint_zoo !Salinity factor represents natural mortality in response to salinity stress. ! f(S) = 1 at Smin<=S<=Smax, f(S) = Bep at S=0 & S=2*Smax. IF (S < Smin) THEN fSal = (Sint-1.0)/(Smin**2.0)*(S**2.0) - 2*(Sint-1.0)/Smin*S + Sint ELSEIF(S > Smax) THEN fSal = (Sint-1.0)/(Smax**2.0)*(S**2.0) - 2*(Sint-1.0)/Smax*S + Sint ELSE fSal = 1.0 ENDIF IF( fSal<zero_ ) fSal=zero_ END FUNCTION fSalinity_Limitation !+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ END MODULE aed_zoop_utils
gpl-2.0
scarrazza/apfel
src/FTDY/src/writecDY.f
2
1634
************************************************************************ * * writecDY.f: * * It writes to disk the the Drell-Yan hard cross section * ************************************************************************ subroutine writecDY(outputfile) * implicit none * include "../commons/mxdata.h" include "../commons/mxgridsizeDY.h" include "../commons/xgridDY.h" include "../commons/xxDY.h" include "../commons/cDY.h" include "../commons/kinematics.h" include "../commons/set.h" ** * Input Variables * character*50 outputfile ** * Internal Variables * integer ix,jx,ip,ipt integer ls * ls = index(outputfile,".hcx") + 4 open(unit=10,status="unknown",file=outputfile(1:ls)) * * Write name of the set * write(10,*) set * * Write grid * write(10,*) nxDY do ix=1,nxDY write(10,*) xxDY(ix) enddo * * Write Kernels * write(10,*) ndata do ip=1,ndata write(10,*) ip,obs(ip),x1dat(ip),x2dat(ip),q2dat(ip), 1 ixp1DY(ip),ixp2DY(ip) do ipt=0,1 do ix=ixp1DY(ip),nxDY write(10,*) ipt,(cDY_NS(ipt,jx,ix,ip),jx=ixp2DY(ip),nxDY) enddo enddo * * No need to write the LO for QG and GQ because it's identically zero * do ix=ixp1DY(ip),nxDY write(10,*) ipt,(cDY_QG(1,jx,ix,ip),jx=ixp2DY(ip),nxDY) enddo do ix=ixp1DY(ip),nxDY write(10,*) ipt,(cDY_GQ(1,jx,ix,ip),jx=ixp2DY(ip),nxDY) enddo enddo * close(10) * return end
gpl-3.0
CapeDrew/DITK
Modules/ThirdParty/VNL/src/vxl/v3p/netlib/laso/dnlaso.f
24
27019
C VERSION 2 DOES NOT USE EISPACK C C ------------------------------------------------------------------ C SUBROUTINE DNLASO(OP, IOVECT, N, NVAL, NFIG, NPERM, * NMVAL, VAL, NMVEC, VEC, NBLOCK, MAXOP, MAXJ, WORK, * IND, IERR) C INTEGER N, NVAL, NFIG, NPERM, NMVAL, NMVEC, NBLOCK, * MAXOP, MAXJ, IND(1), IERR DOUBLE PRECISION VEC(NMVEC,1), VAL(NMVAL,4), WORK(1) EXTERNAL OP, IOVECT C C AUTHOR/IMPLEMENTER D.S.SCOTT-B.N.PARLETT/D.S.SCOTT C C COMPUTER SCIENCES DEPARTMENT C UNIVERSITY OF TEXAS AT AUSTIN C AUSTIN, TX 78712 C C VERSION 2 ORIGINATED APRIL 1982 C C CURRENT VERSION JUNE 1983 C C DNLASO FINDS A FEW EIGENVALUES AND EIGENVECTORS AT EITHER END OF C THE SPECTRUM OF A LARGE SPARSE SYMMETRIC MATRIX. THE SUBROUTINE C DNLASO IS PRIMARILY A DRIVER FOR SUBROUTINE DNWLA WHICH IMPLEMENTS C THE LANCZOS ALGORITHM WITH SELECTIVE ORTHOGONALIZATION AND C SUBROUTINE DNPPLA WHICH POST PROCESSES THE OUTPUT OF DNWLA. C HOWEVER DNLASO DOES CHECK FOR INCONSISTENCIES IN THE CALLING C PARAMETERS AND DOES PREPROCESS ANY USER SUPPLIED EIGENPAIRS. C DNLASO ALWAYS LOOKS FOR THE SMALLEST (LEFTMOST) EIGENVALUES. IF C THE LARGEST EIGENVALUES ARE DESIRED DNLASO IMPLICITLY USES THE C NEGATIVE OF THE MATRIX. C C C ON INPUT C C C OP A USER SUPPLIED SUBROUTINE WITH CALLING SEQUENCE C OP(N,M,P,Q). P AND Q ARE N X M MATRICES AND Q IS C RETURNED AS THE MATRIX TIMES P. C C IOVECT A USER SUPPLIED SUBROUTINE WITH CALLING SEQUENCE C IOVECT(N,M,Q,J,K). Q IS AN N X M MATRIX. IF K = 0 C THE COLUMNS OF Q ARE STORED AS THE (J-M+1)TH THROUGH C THE JTH LANCZOS VECTORS. IF K = 1 THEN Q IS RETURNED C AS THE (J-M+1)TH THROUGH THE JTH LANCZOS VECTORS. SEE C DOCUMENTATION FOR FURTHER DETAILS AND EXAMPLES. C C N THE ORDER OF THE MATRIX. C C NVAL NVAL SPECIFIES THE EIGENVALUES TO BE FOUND. C DABS(NVAL) IS THE NUMBER OF EIGENVALUES DESIRED. C IF NVAL < 0 THE ALGEBRAICALLY SMALLEST (LEFTMOST) C EIGENVALUES ARE FOUND. IF NVAL > 0 THE ALGEBRAICALLY C LARGEST (RIGHTMOST) EIGENVALUES ARE FOUND. NVAL MUST NOT C BE ZERO. DABS(NVAL) MUST BE LESS THAN MAXJ/2. C C NFIG THE NUMBER OF DECIMAL DIGITS OF ACCURACY DESIRED IN THE C EIGENVALUES. NFIG MUST BE GREATER THAN OR EQUAL TO 1. C C NPERM AN INTEGER VARIABLE WHICH SPECIFIES THE NUMBER OF USER C SUPPLIED EIGENPAIRS. IN MOST CASES NPERM WILL BE ZERO. SEE C DOCUMENTAION FOR FURTHER DETAILS OF USING NPERM GREATER C THAN ZERO. NPERM MUST NOT BE LESS THAN ZERO. C C NMVAL THE ROW DIMENSION OF THE ARRAY VAL. NMVAL MUST BE GREATER C THAN OR EQUAL TO DABS(NVAL). C C VAL A TWO DIMENSIONAL DOUBLE PRECISION ARRAY OF ROW C DIMENSION NMVAL AND COLUMN DIMENSION AT LEAST 4. IF NPERM C IS GREATER THAN ZERO THEN CERTAIN INFORMATION MUST BE STORED C IN VAL. SEE DOCUMENTATION FOR DETAILS. C C NMVEC THE ROW DIMENSION OF THE ARRAY VEC. NMVEC MUST BE GREATER C THAN OR EQUAL TO N. C C VEC A TWO DIMENSIONAL DOUBLE PRECISION ARRAY OF ROW C DIMENSION NMVEC AND COLUMN DIMENSION AT LEAST DABS(NVAL). IF C NPERM > 0 THEN THE FIRST NPERM COLUMNS OF VEC MUST C CONTAIN THE USER SUPPLIED EIGENVECTORS. C C NBLOCK THE BLOCK SIZE. SEE DOCUMENTATION FOR CHOOSING C AN APPROPRIATE VALUE FOR NBLOCK. NBLOCK MUST BE GREATER C THAN ZERO AND LESS THAN MAXJ/6. C C MAXOP AN UPPER BOUND ON THE NUMBER OF CALLS TO THE SUBROUTINE C OP. DNLASO TERMINATES WHEN MAXOP IS EXCEEDED. SEE C DOCUMENTATION FOR GUIDELINES IN CHOOSING A VALUE FOR MAXOP. C C MAXJ AN INDICATION OF THE AVAILABLE STORAGE (SEE WORK AND C DOCUMENTATION ON IOVECT). FOR THE FASTEST CONVERGENCE MAXJ C SHOULD BE AS LARGE AS POSSIBLE, ALTHOUGH IT IS USELESS TO HAVE C MAXJ LARGER THAN MAXOP*NBLOCK. C C WORK A DOUBLE PRECISION ARRAY OF DIMENSION AT LEAST AS C LARGE AS C C 2*N*NBLOCK + MAXJ*(NBLOCK+NV+2) + 2*NBLOCK*NBLOCK + 3*NV C C + THE MAXIMUM OF C N*NBLOCK C AND C MAXJ*(2*NBLOCK+3) + 2*NV + 6 + (2*NBLOCK+2)*(NBLOCK+1) C C WHERE NV = DABS(NVAL) C C THE FIRST N*NBLOCK ELEMENTS OF WORK MUST CONTAIN THE DESIRED C STARTING VECTORS. SEE DOCUMENTATION FOR GUIDELINES IN C CHOOSING STARTING VECTORS. C C IND AN INTEGER ARRAY OF DIMENSION AT LEAST DABS(NVAL). C C IERR AN INTEGER VARIABLE. C C C ON OUTPUT C C C NPERM THE NUMBER OF EIGENPAIRS NOW KNOWN. C C VEC THE FIRST NPERM COLUMNS OF VEC CONTAIN THE EIGENVECTORS. C C VAL THE FIRST COLUMN OF VAL CONTAINS THE CORRESPONDING C EIGENVALUES. THE SECOND COLUMN CONTAINS THE RESIDUAL NORMS OF C THE EIGENPAIRS WHICH ARE BOUNDS ON THE ACCURACY OF THE EIGEN- C VALUES. THE THIRD COLUMN CONTAINS MORE DOUBLE PRECISIONISTIC ESTIMATES C OF THE ACCURACY OF THE EIGENVALUES. THE FOURTH COLUMN CONTAINS C ESTIMATES OF THE ACCURACY OF THE EIGENVECTORS. SEE C DOCUMENTATION FOR FURTHER INFORMATION ON THESE QUANTITIES. C C WORK IF WORK IS TERMINATED BEFORE COMPLETION (IERR = -2) C THE FIRST N*NBLOCK ELEMENTS OF WORK CONTAIN THE BEST VECTORS C FOR RESTARTING THE ALGORITHM AND DNLASO CAN BE IMMEDIATELY C RECALLED TO CONTINUE WORKING ON THE PROBLEM. C C IND IND(1) CONTAINS THE ACTUAL NUMBER OF CALLS TO OP. ON SOME C OCCASIONS THE NUMBER OF CALLS TO OP MAY BE SLIGHTLY LARGER C THAN MAXOP. C C IERR AN ERROR COMPLETION CODE. THE NORMAL COMPLETION CODE IS C ZERO. SEE THE DOCUMENTATION FOR INTERPRETATIONS OF NON-ZERO C COMPLETION CODES. C C C INTERNAL VARIABLES. C C INTEGER I, I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, I11, * I12, I13, M, NBAND, NOP, NV, IABS, MAX0 LOGICAL RARITZ, SMALL DOUBLE PRECISION DELTA, EPS, TEMP, DNRM2, DABS, TARR(1) EXTERNAL DNPPLA, DNWLA, DORTQR, DCOPY, DNRM2, DVSORT C C NOP RETURNED FROM DNWLA AS THE NUMBER OF CALLS TO THE C SUBROUTINE OP. C C NV SET EQUAL TO DABS(NVAL), THE NUMBER OF EIGENVALUES DESIRED, C AND PASSED TO DNWLA. C C SMALL SET TO .TRUE. IF THE SMALLEST EIGENVALUES ARE DESIRED. C C RARITZ RETURNED FROM DNWLA AND PASSED TO DNPPLA. RARITZ IS .TRUE. C IF A FINAL RAYLEIGH-RITZ PROCEDURE IS NEEDED. C C DELTA RETURNED FROM DNWLA AS THE EIGENVALUE OF THE MATRIX C WHICH IS CLOSEST TO THE DESIRED EIGENVALUES. C C DNPPLA A SUBROUTINE FOR POST-PROCESSING THE EIGENVECTORS COMPUTED C BY DNWLA. C C DNWLA A SUBROUTINE FOR IMPLEMENTING THE LANCZOS ALGORITHM C WITH SELECTIVE ORTHOGONALIZATION. C C DMVPC A SUBROUTINE FOR COMPUTING THE RESIDUAL NORM AND C ORTHOGONALITY COEFFICIENT OF GIVEN RITZ VECTORS. C C DORTQR A SUBROUTINE FOR ORTHONORMALIZING A BLOCK OF VECTORS C USING HOUSEHOLDER REFLECTIONS. C C DAXPY,DCOPY,DDOT,DNRM2,DSCAL,DSWAP A SUBSET OF THE BASIC LINEAR C ALGEBRA SUBPROGRAMS USED FOR VECTOR MANIPULATION. C C DLARAN A SUBROUTINE TO GENERATE RANDOM VECTORS C C DLAEIG, DLAGER, DLABCM, DLABFC SUBROUTINES FOR BAND EIGENVALUE C CALCULATIONS. C C ------------------------------------------------------------------ C C THIS SECTION CHECKS FOR INCONSISTENCY IN THE INPUT PARAMETERS. C NV = IABS(NVAL) IND(1) = 0 IERR = 0 IF (N.LT.6*NBLOCK) IERR = 1 IF (NFIG.LE.0) IERR = IERR + 2 IF (NMVEC.LT.N) IERR = IERR + 4 IF (NPERM.LT.0) IERR = IERR + 8 IF (MAXJ.LT.6*NBLOCK) IERR = IERR + 16 IF (NV.LT.MAX0(1,NPERM)) IERR = IERR + 32 IF (NV.GT.NMVAL) IERR = IERR + 64 IF (NV.GT.MAXOP) IERR = IERR + 128 IF (NV.GE.MAXJ/2) IERR = IERR + 256 IF (NBLOCK.LT.1) IERR = IERR + 512 IF (IERR.NE.0) RETURN C SMALL = NVAL.LT.0 C C ------------------------------------------------------------------ C C THIS SECTION SORTS AND ORTHONORMALIZES THE USER SUPPLIED VECTORS. C IF A USER SUPPLIED VECTOR IS ZERO OR IF DSIGNIFICANT CANCELLATION C OCCURS IN THE ORTHOGONALIZATION PROCESS THEN IERR IS SET TO -1 C AND DNLASO TERMINATES. C IF (NPERM.EQ.0) GO TO 110 C C THIS NEGATES THE USER SUPPLIED EIGENVALUES WHEN THE LARGEST C EIGENVALUES ARE DESIRED, SINCE DNWLA WILL IMPLICITLY USE THE C NEGATIVE OF THE MATRIX. C IF (SMALL) GO TO 20 DO 10 I=1,NPERM VAL(I,1) = -VAL(I,1) 10 CONTINUE C C THIS SORTS THE USER SUPPLIED VALUES AND VECTORS. C 20 CALL DVSORT(NPERM, VAL, VAL(1,2), 0, TARR, NMVEC, N, VEC) C C THIS STORES THE NORMS OF THE VECTORS FOR LATER COMPARISON. C IT ALSO INSURES THAT THE RESIDUAL NORMS ARE POSITIVE. C DO 60 I=1,NPERM VAL(I,2) = DABS(VAL(I,2)) VAL(I,3) = DNRM2(N,VEC(1,I),1) 60 CONTINUE C C THIS PERFORMS THE ORTHONORMALIZATION. C M = N*NBLOCK + 1 CALL DORTQR(NMVEC, N, NPERM, VEC, WORK(M)) M = N*NBLOCK - NPERM DO 70 I = 1, NPERM M = M + NPERM + 1 IF(DABS(WORK(M)) .GT. 0.9*VAL(I,3)) GO TO 70 IERR = -1 RETURN C 70 CONTINUE C C THIS COPIES THE RESIDUAL NORMS INTO THE CORRECT LOCATIONS IN C THE ARRAY WORK FOR LATER REFERENCE IN DNWLA. C M = 2*N*NBLOCK + 1 CALL DCOPY(NPERM, VAL(1,2), 1, WORK(M), 1) C C THIS SETS EPS TO AN APPROXIMATION OF THE RELATIVE MACHINE C PRECISION C C ***THIS SHOULD BE REPLACED BY AN ASDSIGNMENT STATEMENT C ***IN A PRODUCTION CODE C 110 EPS = 1.0D0 DO 120 I = 1,1000 EPS = 0.5D0*EPS TEMP = 1.0D0 + EPS IF(TEMP.EQ.1.0D0) GO TO 130 120 CONTINUE C C ------------------------------------------------------------------ C C THIS SECTION CALLS DNWLA WHICH IMPLEMENTS THE LANCZOS ALGORITHM C WITH SELECTIVE ORTHOGONALIZATION. C 130 NBAND = NBLOCK + 1 I1 = 1 + N*NBLOCK I2 = I1 + N*NBLOCK I3 = I2 + NV I4 = I3 + NV I5 = I4 + NV I6 = I5 + MAXJ*NBAND I7 = I6 + NBLOCK*NBLOCK I8 = I7 + NBLOCK*NBLOCK I9 = I8 + MAXJ*(NV+1) I10 = I9 + NBLOCK I11 = I10 + 2*NV + 6 I12 = I11 + MAXJ*(2*NBLOCK+1) I13 = I12 + MAXJ CALL DNWLA(OP, IOVECT, N, NBAND, NV, NFIG, NPERM, VAL, NMVEC, * VEC, NBLOCK, MAXOP, MAXJ, NOP, WORK(1), WORK(I1), * WORK(I2), WORK(I3), WORK(I4), WORK(I5), WORK(I6), * WORK(I7), WORK(I8), WORK(I9), WORK(I10), WORK(I11), * WORK(I12), WORK(I13), IND, SMALL, RARITZ, DELTA, EPS, IERR) C C ------------------------------------------------------------------ C C THIS SECTION CALLS DNPPLA (THE POST PROCESSOR). C IF (NPERM.EQ.0) GO TO 140 I1 = N*NBLOCK + 1 I2 = I1 + NPERM*NPERM I3 = I2 + NPERM*NPERM I4 = I3 + MAX0(N*NBLOCK,2*NPERM*NPERM) I5 = I4 + N*NBLOCK I6 = I5 + 2*NPERM + 4 CALL DNPPLA(OP, IOVECT, N, NPERM, NOP, NMVAL, VAL, NMVEC, * VEC, NBLOCK, WORK(I1), WORK(I2), WORK(I3), WORK(I4), * WORK(I5), WORK(I6), DELTA, SMALL, RARITZ, EPS) C 140 IND(1) = NOP RETURN END C C ------------------------------------------------------------------ C SUBROUTINE DNWLA(OP, IOVECT, N, NBAND, NVAL, NFIG, NPERM, VAL, * NMVEC, VEC, NBLOCK, MAXOP, MAXJ, NOP, P1, P0, * RES, TAU, OTAU, T, ALP, BET, S, P2, BOUND, ATEMP, VTEMP, D, * IND, SMALL, RARITZ, DELTA, EPS, IERR) C INTEGER N, NBAND, NVAL, NFIG, NPERM, NMVEC, NBLOCK, MAXOP, MAXJ, * NOP, IND(1), IERR LOGICAL RARITZ, SMALL DOUBLE PRECISION VAL(1), VEC(NMVEC,1), P0(N,1), P1(N,1), * P2(N,1), RES(1), TAU(1), OTAU(1), T(NBAND,1), * ALP(NBLOCK,1), BET(NBLOCK,1), BOUND(1), ATEMP(1), * VTEMP(1), D(1), S(MAXJ,1), DELTA, EPS EXTERNAL OP, IOVECT C C DNWLA IMPLEMENTS THE LANCZOS ALGORITHM WITH SELECTIVE C ORTHOGONALIZATION. C C NBAND NBLOCK + 1 THE BAND WIDTH OF T. C C NVAL THE NUMBER OF DESIRED EIGENVALUES. C C NPERM THE NUMBER OF PERMANENT VECTORS (THOSE EIGENVECTORS C INPUT BY THE USER OR THOSE EIGENVECTORS SAVED WHEN THE C ALGORITHM IS ITERATED). PERMANENT VECTORS ARE ORTHOGONAL C TO THE CURRENT KRYLOV SUBSPACE. C C NOP THE NUMBER OF CALLS TO OP. C C P0, P1, AND P2 THE CURRENT BLOCKS OF LANCZOS VECTORS. C C RES THE (APPROXIMATE) RESIDUAL NORMS OF THE PERMANENT VECTORS. C C TAU AND OTAU USED TO MONITOR THE NEED FOR ORTHOGONALIZATION. C C T THE BAND MATRIX. C C ALP THE CURRENT DIAGONAL BLOCK. C C BET THE CURRENT OFF DIAGONAL BLOCK. C C BOUND, ATEMP, VTEMP, D TEMPORARY STORAGE USED BY THE BAND C EIGENVALUE SOLVER DLAEIG. C C S EIGENVECTORS OF T. C C SMALL .TRUE. IF THE SMALL EIGENVALUES ARE DESIRED. C C RARITZ RETURNED AS .TRUE. IF A FINAL RAYLEIGH-RITZ PROCEDURE C IS TO BE DONE. C C DELTA RETURNED AS THE VALUE OF THE (NVAL+1)TH EIGENVALUE C OF THE MATRIX. USED IN ESTIMATING THE ACCURACY OF THE C COMPUTED EIGENVALUES. C C C INTERNAL VARIABLES USED C INTEGER I, I1, II, J, K, L, M, NG, NGOOD, * NLEFT, NSTART, NTHETA, NUMBER, MIN0, MTEMP LOGICAL ENOUGH, TEST DOUBLE PRECISION ALPMAX, ALPMIN, ANORM, BETMAX, BETMIN, * EPSRT, PNORM, RNORM, TEMP, * TMAX, TMIN, TOLA, TOLG, UTOL, DABS, * DMAX1, DMIN1, DSQRT, DDOT, DNRM2, TARR(1), DZERO(1) EXTERNAL DMVPC, DORTQR, DAXPY, DCOPY, DDOT, * DNRM2, DSCAL, DLAEIG, DLAGER, DLARAN, DVSORT C C J THE CURRENT DIMENSION OF T. (THE DIMENSION OF THE CURRENT C KRYLOV SUBSPACE. C C NGOOD THE NUMBER OF GOOD RITZ VECTORS (GOOD VECTORS C LIE IN THE CURRENT KRYLOV SUBSPACE). C C NLEFT THE NUMBER OF VALUES WHICH REMAIN TO BE DETERMINED, C I.E. NLEFT = NVAL - NPERM. C C NUMBER = NPERM + NGOOD. C C ANORM AN ESTIMATE OF THE NORM OF THE MATRIX. C C EPS THE RELATIVE MACHINE PRECISION. C C UTOL THE USER TOLERANCE. C C TARR AN ARRAY OF LENGTH ONE USED TO INSURE TYPE CONSISTENCY IN CALLS TO C DLAEIG C C DZERO AN ARRAY OF LENGTH ONE CONTAINING DZERO, USED TO INSURE TYPE C CONSISTENCY IN CALLS TO DCOPY C DZERO(1) = 0.0D0 RNORM = 0.0D0 IF (NPERM.NE.0) RNORM = DMAX1(-VAL(1),VAL(NPERM)) PNORM = RNORM DELTA = 10.D30 EPSRT = DSQRT(EPS) NLEFT = NVAL - NPERM NOP = 0 NUMBER = NPERM RARITZ = .FALSE. UTOL = DMAX1(DBLE(FLOAT(N))*EPS,10.0D0**DBLE((-FLOAT(NFIG)))) J = MAXJ C C ------------------------------------------------------------------ C C ANY ITERATION OF THE ALGORITHM BEGINS HERE. C 30 DO 50 I=1,NBLOCK TEMP = DNRM2(N,P1(1,I),1) IF (TEMP.EQ.0D0) CALL DLARAN(N, P1(1,I)) 50 CONTINUE IF (NPERM.EQ.0) GO TO 70 DO 60 I=1,NPERM TAU(I) = 1.0D0 OTAU(I) = 0.0D0 60 CONTINUE 70 CALL DCOPY(N*NBLOCK, DZERO, 0, P0, 1) CALL DCOPY(NBLOCK*NBLOCK, DZERO, 0, BET, 1) CALL DCOPY(J*NBAND, DZERO, 0, T, 1) MTEMP = NVAL + 1 DO 75 I = 1, MTEMP CALL DCOPY(J, DZERO, 0, S(1,I), 1) 75 CONTINUE NGOOD = 0 TMIN = 1.0D30 TMAX = -1.0D30 TEST = .TRUE. ENOUGH = .FALSE. BETMAX = 0.0D0 J = 0 C C ------------------------------------------------------------------ C C THIS SECTION TAKES A SINGLE BLOCK LANCZOS STEP. C 80 J = J + NBLOCK C C THIS IS THE SELECTIVE ORTHOGONALIZATION. C IF (NUMBER.EQ.0) GO TO 110 DO 100 I=1,NUMBER IF (TAU(I).LT.EPSRT) GO TO 100 TEST = .TRUE. TAU(I) = 0.0D0 IF (OTAU(I).NE.0.0D0) OTAU(I) = 1.0D0 DO 90 K=1,NBLOCK TEMP = -DDOT(N,VEC(1,I),1,P1(1,K),1) CALL DAXPY(N, TEMP, VEC(1,I), 1, P1(1,K), 1) C C THIS CHECKS FOR TOO GREAT A LOSS OF ORTHOGONALITY BETWEEN A C NEW LANCZOS VECTOR AND A GOOD RITZ VECTOR. THE ALGORITHM IS C TERMINATED IF TOO MUCH ORTHOGONALITY IS LOST. C IF (DABS(TEMP*BET(K,K)).GT.DBLE(FLOAT(N))*EPSRT* * ANORM .AND. I.GT.NPERM) GO TO 380 90 CONTINUE 100 CONTINUE C C IF NECESSARY, THIS REORTHONORMALIZES P1 AND UPDATES BET. C 110 IF(.NOT. TEST) GO TO 160 CALL DORTQR(N, N, NBLOCK, P1, ALP) TEST = .FALSE. IF(J .EQ. NBLOCK) GO TO 160 DO 130 I = 1,NBLOCK IF(ALP(I,I) .GT. 0.0D0) GO TO 130 M = J - 2*NBLOCK + I L = NBLOCK + 1 DO 120 K = I,NBLOCK BET(I,K) = -BET(I,K) T(L,M) = -T(L,M) L = L - 1 M = M + 1 120 CONTINUE 130 CONTINUE C C THIS IS THE LANCZOS STEP. C 160 CALL OP(N, NBLOCK, P1, P2) NOP = NOP + 1 CALL IOVECT(N, NBLOCK, P1, J, 0) C C THIS COMPUTES P2=P2-P0*BET(TRANSPOSE) C DO 180 I=1,NBLOCK DO 170 K=I,NBLOCK CALL DAXPY(N, -BET(I,K), P0(1,K), 1, P2(1,I), 1) 170 CONTINUE 180 CONTINUE C C THIS COMPUTES ALP AND P2=P2-P1*ALP. C DO 200 I=1,NBLOCK DO 190 K=1,I II = I - K + 1 ALP(II,K) = DDOT(N,P1(1,I),1,P2(1,K),1) CALL DAXPY(N, -ALP(II,K), P1(1,I), 1, P2(1,K), 1) IF (K.NE.I) CALL DAXPY(N, -ALP(II,K), P1(1,K), * 1, P2(1,I), 1) 190 CONTINUE 200 CONTINUE C C REORTHOGONALIZATION OF THE SECOND BLOCK C IF(J .NE. NBLOCK) GO TO 220 DO 215 I=1,NBLOCK DO 210 K=1,I TEMP = DDOT(N,P1(1,I),1,P2(1,K),1) CALL DAXPY(N, -TEMP, P1(1,I), 1, P2(1,K), 1) IF (K.NE.I) CALL DAXPY(N, -TEMP, P1(1,K), * 1, P2(1,I), 1) II = I - K + 1 ALP(II,K) = ALP(II,K) + TEMP 210 CONTINUE 215 CONTINUE C C THIS ORTHONORMALIZES THE NEXT BLOCK C 220 CALL DORTQR(N, N, NBLOCK, P2, BET) C C THIS STORES ALP AND BET IN T. C DO 250 I=1,NBLOCK M = J - NBLOCK + I DO 230 K=I,NBLOCK L = K - I + 1 T(L,M) = ALP(L,I) 230 CONTINUE DO 240 K=1,I L = NBLOCK - I + K + 1 T(L,M) = BET(K,I) 240 CONTINUE 250 CONTINUE C C THIS NEGATES T IF SMALL IS FALSE. C IF (SMALL) GO TO 280 M = J - NBLOCK + 1 DO 270 I=M,J DO 260 K=1,L T(K,I) = -T(K,I) 260 CONTINUE 270 CONTINUE C C THIS SHIFTS THE LANCZOS VECTORS C 280 CALL DCOPY(NBLOCK*N, P1, 1, P0, 1) CALL DCOPY(NBLOCK*N, P2, 1, P1, 1) CALL DLAGER(J, NBAND, J-NBLOCK+1, T, TMIN, TMAX) ANORM = DMAX1(RNORM, TMAX, -TMIN) IF (NUMBER.EQ.0) GO TO 305 C C THIS COMPUTES THE EXTREME EIGENVALUES OF ALP. C CALL DCOPY(NBLOCK, DZERO, 0, P2, 1) CALL DLAEIG(NBLOCK, NBLOCK, 1, 1, ALP, TARR, NBLOCK, 1 P2, BOUND, ATEMP, D, VTEMP, EPS, TMIN, TMAX) ALPMIN = TARR(1) CALL DCOPY(NBLOCK, DZERO, 0, P2, 1) CALL DLAEIG(NBLOCK, NBLOCK, NBLOCK, NBLOCK, ALP, TARR, 1 NBLOCK, P2, BOUND, ATEMP, D, VTEMP, EPS, TMIN, TMAX) ALPMAX = TARR(1) C C THIS COMPUTES ALP = BET(TRANSPOSE)*BET. C 305 DO 310 I = 1, NBLOCK DO 300 K = 1, I L = I - K + 1 ALP(L,K) = DDOT(NBLOCK-I+1, BET(I,I), NBLOCK, BET(K,I), 1 NBLOCK) 300 CONTINUE 310 CONTINUE IF(NUMBER .EQ. 0) GO TO 330 C C THIS COMPUTES THE SMALLEST SINGULAR VALUE OF BET. C CALL DCOPY(NBLOCK, DZERO, 0, P2, 1) CALL DLAEIG(NBLOCK, NBLOCK, 1, 1, ALP, TARR, NBLOCK, 1 P2, BOUND, ATEMP, D, VTEMP, EPS, 0.0D0, ANORM*ANORM) BETMIN = DSQRT(TARR(1)) C C THIS UPDATES TAU AND OTAU. C DO 320 I=1,NUMBER TEMP = (TAU(I)*DMAX1(ALPMAX-VAL(I),VAL(I)-ALPMIN) * +OTAU(I)*BETMAX+EPS*ANORM)/BETMIN IF (I.LE.NPERM) TEMP = TEMP + RES(I)/BETMIN OTAU(I) = TAU(I) TAU(I) = TEMP 320 CONTINUE C C THIS COMPUTES THE LARGEST SINGULAR VALUE OF BET. C 330 CALL DCOPY(NBLOCK, DZERO, 0, P2, 1) CALL DLAEIG(NBLOCK, NBLOCK, NBLOCK, NBLOCK, ALP, TARR, 1 NBLOCK, P2, BOUND, ATEMP, D, VTEMP, EPS, 0.0D0, 2 ANORM*ANORM) BETMAX = DSQRT(TARR(1)) IF (J.LE.2*NBLOCK) GO TO 80 C C ------------------------------------------------------------------ C C THIS SECTION COMPUTES AND EXAMINES THE SMALLEST NONGOOD AND C LARGEST DESIRED EIGENVALUES OF T TO SEE IF A CLOSER LOOK C IS JUSTIFIED. C TOLG = EPSRT*ANORM TOLA = UTOL*RNORM IF(MAXJ-J .LT. NBLOCK .OR. (NOP .GE. MAXOP .AND. 1 NLEFT .NE. 0)) GO TO 390 GO TO 400 C C ------------------------------------------------------------------ C C THIS SECTION COMPUTES SOME EIGENVALUES AND EIGENVECTORS OF T TO C SEE IF FURTHER ACTION IS INDICATED, ENTRY IS AT 380 OR 390 IF AN C ITERATION (OR TERMINATION) IS KNOWN TO BE NEEDED, OTHERWISE ENTRY C IS AT 400. C 380 J = J - NBLOCK IERR = -8 390 IF (NLEFT.EQ.0) RETURN TEST = .TRUE. 400 NTHETA = MIN0(J/2,NLEFT+1) CALL DLAEIG(J, NBAND, 1, NTHETA, T, VAL(NUMBER+1), 1 MAXJ, S, BOUND, ATEMP, D, VTEMP, EPS, TMIN, TMAX) CALL DMVPC(NBLOCK, BET, MAXJ, J, S, NTHETA, ATEMP, VTEMP, D) C C THIS CHECKS FOR TERMINATION OF A CHECK RUN C IF(NLEFT .NE. 0 .OR. J .LT. 6*NBLOCK) GO TO 410 IF(VAL(NUMBER+1)-ATEMP(1) .GT. VAL(NPERM) - TOLA) GO TO 790 C C THIS UPDATES NLEFT BY EXAMINING THE COMPUTED EIGENVALUES OF T C TO DETERMINE IF SOME PERMANENT VALUES ARE NO LONGER DESIRED. C 410 IF (NTHETA.LE.NLEFT) GO TO 470 IF (NPERM.EQ.0) GO TO 430 M = NUMBER + NLEFT + 1 IF (VAL(M).GE.VAL(NPERM)) GO TO 430 NPERM = NPERM - 1 NGOOD = 0 NUMBER = NPERM NLEFT = NLEFT + 1 GO TO 400 C C THIS UPDATES DELTA. C 430 M = NUMBER + NLEFT + 1 DELTA = DMIN1(DELTA,VAL(M)) ENOUGH = .TRUE. IF(NLEFT .EQ. 0) GO TO 80 NTHETA = NLEFT VTEMP(NTHETA+1) = 1 C C ------------------------------------------------------------------ C C THIS SECTION EXAMINES THE COMPUTED EIGENPAIRS IN DETAIL. C C THIS CHECKS FOR ENOUGH ACCEPTABLE VALUES. C IF (.NOT.(TEST .OR. ENOUGH)) GO TO 470 DELTA = DMIN1(DELTA,ANORM) PNORM = DMAX1(RNORM,DMAX1(-VAL(NUMBER+1),DELTA)) TOLA = UTOL*PNORM NSTART = 0 DO 460 I=1,NTHETA M = NUMBER + I IF (DMIN1(ATEMP(I)*ATEMP(I)/(DELTA-VAL(M)),ATEMP(I)) * .GT.TOLA) GO TO 450 IND(I) = -1 GO TO 460 C 450 ENOUGH = .FALSE. IF (.NOT.TEST) GO TO 470 IND(I) = 1 NSTART = NSTART + 1 460 CONTINUE C C COPY VALUES OF IND INTO VTEMP C DO 465 I = 1,NTHETA VTEMP(I) = DBLE(FLOAT(IND(I))) 465 CONTINUE GO TO 500 C C THIS CHECKS FOR NEW GOOD VECTORS. C 470 NG = 0 DO 490 I=1,NTHETA IF (VTEMP(I).GT.TOLG) GO TO 480 NG = NG + 1 VTEMP(I) = -1 GO TO 490 C 480 VTEMP(I) = 1 490 CONTINUE C IF (NG.LE.NGOOD) GO TO 80 NSTART = NTHETA - NG C C ------------------------------------------------------------------ C C THIS SECTION COMPUTES AND NORMALIZES THE INDICATED RITZ VECTORS. C IF NEEDED (TEST = .TRUE.), NEW STARTING VECTORS ARE COMPUTED. C 500 TEST = TEST .AND. .NOT.ENOUGH NGOOD = NTHETA - NSTART NSTART = NSTART + 1 NTHETA = NTHETA + 1 C C THIS ALIGNS THE DESIRED (ACCEPTABLE OR GOOD) EIGENVALUES AND C EIGENVECTORS OF T. THE OTHER EIGENVECTORS ARE SAVED FOR C FORMING STARTING VECTORS, IF NECESSARY. IT ALSO SHIFTS THE C EIGENVALUES TO OVERWRITE THE GOOD VALUES FROM THE PREVIOUS C PAUSE. C CALL DCOPY(NTHETA, VAL(NUMBER+1), 1, VAL(NPERM+1), 1) IF (NSTART.EQ.0) GO TO 580 IF (NSTART.EQ.NTHETA) GO TO 530 CALL DVSORT(NTHETA, VTEMP, ATEMP, 1, VAL(NPERM+1), MAXJ, * J, S) C C THES ACCUMULATES THE J-VECTORS USED TO FORM THE STARTING C VECTORS. C 530 IF (.NOT.TEST) NSTART = 0 IF (.NOT.TEST) GO TO 580 C C FIND MINIMUM ATEMP VALUE TO AVOID POSSIBLE OVERFLOW C TEMP = ATEMP(1) DO 535 I = 1, NSTART TEMP = DMIN1(TEMP, ATEMP(I)) 535 CONTINUE M = NGOOD + 1 L = NGOOD + MIN0(NSTART,NBLOCK) DO 540 I=M,L CALL DSCAL(J, TEMP/ATEMP(I), S(1,I), 1) 540 CONTINUE M = (NSTART-1)/NBLOCK IF (M.EQ.0) GO TO 570 L = NGOOD + NBLOCK DO 560 I=1,M DO 550 K=1,NBLOCK L = L + 1 IF (L.GT.NTHETA) GO TO 570 I1 = NGOOD + K CALL DAXPY(J, TEMP/ATEMP(L), S(1,L), 1, S(1,I1), 1) 550 CONTINUE 560 CONTINUE 570 NSTART = MIN0(NSTART,NBLOCK) C C THIS STORES THE RESIDUAL NORMS OF THE NEW PERMANENT VECTORS. C 580 IF (NGOOD.EQ.0 .OR. .NOT.(TEST .OR. ENOUGH)) GO TO 600 DO 590 I=1,NGOOD M = NPERM + I RES(M) = ATEMP(I) 590 CONTINUE C C THIS COMPUTES THE RITZ VECTORS BY SEQUENTIALLY RECALLING THE C LANCZOS VECTORS. C 600 NUMBER = NPERM + NGOOD IF (TEST .OR. ENOUGH) CALL DCOPY(N*NBLOCK, DZERO, 0, P1, 1) IF (NGOOD.EQ.0) GO TO 620 M = NPERM + 1 DO 610 I=M,NUMBER CALL DCOPY(N, DZERO, 0, VEC(1,I), 1) 610 CONTINUE 620 DO 670 I=NBLOCK,J,NBLOCK CALL IOVECT(N, NBLOCK, P2, I, 1) DO 660 K=1,NBLOCK M = I - NBLOCK + K IF (NSTART.EQ.0) GO TO 640 DO 630 L=1,NSTART I1 = NGOOD + L CALL DAXPY(N, S(M,I1), P2(1,K), 1, P1(1,L), 1) 630 CONTINUE 640 IF (NGOOD.EQ.0) GO TO 660 DO 650 L=1,NGOOD I1 = L + NPERM CALL DAXPY(N, S(M,L), P2(1,K), 1, VEC(1,I1), 1) 650 CONTINUE 660 CONTINUE 670 CONTINUE IF (TEST .OR. ENOUGH) GO TO 690 C C THIS NORMALIZES THE RITZ VECTORS AND INITIALIZES THE C TAU RECURRENCE. C M = NPERM + 1 DO 680 I=M,NUMBER TEMP = 1.0D0/DNRM2(N,VEC(1,I),1) CALL DSCAL(N, TEMP, VEC(1,I), 1) TAU(I) = 1.0D0 OTAU(I) = 1.0D0 680 CONTINUE C C SHIFT S VECTORS TO ALIGN FOR LATER CALL TO DLAEIG C CALL DCOPY(NTHETA, VAL(NPERM+1), 1, VTEMP, 1) CALL DVSORT(NTHETA, VTEMP, ATEMP, 0, TARR, MAXJ, J, S) GO TO 80 C C ------------------------------------------------------------------ C C THIS SECTION PREPARES TO ITERATE THE ALGORITHM BY SORTING THE C PERMANENT VALUES, RESETTING SOME PARAMETERS, AND ORTHONORMALIZING C THE PERMANENT VECTORS. C 690 IF (NGOOD.EQ.0 .AND. NOP.GE.MAXOP) GO TO 810 IF (NGOOD.EQ.0) GO TO 30 C C THIS ORTHONORMALIZES THE VECTORS C CALL DORTQR(NMVEC, N, NPERM+NGOOD, VEC, S) C C THIS SORTS THE VALUES AND VECTORS. C IF(NPERM .NE. 0) CALL DVSORT(NPERM+NGOOD, VAL, RES, 0, TEMP, * NMVEC, N, VEC) NPERM = NPERM + NGOOD NLEFT = NLEFT - NGOOD RNORM = DMAX1(-VAL(1),VAL(NPERM)) C C THIS DECIDES WHERE TO GO NEXT. C IF (NOP.GE.MAXOP .AND. NLEFT.NE.0) GO TO 810 IF (NLEFT.NE.0) GO TO 30 IF (VAL(NVAL)-VAL(1).LT.TOLA) GO TO 790 C C THIS DOES A CLUSTER TEST TO SEE IF A CHECK RUN IS NEEDED C TO LOOK FOR UNDISCLOSED MULTIPLICITIES. C M = NPERM - NBLOCK + 1 IF (M.LE.0) RETURN DO 780 I=1,M L = I + NBLOCK - 1 IF (VAL(L)-VAL(I).LT.TOLA) GO TO 30 780 CONTINUE C C THIS DOES A CLUSTER TEST TO SEE IF A FINAL RAYLEIGH-RITZ C PROCEDURE IS NEEDED. C 790 M = NPERM - NBLOCK IF (M.LE.0) RETURN DO 800 I=1,M L = I + NBLOCK IF (VAL(L)-VAL(I).GE.TOLA) GO TO 800 RARITZ = .TRUE. RETURN 800 CONTINUE C RETURN C C ------------------------------------------------------------------ C C THIS REPORTS THAT MAXOP WAS EXCEEDED. C 810 IERR = -2 GO TO 790 C END
apache-2.0
mingwpy/scipy
scipy/sparse/linalg/eigen/arpack/ARPACK/SRC/dnconv.f
141
4085
c----------------------------------------------------------------------- c\BeginDoc c c\Name: dnconv c c\Description: c Convergence testing for the nonsymmetric Arnoldi eigenvalue routine. c c\Usage: c call dnconv c ( N, RITZR, RITZI, BOUNDS, TOL, NCONV ) c c\Arguments c N Integer. (INPUT) c Number of Ritz values to check for convergence. c c RITZR, Double precision arrays of length N. (INPUT) c RITZI Real and imaginary parts of the Ritz values to be checked c for convergence. c BOUNDS Double precision array of length N. (INPUT) c Ritz estimates for the Ritz values in RITZR and RITZI. c c TOL Double precision scalar. (INPUT) c Desired backward error for a Ritz value to be considered c "converged". c c NCONV Integer scalar. (OUTPUT) c Number of "converged" Ritz values. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\Routines called: c arscnd ARPACK utility routine for timing. c dlamch LAPACK routine that determines machine constants. c dlapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/92: Version ' 2.1' c c\SCCS Information: @(#) c FILE: nconv.F SID: 2.3 DATE OF SID: 4/20/96 RELEASE: 2 c c\Remarks c 1. xxxx c c\EndLib c c----------------------------------------------------------------------- c subroutine dnconv (n, ritzr, ritzi, bounds, tol, nconv) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c integer n, nconv Double precision & tol c c %-----------------% c | Array Arguments | c %-----------------% Double precision & ritzr(n), ritzi(n), bounds(n) c c %---------------% c | Local Scalars | c %---------------% c integer i Double precision & temp, eps23 c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlapy2, dlamch external dlapy2, dlamch c %-----------------------% c | Executable Statements | c %-----------------------% c c %-------------------------------------------------------------% c | Convergence test: unlike in the symmetric code, I am not | c | using things like refined error bounds and gap condition | c | because I don't know the exact equivalent concept. | c | | c | Instead the i-th Ritz value is considered "converged" when: | c | | c | bounds(i) .le. ( TOL * | ritz | ) | c | | c | for some appropriate choice of norm. | c %-------------------------------------------------------------% c call arscnd (t0) c c %---------------------------------% c | Get machine dependent constant. | c %---------------------------------% c eps23 = dlamch('Epsilon-Machine') eps23 = eps23**(2.0D+0 / 3.0D+0) c nconv = 0 do 20 i = 1, n temp = max( eps23, dlapy2( ritzr(i), ritzi(i) ) ) if (bounds(i) .le. tol*temp) nconv = nconv + 1 20 continue c call arscnd (t1) tnconv = tnconv + (t1 - t0) c return c c %---------------% c | End of dnconv | c %---------------% c end
bsd-3-clause
rgwan/gcc
gcc/testsuite/gfortran.dg/alloc_comp_basics_1.f90
46
3630
! { dg-do run } ! { dg-options "-fdump-tree-original" } ! ! Check some basic functionality of allocatable components, including that they ! are nullified when created and automatically deallocated when ! 1. A variable goes out of scope ! 2. INTENT(OUT) dummies ! 3. Function results ! ! ! Contributed by Erik Edelmann <eedelmann@gcc.gnu.org> ! and Paul Thomas <pault@gcc.gnu.org> ! module alloc_m implicit none type :: alloc1 real, allocatable :: x(:) end type alloc1 end module alloc_m program alloc use alloc_m implicit none type :: alloc2 type(alloc1), allocatable :: a1(:) integer, allocatable :: a2(:) end type alloc2 integer :: i BLOCK ! To ensure that the allocatables are freed at the end of the scope type(alloc2) :: b type(alloc2), allocatable :: c(:) if (allocated(b%a2) .OR. allocated(b%a1)) then write (0, *) 'main - 1' call abort() end if ! 3 calls to _gfortran_deallocate (INTENT(OUT) dummy) call allocate_alloc2(b) call check_alloc2(b) do i = 1, size(b%a1) ! 1 call to _gfortran_deallocate deallocate(b%a1(i)%x) end do ! 3 calls to _gfortran_deallocate (INTENT(OUT) dummy) call allocate_alloc2(b) call check_alloc2(return_alloc2()) ! 3 calls to _gfortran_deallocate (function result) allocate(c(1)) ! 3 calls to _gfortran_deallocate (INTENT(OUT) dummy) call allocate_alloc2(c(1)) ! 4 calls to _gfortran_deallocate deallocate(c) ! 7 calls to _gfortran_deallocate (b (3) and c(4) goes aout of scope) END BLOCK contains subroutine allocate_alloc2(b) type(alloc2), intent(out) :: b integer :: i if (allocated(b%a2) .OR. allocated(b%a1)) then write (0, *) 'allocate_alloc2 - 1' call abort() end if allocate (b%a2(3)) b%a2 = [ 1, 2, 3 ] allocate (b%a1(3)) do i = 1, 3 if (allocated(b%a1(i)%x)) then write (0, *) 'allocate_alloc2 - 2', i call abort() end if allocate (b%a1(i)%x(3)) b%a1(i)%x = i + [ 1.0, 2.0, 3.0 ] end do end subroutine allocate_alloc2 type(alloc2) function return_alloc2() result(b) if (allocated(b%a2) .OR. allocated(b%a1)) then write (0, *) 'return_alloc2 - 1' call abort() end if allocate (b%a2(3)) b%a2 = [ 1, 2, 3 ] allocate (b%a1(3)) do i = 1, 3 if (allocated(b%a1(i)%x)) then write (0, *) 'return_alloc2 - 2', i call abort() end if allocate (b%a1(i)%x(3)) b%a1(i)%x = i + [ 1.0, 2.0, 3.0 ] end do end function return_alloc2 subroutine check_alloc2(b) type(alloc2), intent(in) :: b if (.NOT.(allocated(b%a2) .AND. allocated(b%a1))) then write (0, *) 'check_alloc2 - 1' call abort() end if if (any(b%a2 /= [ 1, 2, 3 ])) then write (0, *) 'check_alloc2 - 2' call abort() end if do i = 1, 3 if (.NOT.allocated(b%a1(i)%x)) then write (0, *) 'check_alloc2 - 3', i call abort() end if if (any(b%a1(i)%x /= i + [ 1.0, 2.0, 3.0 ])) then write (0, *) 'check_alloc2 - 4', i call abort() end if end do end subroutine check_alloc2 end program alloc ! { dg-final { scan-tree-dump-times "builtin_free" 18 "original" } }
gpl-2.0
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/coarray_27.f90
155
1163
! { dg-do compile } ! { dg-options "-fcoarray=single" } ! ! Coarray/coindex checks for MOVE_ALLOC ! integer, allocatable :: a(:), b(:)[:,:], c(:)[:,:] type t integer, allocatable :: d(:) end type t type(t) :: x[*] class(t), allocatable :: y[:], z[:], u call move_alloc (A, b) ! { dg-error "must have the same corank" } call move_alloc (c, A) ! { dg-error "must have the same corank" } call move_alloc (b, c) ! OK - same corank call move_alloc (u, y) ! { dg-error "must have the same corank" } call move_alloc (z, u) ! { dg-error "must have the same corank" } call move_alloc (y, z) ! OK - same corank call move_alloc (x%d, a) ! OK call move_alloc (a, x%d) ! OK call move_alloc (x[1]%d, a) ! { dg-error "The FROM argument to MOVE_ALLOC at .1. shall not be coindexed" } call move_alloc (a, x[1]%d) ! { dg-error "The TO argument to MOVE_ALLOC at .1. shall not be coindexed" } call move_alloc (y%d, a) ! OK call move_alloc (a, y%d) ! OK call move_alloc (y[1]%d, a) ! { dg-error "The FROM argument to MOVE_ALLOC at .1. shall not be coindexed" } call move_alloc (a, y[1]%d) ! { dg-error "The TO argument to MOVE_ALLOC at .1. shall not be coindexed" } end
gpl-2.0
Gd58/gcc
libgomp/testsuite/libgomp.oacc-fortran/pset-1.f90
72
4225
! { dg-do run } program test implicit none integer, allocatable :: a1(:) integer, allocatable :: b1(:) integer, allocatable :: c1(:) integer, allocatable :: b2(:,:) integer, allocatable :: c3(:,:,:) allocate (a1(5)) if (.not.allocated (a1)) call abort() a1 = 10 !$acc parallel copy(a1(1:5)) a1(1) = 1 a1(2) = 2 a1(3) = 3 a1(4) = 4 a1(5) = 5 !$acc end parallel if (a1(1) .ne. 1) call abort if (a1(2) .ne. 2) call abort if (a1(3) .ne. 3) call abort if (a1(4) .ne. 4) call abort if (a1(5) .ne. 5) call abort deallocate(a1) allocate (a1(0:4)) if (.not.allocated (a1)) call abort() a1 = 10 !$acc parallel copy(a1(0:4)) a1(0) = 1 a1(1) = 2 a1(2) = 3 a1(3) = 4 a1(4) = 5 !$acc end parallel if (a1(0) .ne. 1) call abort if (a1(1) .ne. 2) call abort if (a1(2) .ne. 3) call abort if (a1(3) .ne. 4) call abort if (a1(4) .ne. 5) call abort deallocate(a1) allocate (b2(5,5)) if (.not.allocated (b2)) call abort() b2 = 11 !$acc parallel copy(b2(1:5,1:5)) b2(1,1) = 1 b2(2,2) = 2 b2(3,3) = 3 b2(4,4) = 4 b2(5,5) = 5 !$acc end parallel if (b2(1,1) .ne. 1) call abort if (b2(2,2) .ne. 2) call abort if (b2(3,3) .ne. 3) call abort if (b2(4,4) .ne. 4) call abort if (b2(5,5) .ne. 5) call abort deallocate(b2) allocate (b2(0:4,0:4)) if (.not.allocated (b2)) call abort() b2 = 11 !$acc parallel copy(b2(0:4,0:4)) b2(0,0) = 1 b2(1,1) = 2 b2(2,2) = 3 b2(3,3) = 4 b2(4,4) = 5 !$acc end parallel if (b2(0,0) .ne. 1) call abort if (b2(1,1) .ne. 2) call abort if (b2(2,2) .ne. 3) call abort if (b2(3,3) .ne. 4) call abort if (b2(4,4) .ne. 5) call abort deallocate(b2) allocate (c3(5,5,5)) if (.not.allocated (c3)) call abort() c3 = 12 !$acc parallel copy(c3(1:5,1:5,1:5)) c3(1,1,1) = 1 c3(2,2,2) = 2 c3(3,3,3) = 3 c3(4,4,4) = 4 c3(5,5,5) = 5 !$acc end parallel if (c3(1,1,1) .ne. 1) call abort if (c3(2,2,2) .ne. 2) call abort if (c3(3,3,3) .ne. 3) call abort if (c3(4,4,4) .ne. 4) call abort if (c3(5,5,5) .ne. 5) call abort deallocate(c3) allocate (c3(0:4,0:4,0:4)) if (.not.allocated (c3)) call abort() c3 = 12 !$acc parallel copy(c3(0:4,0:4,0:4)) c3(0,0,0) = 1 c3(1,1,1) = 2 c3(2,2,2) = 3 c3(3,3,3) = 4 c3(4,4,4) = 5 !$acc end parallel if (c3(0,0,0) .ne. 1) call abort if (c3(1,1,1) .ne. 2) call abort if (c3(2,2,2) .ne. 3) call abort if (c3(3,3,3) .ne. 4) call abort if (c3(4,4,4) .ne. 5) call abort deallocate(c3) allocate (a1(5)) if (.not.allocated (a1)) call abort() allocate (b1(5)) if (.not.allocated (b1)) call abort() allocate (c1(5)) if (.not.allocated (c1)) call abort() a1 = 10 b1 = 3 c1 = 7 !$acc parallel copyin(a1(1:5)) create(c1(1:5)) copyout(b1(1:5)) c1(1) = a1(1) c1(2) = a1(2) c1(3) = a1(3) c1(4) = a1(4) c1(5) = a1(5) b1(1) = c1(1) b1(2) = c1(2) b1(3) = c1(3) b1(4) = c1(4) b1(5) = c1(5) !$acc end parallel if (b1(1) .ne. 10) call abort if (b1(2) .ne. 10) call abort if (b1(3) .ne. 10) call abort if (b1(4) .ne. 10) call abort if (b1(5) .ne. 10) call abort deallocate(a1) deallocate(b1) deallocate(c1) allocate (a1(0:4)) if (.not.allocated (a1)) call abort() allocate (b1(0:4)) if (.not.allocated (b1)) call abort() allocate (c1(0:4)) if (.not.allocated (c1)) call abort() a1 = 10 b1 = 3 c1 = 7 !$acc parallel copyin(a1(0:4)) create(c1(0:4)) copyout(b1(0:4)) c1(0) = a1(0) c1(1) = a1(1) c1(2) = a1(2) c1(3) = a1(3) c1(4) = a1(4) b1(0) = c1(0) b1(1) = c1(1) b1(2) = c1(2) b1(3) = c1(3) b1(4) = c1(4) !$acc end parallel if (b1(0) .ne. 10) call abort if (b1(1) .ne. 10) call abort if (b1(2) .ne. 10) call abort if (b1(3) .ne. 10) call abort if (b1(4) .ne. 10) call abort deallocate(a1) deallocate(b1) deallocate(c1) allocate (a1(5)) if (.not.allocated (a1)) call abort() a1 = 10 !$acc parallel copy(a1(2:3)) a1(2) = 2 a1(3) = 3 !$acc end parallel if (a1(1) .ne. 10) call abort if (a1(2) .ne. 2) call abort if (a1(3) .ne. 3) call abort if (a1(4) .ne. 10) call abort if (a1(5) .ne. 10) call abort deallocate(a1) end program test
gpl-2.0
emb-team/loongson-gccgo
gcc/testsuite/gfortran.fortran-torture/execute/math.f90
174
2443
! Program to test mathematical intrinsics subroutine dotest (n, val4, val8, known) implicit none real(kind=4) val4, known real(kind=8) val8 integer n if (abs (val4 - known) .gt. 0.001) call abort if (abs (real (val8, kind=4) - known) .gt. 0.001) call abort end subroutine subroutine dotestc (n, val4, val8, known) implicit none complex(kind=4) val4, known complex(kind=8) val8 integer n if (abs (val4 - known) .gt. 0.001) call abort if (abs (cmplx (val8, kind=4) - known) .gt. 0.001) call abort end subroutine program testmath implicit none real(kind=4) r, two4, half4 real(kind=8) q, two8, half8 complex(kind=4) cr complex(kind=8) cq external dotest, dotestc two4 = 2.0 two8 = 2.0_8 half4 = 0.5 half8 = 0.5_8 r = sin (two4) q = sin (two8) call dotest (1, r, q, 0.9093) r = cos (two4) q = cos (two8) call dotest (2, r, q, -0.4161) r = tan (two4) q = tan (two8) call dotest (3, r, q, -2.1850) r = asin (half4) q = asin (half8) call dotest (4, r, q, 0.5234) r = acos (half4) q = acos (half8) call dotest (5, r, q, 1.0472) r = atan (half4) q = atan (half8) call dotest (6, r, q, 0.4636) r = atan2 (two4, half4) q = atan2 (two8, half8) call dotest (7, r, q, 1.3258) r = exp (two4) q = exp (two8) call dotest (8, r, q, 7.3891) r = log (two4) q = log (two8) call dotest (9, r, q, 0.6931) r = log10 (two4) q = log10 (two8) call dotest (10, r, q, 0.3010) r = sinh (two4) q = sinh (two8) call dotest (11, r, q, 3.6269) r = cosh (two4) q = cosh (two8) call dotest (12, r, q, 3.7622) r = tanh (two4) q = tanh (two8) call dotest (13, r, q, 0.9640) r = sqrt (two4) q = sqrt (two8) call dotest (14, r, q, 1.4142) r = atan2 (0.0, 1.0) q = atan2 (0.0_8, 1.0_8) call dotest (15, r, q, 0.0) r = atan2 (-1.0, 1.0) q = atan2 (-1.0_8, 1.0_8) call dotest (16, r, q, -0.7854) r = atan2 (0.0, -1.0) q = atan2 (0.0_8, -1.0_8) call dotest (17, r, q, 3.1416) r = atan2 (-1.0, -1.0) q = atan2 (-1.0_8, -1.0_8) call dotest (18, r, q, -2.3562) r = atan2 (1.0, 0.0) q = atan2 (1.0_8, 0.0_8) call dotest (19, r, q, 1.5708) r = atan2 (-1.0, 0.0) q = atan2 (-1.0_8, 0.0_8) call dotest (20, r, q, -1.5708) cr = log ((-1.0, -1.0)) cq = log ((-1.0_8, -1.0_8)) call dotestc (21, cr, cq, (0.3466, -2.3562)) end program
gpl-2.0
emb-team/loongson-gccgo
libgomp/testsuite/libgomp.fortran/omp_orphan.f
221
1188
C****************************************************************************** C FILE: omp_orphan.f C DESCRIPTION: C OpenMP Example - Parallel region with an orphaned directive - Fortran C Version C This example demonstrates a dot product being performed by an orphaned C loop reduction construct. Scoping of the reduction variable is critical. C AUTHOR: Blaise Barney 5/99 C LAST REVISED: C****************************************************************************** PROGRAM ORPHAN COMMON /DOTDATA/ A, B, SUM INTEGER I, VECLEN PARAMETER (VECLEN = 100) REAL*8 A(VECLEN), B(VECLEN), SUM DO I=1, VECLEN A(I) = 1.0 * I B(I) = A(I) ENDDO SUM = 0.0 !$OMP PARALLEL CALL DOTPROD !$OMP END PARALLEL WRITE(*,*) "Sum = ", SUM END SUBROUTINE DOTPROD COMMON /DOTDATA/ A, B, SUM INTEGER I, TID, OMP_GET_THREAD_NUM, VECLEN PARAMETER (VECLEN = 100) REAL*8 A(VECLEN), B(VECLEN), SUM TID = OMP_GET_THREAD_NUM() !$OMP DO REDUCTION(+:SUM) DO I=1, VECLEN SUM = SUM + (A(I)*B(I)) PRINT *, ' TID= ',TID,'I= ',I ENDDO RETURN END
gpl-2.0
rgwan/gcc
gcc/testsuite/gfortran.dg/pr63778.f
92
1542
! { dg-do compile } ! { dg-options "-O3 -ffast-math" } SUBROUTINE ZUNG2L( M, N, K, A, LDA, TAU, WORK, INFO ) COMPLEX*16 A( LDA, * ), TAU( * ), WORK( * ) IF( M.LT.0 ) THEN END IF CALL ZLARF( 'LEFT', M-N+II, II-1, A( 1, II ), 1, TAU( I ), A, $ LDA, WORK ) CALL ZSCAL( M-N+II-1, -TAU( I ), A( 1, II ), 1 ) A( M-N+II, II ) = ONE - TAU( I ) END SUBROUTINE ZLARF( SIDE, M, N, V, INCV, TAU, C, LDC, WORK ) CHARACTER SIDE(*) LOGICAL LSAME COMPLEX*16 C( LDC, * ), V(*), WORK(*), TAU IF( LSAME( SIDE, 'L' ) ) THEN IF( TAU.NE.ZERO ) THEN CALL ZGEMV( 'CONJUGATE TRANSPOSE', M, N, ONE, C, LDC, V, $ INCV, ZERO, WORK, 1 ) END IF END IF END LOGICAL FUNCTION LSAME( CA, CB ) CHARACTER CA(*), CB(*) END SUBROUTINE ZGEMV ( TRANS, M, N, ALPHA, A, LDA, X, INCX, $ BETA, Y, INCY ) COMPLEX*16 A( LDA, * ), X( * ), Y( * ) CHARACTER TRANS(*) LOGICAL LSAME IF( LSAME( TRANS, 'N' ) )THEN IF( INCY.EQ.1 )THEN IF( X( JX ).NE.ZERO )THEN Y( I ) = Y( I ) + TEMP*A( I, J ) END IF END IF END IF END SUBROUTINE ZSCAL(N,ZA,ZX,INCX) COMPLEX*16 ZA,ZX(1) IF( N.LE.0 .OR. INCX.LE.0 )RETURN 20 DO 30 I = 1,N ZX(I) = ZA*ZX(I) 30 CONTINUE END
gpl-2.0
jrper/fluidity
tools/triangle2vtu.F90
5
2829
! Copyright (C) 2006 Imperial College London and others. ! ! Please see the AUTHORS file in the main source directory for a full list ! of copyright holders. ! ! Prof. C Pain ! Applied Modelling and Computation Group ! Department of Earth Science and Engineering ! Imperial College London ! ! amcgsoftware@imperial.ac.uk ! ! 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, ! version 2.1 of the License. ! ! 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ! USA subroutine triangle2vtu(filename_, filename_len) bind(c) !!< Read in a triangle mesh and output a vtu mesh. use fields use read_triangle use vtk_interfaces use iso_c_binding implicit none integer(kind=c_size_t), value :: filename_len character(kind=c_char, len=1) :: filename_(*) character(len=filename_len) :: filename integer :: stat, i type(vector_field), target :: positions type(scalar_field) :: mapA, mapB, regions do i=1, filename_len filename(i:i)=filename_(i) end do positions=read_triangle_files(filename, quad_degree=3, no_faces=.true.) ! For supermesh stuff. ! It tests for the existence of the mapping files ! mapping from elements in the supermesh to elements ! in the original mesh. ! If they're not there, nothing changes in the output. mapA = read_elemental_mappings(positions, filename, "mapCA", stat = stat) if(stat == 0) mapB = read_elemental_mappings(positions, filename, "mapCB", stat = stat) if (stat == 0) then call vtk_write_fields(filename, position=positions, & model=positions%mesh, sfields=(/mapA, mapB/), vfields=(/positions/)) else if (associated(positions%mesh%region_ids)) then regions=piecewise_constant_field(positions%mesh, name="Regions") regions%val=float(positions%mesh%region_ids) call vtk_write_fields(filename, position=positions, & model=positions%mesh, vfields=(/positions/), sfields=(/ regions /)) call deallocate(regions) else call vtk_write_fields(filename, position=positions, model=positions%mesh) end if call deallocate(positions) if (associated(mapA%val)) then call deallocate(mapA) end if if (associated(mapB%val)) then call deallocate(mapB) end if end subroutine triangle2vtu
lgpl-2.1
mingwpy/scipy
scipy/linalg/src/id_dist/src/iddr_asvd.f
128
3181
c this file contains the following user-callable routines: c c c routine iddr_aid computes the SVD, to a specified rank, c of an arbitrary matrix. This routine is randomized. c c ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c c c c subroutine iddr_asvd(m,n,a,krank,w,u,v,s,ier) c c constructs a rank-krank SVD u diag(s) v^T approximating a, c where u is an m x krank matrix whose columns are orthonormal, c v is an n x krank matrix whose columns are orthonormal, c and diag(s) is a diagonal krank x krank matrix whose entries c are all nonnegative. This routine uses a randomized algorithm. c c input: c m -- number of rows in a c n -- number of columns in a c a -- matrix to be decomposed; the present routine does not c alter a c krank -- rank of the SVD being constructed c w -- initialization array that routine iddr_aidi c has constructed (for use in the present routine, w must c be at least (2*krank+28)*m+(6*krank+21)*n+25*krank**2+100 c real*8 elements long) c c output: c u -- matrix of orthonormal left singular vectors of a c v -- matrix of orthonormal right singular vectors of a c s -- array of singular values of a c ier -- 0 when the routine terminates successfully; c nonzero otherwise c c _N.B._: The algorithm used by this routine is randomized. c implicit none integer m,n,krank,lw,ilist,llist,iproj,lproj,icol,lcol, 1 iwork,lwork,iwinit,lwinit,ier real*8 a(m,n),u(m,krank),v(n,krank),s(krank), 1 w((2*krank+28)*m+(6*krank+21)*n+25*krank**2+100) c c c Allocate memory in w. c lw = 0 c iwinit = lw+1 lwinit = (2*krank+17)*n+27*m+100 lw = lw+lwinit c ilist = lw+1 llist = n lw = lw+llist c iproj = lw+1 lproj = krank*(n-krank) lw = lw+lproj c icol = lw+1 lcol = m*krank lw = lw+lcol c iwork = lw+1 lwork = (krank+1)*(m+3*n)+26*krank**2 lw = lw+lwork c c call iddr_asvd0(m,n,a,krank,w(iwinit),u,v,s,ier, 1 w(ilist),w(iproj),w(icol),w(iwork)) c c return end c c c c subroutine iddr_asvd0(m,n,a,krank,winit,u,v,s,ier, 1 list,proj,col,work) c c routine iddr_asvd serves as a memory wrapper c for the present routine (please see routine iddr_asvd c for further documentation). c implicit none integer m,n,krank,list(n),ier real*8 a(m,n),u(m,krank),v(n,krank),s(krank), 1 proj(krank,n-krank),col(m*krank), 2 winit((2*krank+17)*n+27*m+100), 3 work((krank+1)*(m+3*n)+26*krank**2) c c c ID a. c call iddr_aid(m,n,a,krank,winit,list,proj) c c c Collect together the columns of a indexed by list into col. c call idd_copycols(m,n,a,krank,list,col) c c c Convert the ID to an SVD. c call idd_id2svd(m,krank,col,n,list,proj,u,v,s,ier,work) c c return end
bsd-3-clause
jrper/fluidity
femtools/CV_Faces.F90
5
53047
! Copyright (C) 2006 Imperial College London and others. ! ! Please see the AUTHORS file in the main source directory for a full list ! of copyright holders. ! ! Prof. C Pain ! Applied Modelling and Computation Group ! Department of Earth Science and Engineering ! Imperial College London ! ! amcgsoftware@imperial.ac.uk ! ! 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, ! version 2.1 of the License. ! ! 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ! USA #include "fdebug.h" module cv_faces use FLDebug use shape_functions implicit none type cv_faces_type ! vertices = number of vertices, nodes = number of nodes, faces = number of faces ! degree = degree of polynomial, dim = dimensions of parent element integer :: vertices, nodes, faces, coords, degree, dim integer :: svertices, snodes, sfaces, scoords ! corners = volume coordinates of corners of faces ! faces x coords x face vertices real, dimension(:,:,:), pointer :: corners, scorners ! neiloc = relates faces to nodes and vice versa ! nodes x faces integer, dimension(:,:), pointer :: neiloc, sneiloc ! shape = shape function used in quadrature of faces ! 1 dimension lower than parent element type(element_type) :: shape end type cv_faces_type type corner_permutation_type integer, pointer, dimension(:,:) :: p end type corner_permutation_type type face_generator_type integer, dimension(:,:), pointer :: permutation real, dimension(:), pointer :: coords integer, dimension(2) :: nodes end type face_generator_type type face_corner_template !! A face is defined by a set of generators. type(face_generator_type), dimension(:), pointer :: generator integer :: dimension, vertices, ncorn, nodes integer :: degree, faces, coords end type face_corner_template integer, private, parameter :: CV_TET_MAX_DEGREE=2, CV_HEX_MAX_DEGREE=1, & CV_TRI_MAX_DEGREE=2, CV_QUAD_MAX_DEGREE=1, CV_LINE_MAX_DEGREE=1 type(corner_permutation_type), dimension(30), private, target, save :: cv_tet_face_permutations type(corner_permutation_type), dimension(12), private, target, save :: cv_tet_bdy_permutations type(corner_permutation_type), dimension(12), private, target, save :: cv_hex_face_permutations type(corner_permutation_type), dimension(4), private, target, save :: cv_hex_bdy_permutations type(corner_permutation_type), dimension(12), private, target, save :: cv_tri_face_permutations type(corner_permutation_type), dimension(4), private, target, save :: cv_quad_face_permutations type(corner_permutation_type), dimension(5), private, target, save :: cv_line_bdy_permutations type(corner_permutation_type), dimension(1), private, target, save :: cv_line_face_permutations type(corner_permutation_type), dimension(1), private, target, save :: cv_point_bdy_permutations type(face_corner_template), dimension(CV_TET_MAX_DEGREE), private, target, save :: cv_tet_face_temp type(face_corner_template), dimension(CV_TET_MAX_DEGREE), private, target, save :: cv_tet_bdy_temp type(face_corner_template), dimension(CV_HEX_MAX_DEGREE), private, target, save :: cv_hex_face_temp type(face_corner_template), dimension(CV_HEX_MAX_DEGREE), private, target, save :: cv_hex_bdy_temp type(face_corner_template), dimension(CV_TRI_MAX_DEGREE), private, target, save :: cv_tri_face_temp type(face_corner_template), dimension(CV_LINE_MAX_DEGREE), private, target, save :: cv_line_face_temp type(face_corner_template), dimension(CV_QUAD_MAX_DEGREE), private, target, save :: cv_quad_face_temp type(face_corner_template), dimension(max(CV_TRI_MAX_DEGREE,CV_QUAD_MAX_DEGREE)), private, target, save :: cv_line_bdy_temp type(face_corner_template), dimension(CV_LINE_MAX_DEGREE), private, target, save :: cv_point_bdy_temp logical, private, save :: initialised=.false. interface allocate module procedure allocate_cv_faces_type end interface interface deallocate module procedure deallocate_cv_faces_type end interface private public :: deallocate, find_cv_faces, cv_faces_type contains function find_cv_faces(vertices, dimension, polydegree, quaddegree, quadngi) result (cvfaces) ! Return the element numbering type for an element in dimension ! dimensions with vertices vertices and degree polynomial bases. ! ! If no suitable numbering is available, return a null pointer. type(face_corner_template), dimension(:), pointer :: cv_temp_list, cvbdy_temp_list type(face_corner_template), pointer :: cv_temp, cvbdy_temp type(cv_faces_type) :: cvfaces integer, intent(in) :: vertices, dimension, polydegree integer, intent(in), optional :: quaddegree, quadngi type(quadrature_type) :: face_quad if (.not.initialised) call locate_controlvolume_corners select case(dimension) case(1) select case (vertices) case (2) !Line segments if (polydegree>CV_LINE_MAX_DEGREE) then FLExit('Invalid control volume degree') else cv_temp_list=>cv_line_face_temp cvbdy_temp_list=> cv_point_bdy_temp end if case default FLExit('Invalid control volume type.') end select case(2) select case (vertices) case (3) !Triangles if (polydegree>CV_TRI_MAX_DEGREE) then FLExit('Invalid control volume degree.') else cv_temp_list=>cv_tri_face_temp cvbdy_temp_list=>cv_line_bdy_temp end if case (4) !Quads if (polydegree>CV_QUAD_MAX_DEGREE) then FLExit('Invalid control volume degree.') else cv_temp_list=>cv_quad_face_temp cvbdy_temp_list=>cv_line_bdy_temp end if case default FLExit('Invalid control volume type.') end select case(3) select case (vertices) case (4) !Tets if (polydegree>CV_TET_MAX_DEGREE) then FLExit('Invalid control volume degree.') else cv_temp_list=>cv_tet_face_temp cvbdy_temp_list=>cv_tet_bdy_temp end if case(8) !Hexes if (polydegree>CV_HEX_MAX_DEGREE) then FLExit('Invalid control volume degree.') else cv_temp_list=>cv_hex_face_temp cvbdy_temp_list=>cv_hex_bdy_temp end if case default FLExit('Invalid control volume type.') end select case default FLExit('Invalid control volume type.') end select cv_temp=>cv_temp_list(minloc(cv_temp_list%degree, dim=1,& mask=cv_temp_list%degree>=polydegree)) cvbdy_temp=>cvbdy_temp_list(minloc(cvbdy_temp_list%degree, dim=1,& mask=cvbdy_temp_list%degree>=polydegree)) ! Now we can start putting together the face info. call allocate(cvfaces, cv_temp%nodes, cvbdy_temp%nodes, cv_temp%faces, cvbdy_temp%faces, & cv_temp%coords, cvbdy_temp%coords, & cv_temp%ncorn) cvfaces%vertices=cv_temp%vertices cvfaces%nodes=cv_temp%nodes cvfaces%svertices=cvbdy_temp%vertices cvfaces%snodes=cvbdy_temp%nodes cvfaces%coords=cv_temp%coords cvfaces%scoords=cvbdy_temp%coords cvfaces%faces=cv_temp%faces cvfaces%sfaces=cvbdy_temp%faces cvfaces%dim=dimension cvfaces%degree=polydegree call expand_cv_faces_template(cvfaces, cv_temp, cvbdy_temp) if(present(quaddegree)) then face_quad=make_quadrature(vertices=size(cvfaces%corners, 3),dim=(cvfaces%dim-1), & degree=quaddegree) elseif(present(quadngi)) then face_quad=make_quadrature(vertices=size(cvfaces%corners, 3),dim=(cvfaces%dim-1), & ngi=quadngi) else ! code error FLAbort('Must specifiy either quaddegree or quadngi') end if cvfaces%shape=make_element_shape(vertices=size(cvfaces%corners, 3), dim=(cvfaces%dim-1), & degree=1, quad=face_quad, & type=ELEMENT_LAGRANGIAN) call deallocate(face_quad) end function find_cv_faces subroutine allocate_cv_faces_type(cvfaces, nodes, snodes, faces, sfaces, coords, scoords, & ncorn, stat) !!< Allocate memory for a quadrature type. Note that this is done !!< automatically in make_quadrature. type(cv_faces_type), intent(inout) :: cvfaces !! nodes is the number of nodes integer, intent(in) :: nodes, snodes, faces, sfaces, ncorn, coords, scoords !! Stat returns zero for successful completion and nonzero otherwise. integer, intent(out), optional :: stat integer :: lstat allocate(cvfaces%corners(faces,coords,ncorn), cvfaces%neiloc(nodes,faces), & cvfaces%scorners(sfaces,scoords,ncorn), cvfaces%sneiloc(snodes,sfaces), & stat=lstat) if (present(stat)) then stat=lstat else if (lstat/=0) then FLAbort("Error allocating cvfaces") end if end subroutine allocate_cv_faces_type subroutine deallocate_cv_faces_type(cvfaces,stat) !! The cvloc type to be deallocated. type(cv_faces_type), intent(inout) :: cvfaces !! Stat returns zero for successful completion and nonzero otherwise. integer, intent(out), optional :: stat integer :: lstat, tstat lstat=0 tstat=0 deallocate(cvfaces%corners, cvfaces%neiloc, & cvfaces%scorners, cvfaces%sneiloc, stat = tstat) lstat=max(tstat,lstat) call deallocate(cvfaces%shape, stat= tstat) lstat=max(tstat,lstat) if (present(stat)) then stat=lstat else if (lstat/=0) then FLAbort("Error deallocating cvfaces") end if end subroutine deallocate_cv_faces_type !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine locate_controlvolume_corners ! Fill the values in in element_numbering. ! make sure this is idempotent. if (initialised) return initialised=.true. call construct_cv_tet_face_permutations call construct_cv_tet_face_templates call construct_cv_tet_bdy_permutations call construct_cv_tet_bdy_templates call construct_cv_hex_face_permutations call construct_cv_hex_face_templates call construct_cv_hex_bdy_permutations call construct_cv_hex_bdy_templates call construct_cv_tri_face_permutations call construct_cv_tri_face_templates call construct_cv_quad_face_permutations call construct_cv_quad_face_templates call construct_cv_line_bdy_permutations call construct_cv_line_bdy_templates call construct_cv_line_face_permutations call construct_cv_line_face_templates call construct_cv_point_bdy_permutations call construct_cv_point_bdy_templates end subroutine locate_controlvolume_corners !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_tet_face_templates ! Construct list of available templates. integer :: i real, dimension(7) :: coords coords=0.0 cv_tet_face_temp%dimension=3 cv_tet_face_temp%vertices=4 cv_tet_face_temp%ncorn=4 cv_tet_face_temp%coords=4 i=0 !---------------------------------------------------------------------- ! Linear tet i=i+1 ! One generator per face. allocate(cv_tet_face_temp(i)%generator(6)) cv_tet_face_temp(i)%faces=6 cv_tet_face_temp(i)%degree=1 cv_tet_face_temp(i)%nodes=4 coords(1)=0.25 coords(2)=0.333333333333333333333333333333333 coords(3)=0.5 cv_tet_face_temp(i)%generator(1)=make_face_generator( & permutation=cv_tet_face_permutations(1), & nodes=(/1,2/), & coords=coords) cv_tet_face_temp(i)%generator(2)=make_face_generator( & permutation=cv_tet_face_permutations(2), & nodes=(/2,3/), & coords=coords) cv_tet_face_temp(i)%generator(3)=make_face_generator( & permutation=cv_tet_face_permutations(3), & nodes=(/1,3/), & coords=coords) cv_tet_face_temp(i)%generator(4)=make_face_generator( & permutation=cv_tet_face_permutations(4), & nodes=(/1,4/), & coords=coords) cv_tet_face_temp(i)%generator(5)=make_face_generator( & permutation=cv_tet_face_permutations(5), & nodes=(/2,4/), & coords=coords) cv_tet_face_temp(i)%generator(6)=make_face_generator( & permutation=cv_tet_face_permutations(6), & nodes=(/3,4/), & coords=coords) !---------------------------------------------------------------------- ! Quadratic tet i=i+1 ! One generator per face. allocate(cv_tet_face_temp(i)%generator(24)) cv_tet_face_temp(i)%faces=24 cv_tet_face_temp(i)%degree=2 cv_tet_face_temp(i)%nodes=10 coords(1)=0.125 coords(2)=0.166666666666666666666666666666666 coords(3)=0.25 coords(4)=0.333333333333333333333333333333333 coords(5)=0.625 coords(6)=0.666666666666666666666666666666666 coords(7)=0.75 cv_tet_face_temp(i)%generator(1)=make_face_generator( & permutation=cv_tet_face_permutations(7), & nodes=(/1,2/), & coords=coords) cv_tet_face_temp(i)%generator(2)=make_face_generator( & permutation=cv_tet_face_permutations(8), & nodes=(/1,4/), & coords=coords) cv_tet_face_temp(i)%generator(3)=make_face_generator( & permutation=cv_tet_face_permutations(9), & nodes=(/1,7/), & coords=coords) cv_tet_face_temp(i)%generator(4)=make_face_generator( & permutation=cv_tet_face_permutations(10), & nodes=(/2,3/), & coords=coords) cv_tet_face_temp(i)%generator(5)=make_face_generator( & permutation=cv_tet_face_permutations(11), & nodes=(/3,5/), & coords=coords) cv_tet_face_temp(i)%generator(6)=make_face_generator( & permutation=cv_tet_face_permutations(12), & nodes=(/3,8/), & coords=coords) cv_tet_face_temp(i)%generator(7)=make_face_generator( & permutation=cv_tet_face_permutations(13), & nodes=(/4,6/), & coords=coords) cv_tet_face_temp(i)%generator(8)=make_face_generator( & permutation=cv_tet_face_permutations(14), & nodes=(/5,6/), & coords=coords) cv_tet_face_temp(i)%generator(9)=make_face_generator( & permutation=cv_tet_face_permutations(15), & nodes=(/6,9/), & coords=coords) cv_tet_face_temp(i)%generator(10)=make_face_generator( & permutation=cv_tet_face_permutations(16), & nodes=(/7,10/), & coords=coords) cv_tet_face_temp(i)%generator(11)=make_face_generator( & permutation=cv_tet_face_permutations(17), & nodes=(/8,10/), & coords=coords) cv_tet_face_temp(i)%generator(12)=make_face_generator( & permutation=cv_tet_face_permutations(18), & nodes=(/9,10/), & coords=coords) cv_tet_face_temp(i)%generator(13)=make_face_generator( & permutation=cv_tet_face_permutations(19), & nodes=(/2,7/), & coords=coords) cv_tet_face_temp(i)%generator(14)=make_face_generator( & permutation=cv_tet_face_permutations(20), & nodes=(/2,8/), & coords=coords) cv_tet_face_temp(i)%generator(15)=make_face_generator( & permutation=cv_tet_face_permutations(21), & nodes=(/7,8/), & coords=coords) cv_tet_face_temp(i)%generator(16)=make_face_generator( & permutation=cv_tet_face_permutations(22), & nodes=(/5,8/), & coords=coords) cv_tet_face_temp(i)%generator(17)=make_face_generator( & permutation=cv_tet_face_permutations(23), & nodes=(/5,9/), & coords=coords) cv_tet_face_temp(i)%generator(18)=make_face_generator( & permutation=cv_tet_face_permutations(24), & nodes=(/8,9/), & coords=coords) cv_tet_face_temp(i)%generator(19)=make_face_generator( & permutation=cv_tet_face_permutations(25), & nodes=(/4,7/), & coords=coords) cv_tet_face_temp(i)%generator(20)=make_face_generator( & permutation=cv_tet_face_permutations(26), & nodes=(/4,9/), & coords=coords) cv_tet_face_temp(i)%generator(21)=make_face_generator( & permutation=cv_tet_face_permutations(27), & nodes=(/7,9/), & coords=coords) cv_tet_face_temp(i)%generator(22)=make_face_generator( & permutation=cv_tet_face_permutations(28), & nodes=(/2,4/), & coords=coords) cv_tet_face_temp(i)%generator(23)=make_face_generator( & permutation=cv_tet_face_permutations(29), & nodes=(/2,5/), & coords=coords) cv_tet_face_temp(i)%generator(24)=make_face_generator( & permutation=cv_tet_face_permutations(30), & nodes=(/4,5/), & coords=coords) end subroutine construct_cv_tet_face_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_tri_face_templates ! Construct list of available templates. integer :: i real, dimension(5) :: coords coords=0.0 cv_tri_face_temp%dimension=2 cv_tri_face_temp%vertices=3 cv_tri_face_temp%ncorn=2 cv_tri_face_temp%coords=3 i=0 !---------------------------------------------------------------------- ! Linear triangle i=i+1 ! One generator per face. allocate(cv_tri_face_temp(i)%generator(3)) cv_tri_face_temp(i)%faces=3 cv_tri_face_temp(i)%degree=1 cv_tri_face_temp(i)%nodes=3 coords(1)=0.333333333333333333333333333333333 coords(2)=0.5 cv_tri_face_temp(i)%generator(1)=make_face_generator( & permutation=cv_tri_face_permutations(1), & nodes=(/1,2/), & coords=coords) cv_tri_face_temp(i)%generator(2)=make_face_generator( & permutation=cv_tri_face_permutations(2), & nodes=(/2,3/), & coords=coords) cv_tri_face_temp(i)%generator(3)=make_face_generator( & permutation=cv_tri_face_permutations(3), & nodes=(/1,3/), & coords=coords) !---------------------------------------------------------------------- ! Quadratic triangle i=i+1 ! One generator per face. allocate(cv_tri_face_temp(i)%generator(9)) cv_tri_face_temp(i)%faces=9 cv_tri_face_temp(i)%degree=2 cv_tri_face_temp(i)%nodes=6 coords(1)=0.166666666666666666666666666666666 coords(2)=0.25 coords(3)=0.333333333333333333333333333333333 coords(4)=0.666666666666666666666666666666666 coords(5)=0.75 cv_tri_face_temp(i)%generator(1)=make_face_generator( & permutation=cv_tri_face_permutations(4), & nodes=(/1,2/), & coords=coords) cv_tri_face_temp(i)%generator(2)=make_face_generator( & permutation=cv_tri_face_permutations(5), & nodes=(/1,4/), & coords=coords) cv_tri_face_temp(i)%generator(3)=make_face_generator( & permutation=cv_tri_face_permutations(6), & nodes=(/2,3/), & coords=coords) cv_tri_face_temp(i)%generator(4)=make_face_generator( & permutation=cv_tri_face_permutations(7), & nodes=(/3,5/), & coords=coords) cv_tri_face_temp(i)%generator(5)=make_face_generator( & permutation=cv_tri_face_permutations(8), & nodes=(/5,6/), & coords=coords) cv_tri_face_temp(i)%generator(6)=make_face_generator( & permutation=cv_tri_face_permutations(9), & nodes=(/4,6/), & coords=coords) cv_tri_face_temp(i)%generator(7)=make_face_generator( & permutation=cv_tri_face_permutations(10), & nodes=(/2,4/), & coords=coords) cv_tri_face_temp(i)%generator(8)=make_face_generator( & permutation=cv_tri_face_permutations(11), & nodes=(/2,5/), & coords=coords) cv_tri_face_temp(i)%generator(9)=make_face_generator( & permutation=cv_tri_face_permutations(12), & nodes=(/4,5/), & coords=coords) end subroutine construct_cv_tri_face_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_line_face_templates ! Construct list of available templates. integer :: i real, dimension(5) :: coords coords=0.0 cv_line_face_temp%dimension=1 cv_line_face_temp%vertices=2 cv_line_face_temp%ncorn=1 cv_line_face_temp%coords=2 i=0 !---------------------------------------------------------------------- ! Linear line i=i+1 ! One generator per face. allocate(cv_line_face_temp(i)%generator(1)) cv_line_face_temp(i)%faces=1 cv_line_face_temp(i)%degree=1 cv_line_face_temp(i)%nodes=2 coords(1)=0.5 cv_line_face_temp(i)%generator(1)=make_face_generator( & permutation=cv_line_face_permutations(1), & nodes=(/1,2/), & coords=coords) end subroutine construct_cv_line_face_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_hex_face_templates ! Construct list of available templates. integer :: i real, dimension(4) :: coords coords=0.0 cv_hex_face_temp%dimension=3 cv_hex_face_temp%vertices=8 cv_hex_face_temp%ncorn=4 cv_hex_face_temp%coords=3 i=0 !---------------------------------------------------------------------- ! Tri-Linear hex i=i+1 ! One generator per face. allocate(cv_hex_face_temp(i)%generator(12)) cv_hex_face_temp(i)%faces=12 cv_hex_face_temp(i)%degree=1 cv_hex_face_temp(i)%nodes=8 coords(1)=1.0 cv_hex_face_temp(i)%generator(1)=make_face_generator( & permutation=cv_hex_face_permutations(1), & nodes=(/1,3/), & coords=coords) cv_hex_face_temp(i)%generator(2)=make_face_generator( & permutation=cv_hex_face_permutations(2), & nodes=(/2,4/), & coords=coords) cv_hex_face_temp(i)%generator(3)=make_face_generator( & permutation=cv_hex_face_permutations(3), & nodes=(/1,2/), & coords=coords) cv_hex_face_temp(i)%generator(4)=make_face_generator( & permutation=cv_hex_face_permutations(4), & nodes=(/3,4/), & coords=coords) cv_hex_face_temp(i)%generator(5)=make_face_generator( & permutation=cv_hex_face_permutations(5), & nodes=(/1,5/), & coords=coords) cv_hex_face_temp(i)%generator(6)=make_face_generator( & permutation=cv_hex_face_permutations(6), & nodes=(/2,6/), & coords=coords) cv_hex_face_temp(i)%generator(7)=make_face_generator( & permutation=cv_hex_face_permutations(7), & nodes=(/3,7/), & coords=coords) cv_hex_face_temp(i)%generator(8)=make_face_generator( & permutation=cv_hex_face_permutations(8), & nodes=(/4,8/), & coords=coords) cv_hex_face_temp(i)%generator(9)=make_face_generator( & permutation=cv_hex_face_permutations(9), & nodes=(/5,7/), & coords=coords) cv_hex_face_temp(i)%generator(10)=make_face_generator( & permutation=cv_hex_face_permutations(10), & nodes=(/6,8/), & coords=coords) cv_hex_face_temp(i)%generator(11)=make_face_generator( & permutation=cv_hex_face_permutations(11), & nodes=(/5,6/), & coords=coords) cv_hex_face_temp(i)%generator(12)=make_face_generator( & permutation=cv_hex_face_permutations(12), & nodes=(/7,8/), & coords=coords) end subroutine construct_cv_hex_face_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_quad_face_templates ! Construct list of available templates. integer :: i real, dimension(4) :: coords coords=0.0 cv_quad_face_temp%dimension=2 cv_quad_face_temp%vertices=4 cv_quad_face_temp%ncorn=2 cv_quad_face_temp%coords=2 i=0 !---------------------------------------------------------------------- ! Tri-Linear quad i=i+1 ! One generator per face. allocate(cv_quad_face_temp(i)%generator(4)) cv_quad_face_temp(i)%faces=4 cv_quad_face_temp(i)%degree=1 cv_quad_face_temp(i)%nodes=4 coords(1)=1.0 cv_quad_face_temp(i)%generator(1)=make_face_generator( & permutation=cv_quad_face_permutations(1), & nodes=(/1,2/), & coords=coords) cv_quad_face_temp(i)%generator(2)=make_face_generator( & permutation=cv_quad_face_permutations(2), & nodes=(/3,4/), & coords=coords) cv_quad_face_temp(i)%generator(3)=make_face_generator( & permutation=cv_quad_face_permutations(3), & nodes=(/1,3/), & coords=coords) cv_quad_face_temp(i)%generator(4)=make_face_generator( & permutation=cv_quad_face_permutations(4), & nodes=(/2,4/), & coords=coords) end subroutine construct_cv_quad_face_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_tet_bdy_templates ! Construct list of available templates. integer :: i real, dimension(7) :: coords coords=0.0 cv_tet_bdy_temp%dimension=2 cv_tet_bdy_temp%vertices=3 cv_tet_bdy_temp%ncorn=4 cv_tet_bdy_temp%coords=3 i=0 !---------------------------------------------------------------------- ! Linear tet boundary i=i+1 ! One generator per face. allocate(cv_tet_bdy_temp(i)%generator(3)) cv_tet_bdy_temp(i)%faces=3 cv_tet_bdy_temp(i)%degree=1 cv_tet_bdy_temp(i)%nodes=3 coords(1)=0.333333333333333333333333333333333 coords(2)=0.5 coords(3)=1.0 cv_tet_bdy_temp(i)%generator(1)=make_face_generator( & permutation=cv_tet_bdy_permutations(1), & nodes=(/1,1/), & coords=coords) cv_tet_bdy_temp(i)%generator(2)=make_face_generator( & permutation=cv_tet_bdy_permutations(2), & nodes=(/2,2/), & coords=coords) cv_tet_bdy_temp(i)%generator(3)=make_face_generator( & permutation=cv_tet_bdy_permutations(3), & nodes=(/3,3/), & coords=coords) !---------------------------------------------------------------------- ! Quadratic tet boundary i=i+1 ! One generator per face. ! (Multiple faces per node to allow non-quadrilateral shapes) allocate(cv_tet_bdy_temp(i)%generator(9)) cv_tet_bdy_temp(i)%faces=9 ! should only be 6 but 3 are fictitious to account for non-quadrilateral shapes cv_tet_bdy_temp(i)%degree=2 cv_tet_bdy_temp(i)%nodes=6 coords(1)=0.166666666666666666666666666666666 coords(2)=0.25 coords(3)=0.333333333333333333333333333333333 coords(4)=0.5 coords(5)=0.666666666666666666666666666666666 coords(6)=0.75 coords(7)=1.0 cv_tet_bdy_temp(i)%generator(1)=make_face_generator( & permutation=cv_tet_bdy_permutations(4), & nodes=(/1,1/), & coords=coords) cv_tet_bdy_temp(i)%generator(2)=make_face_generator( & permutation=cv_tet_bdy_permutations(5), & nodes=(/2,2/), & coords=coords) cv_tet_bdy_temp(i)%generator(3)=make_face_generator( & permutation=cv_tet_bdy_permutations(6), & nodes=(/2,2/), & coords=coords) cv_tet_bdy_temp(i)%generator(4)=make_face_generator( & permutation=cv_tet_bdy_permutations(7), & nodes=(/3,3/), & coords=coords) cv_tet_bdy_temp(i)%generator(5)=make_face_generator( & permutation=cv_tet_bdy_permutations(8), & nodes=(/4,4/), & coords=coords) cv_tet_bdy_temp(i)%generator(6)=make_face_generator( & permutation=cv_tet_bdy_permutations(9), & nodes=(/4,4/), & coords=coords) cv_tet_bdy_temp(i)%generator(7)=make_face_generator( & permutation=cv_tet_bdy_permutations(10), & nodes=(/5,5/), & coords=coords) cv_tet_bdy_temp(i)%generator(8)=make_face_generator( & permutation=cv_tet_bdy_permutations(11), & nodes=(/5,5/), & coords=coords) cv_tet_bdy_temp(i)%generator(9)=make_face_generator( & permutation=cv_tet_bdy_permutations(12), & nodes=(/6,6/), & coords=coords) end subroutine construct_cv_tet_bdy_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_line_bdy_templates ! Construct list of available templates. integer :: i real, dimension(4) :: coords coords=0.0 cv_line_bdy_temp%dimension=1 cv_line_bdy_temp%vertices=2 cv_line_bdy_temp%ncorn=2 cv_line_bdy_temp%coords=2 i=0 !---------------------------------------------------------------------- ! Linear line boundary i=i+1 ! One generator per face. allocate(cv_line_bdy_temp(i)%generator(2)) cv_line_bdy_temp(i)%faces=2 cv_line_bdy_temp(i)%degree=1 cv_line_bdy_temp(i)%nodes=2 coords(1)=0.5 coords(2)=1.0 cv_line_bdy_temp(i)%generator(1)=make_face_generator( & permutation=cv_line_bdy_permutations(1), & nodes=(/1,1/), & coords=coords) cv_line_bdy_temp(i)%generator(2)=make_face_generator( & permutation=cv_line_bdy_permutations(2), & nodes=(/2,2/), & coords=coords) !---------------------------------------------------------------------- ! Quadratic line boundary i=i+1 ! One generator per face. allocate(cv_line_bdy_temp(i)%generator(3)) cv_line_bdy_temp(i)%faces=3 cv_line_bdy_temp(i)%degree=2 cv_line_bdy_temp(i)%nodes=3 coords(1)=0.25 coords(2)=0.75 coords(3)=1.0 cv_line_bdy_temp(i)%generator(1)=make_face_generator( & permutation=cv_line_bdy_permutations(3), & nodes=(/1,1/), & coords=coords) cv_line_bdy_temp(i)%generator(2)=make_face_generator( & permutation=cv_line_bdy_permutations(4), & nodes=(/2,2/), & coords=coords) cv_line_bdy_temp(i)%generator(3)=make_face_generator( & permutation=cv_line_bdy_permutations(5), & nodes=(/3,3/), & coords=coords) end subroutine construct_cv_line_bdy_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_point_bdy_templates ! Construct list of available templates. integer :: i real, dimension(4) :: coords coords=0.0 cv_point_bdy_temp%dimension=0 cv_point_bdy_temp%vertices=1 cv_point_bdy_temp%ncorn=1 cv_point_bdy_temp%coords=1 i=0 !---------------------------------------------------------------------- ! Linear line boundary i=i+1 ! One generator per face. allocate(cv_point_bdy_temp(i)%generator(1)) cv_point_bdy_temp(i)%faces=1 cv_point_bdy_temp(i)%degree=1 cv_point_bdy_temp(i)%nodes=1 coords(1)=1.0 cv_point_bdy_temp(i)%generator(1)=make_face_generator( & permutation=cv_point_bdy_permutations(1), & nodes=(/1,1/), & coords=coords) end subroutine construct_cv_point_bdy_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_hex_bdy_templates ! Construct list of available templates. integer :: i real, dimension(4) :: coords coords=0.0 cv_hex_bdy_temp%dimension=2 cv_hex_bdy_temp%vertices=4 cv_hex_bdy_temp%ncorn=4 cv_hex_bdy_temp%coords=2 i=0 !---------------------------------------------------------------------- ! Tri-Linear hex boundary i=i+1 ! One generator per face. allocate(cv_hex_bdy_temp(i)%generator(4)) cv_hex_bdy_temp(i)%faces=4 cv_hex_bdy_temp(i)%degree=1 cv_hex_bdy_temp(i)%nodes=4 coords(1)=1.0 cv_hex_bdy_temp(i)%generator(1)=make_face_generator( & permutation=cv_hex_bdy_permutations(1), & nodes=(/1,1/), & coords=coords) cv_hex_bdy_temp(i)%generator(2)=make_face_generator( & permutation=cv_hex_bdy_permutations(2), & nodes=(/2,2/), & coords=coords) cv_hex_bdy_temp(i)%generator(3)=make_face_generator( & permutation=cv_hex_bdy_permutations(3), & nodes=(/3,3/), & coords=coords) cv_hex_bdy_temp(i)%generator(4)=make_face_generator( & permutation=cv_hex_bdy_permutations(4), & nodes=(/4,4/), & coords=coords) end subroutine construct_cv_hex_bdy_templates !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_tet_face_permutations ! linear faces allocate(cv_tet_face_permutations(1)%p(4,4)) cv_tet_face_permutations(1)%p=reshape((/& 3, 3, 0, 0, & 2, 2, 2, 0, & 2, 2, 0, 2, & 1, 1, 1, 1/),(/4,4/)) allocate(cv_tet_face_permutations(2)%p(4,4)) cv_tet_face_permutations(2)%p=reshape((/& 2, 2, 2, 0, & 0, 3, 3, 0, & 1, 1, 1, 1, & 0, 2, 2, 2/),(/4,4/)) allocate(cv_tet_face_permutations(3)%p(4,4)) cv_tet_face_permutations(3)%p=reshape((/& 2, 2, 2, 0, & 3, 0, 3, 0, & 1, 1, 1, 1, & 2, 0, 2, 2/),(/4,4/)) allocate(cv_tet_face_permutations(4)%p(4,4)) cv_tet_face_permutations(4)%p=reshape((/& 3, 0, 0, 3, & 2, 2, 0, 2, & 2, 0, 2, 2, & 1, 1, 1, 1/),(/4,4/)) allocate(cv_tet_face_permutations(5)%p(4,4)) cv_tet_face_permutations(5)%p=reshape((/& 2, 2, 0, 2, & 0, 3, 0, 3, & 1, 1, 1, 1, & 0, 2, 2, 2/),(/4,4/)) allocate(cv_tet_face_permutations(6)%p(4,4)) cv_tet_face_permutations(6)%p=reshape((/& 1, 1, 1, 1, & 0, 2, 2, 2, & 2, 0, 2, 2, & 0, 0, 3, 3/),(/4,4/)) ! end of linear faces ! quadratic faces allocate(cv_tet_face_permutations(7)%p(4,4)) cv_tet_face_permutations(7)%p=reshape((/& 7, 3, 0, 0, & 6, 2, 2, 0, & 6, 2, 0, 2, & 5, 1, 1, 1/),(/4,4/)) ! 1,2 allocate(cv_tet_face_permutations(8)%p(4,4)) cv_tet_face_permutations(8)%p=reshape((/& 6, 2, 2, 0, & 7, 0, 3, 0, & 5, 1, 1, 1, & 6, 0, 2, 2/),(/4,4/)) ! 1,4 allocate(cv_tet_face_permutations(9)%p(4,4)) cv_tet_face_permutations(9)%p=reshape((/& 7, 0, 0, 3, & 6, 2, 0, 2, & 6, 0, 2, 2, & 5, 1, 1, 1/),(/4,4/)) ! 1,7 allocate(cv_tet_face_permutations(10)%p(4,4)) cv_tet_face_permutations(10)%p=reshape((/& 3, 7, 0, 0, & 2, 6, 2, 0, & 2, 6, 0, 2, & 1, 5, 1, 1/),(/4,4/)) ! 2,3 allocate(cv_tet_face_permutations(11)%p(4,4)) cv_tet_face_permutations(11)%p=reshape((/& 2, 6, 2, 0, & 0, 7, 3, 0, & 1, 5, 1, 1, & 0, 6, 2, 2/),(/4,4/)) ! 3,5 allocate(cv_tet_face_permutations(12)%p(4,4)) cv_tet_face_permutations(12)%p=reshape((/& 0, 7, 0, 3, & 2, 6, 0, 2, & 0, 6, 2, 2, & 1, 5, 1, 1/),(/4,4/)) ! 3,8 allocate(cv_tet_face_permutations(13)%p(4,4)) cv_tet_face_permutations(13)%p=reshape((/& 3, 0, 7, 0, & 2, 2, 6, 0, & 2, 0, 6, 2, & 1, 1, 5, 1/),(/4,4/)) ! 4,6 allocate(cv_tet_face_permutations(14)%p(4,4)) cv_tet_face_permutations(14)%p=reshape((/& 2, 2, 6, 0, & 0, 3, 7, 0, & 1, 1, 5, 1, & 0, 2, 6, 2/),(/4,4/)) ! 5,6 allocate(cv_tet_face_permutations(15)%p(4,4)) cv_tet_face_permutations(15)%p=reshape((/& 0, 0, 7, 3, & 2, 0, 6, 2, & 0, 2, 6, 2, & 1, 1, 5, 1/),(/4,4/)) ! 6,9 allocate(cv_tet_face_permutations(16)%p(4,4)) cv_tet_face_permutations(16)%p=reshape((/& 3, 0, 0, 7, & 2, 2, 0, 6, & 2, 0, 2, 6, & 1, 1, 1, 5/),(/4,4/)) ! 7,10 allocate(cv_tet_face_permutations(17)%p(4,4)) cv_tet_face_permutations(17)%p=reshape((/& 2, 2, 0, 6, & 0, 3, 0, 7, & 1, 1, 1, 5, & 0, 2, 2, 6/),(/4,4/)) ! 8,10 allocate(cv_tet_face_permutations(18)%p(4,4)) cv_tet_face_permutations(18)%p=reshape((/& 0, 0, 3, 7, & 2, 0, 2, 6, & 0, 2, 2, 6, & 1, 1, 1, 5/),(/4,4/)) ! 9,10 allocate(cv_tet_face_permutations(19)%p(4,4)) cv_tet_face_permutations(19)%p=reshape((/& 6, 2, 0, 2, & 4, 4, 0, 4, & 5, 1, 1, 1, & 3, 3, 3, 3/),(/4,4/)) ! 2,7 allocate(cv_tet_face_permutations(20)%p(4,4)) cv_tet_face_permutations(20)%p=reshape((/& 4, 4, 0, 4, & 2, 6, 0, 2, & 3, 3, 3, 3, & 1, 5, 1, 1/),(/4,4/)) ! 2,8 allocate(cv_tet_face_permutations(21)%p(4,4)) cv_tet_face_permutations(21)%p=reshape((/& 2, 2, 0, 6, & 4, 4, 0, 4, & 1, 1, 1, 5, & 3, 3, 3, 3/),(/4,4/)) ! 7,8 allocate(cv_tet_face_permutations(22)%p(4,4)) cv_tet_face_permutations(22)%p=reshape((/& 0, 6, 2, 2, & 0, 4, 4, 4, & 1, 5, 1, 1, & 3, 3, 3, 3/),(/4,4/)) ! 5,8 allocate(cv_tet_face_permutations(23)%p(4,4)) cv_tet_face_permutations(23)%p=reshape((/& 0, 4, 4, 4, & 0, 2, 6, 2, & 3, 3, 3, 3, & 1, 1, 5, 1/),(/4,4/)) ! 5,9 allocate(cv_tet_face_permutations(24)%p(4,4)) cv_tet_face_permutations(24)%p=reshape((/& 0, 2, 2, 6, & 0, 4, 4, 4, & 1, 1, 1, 5, & 3, 3, 3, 3/),(/4,4/)) ! 8,9 allocate(cv_tet_face_permutations(25)%p(4,4)) cv_tet_face_permutations(25)%p=reshape((/& 6, 0, 2, 2, & 4, 0, 4, 4, & 5, 1, 1, 1, & 3, 3, 3, 3/),(/4,4/)) ! 4,7 allocate(cv_tet_face_permutations(26)%p(4,4)) cv_tet_face_permutations(26)%p=reshape((/& 4, 0, 4, 4, & 2, 0, 6, 2, & 3, 3, 3, 3, & 1, 1, 5, 1/),(/4,4/)) ! 4,9 allocate(cv_tet_face_permutations(27)%p(4,4)) cv_tet_face_permutations(27)%p=reshape((/& 2, 0, 2, 6, & 4, 0, 4, 4, & 1, 1, 1, 5, & 3, 3, 3, 3/),(/4,4/)) ! 7,9 allocate(cv_tet_face_permutations(28)%p(4,4)) cv_tet_face_permutations(28)%p=reshape((/& 6, 2, 2, 0, & 4, 4, 4, 0, & 5, 1, 1, 1, & 3, 3, 3, 3/),(/4,4/)) ! 2,4 allocate(cv_tet_face_permutations(29)%p(4,4)) cv_tet_face_permutations(29)%p=reshape((/& 4, 4, 4, 0, & 2, 6, 2, 0, & 3, 3, 3, 3, & 1, 5, 1, 1/),(/4,4/)) ! 2,5 allocate(cv_tet_face_permutations(30)%p(4,4)) cv_tet_face_permutations(30)%p=reshape((/& 2, 2, 6, 0, & 4, 4, 4, 0, & 1, 1, 5, 1, & 3, 3, 3, 3/),(/4,4/)) ! 4,5 ! end of quadratic faces end subroutine construct_cv_tet_face_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_tri_face_permutations ! linear faces allocate(cv_tri_face_permutations(1)%p(3,2)) cv_tri_face_permutations(1)%p=reshape((/& 1, 1, 1, & 2, 2, 0/),(/3,2/)) allocate(cv_tri_face_permutations(2)%p(3,2)) cv_tri_face_permutations(2)%p=reshape((/& 1, 1, 1, & 0, 2, 2/),(/3,2/)) allocate(cv_tri_face_permutations(3)%p(3,2)) cv_tri_face_permutations(3)%p=reshape((/& 1, 1, 1, & 2, 0, 2/),(/3,2/)) ! end of linear faces ! quadratic faces allocate(cv_tri_face_permutations(4)%p(3,2)) cv_tri_face_permutations(4)%p=reshape((/& 5, 2, 0, & 4, 1, 1/),(/3,2/)) allocate(cv_tri_face_permutations(5)%p(3,2)) cv_tri_face_permutations(5)%p=reshape((/& 4, 1, 1, & 5, 0, 2/),(/3,2/)) allocate(cv_tri_face_permutations(6)%p(3,2)) cv_tri_face_permutations(6)%p=reshape((/& 2, 5, 0, & 1, 4, 1/),(/3,2/)) allocate(cv_tri_face_permutations(7)%p(3,2)) cv_tri_face_permutations(7)%p=reshape((/& 1, 4, 1, & 0, 5, 2/),(/3,2/)) allocate(cv_tri_face_permutations(8)%p(3,2)) cv_tri_face_permutations(8)%p=reshape((/& 0, 2, 5, & 1, 1, 4/),(/3,2/)) allocate(cv_tri_face_permutations(9)%p(3,2)) cv_tri_face_permutations(9)%p=reshape((/& 2, 0, 5, & 1, 1, 4/),(/3,2/)) allocate(cv_tri_face_permutations(10)%p(3,2)) cv_tri_face_permutations(10)%p=reshape((/& 4, 1, 1, & 3, 3, 3/),(/3,2/)) allocate(cv_tri_face_permutations(11)%p(3,2)) cv_tri_face_permutations(11)%p=reshape((/& 3, 3, 3, & 1, 4, 1/),(/3,2/)) allocate(cv_tri_face_permutations(12)%p(3,2)) cv_tri_face_permutations(12)%p=reshape((/& 3, 3, 3, & 1, 1, 4/),(/3,2/)) ! end of quadratic faces end subroutine construct_cv_tri_face_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_line_face_permutations allocate(cv_line_face_permutations(1)%p(2,1)) cv_line_face_permutations(1)%p=reshape((/& 1, 1/),(/2,1/)) end subroutine construct_cv_line_face_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_hex_face_permutations allocate(cv_hex_face_permutations(1)%p(3,4)) cv_hex_face_permutations(1)%p=reshape((/& -1, 0, -1, & 0, 0, -1, & -1, 0, 0, & 0, 0, 0/),(/3,4/)) allocate(cv_hex_face_permutations(2)%p(3,4)) cv_hex_face_permutations(2)%p=reshape((/& 0, 0, -1, & 1, 0, -1, & 0, 0, 0, & 1, 0, 0/),(/3,4/)) allocate(cv_hex_face_permutations(3)%p(3,4)) cv_hex_face_permutations(3)%p=reshape((/& 0, -1, -1, & 0, 0, -1, & 0, -1, 0, & 0, 0, 0/),(/3,4/)) allocate(cv_hex_face_permutations(4)%p(3,4)) cv_hex_face_permutations(4)%p=reshape((/& 0, 0, -1, & 0, 1, -1, & 0, 0, 0, & 0, 1, 0/),(/3,4/)) allocate(cv_hex_face_permutations(5)%p(3,4)) cv_hex_face_permutations(5)%p=reshape((/& -1, -1, 0, & 0, -1, 0, & -1, 0, 0, & 0, 0, 0/),(/3,4/)) allocate(cv_hex_face_permutations(6)%p(3,4)) cv_hex_face_permutations(6)%p=reshape((/& 0, -1, 0, & 1, -1, 0, & 0, 0, 0, & 1, 0, 0/),(/3,4/)) allocate(cv_hex_face_permutations(7)%p(3,4)) cv_hex_face_permutations(7)%p=reshape((/& -1, 0, 0, & 0, 0, 0, & -1, 1, 0, & 0, 1, 0/),(/3,4/)) allocate(cv_hex_face_permutations(8)%p(3,4)) cv_hex_face_permutations(8)%p=reshape((/& 0, 0, 0, & 1, 0, 0, & 0, 1, 0, & 1, 1, 0/),(/3,4/)) allocate(cv_hex_face_permutations(9)%p(3,4)) cv_hex_face_permutations(9)%p=reshape((/& -1, 0, 0, & 0, 0, 0, & -1, 0, 1, & 0, 0, 1/),(/3,4/)) allocate(cv_hex_face_permutations(10)%p(3,4)) cv_hex_face_permutations(10)%p=reshape((/& 0, 0, 0, & 1, 0, 0, & 0, 0, 1, & 1, 0, 1/),(/3,4/)) allocate(cv_hex_face_permutations(11)%p(3,4)) cv_hex_face_permutations(11)%p=reshape((/& 0, -1, 0, & 0, 0, 0, & 0, -1, 1, & 0, 0, 1/),(/3,4/)) allocate(cv_hex_face_permutations(12)%p(3,4)) cv_hex_face_permutations(12)%p=reshape((/& 0, 0, 0, & 0, 1, 0, & 0, 0, 1, & 0, 1, 1/),(/3,4/)) end subroutine construct_cv_hex_face_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_quad_face_permutations allocate(cv_quad_face_permutations(1)%p(2,2)) cv_quad_face_permutations(1)%p=reshape((/& -1, 0, & 0, 0/),(/2,2/)) allocate(cv_quad_face_permutations(2)%p(2,2)) cv_quad_face_permutations(2)%p=reshape((/& 0, 0, & 1, 0/),(/2,2/)) allocate(cv_quad_face_permutations(3)%p(2,2)) cv_quad_face_permutations(3)%p=reshape((/& 0, -1, & 0, 0/),(/2,2/)) allocate(cv_quad_face_permutations(4)%p(2,2)) cv_quad_face_permutations(4)%p=reshape((/& 0, 0, & 0, 1/),(/2,2/)) end subroutine construct_cv_quad_face_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_tet_bdy_permutations ! linear allocate(cv_tet_bdy_permutations(1)%p(3,4)) cv_tet_bdy_permutations(1)%p=reshape((/& 3, 0, 0, & 2, 2, 0, & 2, 0, 2, & 1, 1, 1/),(/3,4/)) allocate(cv_tet_bdy_permutations(2)%p(3,4)) cv_tet_bdy_permutations(2)%p=reshape((/& 2, 2, 0, & 0, 3, 0, & 1, 1, 1, & 0, 2, 2/),(/3,4/)) allocate(cv_tet_bdy_permutations(3)%p(3,4)) cv_tet_bdy_permutations(3)%p=reshape((/& 2, 0, 2, & 1, 1, 1, & 0, 0, 3, & 0, 2, 2/),(/3,4/)) ! end of linear ! quadratic allocate(cv_tet_bdy_permutations(4)%p(3,4)) cv_tet_bdy_permutations(4)%p=reshape((/& 7, 0, 0, & 6, 2, 0, & 6, 0, 2, & 5, 1, 1/),(/3,4/)) !1 allocate(cv_tet_bdy_permutations(5)%p(3,4)) cv_tet_bdy_permutations(5)%p=reshape((/& 5, 1, 1, & 6, 2, 0, & 3, 3, 3, & 4, 4, 0/),(/3,4/)) !2 allocate(cv_tet_bdy_permutations(6)%p(3,4)) cv_tet_bdy_permutations(6)%p=reshape((/& 3, 3, 3, & 4, 4, 0, & 1, 5, 1, & 2, 6, 0/),(/3,4/)) !2 allocate(cv_tet_bdy_permutations(7)%p(3,4)) cv_tet_bdy_permutations(7)%p=reshape((/& 0, 7, 0, & 2, 6, 0, & 0, 6, 2, & 1, 5, 1/),(/3,4/)) !3 allocate(cv_tet_bdy_permutations(8)%p(3,4)) cv_tet_bdy_permutations(8)%p=reshape((/& 5, 1, 1, & 6, 0, 2, & 3, 3, 3, & 4, 0, 4/),(/3,4/)) !4 allocate(cv_tet_bdy_permutations(9)%p(3,4)) cv_tet_bdy_permutations(9)%p=reshape((/& 3, 3, 3, & 4, 0, 4, & 1, 1, 5, & 2, 0, 6/),(/3,4/)) !4 allocate(cv_tet_bdy_permutations(10)%p(3,4)) cv_tet_bdy_permutations(10)%p=reshape((/& 1, 5, 1, & 0, 6, 2, & 3, 3, 3, & 0, 4, 4/),(/3,4/)) !5 allocate(cv_tet_bdy_permutations(11)%p(3,4)) cv_tet_bdy_permutations(11)%p=reshape((/& 3, 3, 3, & 0, 4, 4, & 1, 1, 5, & 0, 2, 6/),(/3,4/)) !5 allocate(cv_tet_bdy_permutations(12)%p(3,4)) cv_tet_bdy_permutations(12)%p=reshape((/& 0, 0, 7, & 2, 0, 6, & 0, 2, 6, & 1, 1, 5/),(/3,4/)) !6 ! end of quadratic end subroutine construct_cv_tet_bdy_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_line_bdy_permutations ! linear allocate(cv_line_bdy_permutations(1)%p(2,2)) cv_line_bdy_permutations(1)%p=reshape((/& 2, 0, & 1, 1/),(/2,2/)) allocate(cv_line_bdy_permutations(2)%p(2,2)) cv_line_bdy_permutations(2)%p=reshape((/& 1, 1, & 0, 2/),(/2,2/)) ! end of linear ! quadratic allocate(cv_line_bdy_permutations(3)%p(2,2)) cv_line_bdy_permutations(3)%p=reshape((/& 3, 0, & 2, 1/),(/2,2/)) allocate(cv_line_bdy_permutations(4)%p(2,2)) cv_line_bdy_permutations(4)%p=reshape((/& 2, 1, & 1, 2/),(/2,2/)) allocate(cv_line_bdy_permutations(5)%p(2,2)) cv_line_bdy_permutations(5)%p=reshape((/& 1, 2, & 0, 3/),(/2,2/)) ! end of quadratic end subroutine construct_cv_line_bdy_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_point_bdy_permutations allocate(cv_point_bdy_permutations(1)%p(1,1)) cv_point_bdy_permutations(1)%p=reshape((/& 1/),(/1,1/)) end subroutine construct_cv_point_bdy_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! subroutine construct_cv_hex_bdy_permutations allocate(cv_hex_bdy_permutations(1)%p(2,4)) cv_hex_bdy_permutations(1)%p=reshape((/& -1, -1, & 0, -1, & -1, 0, & 0, 0/),(/2,4/)) allocate(cv_hex_bdy_permutations(2)%p(2,4)) cv_hex_bdy_permutations(2)%p=reshape((/& 0, -1, & 1, -1, & 0, 0, & 1, 0/),(/2,4/)) allocate(cv_hex_bdy_permutations(3)%p(2,4)) cv_hex_bdy_permutations(3)%p=reshape((/& -1, 0, & 0, 0, & -1, 1, & 0, 1/),(/2,4/)) allocate(cv_hex_bdy_permutations(4)%p(2,4)) cv_hex_bdy_permutations(4)%p=reshape((/& 0, 0, & 1, 0, & 0, 1, & 1, 1/),(/2,4/)) end subroutine construct_cv_hex_bdy_permutations !< ------------------------------------------------- >! !< ------------------------------------------------- >! function make_face_generator(permutation, nodes, coords) result (generator) !!< Function hiding the fact that generators are dynamically sized. type(face_generator_type) :: generator type(corner_permutation_type), intent(in) :: permutation integer, dimension(:), intent(in) :: nodes real, dimension(:), intent(in) :: coords generator%permutation=>permutation%p allocate(generator%coords(size(coords))) generator%nodes=nodes generator%coords=coords end function make_face_generator subroutine expand_cv_faces_template(cvfaces, cv_temp, cvbdy_temp) ! Expand the given template into the cvfaces provided. type(cv_faces_type), intent(inout) :: cvfaces type(face_corner_template), intent(in) :: cv_temp, cvbdy_temp integer :: i, j, k type(face_generator_type), pointer :: lgen cvfaces%corners=0.0 cvfaces%neiloc=0 do i=1,size(cv_temp%generator) lgen=>cv_temp%generator(i) ! Permute coordinates and insert into cvloc%corners forall(j=1:size(lgen%permutation,1), & k=1:size(lgen%permutation,2), & lgen%permutation(j,k)/=0) ! The permutation stores both the permutation order and (for ! quads and hexs) the sign of the coordinate. cvfaces%corners(i,j,k)=sign(lgen%coords(abs(lgen%permutation(j,k))),& & real(lgen%permutation(j,k))) end forall cvfaces%neiloc(lgen%nodes(1),i)=lgen%nodes(2) cvfaces%neiloc(lgen%nodes(2),i)=lgen%nodes(1) end do cvfaces%scorners=0.0 cvfaces%sneiloc=0 do i=1,size(cvbdy_temp%generator) lgen=>cvbdy_temp%generator(i) ! Permute coordinates and insert into cvloc%corners forall(j=1:size(lgen%permutation,1), & k=1:size(lgen%permutation,2), & lgen%permutation(j,k)/=0) ! The permutation stores both the permutation order and (for ! quads and hexs) the sign of the coordinate. cvfaces%scorners(i,j,k)=sign(lgen%coords(abs(lgen%permutation(j,k))),& & real(lgen%permutation(j,k))) end forall cvfaces%sneiloc(lgen%nodes(1),i)=lgen%nodes(2) end do end subroutine expand_cv_faces_template end module cv_faces
lgpl-2.1
Gd58/gcc
gcc/testsuite/gfortran.dg/coarray_lock_3.f90
155
3087
! { dg-do compile } ! { dg-options "-fcoarray=single" } ! ! ! LOCK/LOCK_TYPE checks ! subroutine extends() use iso_fortran_env type t end type t type, extends(t) :: t2 ! { dg-error "coarray component, parent type .t. shall also have one" } type(lock_type), allocatable :: c(:)[:] end type t2 end subroutine extends module m use iso_fortran_env type t type(lock_type), allocatable :: x(:)[:] end type t end module m module m2 use iso_fortran_env type t2 type(lock_type), allocatable :: x ! { dg-error "Allocatable component x at .1. of type LOCK_TYPE must have a codimension" } end type t2 end module m2 module m3 use iso_fortran_env type t3 type(lock_type) :: x ! OK end type t3 end module m3 subroutine sub(x) use iso_fortran_env type(lock_type), intent(out) :: x[*] ! OK end subroutine sub subroutine sub1(x) ! { dg-error "is INTENT.OUT. and can thus not be an allocatable coarray or have coarray components" } use iso_fortran_env type(lock_type), allocatable, intent(out) :: x(:)[:] end subroutine sub1 subroutine sub2(x) ! { dg-error "is INTENT.OUT. and can thus not be an allocatable coarray or have coarray components" } use m type(t), intent(out) :: x end subroutine sub2 subroutine sub3(x) ! { dg-error "with coarray component shall be a nonpointer, nonallocatable scalar" } use m type(t), intent(inout) :: x[*] end subroutine sub3 subroutine sub4(x) use m3 type(t3), intent(inout) :: x[*] ! OK end subroutine sub4 subroutine lock_test use iso_fortran_env type t end type t type(lock_type) :: lock ! { dg-error "of type LOCK_TYPE or with subcomponent of type LOCK_TYPE must be a coarray" } end subroutine lock_test subroutine lock_test2 use iso_fortran_env implicit none type t end type t type(t) :: x type(lock_type), save :: lock[*],lock2(2)[*] lock(t) ! { dg-error "Syntax error in LOCK statement" } lock(x) ! { dg-error "must be a scalar of type LOCK_TYPE" } lock(lock) lock(lock2(1)) lock(lock2) ! { dg-error "must be a scalar of type LOCK_TYPE" } lock(lock[1]) ! OK end subroutine lock_test2 subroutine lock_test3 use iso_fortran_env type(lock_type), save :: a[*], b[*] a = b ! { dg-error "LOCK_TYPE in variable definition context" } b = lock_type() ! { dg-error "LOCK_TYPE in variable definition context" } print *, a ! { dg-error "cannot have PRIVATE components" } end subroutine lock_test3 subroutine lock_test4 use iso_fortran_env type(lock_type), allocatable :: A(:)[:] logical :: ob allocate(A(1)[*]) lock(A(1), acquired_lock=ob) unlock(A(1)) deallocate(A) end subroutine lock_test4 subroutine argument_check() use iso_fortran_env type(lock_type), SAVE :: ll[*] call no_interface(ll) ! { dg-error "Actual argument of LOCK_TYPE or with LOCK_TYPE component at .1. requires an explicit interface" } call test(ll) ! { dg-error "non-INTENT.INOUT. dummy .x. at .1., which is LOCK_TYPE or has a LOCK_TYPE component" } contains subroutine test(x) type(lock_type), intent(in) :: x[*] end subroutine test end subroutine argument_check
gpl-2.0
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/dec_structure_13.f90
29
1276
! { dg-do compile } ! { dg-options "-fdec-structure" } ! ! Verify that the comparisons in gfc_compare_derived_types can correctly ! match nested anonymous subtypes. ! subroutine sub0 (u) structure /t/ structure sub integer i end structure endstructure record /t/ u u.sub.i = 0 end subroutine sub0 subroutine sub1 () structure /t/ structure sub integer i end structure endstructure record /t/ u interface subroutine sub0 (u) ! regression: Interface mismatch.*Type mismatch structure /t/ structure sub integer i end structure endstructure record /t/ u end subroutine end interface call sub0(u) ! regression: Type mismatch in argument end subroutine subroutine sub2(u) structure /tu/ union map integer i end map map real r end map end union end structure record /tu/ u u.r = 1.0 end subroutine implicit none structure /t/ structure sub integer i end structure endstructure structure /tu/ union map integer i end map map real r end map end union end structure record /t/ u record /tu/ u2 call sub0(u) ! regression: Type mismatch in argument call sub1() call sub2(u2) end
gpl-2.0
brodeau/sosie
src/mod_akima_2d.f90
1
28268
MODULE MOD_AKIMA_2D !!----------------------------------------------------------------- !! A Method Of Bivariate Interpolation And Smooth !! Surface Fitting Based On Local Procedures !! !! Hiroshi AKIMA, 1974 !! !! author={Akima, H.}, !! title={A Method of Bivariate Interpolation and Smooth Surface Fitting !! Based on Local Procedures}, !! journal={Commun. ACM}, !! year={1974}, !! pages={18-20}, !! volume={17}, !! number={1} !! !! !! AUTHORS: !! Coded from scratch by Laurent BRODEAU, 2007 !! !! Stylish and more efficient method to solve the 16x16 linear system: !! Jean-Michel Brankart, October 2010 !! !! Last update: Laurent Brodeau, June 2014 !! !! Contact: https://github.com/brodeau/sosie !! !!----------------------------------------------------------------- USE mod_conf USE mod_manip, ONLY: FILL_EXTRA_BANDS USE io_ezcdf, ONLY: TEST_XYZ IMPLICIT NONE LOGICAL, PUBLIC, SAVE :: & & l_always_first_call = .FALSE. INTEGER, DIMENSION(:,:,:), ALLOCATABLE, SAVE :: ixy_pos !: table storing source/target grids mapping PRIVATE PUBLIC :: AKIMA_2D REAL(8), PARAMETER :: repsilon = 1.E-9 INTEGER, PARAMETER :: nsys = 16 !: Dimmension of the linear sytem to solve CONTAINS SUBROUTINE AKIMA_2D(k_ew_per, X10, Y10, Z1, X20, Y20, Z2, icall) !!================================================================ !! !! INPUT : k_ew_per : east-west periodicity !! k_ew_per = -1 --> no periodicity !! k_ew_per >= 0 --> periodicity with overlap of k_ew_per points !! X10 : 2D source longitude array (ni*nj) or (ni*1) (must be regular!) !! Y10 : 2D source latitude array (ni*nj) or (nj*1) (must be regular!) !! Z1 : source field on source grid !! !! X20 : 2D target longitude array (ni*nj) or (ni*1) (can be irregular) !! Y20 : 2D target latitude array (ni*nj) or (nj*1) (can be irregular) !! !! OUTPUT : !! Z2 : input field on target grid !! !! input (optional) : icall : if icall=1, will always force 'l_first_call_interp_routine' to .TRUE. !! !!================================================================ !! Input/Output arguments INTEGER, INTENT(in) :: k_ew_per REAL(8), DIMENSION(:,:), INTENT(in) :: X10, Y10 REAL(4), DIMENSION(:,:), INTENT(in) :: Z1 REAL(8), DIMENSION(:,:), INTENT(in) :: X20, Y20 REAL(4), DIMENSION(:,:), INTENT(out) :: Z2 INTEGER, OPTIONAL, INTENT(in) :: icall !! Local variables INTEGER :: nx1, ny1, nx2, ny2, ji, jj, kewp INTEGER, PARAMETER :: n_extd = 4 ! source grid extension INTEGER :: & & ji1, jj1, ji2, jj2, & & ni1, nj1 REAL(8), DIMENSION(nsys) :: vpl REAL(8), DIMENSION(:,:,:), ALLOCATABLE :: poly REAL(8), DIMENSION(:,:), ALLOCATABLE :: & & X1, Y1, X2, Y2, & & zFs , zXs , zYs REAL(8), DIMENSION(:,:), ALLOCATABLE :: slpx, slpy, slpxy REAL(8) :: & & px2, py2, & & min_lon1, max_lon1, min_lat1, max_lat1, & & min_lon2, max_lon2, min_lat2, max_lat2 REAL(8), DIMENSION(4) :: xy_range_src CHARACTER(len=2) :: ctype IF ( present(icall) ) THEN IF ( icall == 1 ) THEN l_first_call_interp_routine = .TRUE. l_always_first_call = .TRUE. END IF END IF !! Create 2D (ni*nj) arrays out of 1d (ni*1 and nj*1) arrays if needed: !! => TEST_XYZ tests if a 2D array is a true 2D array (NxM) or a fake (Nx1) !! and returns '1d' if it is a fake 2D array ctype = TEST_XYZ(X10, Y10, Z1) nx1 = SIZE(Z1,1) ny1 = SIZE(Z1,2) ALLOCATE ( X1(nx1,ny1) , Y1(nx1,ny1) ) IF ( ctype == '1d' ) THEN FORALL (jj = 1:ny1) X1(:,jj) = X10(:,1) FORALL (ji = 1:nx1) Y1(ji,:) = Y10(:,1) ELSE X1 = X10 ; Y1 = Y10 END IF ctype = '00' ctype = TEST_XYZ(X20, Y20, Z2) nx2 = SIZE(Z2,1) ny2 = SIZE(Z2,2) ALLOCATE ( X2(nx2,ny2) , Y2(nx2,ny2) ) IF ( ctype == '1d' ) THEN FORALL (jj=1:ny2) X2(:,jj) = X20(:,1) FORALL (ji=1:nx2) Y2(ji,:) = Y20(:,1) ELSE X2 = X20 ; Y2 = Y20 END IF !! S T A R T !! Extending the source 2D domain with a frame of 2 points: !! We extend initial 2D array with a frame, adding n_extd points in each !! dimension This is really needed specially for preserving good east-west !! perdiodicity... ni1 = nx1 + n_extd ; nj1 = ny1 + n_extd ALLOCATE ( zFs(ni1,nj1), zXs(ni1,nj1), zYs(ni1,nj1), & & slpx(ni1,nj1), slpy(ni1,nj1), slpxy(ni1,nj1), & & poly(ni1-1,nj1-1,nsys) ) CALL FILL_EXTRA_BANDS(k_ew_per, X1, Y1, REAL(Z1,8), zXs, zYs, zFs, is_orca_grid=i_orca_src) DEALLOCATE (X1, Y1) !! Computation of partial derivatives: !! * since we use extended arrays (2-point wide frame) we need to adapt E-W periodicity kewp = -1 IF( k_ew_per > -1 ) kewp = k_ew_per + 4 CALL SLOPES_AKIMA(kewp, zXs, zYs, zFs, slpx, slpy, slpxy) !! Polynome: CALL build_pol(zXs, zYs, zFs, slpx, slpy, slpxy, poly) DEALLOCATE ( slpx, slpy, slpxy ) !! Checking if the target grid does not overlap source grid : min_lon1 = minval(zXs) ; max_lon1 = maxval(zXs) min_lat1 = minval(zYs) ; max_lat1 = maxval(zYs) xy_range_src(:) = (/ min_lon1,max_lon1 , min_lat1,max_lat1 /) min_lon2 = MINVAL(X2) ; max_lon2 = MAXVAL(X2) min_lat2 = minval(Y2) ; max_lat2 = maxval(Y2) !! Doing the mapping once for all and saving into ixy_pos: IF ( l_first_call_interp_routine ) THEN ALLOCATE ( ixy_pos(nx2, ny2, 2) ) ixy_pos(:,:,:) = 0 CALL find_nearest_akima( zXs, zYs, xy_range_src, X2, Y2, ixy_pos ) END IF !! Loop on target domain: DO jj2 = 1, ny2 DO ji2 = 1, nx2 !! The coordinates of current target point are (px2,py2) : px2 = X2(ji2,jj2) ; py2 = Y2(ji2,jj2) !! Checking if this belongs to source domain : IF ( ((px2>=min_lon1).AND.(px2<=max_lon1)).AND.((py2>=min_lat1).AND.(py2<=max_lat1)) ) THEN !! We know the right location from time = 1 : ji1 = ixy_pos(ji2,jj2,1) jj1 = ixy_pos(ji2,jj2,2) !! It's time to interpolate: px2 = px2 - zXs(ji1,jj1) py2 = py2 - zYs(ji1,jj1) vpl = poly(ji1,jj1,:) Z2(ji2,jj2) = REAL( pol_val(px2, py2, vpl) , 4) ! back to real(4) ELSE Z2(ji2,jj2) = 0. ! point is not on source domain! END IF END DO END DO !! Deallocation : DEALLOCATE ( zFs , zXs , zYs, poly, X2, Y2 ) l_first_call_interp_routine = .FALSE. IF ( l_always_first_call ) THEN DEALLOCATE ( ixy_pos ) l_first_call_interp_routine = .TRUE. END IF END SUBROUTINE AKIMA_2D !! ######################## !! LOCAL PRIVATE ROUTINES : !! ######################## SUBROUTINE build_pol(ZX, ZY, ZF, sx, sy, sxy, XPLNM) !!================================================================== !! !! Compute the 16 coefficients of the polynomes used to interpolate !! !!================================================================== REAL(8), DIMENSION(:,:), INTENT(in) :: ZX, ZY, ZF, sx, sy, sxy REAL(8), DIMENSION(:,:,:), INTENT(out) :: XPLNM !! Local variables : !! ----------------- REAL(8), DIMENSION(:), ALLOCATABLE :: VX INTEGER :: nx, ny, ji, jj REAL(8) :: & & x, x2, x3, y, y2, y3, xy, & & b1, b2, b3, b4, b5, b6, b7, b8, & & b9, b10, b11, b12, b13, b14, b15, b16, & & c1, c2, c3, c4, c5, c6, c7, c8, & & c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, & & d1, d2, d3, d4, d5, d6, d7, d8, d9, & & f1, f2, f3, f4, f5, f6 nx = SIZE(ZF,1) ny = SIZE(ZF,2) ALLOCATE( VX(nsys) ) DO jj=1, ny-1 DO ji=1, nx-1 VX(:) = 0. !! Local dx and dy : x = ZX(ji+1,jj) - ZX(ji,jj) y = ZY(ji,jj+1) - ZY(ji,jj) x2 = x*x ; x3 = x2*x y2 = y*y ; y3 = y2*y xy = x*y !! Vector B, value at each points, d/dx, d/dy and d2/dxdy : b1 = ZF(ji,jj) ; b2 = ZF(ji+1,jj) ; b3 = ZF(ji+1,jj+1) ; b4 = ZF(ji,jj+1) b5 = sx(ji,jj) ; b6 = sx(ji+1,jj) ; b7 = sx(ji+1,jj+1) ; b8 = sx(ji,jj+1) b9 = sy(ji,jj) ; b10 = sy(ji+1,jj) ; b11 = sy(ji+1,jj+1) ; b12 = sy(ji,jj+1) b13 = sxy(ji,jj) ; b14 = sxy(ji+1,jj) ; b15 = sxy(ji+1,jj+1) ; b16 = sxy(ji,jj+1) ! Linear System 16x16 to be solved ( A.X = B ) ! ============================================ ! ! (/ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. /) ! (/ 0. 0. 0. x^3 0. 0. 0. x^2 0. 0. 0. x 0. 0. 0. 1. /) ! (/ x^3*y^3 x^3*y^2 x^3*y x^3 x^2*y^3 x^2*y^2 x^2*y x^2 x*y^3 x*y^2 x*y x y^3 y^2 y 1. /) ! (/ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. y^3 y^2 y 1. /) ! (/ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. /) ! (/ 0. 0. 0. 3*x^2 0. 0. 0. 2*x 0. 0. 0. 1. 0. 0. 0. 0. /) ! (/ 3*x^2*y^3 3*x^2*y^2 3*x^2*y 3*x^2 2*x*y^3 2*x*y^2 2*x*y 2*x y^3 y^2 y 1. 0. 0. 0. 0. /) ! A = (/ 0. 0. 0. 0. 0. 0. 0. 0. y^3 y^2 y 1. 0. 0. 0. 0. /) ! (/ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. /) ! (/ 0. 0. x^3 0. 0. 0. x^2 0. 0. 0. x 0. 0. 0. 1. 0. /) ! (/ 3*x^3*y^2 2*x^3*y x^3 0. 3*x^2*y^2 2*x^2*y x^2 0. 3*x*y^2 2*x*y x 0. 3*y^2 2*y 1. 0. /) ! (/ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 3*y^2 2*y 1. 0. /) ! (/ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. /) ! (/ 0. 0. 3*x^2 0. 0. 0. 2*x 0. 0. 0. 1. 0. 0. 0. 0. 0. /) ! (/ 9*x^2*y^2 6*x^2*y 3*x^2 0. 6*x*y^2 4*x*y 2*x 0. 3*y^2 2*y 1. 0. 0. 0. 0. 0. /) ! (/ 0. 0. 0. 0. 0. 0. 0. 0. 3*y^2 2*y 1. 0. 0. 0. 0. 0. /) ! ! X = (/ a33, a32, a31, a30, a23, a22, a21, a20, a13, a12, a11, a10, a03, a02, a01, a00 /) ! ! B = (/ b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16 /) !! I keep Jean-Michel's comments in french cause I just love them, !! they are the soul of this code! They are followed my my english !! translation. Note that Jean-Michel's english is excellent but he !! just thought this would stay between us. !! /laurent !! 1) D'abord, calculer les 4 inconnues (du système à 16 éqs) qui !! dépendent directement des second membres bj (avant de faire la !! modification des bj): !! 1) First, calculate the 4 unknowns (of the 16-eq. system) that !! directly depend on second members bj, and do this before modifying !! bj : VX(11) = b13 ; VX(12) = b5 ; VX(15) = b9 ; VX(16) = b1 !! 2) Ensuite, mettre à échelle les seconds membres bj !! (b1 à b4 restent inchangés): !! 2) Then, scale bj second members (b1 to b4 remain unchanged): b5 = x*b5 ; b6 = x*b6 ; b7 = x*b7 ; b8 = x*b8 b9 = y*b9 ; b10 = y*b10 ; b11 = y*b11 ; b12 = y*b12 b13 = xy*b13 ; b14 = xy*b14 ; b15 = xy*b15 ; b16 = xy*b16 !! 3) Puis, résoudre le système avec x=1 et y=1 (ou bien utiliser ta !! solution symbolique avec x=1 et y=1), en remarquant que, dans ce !! cas particulier, certaines combinaisons apparaissent souvent, et !! qu'il vaut mieux les calculer d'abord: !! 3) Then, solve the system with x=1 and y=1, taking advantage of the !! fact, that in that particular case, some combinations are often !! appearing and that it is therefore better to calculate them before: !! a) Premierement: c1 = b1-b2 ; c2 = b3-b4 ; c3 = b5+b6 c4 = b7+b8 ; c5 = b9-b10 ; c6 = b11-b12 c7 = b13+b14 ; c8 = b15+b16 ; c9 = 2*b5+b6 c10 = b7+2*b8 ; c11 = 2*b13+b14 ; c12 = b15+2*b16 c13 = b5-b8 ; c14 = b1-b4 ; c15 = b13+b16 c16 = 2*b13 + b16 ; c17 = b9+b12 ; c18 = 2*b9+b12 !! b) Deuxiemement: d1 = c1+c2 ; d2 = c3-c4 ; d3 = c5-c6 d4 = c7+c8 ; d5 = c9-c10 ; d6 = 2*c5-c6 d7 = 2*c7+c8 ; d8 = c11+c12 ; d9 = 2*c11+c12 !! c) Troisiemement: f1 = 2*d1+d2 ; f2 = 2*d3+d4 ; f3 = 2*d6+d7 f4 = 3*d1+d5 ; f5 = 3*d3+d8 ; f6 = 3*d6+d9 !! d) De sorte que la solution s'écrit simplement: !! d) So that the solution simply writes: VX(1) = 2*f1+f2 ; VX(2) = -(3*f1+f3) ; VX(3) = 2*c5+c7 VX(4) = 2*c1+c3 ; VX(5) = -(2*f4+f5) ; VX(6) = 3*f4+f6 VX(7) = -(3*c5+c11) ; VX(8) = -(3*c1+c9) ; VX(9) = 2*c13+c15 VX(10) = -(3*c13+c16) ; VX(13) = 2*c14+c17 ; VX(14) = -(3*c14+c18) !! On remarque même que les seules mulitplications qui apparaissent !! sont des doublements ou des triplements, qu'on pourrait donc !! remplacer par des additions, par ex.: cc14=c14+c14, puis ccc14=cc14+c14, !! et donc résoudre le systeme simplifié sans aucune multiplication !! ni division, ce qui est tout de même assez émouvant :-) !! One can even notice that the only multiplications that show up are !! multiplications by 2 or by 3. It would therefore be possible to !! replace them by additions, for example: cc14=c14+c14, then !! ccc14=cc14+c14, and therefore solve the simplified system without !! any multiplication and division, which I found rather touching :-) !! 4) Et finalement, il ne reste plus qu'à remettre à échelle la solution: !! 4) Finally, all that remains to be done is to scale back the solution: VX(1)=VX(1)/(x3*y3) ; VX(2)=VX(2)/(x3*y2) ; VX(3)=VX(3)/(x3*y) ; VX(4)=VX(4)/x3 VX(5)=VX(5)/(x2*y3) ; VX(6)=VX(6)/(x2*y2) ; VX(7)=VX(7)/(x2*y) ; VX(8)=VX(8)/x2 VX(9)=VX(9)/(x*y3) ; VX(10)=VX(10)/(x*y2); VX(13)=VX(13)/y3 ; VX(14)=VX(14)/y2 !! Bien sûr, je n'ai pas vérifié et j'ai pu faire des erreurs de calcul !! ou de recopiage, mais le principe me semble bon, et on aboutit !! à un nombre d'opérations: !! Etape 2: 9x !! Etape 3: 45+, 26x (ou même simplement 69+) !! Etape 4: 8x, 12/ !! Soit un total de: 45+, 43x, 12/ pour résoudre le systeme, !! au lieu de: 84+, 140x, 16/ pour la solution symbolique de SOSIE. !! !! Je suis conscient que ça ne sert sans doute pas à grand chose !! car le calcul n'est fait que pour chaque point de la grille de départ !! (si je comprends bien) et ce coût n'était probablement déjà plus dominant. !! Il était déjà largement dépassé (j'imagine) par le coût d'évaluation !! des polynômes aux noeuds de la grille d'arrivée, du moins quand !! sa résolution est beaucoup plus fine que celle de la grille de départ. !! Number of operations: !! Point 2: 9x !! Point 3: 45+, 26x (or even possibly 69+) !! Point 4: 8x, 12/ !! A total of 45+, 43x and 12/ to solve the system !! Instead of 84+, 140x and 16/ for the original symbolic solution !! Storing the 16 coefficients of the polynome for point [ji,jj] : XPLNM(ji,jj,:) = VX(:) END DO END DO DEALLOCATE( VX ) END SUBROUTINE build_pol FUNCTION pol_val(x, y, V) !!====================================================== !! !! Give value of polynome pol_val(x,y), polynome coefficients !! are stored in to vector V !! !! Optimizing by using Horner's scheme (http://en.wikipedia.org/wiki/Horner_scheme) !! !! "It has been shown that the Horner scheme is optimal, !! in the sense that any algorithm to evaluate an arbitrary polynomial !! must use at least as many operations. !! That the number of additions required is minimal was shown !! by Alexander Ostrowski in 1954; that the number of multiplications !! is minimal by Victor Pan." !! !! => we perform the minimum number of multiplications possible: 15 ! !! !! Big thanks to Jean-Michel Brankart (Jean-Michel.Brankart@hmg.inpg.fr) for !! adapting this scheme to Sosie. !! !!===================================================================== REAL(8) :: pol_val REAL(8), INTENT(in) :: x, y REAL(8), DIMENSION(nsys), INTENT(in) :: V REAL(8) :: p1, p2, p3, p4 p1 = ( ( V(1) * y + V(2) ) * y + V(3) ) * y + V(4) p2 = ( ( V(5) * y + V(6) ) * y + V(7) ) * y + V(8) p3 = ( ( V(9) * y + V(10) ) * y + V(11) ) * y + V(12) p4 = ( ( V(13) * y + V(14) ) * y + V(15) ) * y + V(16) pol_val = ( ( p1 * x + p2 ) * x + p3 ) * x + p4 END FUNCTION pol_val SUBROUTINE SLOPES_AKIMA(k_ew, XX, XY, XF, dFdX, dFdY, d2FdXdY) !! Slopes ~ partial derivatives of a field ZF according to Akima method !! given on a regular gird !! !! k_ew : east-west periodicity on the source file/grid !! k_ew = -1 --> no east-west periodicity (along x) !! k_ew >= 0 --> east-west periodicity with overlap of k_ew points (along x) !! lulu INTEGER, INTENT(in) :: k_ew REAL(8), DIMENSION(:,:), INTENT(in) :: XX, XY, XF REAL(8), DIMENSION(:,:), INTENT(out) :: dFdX, dFdY, d2FdXdY !! Local variables : REAL(8), DIMENSION(:,:), ALLOCATABLE :: ZX, ZY, ZF INTEGER :: nx, ny, ji, jj, ip1, ip2, jp1, jp2 REAL(8) :: m1, m2, m3, m4, rx REAL(8) :: Wx2, Wx3, Wy2, Wy3 REAL(8) :: d22, e22, d23, e23, d42, e32, d43, e33 dFdX = 0. dFdY = 0. d2FdXdY = 0. nx = SIZE(XF,1) ny = SIZE(XF,2) !! Extended arrays with a frame of 2 points... ALLOCATE ( ZX(nx+4,ny+4), ZY(nx+4,ny+4), ZF(nx+4,ny+4) ) ! We don't want any smart extrapolation in the north because it has already be done... ! (and `k_ew` should take into account that we are dealing with arrays extended with 2-point frame) CALL FILL_EXTRA_BANDS(k_ew, XX, XY, XF, ZX, ZY, ZF, is_orca_grid=0) !debug: !CALL DUMP_FIELD(REAL(ZX,4), 'slopes_akima_extended_LON.nc', 'lon') !lolo: bug corners!!! !CALL DUMP_FIELD(REAL(ZY,4), 'slopes_akima_extended_LAT.nc', 'lat') !CALL DUMP_FIELD(REAL(ZF,4), 'slopes_akima_extended_FLD.nc', 'field') !STOP'SLOPES_AKIMA' !debug. !! Treating middle of array ( at least 2 points away from the bordures ) : !!------------------------------------------------------------------------ DO jj=1, ny DO ji=1, nx ! Initialisation MB Problem when they are close to zero but not zero m1=0. ; m2=0. ; m3=0. ; m4=0. ; Wx2=0. ; Wx3=0. ; Wy2=0. ; Wy3=0. ip1 = ji+1 ip2 = ji+2 jp1 = jj+1 jp2 = jj+2 !! SLOPE / X : !! *********** rx = ZX(ip1,jp2) - ZX(ji, jp2) m1 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m1 = (ZF(ip1,jp2) - ZF(ji, jp2)) / m1 rx = ZX(ip2,jp2) - ZX(ip1,jp2) m2 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m2 = (ZF(ip2,jp2) - ZF(ip1,jp2)) / m2 rx = ZX(ji+3,jp2) - ZX(ip2,jp2) m3 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m3 = (ZF(ji+3,jp2) - ZF(ip2,jp2)) / m3 rx = ZX(ji+4,jp2) - ZX(ji+3,jp2) m4 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m4 = (ZF(ji+4,jp2) - ZF(ji+3,jp2)) / m4 IF ( (m1 == m2).and.(m3 == m4) ) THEN dFdX(ji,jj) = 0.5*(m2 + m3) ELSE Wx2 = ABS(m4 - m3) Wx3 = ABS(m2 - m1) dFdX(ji,jj) = ( Wx2*m2 + Wx3*m3 ) / ( Wx2 + Wx3 ) END IF !! SLOPE / Y : !! *********** rx = ZY(ip2,jp1) - ZY(ip2,jj ) m1 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m1 = (ZF(ip2,jp1) - ZF(ip2,jj )) / m1 rx = ZY(ip2,jp2) - ZY(ip2,jp1) m2 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m2 = (ZF(ip2,jp2) - ZF(ip2,jp1)) / m2 rx = ZY(ip2,jj+3) - ZY(ip2,jp2) m3 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m3 = (ZF(ip2,jj+3) - ZF(ip2,jp2)) / m3 rx = ZY(ip2,jj+4) - ZY(ip2,jj+3) m4 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) m4 = (ZF(ip2,jj+4) - ZF(ip2,jj+3)) / m4 IF ( (m1 == m2).and.(m3 == m4) ) THEN dFdY(ji,jj) = 0.5*(m2 + m3) ELSE Wy2 = ABS(m4 - m3) Wy3 = ABS(m2 - m1) dFdY(ji,jj) = ( Wy2*m2 + Wy3*m3 ) / ( Wy2 + Wy3 ) END IF !! CROSS DERIVATIVE /XY : !! ********************** !! d22 = d(i-1,j-1) = [ z(i-1,j)-z(i-1,j-1) ] / [ y(j) - y(j-1) ] rx = ZY(ip1,jp2) - ZY(ip1,jp1) d22 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) d22 = (ZF(ip1,jp2) - ZF(ip1,jp1)) / d22 !! d23 = d(i-1 , j) = [ z(i-1,j+1)-z(i-1,j) ] / [ y(j+1) - y(j) ] rx = ZY(ip1,jj+3) - ZY(ip1,jp2) d23 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) d23 = (ZF(ip1,jj+3) - ZF(ip1,jp2)) / d23 !! d42 = d(i+1 , j-1) = [ z(i+1 , j) - z(i+1 , j-1) ] / [ y(j) - y(j-1) ] rx = ZY(ji+3,jp2) - ZY(ji+3,jp1) d42 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) d42 = (ZF(ji+3,jp2) - ZF(ji+3,jp1)) / d42 !! d43 = d(i+1 , j) = [ z(i+1 , j+1)-z(i+1 , j) ] / [ y(j+1) - y(j) ] rx = ZY(ji+3,jj+3) - ZY(ji+3,jp2) d43 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) d43 = (ZF(ji+3,jj+3) - ZF(ji+3,jp2)) / d43 !! e22 = [ m2 - d22 ] / [ x(i) - x(i-1) ] rx = ZX(ip2,jp1) - ZX(ip1,jp1) e22 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) e22 = ( m2 - d22 ) / e22 !! e23 = [ m3 - d23 ] / [ x(i) - x(i-1) ] rx = ZX(ip2,jp2) - ZX(ip1,jp2) e23 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) e23 = ( m3 - d23 ) / e23 !! e32 = [ d42 - m2 ] / [ x(i+1) - x(i) ] rx = ZX(ji+3,jp2) - ZX(ip2,jp2) e32 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) e32 = ( d42 - m2 ) / e32 !! e33 = [ d43 - m3 ] / [ x(i+1) - x(i) ] rx = ZX(ji+3,jp2) - ZX(ip2,jp2) e33 = SIGN(1.d0 , rx) * MAX(ABS(rx),repsilon) e33 = ( d43 - m3 ) / e33 IF ( ((Wx2 == 0).and.(Wx3 == 0)).or.((Wy2 == 0).and.(Wy3 == 0)) ) THEN IF ( (Wx2 == 0).and.(Wx3 == 0) ) THEN Wx2 = 1. ; Wx3 = 1. END IF IF ( (Wy2 == 0).and.(Wy3 == 0) ) THEN Wy2 = 1. ; Wy3 = 1. END IF END IF d2FdXdY(ji,jj) = ( Wx2*(Wy2*e22 + Wy3*e23) + Wx3*(Wy2*e32 + Wy3*e33) ) & & / ( (Wx2 + Wx3) * (Wy2 + Wy3) ) END DO END DO DEALLOCATE ( ZX, ZY, ZF ) !debug: !CALL DUMP_FIELD(REAL(dFdX,4), 'slopes_akima_extended_dFdX.nc', 'dFdX') !CALL DUMP_FIELD(REAL(dFdY,4), 'slopes_akima_extended_dFdY.nc', 'dFdX') !CALL DUMP_FIELD(REAL(d2FdXdY,4), 'slopes_akima_extended_d2FdXdY.nc', 'd2FdXdY') !STOP'SLOPES_AKIMA' !debug. END SUBROUTINE SLOPES_AKIMA SUBROUTINE find_nearest_akima( plon_src, plat_src, pxyr_src, plon_trg, plat_trg, ixyp_trg ) !!--------------------------------------------------------------------------------------- !! Laboriuously scanning the entire source grid to find location of treated point !!--------------------------------------------------------------------------------------- REAL(8), DIMENSION(:,:) , INTENT(in) :: plon_src, plat_src REAL(8), DIMENSION(4) , INTENT(in) :: pxyr_src ! (/ lon_min,lon_max, lat_min,lat_max /) REAL(8), DIMENSION(:,:) , INTENT(in) :: plon_trg, plat_trg INTEGER, DIMENSION(:,:,:), INTENT(out) :: ixyp_trg INTEGER :: jis, jjs, jit, jjt, nxs, nys, nxt, nyt REAL(8) :: pxt, pyt LOGICAL :: l_x_found, l_y_found nxs = SIZE(plon_src,1) nys = SIZE(plon_src,2) nxt = SIZE(ixyp_trg,1) nyt = SIZE(ixyp_trg,2) !! Loop on target domain: DO jjt = 1, nyt DO jit = 1, nxt jis = 1 jjs = 1 l_x_found = .FALSE. l_y_found = .FALSE. pxt = plon_trg(jit,jjt) pyt = plat_trg(jit,jjt) !! Only searching if inside source domain: IF ( ((pxt>=pxyr_src(1)).AND.(pxt<=pxyr_src(2))).AND.((pyt>=pxyr_src(3)).AND.(pyt<=pxyr_src(4))) ) THEN DO WHILE ( .NOT. (l_x_found .AND. l_y_found) ) l_x_found = .FALSE. DO WHILE ( .NOT. l_x_found ) IF (jis < nxs) THEN IF ((plon_src(jis,jjs) <= pxt).and.(plon_src(jis+1,jjs) > pxt)) THEN l_x_found = .TRUE. ELSE jis = jis+1 END IF ELSE ! jis = nxs jis = jis-1 ! we are at the top need to use former pol. l_x_found = .TRUE. END IF END DO l_y_found = .FALSE. DO WHILE ( .NOT. l_y_found ) IF ( jjs < nys ) THEN IF ((plat_src(jis,jjs) <= pyt).and.(plat_src(jis,jjs+1) > pyt)) THEN l_y_found = .TRUE. ELSE jjs = jjs + 1 l_x_found = .FALSE. l_y_found = .TRUE. ! just so that we exit the loop on l_y_found END IF ELSE ! jjs == nys jjs = nys-1 ! we are using polynome at (ji,nys-1) l_y_found = .TRUE. ! for extreme right boundary END IF END DO END DO !DO WHILE ( .NOT. (l_x_found .AND. l_y_found) ) ixyp_trg(jit,jjt,:) = (/ jis, jjs /) END IF !IF ( ((pxt>=pxyr_src(1)).AND.(pxt<=pxyr_src(2))).AND.((pyt>=pxyr_src(3)).AND.(pyt<=pxyr_src(4))) ) END DO !DO jit = 1, nxt END DO !DO jjt = 1, nyt END SUBROUTINE find_nearest_akima END MODULE MOD_AKIMA_2D
gpl-3.0
Gd58/gcc
gcc/testsuite/gfortran.dg/parameter_array_init_2.f90
171
1056
! { dg-do run } ! { dg-options "-std=gnu" } ! suppress the warning about line 15 ! Thrashes the fix for PR29400, where the scalar initializers ! were not expanded to arrays with the appropriate shape. ! ! Contributed by Francois-Xavier Coudert <fxcoudert@gcc.gnu.org> ! integer,parameter :: i(1,1) = 0, j(2) = 42 if (any (maxloc(j+j,mask=(j==2)) .ne. 0)) call abort () if (size(j+j) .ne. 2) call abort () if (minval(j+j) .ne. 84) call abort () if (minval(j,mask=(j==2)) .ne. huge (j)) call abort () if (maxval(j+j) .ne. 84) call abort () if (maxval(j,mask=(j==2)) .ne. -huge (j)-1) call abort () if (sum(j,mask=j==2) .ne. 0) call abort () if (sum(j+j) .ne. 168) call abort () if (product(j+j) .ne. 7056) call abort () if (any(ubound(j+j) .ne. 2)) call abort () if (any(lbound(j+j) .ne. 1)) call abort () if (dot_product(j+j,j) .ne. 7056) call abort () if (dot_product(j,j+j) .ne. 7056) call abort () if (count(i==1) .ne. 0) call abort () if (any(i==1)) call abort () if (all(i==1)) call abort () end
gpl-2.0
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/complex_read.f90
174
1314
! { dg-do run { target fd_truncate } } ! Test of the fix to the bug in NIST fm906.for. ! Contributed by Paul Thomas <pault@gcc.gnu.org> ! program complex_read complex :: a open (10, status="scratch") ! Test that we have not broken the one line form. write (10, *) " ( 0.99 , 9.9 )" rewind (10) read (10,*) a if (a.ne.(0.99, 9.90)) call abort () ! Test a new record after the.comma (the original bug). rewind (10) write (10, *) " ( 99.0 ," write (10, *) " 999.0 )" rewind (10) read (10,*) a if (a.ne.(99.0, 999.0)) call abort () ! Test a new record before the.comma rewind (10) write (10, *) " ( 0.99 " write (10, *) " , 9.9 )" rewind (10) read (10,*) a if (a.ne.(0.99, 9.90)) call abort () ! Test a new records before and after the.comma rewind (10) write (10, *) " ( 99.0 " write (10, *) ", " write (10, *) " 999.0 )" rewind (10) read (10,*) a if (a.ne.(99.0, 999.0)) call abort () ! Test a new records and blank records before and after the.comma rewind (10) write (10, *) " ( 0.99 " write (10, *) " " write (10, *) ", " write (10, *) " " write (10, *) " 9.9 )" rewind (10) read (10,*) a if (a.ne.(0.99, 9.9)) call abort () close (10) end program complex_read
gpl-2.0
rgwan/gcc
libgomp/testsuite/libgomp.fortran/allocatable9.f90
102
6972
! { dg-do run } integer, allocatable :: a, b(:), c(:,:) logical :: l if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort !$omp parallel private (a, b, c) if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort allocate (a, b(-7:-1), c(2:3, 3:5)) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 7) call abort if (lbound (b, 1) /= -7 .or. ubound (b, 1) /= -1) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 2 .or. size (c, 2) /= 3) call abort if (lbound (c, 1) /= 2 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 3 .or. ubound (c, 2) /= 5) call abort a = 4 b = 3 c = 2 !$omp end parallel if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort !$omp parallel firstprivate (a, b, c) if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort allocate (a, b(-7:-1), c(2:3, 3:5)) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 7) call abort if (lbound (b, 1) /= -7 .or. ubound (b, 1) /= -1) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 2 .or. size (c, 2) /= 3) call abort if (lbound (c, 1) /= 2 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 3 .or. ubound (c, 2) /= 5) call abort a = 4 b = 3 c = 2 !$omp end parallel if (allocated (a) .or. allocated (b) .or. allocated (c)) call abort allocate (a, b(6:9), c(3, 8:9)) a = 2 b = 4 c = 5 if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 4) call abort if (lbound (b, 1) /= 6 .or. ubound (b, 1) /= 9) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 8 .or. ubound (c, 2) /= 9) call abort !$omp parallel firstprivate (a, b, c) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 4) call abort if (lbound (b, 1) /= 6 .or. ubound (b, 1) /= 9) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 8 .or. ubound (c, 2) /= 9) call abort if (a /= 2 .or. any (b .ne. 4) .or. any (c .ne. 5)) call abort deallocate (a) if (allocated (a)) call abort allocate (a) a = 8 b = (/ 1, 2, 3 /) c = reshape ((/ 1, 2, 3, 4, 5, 6, 7, 8 /), (/ 2, 4 /)) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 3) call abort if (lbound (b, 1) /= 1 .or. ubound (b, 1) /= 3) call abort if (.not.allocated (c) .or. size (c) /= 8) call abort if (size (c, 1) /= 2 .or. size (c, 2) /= 4) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 2) call abort if (lbound (c, 2) /= 1 .or. ubound (c, 2) /= 4) call abort if (a /= 8 .or. b(2) /= 2 .or. c(1, 2) /= 3) call abort !$omp end parallel if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 4) call abort if (lbound (b, 1) /= 6 .or. ubound (b, 1) /= 9) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 8 .or. ubound (c, 2) /= 9) call abort if (a /= 2 .or. any (b .ne. 4) .or. any (c .ne. 5)) call abort l = .false. !$omp parallel sections lastprivate (a, b, c) firstprivate (l) !$omp section if (.not.allocated (a)) call abort if (l) then if (.not.allocated (b) .or. size (b) /= 6) call abort if (lbound (b, 1) /= 1 .or. ubound (b, 1) /= 6) call abort if (.not.allocated (c) .or. size (c) /= 8) call abort if (size (c, 1) /= 4 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 4) call abort if (lbound (c, 2) /= 1 .or. ubound (c, 2) /= 2) call abort if (a /= 12 .or. b(2) /= 8 .or. c(1, 2) /= 5) call abort else if (.not.allocated (b) .or. size (b) /= 4) call abort if (lbound (b, 1) /= 6 .or. ubound (b, 1) /= 9) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 8 .or. ubound (c, 2) /= 9) call abort end if l = .true. deallocate (a) if (allocated (a)) call abort allocate (a) a = 8 b = (/ 1, 2, 3 /) c = reshape ((/ 1, 2, 3, 4, 5, 6, 7, 8 /), (/ 2, 4 /)) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 3) call abort if (lbound (b, 1) /= 1 .or. ubound (b, 1) /= 3) call abort if (.not.allocated (c) .or. size (c) /= 8) call abort if (size (c, 1) /= 2 .or. size (c, 2) /= 4) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 2) call abort if (lbound (c, 2) /= 1 .or. ubound (c, 2) /= 4) call abort if (a /= 8 .or. b(2) /= 2 .or. c(1, 2) /= 3) call abort !$omp section if (.not.allocated (a)) call abort if (l) then if (.not.allocated (b) .or. size (b) /= 3) call abort if (lbound (b, 1) /= 1 .or. ubound (b, 1) /= 3) call abort if (.not.allocated (c) .or. size (c) /= 8) call abort if (size (c, 1) /= 2 .or. size (c, 2) /= 4) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 2) call abort if (lbound (c, 2) /= 1 .or. ubound (c, 2) /= 4) call abort if (a /= 8 .or. b(2) /= 2 .or. c(1, 2) /= 3) call abort else if (.not.allocated (b) .or. size (b) /= 4) call abort if (lbound (b, 1) /= 6 .or. ubound (b, 1) /= 9) call abort if (.not.allocated (c) .or. size (c) /= 6) call abort if (size (c, 1) /= 3 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 3) call abort if (lbound (c, 2) /= 8 .or. ubound (c, 2) /= 9) call abort end if l = .true. deallocate (a) if (allocated (a)) call abort allocate (a) a = 12 b = (/ 9, 8, 7, 6, 5, 4 /) c = reshape ((/ 1, 2, 3, 4, 5, 6, 7, 8 /), (/ 4, 2 /)) if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 6) call abort if (lbound (b, 1) /= 1 .or. ubound (b, 1) /= 6) call abort if (.not.allocated (c) .or. size (c) /= 8) call abort if (size (c, 1) /= 4 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 4) call abort if (lbound (c, 2) /= 1 .or. ubound (c, 2) /= 2) call abort if (a /= 12 .or. b(2) /= 8 .or. c(1, 2) /= 5) call abort !$omp end parallel sections if (.not.allocated (a)) call abort if (.not.allocated (b) .or. size (b) /= 6) call abort if (lbound (b, 1) /= 1 .or. ubound (b, 1) /= 6) call abort if (.not.allocated (c) .or. size (c) /= 8) call abort if (size (c, 1) /= 4 .or. size (c, 2) /= 2) call abort if (lbound (c, 1) /= 1 .or. ubound (c, 1) /= 4) call abort if (lbound (c, 2) /= 1 .or. ubound (c, 2) /= 2) call abort if (a /= 12 .or. b(2) /= 8 .or. c(1, 2) /= 5) call abort end
gpl-2.0
jrper/fluidity
femtools/tests/test_scalar_field_view.F90
7
1136
subroutine test_scalar_field_view use fields use state_module use vtk_interfaces use unittest_tools implicit none type(state_type) :: state type(scalar_field), pointer :: x integer :: stat logical :: allocated logical :: fail call vtk_read_state("data/pseudo2d.vtu", state) x => extract_scalar_field(state, "Coordinatz%1", stat=stat, allocated=allocated) ! should fail fail = (stat == 0 .or. allocated) call report_test("[scalar field view]", fail, .false., "Searching for a component of a nonexistant field is a problem.") x => extract_scalar_field(state, "Coordinate%10", stat=stat, allocated=allocated) ! should fail fail = (stat == 0 .or. allocated) call report_test("[scalar field view]", fail, .false., "Searching for a nonexistant component of a field is a problem.") x => extract_scalar_field(state, "Coordinate%1", stat=stat, allocated=allocated) ! should work fail = (stat /= 0 .or. (allocated .eqv. .false.) .or. (.not. associated(x))) call report_test("[scalar field view]", fail, .false., "Searching for a component of a field should work.") end subroutine test_scalar_field_view
lgpl-2.1
jrper/fluidity
sediments/Sediment_Diagnostics.F90
4
32168
! Copyright (C) 2006-2009 Imperial College London and others. ! ! Please see the AUTHORS file in the main source directory for a full list ! of copyright holders. ! ! Prof. C Pain ! Applied Modelling and Computation Group ! Department of Earth Science and Engineering ! Imperial College London ! ! amcgsoftware@imperial.ac.uk ! ! 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, ! version 2.1 of the License. ! ! 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ! USA #include "fdebug.h" module sediment_diagnostics use fldebug use global_parameters, only:FIELD_NAME_LEN, OPTION_PATH_LEN, dt, timestep use futils, only: int2str use vector_tools use quadrature use elements use spud use sparse_tools use fetools use fields use state_module use fefields use boundary_conditions use sediment, only: get_n_sediment_fields, get_sediment_item implicit none private public calculate_sediment_flux, calculate_sediment_sinking_velocity,& & calculate_sediment_active_layer_d50, calculate_sediment_active_layer_sigma,& & calculate_sediment_active_layer_volume_fractions contains subroutine calculate_sediment_flux(state) !!< Calculate the advected flux of the sediment through the surfaces of !!< the domain. !!< This is determined based upon a fixed theta of 0.5 !!< Currently erosion bc is calculated explicitly and the value is consistent here type(state_type), intent(inout) :: state type(mesh_type), dimension(:), allocatable :: surface_mesh type surface_nodes_array integer, dimension(:), pointer :: nodes end type surface_nodes_array type(surface_nodes_array), dimension(:), allocatable :: surface_nodes type(vector_field), pointer :: X, old_U, new_U, gravity type(scalar_field), dimension(:), allocatable :: deposited_sediment, erosion type(scalar_field), pointer :: erosion_flux, bedload_field& &, old_sediment_field, new_sediment_field, sink_U, diagnostic_field type(vector_field) :: U type(scalar_field) :: masslump, sediment_field integer :: n_sediment_fields,& & i_field, i_bcs, i_node, ele, n_bcs, stat integer, dimension(2) :: surface_id_count integer, dimension(:), allocatable :: surface_ids integer, dimension(:), pointer :: to_nodes, surface_element_list real, dimension(:), allocatable :: values character(len=FIELD_NAME_LEN) :: bc_name, bc_type character(len=OPTION_PATH_LEN) :: bc_path ewrite(1,*) "In calculate_sediment_bedload" ! obtain some required model variables n_sediment_fields = get_n_sediment_fields() if (n_sediment_fields == 0) return X => extract_vector_field(state, "Coordinate") gravity => extract_vector_field(state, "GravityDirection") new_U => extract_vector_field(state, "Velocity") old_U => extract_vector_field(state, "OldVelocity") call allocate(U, new_U%dim, new_U%mesh, name="CNVelocity") call zero(U) call addto(U, old_U, 0.5) call addto(U, new_U, 0.5) ! allocate space for erosion and deposit field arrays allocate(erosion(n_sediment_fields)) allocate(deposited_sediment(n_sediment_fields)) allocate(surface_mesh(n_sediment_fields)) allocate(surface_nodes(n_sediment_fields)) ! first loop obtains eroded sediment quantities from reentrainment bc's (calculated ! in sediment::set_sediment_reentrainment) erosion_fields_loop: do i_field=1, n_sediment_fields ! obtain scalar fields for this sediment class call get_sediment_item(state, i_field, new_sediment_field) call get_sediment_item(state, i_field, "Bedload", bedload_field) ! generate a surface mesh for this field call create_surface_mesh(surface_mesh(i_field), surface_nodes(i_field)%nodes, & & mesh=bedload_field%mesh, name='SurfaceMesh') ! allocate a field that will hold the quantity of sediment eroded from the bed in ! this timestep call allocate(erosion(i_field), surface_mesh(i_field), "ErosionAmount") call zero(erosion(i_field)) ! get boundary condition path and number of boundary conditions bc_path = trim(new_sediment_field%option_path)//'/prognostic/boundary_conditions' n_bcs = option_count(bc_path) ! Loop over boundary conditions for field do i_bcs=0, n_bcs-1 ! Get name and type of boundary condition call get_option(trim(bc_path)//"["//int2str(i_bcs)//"]"//"/name", bc_name) call get_option(trim(bc_path)//"["//int2str(i_bcs)//"]"//"/type[0]/name", bc_type) ! find reentrainment boundary condition (if there is one) if ((trim(bc_type) .eq. "sediment_reentrainment")) then ! get boundary condition info call get_boundary_condition(new_sediment_field, name=bc_name, type=bc_type, & surface_element_list=surface_element_list) ! get erosion flux erosion_flux => extract_surface_field(new_sediment_field, bc_name=bc_name,& & name="value") ! set erosion field values allocate(values(erosion(i_field)%mesh%shape%loc)) do ele=1,ele_count(erosion_flux) to_nodes => ele_nodes(erosion(i_field), surface_element_list(ele)) values = ele_val(erosion_flux,ele) do i_node=1,size(to_nodes) call set(erosion(i_field),to_nodes(i_node),values(i_node)) end do end do call scale(erosion(i_field),dt) deallocate(values) end if end do end do erosion_fields_loop ! second loop calculates the amount of sediment that has been deposited during the ! timestep deposit_fields_loop: do i_field=1, n_sediment_fields ! obtain scalar fields for this sediment class call get_sediment_item(state, i_field, old_sediment_field, old = .true.) call get_sediment_item(state, i_field, new_sediment_field) call allocate(sediment_field, new_sediment_field%mesh, name="CNSedimentField") call zero(sediment_field) call addto(sediment_field, old_sediment_field, 0.5) call addto(sediment_field, new_sediment_field, 0.5) call get_sediment_item(state, i_field, "Bedload", bedload_field) call get_sediment_item(state, i_field, "SinkingVelocity", sink_U) ! allocate surface field that will contain the calculated deposited sediment for ! this timestep call allocate(deposited_sediment(i_field), surface_mesh(i_field), "DepositedSediment") call zero(deposited_sediment(i_field)) ! For continuous fields we need a global lumped mass. For dg we'll ! do the mass inversion on a per face basis inside the element loop. if(continuity(surface_mesh(i_field))>=0) then call allocate(masslump, surface_mesh(i_field), "SurfaceMassLump") call zero(masslump) end if ! obtain surface ids over which to record deposition surface_id_count=option_shape(trim(bedload_field%option_path)//& &"/prognostic/surface_ids") allocate(surface_ids(surface_id_count(1))) call get_option(trim(bedload_field%option_path)//"/prognostic/surface_ids", & & surface_ids) ! loop through elements in surface field elements: do ele=1,element_count(deposited_sediment(i_field)) ! check if element is on bedload surface if (.not.any(surface_element_id(bedload_field, ele)& &==surface_ids)) then cycle elements end if ! assemble bedload element call assemble_sediment_flux_ele(ele, deposited_sediment,& & sediment_field, X, U, sink_U, gravity, masslump, i_field) end do elements deallocate(surface_ids) ! For continuous fields we divide by the inverse global lumped mass if(continuity(surface_mesh(i_field))>=0) then where (masslump%val/=0.0) masslump%val=1./masslump%val end where call scale(deposited_sediment(i_field), masslump) call deallocate(masslump) end if ! get erosion rate diagnostic field call get_sediment_item(state, i_field, "BedloadDepositRate", diagnostic_field, stat) if (stat == 0) then call zero(diagnostic_field) do i_node = 1, node_count(surface_mesh(i_field)) call set(diagnostic_field, surface_nodes(i_field)%nodes(i_node), & & node_val(deposited_sediment(i_field), i_node)) end do call scale(diagnostic_field, 1./dt) end if call deallocate(sediment_field) end do deposit_fields_loop ! third loop to calculate net flux of sediment for this timestep net_flux_loop: do i_field=1, n_sediment_fields ! obtain scalar fields for this sediment class call get_sediment_item(state, i_field, "Bedload", bedload_field) if (.not. have_option(trim(bedload_field%option_path)//'/prognostic/disable_calculation')) then ! Add on sediment falling in and subtract sediment coming out do i_node = 1, node_count(surface_mesh(i_field)) ! add deposited sediment call addto(bedload_field, surface_nodes(i_field)%nodes(i_node), & & node_val(deposited_sediment(i_field), i_node)) ! remove eroded sediment call addto(bedload_field, surface_nodes(i_field)%nodes(i_node), & & -1.0 * node_val(erosion(i_field), i_node)) end do end if ewrite_minmax(deposited_sediment(i_field)) ewrite_minmax(erosion(i_field)) ewrite_minmax(bedload_field) call deallocate(deposited_sediment(i_field)) call deallocate(erosion(i_field)) call deallocate(surface_mesh(i_field)) deallocate(surface_nodes(i_field)%nodes) end do net_flux_loop call deallocate(U) deallocate(deposited_sediment) deallocate(erosion) deallocate(surface_mesh) deallocate(surface_nodes) end subroutine calculate_sediment_flux subroutine assemble_sediment_flux_ele(ele, deposited_sediment, sediment_field,& & X, U, sink_U, gravity, masslump, i_field) integer, intent(in) :: ele, i_field type(scalar_field), dimension(:), intent(inout) :: deposited_sediment type(vector_field), intent(in) :: X, U, gravity type(scalar_field), intent(in) :: sink_U, sediment_field type(scalar_field), intent(inout) :: masslump integer, dimension(:), pointer :: s_ele real, dimension(ele_loc(deposited_sediment(i_field), ele), & & ele_loc(deposited_sediment(i_field), ele)) :: invmass real, dimension(ele_loc(deposited_sediment(i_field), ele)) :: flux real, dimension(ele_ngi(deposited_sediment(i_field), ele)) :: detwei,& & G_normal_detwei, U_sink_detwei real, dimension(U%dim, ele_ngi(deposited_sediment(i_field), ele)) :: normal type(element_type), pointer :: s_shape s_ele=>ele_nodes(deposited_sediment(i_field), ele) s_shape=>ele_shape(deposited_sediment(i_field), ele) call transform_facet_to_physical(X, ele, detwei, normal) if(continuity(deposited_sediment(i_field))>=0) then call addto(masslump, s_ele, & sum(shape_shape(s_shape, s_shape, detwei), 1)) else ! In the DG case we will apply the inverse mass locally. invmass=inverse(shape_shape(s_shape, s_shape, detwei)) end if G_normal_detwei=sum(face_val_at_quad(gravity,ele)*normal,1)*detwei U_sink_detwei=G_normal_detwei*face_val_at_quad(sink_U,ele) flux=dt*shape_rhs(s_shape, & face_val_at_quad(sediment_field, ele)*U_sink_detwei) if(continuity(deposited_sediment(i_field))<0) then ! DG case. flux=matmul(invmass, flux) end if call addto(deposited_sediment(i_field), s_ele, flux) end subroutine assemble_sediment_flux_ele subroutine calculate_sediment_sinking_velocity(state) type(state_type), intent(inout) :: state type(scalar_field_pointer), dimension(:), allocatable :: sediment_concs type(scalar_field), pointer :: unhindered_sink_u, sink_u type(vector_field), pointer :: X type(scalar_field) :: rhs, rhs_projection integer :: n_sediment_fields,& & i_field, i_node ewrite(1,*) 'In calculate sediment sinking velocities' n_sediment_fields = get_n_sediment_fields() allocate(sediment_concs(n_sediment_fields)) ! allocate storage for rhs and set all to 1 call get_sediment_item(state, 1, sediment_concs(1)%ptr) call allocate(rhs, sediment_concs(1)%ptr%mesh, name="Rhs") call set(rhs, 1.0) ! get sediment concentrations and remove from rhs do i_field=1, n_sediment_fields call get_sediment_item(state, i_field, sediment_concs(i_field)%ptr) call addto(rhs, sediment_concs(i_field)%ptr, scale=-1.0) end do ! raise rhs to power of 2.39 do i_node = 1, node_count(rhs) if (node_val(rhs, i_node) > 1e-3) then call set(rhs, i_node, node_val(rhs, i_node)**2.39) else call set(rhs, i_node, 1e-3**2.39) end if end do do i_field=1, n_sediment_fields ! check for diagnostic sinking velocity if (have_option(trim(sediment_concs(i_field)%ptr%option_path)// & &'/prognostic/scalar_field::SinkingVelocity/diagnostic')) then ewrite(2,*) 'Calculating diagnostic sink velocity for sediment field: ' //& & trim(sediment_concs(i_field)%ptr%name) ! check for presence of unhindered sinking velocity value if (.not. have_option(trim(sediment_concs(i_field)%ptr%option_path)// & &'/prognostic/scalar_field::UnhinderedSinkingVelocity')) then FLExit('You must specify an unhindered sinking velocity field to be able to calculate diagnostic sinking velocity field values for sediments') endif unhindered_sink_u => extract_scalar_field(state, & & trim(sediment_concs(i_field)%ptr%name)//'UnhinderedSinkingVelocity') ewrite_minmax(unhindered_sink_u) sink_u => extract_scalar_field(state, & & trim(sediment_concs(i_field)%ptr%name)//'SinkingVelocity') ! calculate hindered sinking velocity call set(sink_u, unhindered_sink_u) if (rhs%mesh==sink_u%mesh) then call scale(sink_u, rhs) else call allocate(rhs_projection, sink_u%mesh, name="RhsProjection") X => extract_vector_field(state, 'Coordinate') call project_field(rhs, rhs_projection, X) call scale(sink_u, rhs_projection) call deallocate(rhs_projection) end if ewrite_minmax(sink_u) endif end do call deallocate(rhs) deallocate(sediment_concs) end subroutine calculate_sediment_sinking_velocity subroutine calculate_sediment_active_layer_d50(state) type(state_type), intent(inout) :: state type(scalar_field), pointer :: d50 type(scalar_field) :: total_bedload type(scalar_field_pointer), dimension(:), allocatable :: sorted_bedload real, dimension(:), allocatable :: sorted_diameter type(scalar_field_pointer) :: temp_bedload real :: temp_diameter real :: cumulative_bedload logical :: sorted = .false. integer :: i_field, n_fields, i_node, stat real :: min_bedload = 1.0e-20 ewrite(1,*) 'In calculate sediment_active_layer_d50' d50 => extract_scalar_field(state, 'SedimentBedActiveLayerD50', stat) if (stat /= 0) return n_fields = get_n_sediment_fields() allocate(sorted_bedload(n_fields)) allocate(sorted_diameter(n_fields)) do i_field = 1, n_fields call get_sediment_item(state, i_field, 'diameter', sorted_diameter(i_field), stat) if (stat /= 0) FLExit('All sediment fields must have a diameter to be able to calculate the SedimentBedActiveLayerD50') call get_sediment_item(state, i_field, 'Bedload', sorted_bedload(i_field)& &%ptr, stat) end do do while (.not. sorted) sorted = .true. do i_field = 2, n_fields if (sorted_diameter(i_field-1) > sorted_diameter(i_field)) then temp_diameter = sorted_diameter(i_field) sorted_diameter(i_field) = sorted_diameter(i_field-1) sorted_diameter(i_field-1) = temp_diameter temp_bedload = sorted_bedload(i_field) sorted_bedload(i_field) = sorted_bedload(i_field-1) sorted_bedload(i_field-1) = temp_bedload sorted = .false. end if end do end do call allocate(total_bedload, sorted_bedload(1)%ptr%mesh, 'TotalBedload') call zero(d50) call zero(total_bedload) do i_field = 1, n_fields call addto(total_bedload, sorted_bedload(i_field)%ptr) end do nodes: do i_node = 1, node_count(d50) if (node_val(total_bedload, i_node) > min_bedload) then i_field = 0 cumulative_bedload = 0.0 do while (cumulative_bedload < 0.5*node_val(total_bedload, i_node)) i_field = i_field + 1 cumulative_bedload = cumulative_bedload + node_val(sorted_bedload(i_field)%ptr,& & i_node) end do call set(d50, i_node, sorted_diameter(i_field)) else call set(d50, i_node, 0.0) end if end do nodes ewrite_minmax(d50) deallocate(sorted_diameter) deallocate(sorted_bedload) call deallocate(total_bedload) end subroutine calculate_sediment_active_layer_d50 subroutine calculate_sediment_active_layer_sigma(state) type(state_type), intent(inout) :: state type(scalar_field), pointer :: sigma type(mesh_type) :: surface_mesh integer, dimension(:), pointer :: surface_node_list type(vector_field), pointer :: x type(scalar_field_pointer), dimension(:), allocatable :: bedload real, dimension(:), allocatable :: diameter type(scalar_field) :: mean, & & masslump, sigma_surface integer :: n_fields, i_field, i_ele,& & i_node, stat integer, dimension(2) :: surface_id_count integer, dimension(:), allocatable :: surface_ids ewrite(1,*) 'In calculate_sediment_active_layer_sigma' sigma => extract_scalar_field(state, 'SedimentBedActiveLayerSigma', stat) if (stat /= 0) return x => extract_vector_field(state, 'Coordinate') n_fields = get_n_sediment_fields() allocate(bedload(n_fields)) allocate(diameter(n_fields)) ! collect information required to calculate standard deviation data_collection_loop: do i_field = 1, n_fields call get_sediment_item(state, i_field, 'diameter', diameter(i_field), stat) if (stat /= 0) FLExit('All sediment fields must have a diameter to be able to calculate the SedimentBedActiveLayerSigma') call get_sediment_item(state, i_field, 'Bedload', bedload(i_field)%ptr) end do data_collection_loop ! allocate surface field that will contain the calculated sigma values call create_surface_mesh(surface_mesh, surface_node_list, mesh=sigma%mesh, & &name='SurfaceMesh') call allocate(sigma_surface, surface_mesh, 'SigmaSurface') call zero(sigma_surface) ! For continuous fields we need a global lumped mass. For dg we'll ! do the mass inversion on a per face basis inside the element loop. if(continuity(sigma_surface)>=0) then call allocate(masslump, surface_mesh, 'SurfaceMassLump') call zero(masslump) end if ! obtain surface ids over which to calculate sigma surface_id_count=option_shape(trim(sigma%option_path)//'/diagnostic/surface_ids') allocate(surface_ids(surface_id_count(1))) call get_option(trim(sigma%option_path)//'/diagnostic/surface_ids', surface_ids) ! loop through elements in surface field elements: do i_ele=1, element_count(sigma_surface) ! check if element is on prescribed surface if (.not.any(surface_element_id(sigma, i_ele) == surface_ids)) then cycle elements end if ! calculate sigma call calculate_sediment_active_layer_element_sigma(i_ele, sigma_surface, bedload,& & masslump, x, diameter, n_fields) end do elements ! For continuous fields we divide by the inverse global lumped mass if(continuity(surface_mesh)>=0) then where (masslump%val/=0.0) masslump%val=1./masslump%val end where call scale(sigma_surface, masslump) call deallocate(masslump) end if ! remap surface node values on to sigma field do i_node = 1, node_count(surface_mesh) call set(sigma, surface_node_list(i_node), node_val(sigma_surface, i_node)) end do ewrite_minmax(sigma) deallocate(bedload) deallocate(diameter) call deallocate(sigma_surface) call deallocate(surface_mesh) deallocate(surface_node_list) deallocate(surface_ids) end subroutine calculate_sediment_active_layer_sigma subroutine calculate_sediment_active_layer_element_sigma(i_ele, sigma_surface, bedload,& & masslump, x, diameter, n_fields) integer, intent(in) :: i_ele type(scalar_field), intent(inout) :: sigma_surface type(scalar_field_pointer), dimension(:), intent(in) :: bedload type(scalar_field), intent(inout) :: masslump type(vector_field), pointer, intent(in) :: x real, dimension(:), intent(in) :: diameter integer, intent(in) :: n_fields integer, dimension(:), pointer :: ele type(element_type), pointer :: shape real, dimension(ele_loc(sigma_surface, i_ele), & & ele_loc(sigma_surface, i_ele)) :: invmass real, dimension(ele_ngi(sigma_surface, i_ele)) :: detwei, total_bedload, & & mean_diameter, sigma_squared real, dimension(ele_loc(sigma_surface, i_ele)) :: sigma integer :: i_field, i_gi real :: min_bedload = 1.0e-20 ele => ele_nodes(sigma_surface, i_ele) shape => ele_shape(sigma_surface, i_ele) call transform_facet_to_physical(x, i_ele, detwei) if(continuity(sigma_surface)>=0) then call addto(masslump, ele, & sum(shape_shape(shape, shape, detwei), 1)) else ! In the DG case we will apply the inverse mass locally. invmass=inverse(shape_shape(shape, shape, detwei)) end if do i_gi = 1, ele_ngi(sigma_surface, i_ele) total_bedload(i_gi) = 0.0 mean_diameter(i_gi) = 0.0 sigma_squared(i_gi) = 0.0 end do mean_calculation_loop: do i_field = 1, n_fields total_bedload = total_bedload + face_val_at_quad(bedload(i_field)%ptr, i_ele) mean_diameter = mean_diameter + face_val_at_quad(bedload(i_field)%ptr, i_ele) & *diameter(i_field) end do mean_calculation_loop where ((total_bedload > min_bedload)) mean_diameter = mean_diameter / total_bedload elsewhere mean_diameter = 0.0 end where sigma_calculation_loop: do i_field = 1, n_fields sigma_squared = sigma_squared + face_val_at_quad(bedload(i_field)%ptr, i_ele) & *(diameter(i_field) - mean_diameter)**2.0 end do sigma_calculation_loop where ((total_bedload > min_bedload)) sigma_squared = sigma_squared / total_bedload elsewhere sigma_squared = 0.0 end where sigma = shape_rhs(shape, dsqrt(sigma_squared) * detwei) if(continuity(sigma_surface)<0) then ! DG case. sigma = matmul(invmass, sigma) end if call addto(sigma_surface, ele, sigma) end subroutine calculate_sediment_active_layer_element_sigma subroutine calculate_sediment_active_layer_volume_fractions(state) type(state_type), intent(inout) :: state type(scalar_field), pointer :: volume_fraction, bedload type(mesh_type) :: surface_mesh integer, dimension(:), pointer :: surface_node_list type(vector_field), pointer :: x type(scalar_field) :: total_bedload,& & volume_fraction_surface, masslump integer :: n_fields, i_field, i_ele,& & i_node integer, dimension(2) :: surface_id_count integer, dimension(:), allocatable :: surface_ids ewrite(1,*) 'In calculate_sediment_active_layer_volume_fractions' x => extract_vector_field(state, 'Coordinate') n_fields = get_n_sediment_fields() ! calculate combined bedload data_collection_loop: do i_field = 1, n_fields call get_sediment_item(state, i_field, 'Bedload', bedload) if (i_field == 1) then call allocate(total_bedload, bedload%mesh, 'TotalBedload') call zero(total_bedload) end if call addto(total_bedload, bedload) end do data_collection_loop calculation_loop: do i_field = 1, n_fields ! get sediment bedload and volume fraction fields call get_sediment_item(state, i_field, 'Bedload', bedload) call get_sediment_item(state, i_field, 'BedloadVolumeFraction', volume_fraction) ! generate surface_mesh for calculation of volume fraction and create surface field call create_surface_mesh(surface_mesh, surface_node_list, & & mesh=bedload%mesh, name='SurfaceMesh') call allocate(volume_fraction_surface, surface_mesh, 'VolumeFraction') call zero(volume_fraction_surface) ! For continuous fields we need a global lumped mass. For dg we'll ! do the mass inversion on a per face basis inside the element loop. if(continuity(volume_fraction_surface)>=0) then call allocate(masslump, surface_mesh, 'SurfaceMassLump') call zero(masslump) end if ! obtain sediment bedload surface ids surface_id_count=option_shape(trim(bedload%option_path)//& &"/prognostic/surface_ids") allocate(surface_ids(surface_id_count(1))) call get_option(trim(bedload%option_path)//"/prognostic/surface_ids", & & surface_ids) ! loop through elements in surface field elements: do i_ele=1, element_count(volume_fraction_surface) ! check if element is on prescribed surface if (.not.any(surface_element_id(volume_fraction, i_ele) == surface_ids)) then cycle elements end if ! calculate volume_fraction call calculate_sediment_active_layer_element_volume_fractions(i_ele,& & volume_fraction_surface, bedload, total_bedload, masslump, x) end do elements ! For continuous fields we divide by the inverse global lumped mass if(continuity(volume_fraction_surface)>=0) then where (masslump%val/=0.0) masslump%val=1./masslump%val end where call scale(volume_fraction_surface, masslump) call deallocate(masslump) end if ! remap surface node values on to sigma field do i_node = 1, node_count(surface_mesh) call set(volume_fraction, surface_node_list(i_node),& & node_val(volume_fraction_surface, i_node)) end do ewrite_minmax(volume_fraction) call deallocate(volume_fraction_surface) call deallocate(surface_mesh) deallocate(surface_node_list) deallocate(surface_ids) end do calculation_loop call deallocate(total_bedload) end subroutine calculate_sediment_active_layer_volume_fractions subroutine calculate_sediment_active_layer_element_volume_fractions(i_ele,& & volume_fraction_surface, bedload, total_bedload, masslump, x) integer, intent(in) :: i_ele type(scalar_field), intent(inout) :: volume_fraction_surface type(scalar_field), intent(in) :: bedload, total_bedload type(scalar_field), intent(inout) :: masslump type(vector_field), pointer, intent(in) :: x integer, dimension(:), pointer :: ele type(element_type), pointer :: shape real, dimension(ele_loc(volume_fraction_surface, i_ele), & & ele_loc(volume_fraction_surface, i_ele)) :: invmass real, dimension(ele_ngi(volume_fraction_surface, i_ele)) :: detwei, & & volume_fraction_at_quad real, dimension(ele_loc(volume_fraction_surface, i_ele)) :: volume_fraction real :: min_bedload = 1.0e-20 ele => ele_nodes(volume_fraction_surface, i_ele) shape => ele_shape(volume_fraction_surface, i_ele) call transform_facet_to_physical(x, i_ele, detwei) if(continuity(volume_fraction_surface)>=0) then call addto(masslump, ele, & sum(shape_shape(shape, shape, detwei), 1)) else ! In the DG case we will apply the inverse mass locally. invmass=inverse(shape_shape(shape, shape, detwei)) end if where (face_val_at_quad(total_bedload, i_ele) > min_bedload) volume_fraction_at_quad = face_val_at_quad(bedload, i_ele) / & & face_val_at_quad(total_bedload, i_ele) elsewhere volume_fraction_at_quad = 0.0 end where volume_fraction = shape_rhs(shape, volume_fraction_at_quad * detwei) if(continuity(volume_fraction_surface)<0) then ! DG case. volume_fraction = matmul(invmass, volume_fraction) end if call addto(volume_fraction_surface, ele, volume_fraction) end subroutine calculate_sediment_active_layer_element_volume_fractions end module sediment_diagnostics
lgpl-2.1
itsimbal/gcc.cet
gcc/testsuite/gfortran.dg/namelist_39.f90
166
1339
! { dg-do run } ! PR33421 and PR33253 Weird quotation of namelist output of character arrays ! Test case from Toon Moone, adapted by Jerry DeLisle <jvdelisle@gcc.gnu.org> ! Long names used to test line_buffer feature is working. program test implicit none character(len=45) :: b01234567890123456789012345678901234567890123456789012345678901(3) namelist /nam/ b01234567890123456789012345678901234567890123456789012345678901 b01234567890123456789012345678901234567890123456789012345678901 = 'x' open(99, status="scratch") write(99,'(4(a,/),a)') "&NAM", & " b01234567890123456789012345678901234567890123456789012345678901(1)=' AAP NOOT MIES WIM ZUS JET',", & " b01234567890123456789012345678901234567890123456789012345678901(2)='SURF.PRESSURE',", & " b01234567890123456789012345678901234567890123456789012345678901(3)='APEKOOL',", & " /" rewind(99) read(99,nml=nam) close(99) if (b01234567890123456789012345678901234567890123456789012345678901(1).ne.& " AAP NOOT MIES WIM ZUS JET ") call abort if (b01234567890123456789012345678901234567890123456789012345678901(2).ne.& "SURF.PRESSURE ") call abort if (b01234567890123456789012345678901234567890123456789012345678901(3).ne.& "APEKOOL ") call abort end program test
gpl-2.0
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/namelist_39.f90
166
1339
! { dg-do run } ! PR33421 and PR33253 Weird quotation of namelist output of character arrays ! Test case from Toon Moone, adapted by Jerry DeLisle <jvdelisle@gcc.gnu.org> ! Long names used to test line_buffer feature is working. program test implicit none character(len=45) :: b01234567890123456789012345678901234567890123456789012345678901(3) namelist /nam/ b01234567890123456789012345678901234567890123456789012345678901 b01234567890123456789012345678901234567890123456789012345678901 = 'x' open(99, status="scratch") write(99,'(4(a,/),a)') "&NAM", & " b01234567890123456789012345678901234567890123456789012345678901(1)=' AAP NOOT MIES WIM ZUS JET',", & " b01234567890123456789012345678901234567890123456789012345678901(2)='SURF.PRESSURE',", & " b01234567890123456789012345678901234567890123456789012345678901(3)='APEKOOL',", & " /" rewind(99) read(99,nml=nam) close(99) if (b01234567890123456789012345678901234567890123456789012345678901(1).ne.& " AAP NOOT MIES WIM ZUS JET ") call abort if (b01234567890123456789012345678901234567890123456789012345678901(2).ne.& "SURF.PRESSURE ") call abort if (b01234567890123456789012345678901234567890123456789012345678901(3).ne.& "APEKOOL ") call abort end program test
gpl-2.0
emb-team/loongson-gccgo
gcc/testsuite/gfortran.dg/gomp/udr8.f90
100
15353
! { dg-do compile } ! { dg-options "-fmax-errors=1000 -fopenmp" } module m contains function fn1 (x, y) integer, intent(in) :: x, y integer :: fn1 fn1 = x + 2 * y end function subroutine sub1 (x, y) integer, intent(in) :: y integer, intent(out) :: x x = y end subroutine function fn2 (x) integer, intent(in) :: x integer :: fn2 fn2 = x end function subroutine sub2 (x, y) integer, intent(in) :: y integer, intent(inout) :: x x = x + y end subroutine function fn3 (x, y) integer, intent(in) :: x(:), y(:) integer :: fn3(lbound(x, 1):ubound(x, 1)) fn3 = x + 2 * y end function subroutine sub3 (x, y) integer, intent(in) :: y(:) integer, intent(out) :: x(:) x = y end subroutine function fn4 (x) integer, intent(in) :: x(:) integer :: fn4(lbound(x, 1):ubound(x, 1)) fn4 = x end function subroutine sub4 (x, y) integer, intent(in) :: y(:) integer, intent(inout) :: x(:) x = x + y end subroutine function fn5 (x, y) integer, intent(in) :: x(10), y(10) integer :: fn5(10) fn5 = x + 2 * y end function subroutine sub5 (x, y) integer, intent(in) :: y(10) integer, intent(out) :: x(10) x = y end subroutine function fn6 (x) integer, intent(in) :: x(10) integer :: fn6(10) fn6 = x end function subroutine sub6 (x, y) integer, intent(in) :: y(10) integer, intent(inout) :: x(10) x = x + y end subroutine function fn7 (x, y) integer, allocatable, intent(in) :: x(:), y(:) integer, allocatable :: fn7(:) fn7 = x + 2 * y end function subroutine sub7 (x, y) integer, allocatable, intent(in) :: y(:) integer, allocatable, intent(out) :: x(:) x = y end subroutine function fn8 (x) integer, allocatable, intent(in) :: x(:) integer, allocatable :: fn8(:) fn8 = x end function subroutine sub8 (x, y) integer, allocatable, intent(in) :: y(:) integer, allocatable, intent(inout) :: x(:) x = x + y end subroutine end module subroutine test1 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn1 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } !$omp & initializer (sub1 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } !$omp declare reduction (baz : integer : sub2 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } !$omp initializer (omp_priv = fn2 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } integer :: a(10) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test1 subroutine test2 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn1 (omp_out, omp_in)) & !$omp & initializer (sub1 (omp_priv, omp_orig)) !$omp declare reduction (baz : integer : sub2 (omp_out, omp_in)) & !$omp initializer (omp_priv = fn2 (omp_orig)) integer :: a !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test2 subroutine test3 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn1 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } !$omp & initializer (sub1 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } !$omp declare reduction (baz : integer : sub2 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } !$omp initializer (omp_priv = fn2 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*scalar and rank-1" } integer, allocatable :: a(:) allocate (a(10)) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test3 subroutine test4 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn1 (omp_out, omp_in)) & !$omp & initializer (sub1 (omp_priv, omp_orig)) !$omp declare reduction (baz : integer : sub2 (omp_out, omp_in)) & !$omp initializer (omp_priv = fn2 (omp_orig)) integer, allocatable :: a allocate (a) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test4 subroutine test5 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn3 (omp_out, omp_in)) & !$omp & initializer (sub3 (omp_priv, omp_orig)) !$omp declare reduction (baz : integer : sub4 (omp_out, omp_in)) & !$omp initializer (omp_priv = fn4 (omp_orig)) integer :: a(10) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test5 subroutine test6 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn3 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } !$omp & initializer (sub3 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp declare reduction (baz : integer : sub4 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp initializer (omp_priv = fn4 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } integer :: a !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test6 subroutine test7 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn3 (omp_out, omp_in)) & !$omp & initializer (sub3 (omp_priv, omp_orig)) !$omp declare reduction (baz : integer : sub4 (omp_out, omp_in)) & !$omp initializer (omp_priv = fn4 (omp_orig)) integer, allocatable :: a(:) allocate (a(10)) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test7 subroutine test8 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn3 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } !$omp & initializer (sub3 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp declare reduction (baz : integer : sub4 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp initializer (omp_priv = fn4 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } integer, allocatable :: a allocate (a) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test8 subroutine test9 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn5 (omp_out, omp_in)) & !$omp & initializer (sub5 (omp_priv, omp_orig)) !$omp declare reduction (baz : integer : sub6 (omp_out, omp_in)) & !$omp initializer (omp_priv = fn6 (omp_orig)) integer :: a(10) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test9 subroutine test10 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn5 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } !$omp & initializer (sub5 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp declare reduction (baz : integer : sub6 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp initializer (omp_priv = fn6 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } integer :: a !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test10 subroutine test11 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn5 (omp_out, omp_in)) & !$omp & initializer (sub5 (omp_priv, omp_orig)) !$omp declare reduction (baz : integer : sub6 (omp_out, omp_in)) & !$omp initializer (omp_priv = fn6 (omp_orig)) integer, allocatable :: a(:) allocate (a(10)) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test11 subroutine test12 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn5 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } !$omp & initializer (sub5 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp declare reduction (baz : integer : sub6 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp initializer (omp_priv = fn6 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } integer, allocatable :: a allocate (a) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test12 subroutine test13 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = & ! { dg-error "Different shape for array assignment at \[^\n\r]* on dimension 1 .9 and 10" } !$omp & fn5 (omp_out, omp_in)) & ! { dg-warning "Actual argument contains too few elements for dummy argument \[^\n\r]* .9/10" } !$omp & initializer (sub5 (omp_priv, omp_orig)) ! { dg-warning "Actual argument contains too few elements for dummy argument \[^\n\r]* .9/10" } !$omp declare reduction (baz : integer : sub6 (omp_out, omp_in)) & ! { dg-warning "Actual argument contains too few elements for dummy argument \[^\n\r]* .9/10" } !$omp initializer (omp_priv = & ! { dg-error "Different shape for array assignment at \[^\n\r]* on dimension 1 .9 and 10" } !$omp & fn6 (omp_orig)) ! { dg-warning "Actual argument contains too few elements for dummy argument \[^\n\r]* .9/10" } integer :: a(9) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test13 subroutine test14 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn7 (omp_out, omp_in)) & ! { dg-error "Actual argument for \[^\n\r]* must be ALLOCATABLE" } !$omp & initializer (sub7 (omp_priv, omp_orig)) ! { dg-error "Actual argument for \[^\n\r]* must be ALLOCATABLE" } !$omp declare reduction (baz : integer : sub8 (omp_out, omp_in)) & ! { dg-error "Actual argument for \[^\n\r]* must be ALLOCATABLE" } !$omp initializer (omp_priv = fn8 (omp_orig)) ! { dg-error "Actual argument for \[^\n\r]* must be ALLOCATABLE" } integer :: a(10) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test14 subroutine test15 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn7 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } !$omp & initializer (sub7 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp declare reduction (baz : integer : sub8 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp initializer (omp_priv = fn8 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } integer :: a !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test15 subroutine test16 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn7 (omp_out, omp_in)) & !$omp & initializer (sub7 (omp_priv, omp_orig)) !$omp declare reduction (baz : integer : sub8 (omp_out, omp_in)) & !$omp initializer (omp_priv = fn8 (omp_orig)) integer, allocatable :: a(:) allocate (a(10)) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test16 subroutine test17 use m !$omp declare reduction (foo : integer : omp_out = omp_out + omp_in) initializer (omp_priv = 0) !$omp declare reduction (bar : integer : omp_out = fn7 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } !$omp & initializer (sub7 (omp_priv, omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp declare reduction (baz : integer : sub8 (omp_out, omp_in)) & ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar" } !$omp initializer (omp_priv = fn8 (omp_orig)) ! { dg-error "Rank mismatch in argument\[^\n\r]*rank-1 and scalar|Incompatible ranks 0 and 1 in assignment" } integer, allocatable :: a allocate (a) !$omp parallel reduction (foo : a) !$omp end parallel !$omp parallel reduction (bar : a) !$omp end parallel !$omp parallel reduction (baz : a) !$omp end parallel end subroutine test17
gpl-2.0