text
stringlengths 12
986k
| repo_path
stringlengths 6
121
|
---|---|
SUBROUTINE SLAEIN( RIGHTV, NOINIT, N, H, LDH, WR, WI, VR, VI, B,
$ LDB, WORK, EPS3, SMLNUM, BIGNUM, INFO )
*
* -- LAPACK auxiliary routine (instrumented to count operations) --
* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
* Courant Institute, Argonne National Lab, and Rice University
* September 30, 1994
*
* .. Scalar Arguments ..
LOGICAL NOINIT, RIGHTV
INTEGER INFO, LDB, LDH, N
REAL BIGNUM, EPS3, SMLNUM, WI, WR
* ..
* .. Array Arguments ..
REAL B( LDB, * ), H( LDH, * ), VI( * ), VR( * ),
$ WORK( * )
* ..
* Common block to return operation count.
* .. Common blocks ..
COMMON / LATIME / OPS, ITCNT
* ..
* .. Scalars in Common ..
REAL ITCNT, OPS
* ..
*
* Purpose
* =======
*
* SLAEIN uses inverse iteration to find a right or left eigenvector
* corresponding to the eigenvalue (WR,WI) of a real upper Hessenberg
* matrix H.
*
* Arguments
* =========
*
* RIGHTV (input) LOGICAL
* = .TRUE. : compute right eigenvector;
* = .FALSE.: compute left eigenvector.
*
* NOINIT (input) LOGICAL
* = .TRUE. : no initial vector supplied in (VR,VI).
* = .FALSE.: initial vector supplied in (VR,VI).
*
* N (input) INTEGER
* The order of the matrix H. N >= 0.
*
* H (input) REAL array, dimension (LDH,N)
* The upper Hessenberg matrix H.
*
* LDH (input) INTEGER
* The leading dimension of the array H. LDH >= max(1,N).
*
* WR (input) REAL
* WI (input) REAL
* The real and imaginary parts of the eigenvalue of H whose
* corresponding right or left eigenvector is to be computed.
*
* VR (input/output) REAL array, dimension (N)
* VI (input/output) REAL array, dimension (N)
* On entry, if NOINIT = .FALSE. and WI = 0.0, VR must contain
* a real starting vector for inverse iteration using the real
* eigenvalue WR; if NOINIT = .FALSE. and WI.ne.0.0, VR and VI
* must contain the real and imaginary parts of a complex
* starting vector for inverse iteration using the complex
* eigenvalue (WR,WI); otherwise VR and VI need not be set.
* On exit, if WI = 0.0 (real eigenvalue), VR contains the
* computed real eigenvector; if WI.ne.0.0 (complex eigenvalue),
* VR and VI contain the real and imaginary parts of the
* computed complex eigenvector. The eigenvector is normalized
* so that the component of largest magnitude has magnitude 1;
* here the magnitude of a complex number (x,y) is taken to be
* |x| + |y|.
* VI is not referenced if WI = 0.0.
*
* B (workspace) REAL array, dimension (LDB,N)
*
* LDB (input) INTEGER
* The leading dimension of the array B. LDB >= N+1.
*
* WORK (workspace) REAL array, dimension (N)
*
* EPS3 (input) REAL
* A small machine-dependent value which is used to perturb
* close eigenvalues, and to replace zero pivots.
*
* SMLNUM (input) REAL
* A machine-dependent value close to the underflow threshold.
*
* BIGNUM (input) REAL
* A machine-dependent value close to the overflow threshold.
*
* INFO (output) INTEGER
* = 0: successful exit
* = 1: inverse iteration did not converge; VR is set to the
* last iterate, and so is VI if WI.ne.0.0.
*
* =====================================================================
*
* .. Parameters ..
REAL ZERO, ONE, TENTH
PARAMETER ( ZERO = 0.0E+0, ONE = 1.0E+0, TENTH = 1.0E-1 )
* ..
* .. Local Scalars ..
CHARACTER NORMIN, TRANS
INTEGER I, I1, I2, I3, IERR, ITS, J
REAL ABSBII, ABSBJJ, EI, EJ, GROWTO, NORM, NRMSML,
$ OPST, REC, ROOTN, SCALE, TEMP, VCRIT, VMAX,
$ VNORM, W, W1, X, XI, XR, Y
* ..
* .. External Functions ..
INTEGER ISAMAX
REAL SASUM, SLAPY2, SNRM2
EXTERNAL ISAMAX, SASUM, SLAPY2, SNRM2
* ..
* .. External Subroutines ..
EXTERNAL SLADIV, SLATRS, SSCAL
* ..
* .. Intrinsic Functions ..
INTRINSIC ABS, MAX, REAL, SQRT
* ..
* .. Executable Statements ..
*
INFO = 0
***
* Initialize
OPST = 0
***
*
* GROWTO is the threshold used in the acceptance test for an
* eigenvector.
*
ROOTN = SQRT( REAL( N ) )
GROWTO = TENTH / ROOTN
NRMSML = MAX( ONE, EPS3*ROOTN )*SMLNUM
***
* Increment op count for computing ROOTN, GROWTO and NRMSML
OPST = OPST + 4
***
*
* Form B = H - (WR,WI)*I (except that the subdiagonal elements and
* the imaginary parts of the diagonal elements are not stored).
*
DO 20 J = 1, N
DO 10 I = 1, J - 1
B( I, J ) = H( I, J )
10 CONTINUE
B( J, J ) = H( J, J ) - WR
20 CONTINUE
***
OPST = OPST + N
***
*
IF( WI.EQ.ZERO ) THEN
*
* Real eigenvalue.
*
IF( NOINIT ) THEN
*
* Set initial vector.
*
DO 30 I = 1, N
VR( I ) = EPS3
30 CONTINUE
ELSE
*
* Scale supplied initial vector.
*
VNORM = SNRM2( N, VR, 1 )
CALL SSCAL( N, ( EPS3*ROOTN ) / MAX( VNORM, NRMSML ), VR,
$ 1 )
***
OPST = OPST + ( 3*N+2 )
***
END IF
*
IF( RIGHTV ) THEN
*
* LU decomposition with partial pivoting of B, replacing zero
* pivots by EPS3.
*
DO 60 I = 1, N - 1
EI = H( I+1, I )
IF( ABS( B( I, I ) ).LT.ABS( EI ) ) THEN
*
* Interchange rows and eliminate.
*
X = B( I, I ) / EI
B( I, I ) = EI
DO 40 J = I + 1, N
TEMP = B( I+1, J )
B( I+1, J ) = B( I, J ) - X*TEMP
B( I, J ) = TEMP
40 CONTINUE
ELSE
*
* Eliminate without interchange.
*
IF( B( I, I ).EQ.ZERO )
$ B( I, I ) = EPS3
X = EI / B( I, I )
IF( X.NE.ZERO ) THEN
DO 50 J = I + 1, N
B( I+1, J ) = B( I+1, J ) - X*B( I, J )
50 CONTINUE
END IF
END IF
60 CONTINUE
IF( B( N, N ).EQ.ZERO )
$ B( N, N ) = EPS3
***
* Increment op count for LU decomposition
OPS = OPS + ( N-1 )*( N+1 )
***
*
TRANS = 'N'
*
ELSE
*
* UL decomposition with partial pivoting of B, replacing zero
* pivots by EPS3.
*
DO 90 J = N, 2, -1
EJ = H( J, J-1 )
IF( ABS( B( J, J ) ).LT.ABS( EJ ) ) THEN
*
* Interchange columns and eliminate.
*
X = B( J, J ) / EJ
B( J, J ) = EJ
DO 70 I = 1, J - 1
TEMP = B( I, J-1 )
B( I, J-1 ) = B( I, J ) - X*TEMP
B( I, J ) = TEMP
70 CONTINUE
ELSE
*
* Eliminate without interchange.
*
IF( B( J, J ).EQ.ZERO )
$ B( J, J ) = EPS3
X = EJ / B( J, J )
IF( X.NE.ZERO ) THEN
DO 80 I = 1, J - 1
B( I, J-1 ) = B( I, J-1 ) - X*B( I, J )
80 CONTINUE
END IF
END IF
90 CONTINUE
IF( B( 1, 1 ).EQ.ZERO )
$ B( 1, 1 ) = EPS3
***
* Increment op count for UL decomposition
OPS = OPS + ( N-1 )*( N+1 )
***
*
TRANS = 'T'
*
END IF
*
NORMIN = 'N'
DO 110 ITS = 1, N
*
* Solve U*x = scale*v for a right eigenvector
* or U'*x = scale*v for a left eigenvector,
* overwriting x on v.
*
CALL SLATRS( 'Upper', TRANS, 'Nonunit', NORMIN, N, B, LDB,
$ VR, SCALE, WORK, IERR )
***
* Increment opcount for triangular solver, assuming that
* ops SLATRS = ops STRSV, with no scaling in SLATRS.
OPS = OPS + N*N
***
NORMIN = 'Y'
*
* Test for sufficient growth in the norm of v.
*
VNORM = SASUM( N, VR, 1 )
***
OPST = OPST + N
***
IF( VNORM.GE.GROWTO*SCALE )
$ GO TO 120
*
* Choose new orthogonal starting vector and try again.
*
TEMP = EPS3 / ( ROOTN+ONE )
VR( 1 ) = EPS3
DO 100 I = 2, N
VR( I ) = TEMP
100 CONTINUE
VR( N-ITS+1 ) = VR( N-ITS+1 ) - EPS3*ROOTN
***
OPST = OPST + 4
***
110 CONTINUE
*
* Failure to find eigenvector in N iterations.
*
INFO = 1
*
120 CONTINUE
*
* Normalize eigenvector.
*
I = ISAMAX( N, VR, 1 )
CALL SSCAL( N, ONE / ABS( VR( I ) ), VR, 1 )
***
OPST = OPST + ( 2*N+1 )
***
ELSE
*
* Complex eigenvalue.
*
IF( NOINIT ) THEN
*
* Set initial vector.
*
DO 130 I = 1, N
VR( I ) = EPS3
VI( I ) = ZERO
130 CONTINUE
ELSE
*
* Scale supplied initial vector.
*
NORM = SLAPY2( SNRM2( N, VR, 1 ), SNRM2( N, VI, 1 ) )
REC = ( EPS3*ROOTN ) / MAX( NORM, NRMSML )
CALL SSCAL( N, REC, VR, 1 )
CALL SSCAL( N, REC, VI, 1 )
***
OPST = OPST + ( 6*N+5 )
***
END IF
*
IF( RIGHTV ) THEN
*
* LU decomposition with partial pivoting of B, replacing zero
* pivots by EPS3.
*
* The imaginary part of the (i,j)-th element of U is stored in
* B(j+1,i).
*
B( 2, 1 ) = -WI
DO 140 I = 2, N
B( I+1, 1 ) = ZERO
140 CONTINUE
*
DO 170 I = 1, N - 1
ABSBII = SLAPY2( B( I, I ), B( I+1, I ) )
EI = H( I+1, I )
IF( ABSBII.LT.ABS( EI ) ) THEN
*
* Interchange rows and eliminate.
*
XR = B( I, I ) / EI
XI = B( I+1, I ) / EI
B( I, I ) = EI
B( I+1, I ) = ZERO
DO 150 J = I + 1, N
TEMP = B( I+1, J )
B( I+1, J ) = B( I, J ) - XR*TEMP
B( J+1, I+1 ) = B( J+1, I ) - XI*TEMP
B( I, J ) = TEMP
B( J+1, I ) = ZERO
150 CONTINUE
B( I+2, I ) = -WI
B( I+1, I+1 ) = B( I+1, I+1 ) - XI*WI
B( I+2, I+1 ) = B( I+2, I+1 ) + XR*WI
***
OPST = OPST + ( 4*( N-I )+6 )
***
ELSE
*
* Eliminate without interchanging rows.
*
IF( ABSBII.EQ.ZERO ) THEN
B( I, I ) = EPS3
B( I+1, I ) = ZERO
ABSBII = EPS3
END IF
EI = ( EI / ABSBII ) / ABSBII
XR = B( I, I )*EI
XI = -B( I+1, I )*EI
DO 160 J = I + 1, N
B( I+1, J ) = B( I+1, J ) - XR*B( I, J ) +
$ XI*B( J+1, I )
B( J+1, I+1 ) = -XR*B( J+1, I ) - XI*B( I, J )
160 CONTINUE
B( I+2, I+1 ) = B( I+2, I+1 ) - WI
***
OPST = OPST + ( 7*( N-I )+4 )
***
END IF
*
* Compute 1-norm of offdiagonal elements of i-th row.
*
WORK( I ) = SASUM( N-I, B( I, I+1 ), LDB ) +
$ SASUM( N-I, B( I+2, I ), 1 )
***
OPST = OPST + ( 2*( N-I )+4 )
***
170 CONTINUE
IF( B( N, N ).EQ.ZERO .AND. B( N+1, N ).EQ.ZERO )
$ B( N, N ) = EPS3
WORK( N ) = ZERO
*
I1 = N
I2 = 1
I3 = -1
ELSE
*
* UL decomposition with partial pivoting of conjg(B),
* replacing zero pivots by EPS3.
*
* The imaginary part of the (i,j)-th element of U is stored in
* B(j+1,i).
*
B( N+1, N ) = WI
DO 180 J = 1, N - 1
B( N+1, J ) = ZERO
180 CONTINUE
*
DO 210 J = N, 2, -1
EJ = H( J, J-1 )
ABSBJJ = SLAPY2( B( J, J ), B( J+1, J ) )
IF( ABSBJJ.LT.ABS( EJ ) ) THEN
*
* Interchange columns and eliminate
*
XR = B( J, J ) / EJ
XI = B( J+1, J ) / EJ
B( J, J ) = EJ
B( J+1, J ) = ZERO
DO 190 I = 1, J - 1
TEMP = B( I, J-1 )
B( I, J-1 ) = B( I, J ) - XR*TEMP
B( J, I ) = B( J+1, I ) - XI*TEMP
B( I, J ) = TEMP
B( J+1, I ) = ZERO
190 CONTINUE
B( J+1, J-1 ) = WI
B( J-1, J-1 ) = B( J-1, J-1 ) + XI*WI
B( J, J-1 ) = B( J, J-1 ) - XR*WI
***
OPST = OPST + ( 4*( J-1 )+6 )
***
ELSE
*
* Eliminate without interchange.
*
IF( ABSBJJ.EQ.ZERO ) THEN
B( J, J ) = EPS3
B( J+1, J ) = ZERO
ABSBJJ = EPS3
END IF
EJ = ( EJ / ABSBJJ ) / ABSBJJ
XR = B( J, J )*EJ
XI = -B( J+1, J )*EJ
DO 200 I = 1, J - 1
B( I, J-1 ) = B( I, J-1 ) - XR*B( I, J ) +
$ XI*B( J+1, I )
B( J, I ) = -XR*B( J+1, I ) - XI*B( I, J )
200 CONTINUE
B( J, J-1 ) = B( J, J-1 ) + WI
***
OPST = OPST + ( 7*( J-1 )+4 )
***
END IF
*
* Compute 1-norm of offdiagonal elements of j-th column.
*
WORK( J ) = SASUM( J-1, B( 1, J ), 1 ) +
$ SASUM( J-1, B( J+1, 1 ), LDB )
***
OPST = OPST + ( 2*( J-1 )+4 )
***
210 CONTINUE
IF( B( 1, 1 ).EQ.ZERO .AND. B( 2, 1 ).EQ.ZERO )
$ B( 1, 1 ) = EPS3
WORK( 1 ) = ZERO
*
I1 = 1
I2 = N
I3 = 1
END IF
*
DO 270 ITS = 1, N
SCALE = ONE
VMAX = ONE
VCRIT = BIGNUM
*
* Solve U*(xr,xi) = scale*(vr,vi) for a right eigenvector,
* or U'*(xr,xi) = scale*(vr,vi) for a left eigenvector,
* overwriting (xr,xi) on (vr,vi).
*
DO 250 I = I1, I2, I3
*
IF( WORK( I ).GT.VCRIT ) THEN
REC = ONE / VMAX
CALL SSCAL( N, REC, VR, 1 )
CALL SSCAL( N, REC, VI, 1 )
SCALE = SCALE*REC
VMAX = ONE
VCRIT = BIGNUM
END IF
*
XR = VR( I )
XI = VI( I )
IF( RIGHTV ) THEN
DO 220 J = I + 1, N
XR = XR - B( I, J )*VR( J ) + B( J+1, I )*VI( J )
XI = XI - B( I, J )*VI( J ) - B( J+1, I )*VR( J )
220 CONTINUE
ELSE
DO 230 J = 1, I - 1
XR = XR - B( J, I )*VR( J ) + B( I+1, J )*VI( J )
XI = XI - B( J, I )*VI( J ) - B( I+1, J )*VR( J )
230 CONTINUE
END IF
*
W = ABS( B( I, I ) ) + ABS( B( I+1, I ) )
IF( W.GT.SMLNUM ) THEN
IF( W.LT.ONE ) THEN
W1 = ABS( XR ) + ABS( XI )
IF( W1.GT.W*BIGNUM ) THEN
REC = ONE / W1
CALL SSCAL( N, REC, VR, 1 )
CALL SSCAL( N, REC, VI, 1 )
XR = VR( I )
XI = VI( I )
SCALE = SCALE*REC
VMAX = VMAX*REC
END IF
END IF
*
* Divide by diagonal element of B.
*
CALL SLADIV( XR, XI, B( I, I ), B( I+1, I ), VR( I ),
$ VI( I ) )
VMAX = MAX( ABS( VR( I ) )+ABS( VI( I ) ), VMAX )
VCRIT = BIGNUM / VMAX
***
OPST = OPST + 9
***
ELSE
DO 240 J = 1, N
VR( J ) = ZERO
VI( J ) = ZERO
240 CONTINUE
VR( I ) = ONE
VI( I ) = ONE
SCALE = ZERO
VMAX = ONE
VCRIT = BIGNUM
END IF
250 CONTINUE
***
* Increment op count for loop 260, assuming no scaling
OPS = OPS + 4*N*( N-1 )
***
*
* Test for sufficient growth in the norm of (VR,VI).
*
VNORM = SASUM( N, VR, 1 ) + SASUM( N, VI, 1 )
***
OPST = OPST + 2*N
***
IF( VNORM.GE.GROWTO*SCALE )
$ GO TO 280
*
* Choose a new orthogonal starting vector and try again.
*
Y = EPS3 / ( ROOTN+ONE )
VR( 1 ) = EPS3
VI( 1 ) = ZERO
*
DO 260 I = 2, N
VR( I ) = Y
VI( I ) = ZERO
260 CONTINUE
VR( N-ITS+1 ) = VR( N-ITS+1 ) - EPS3*ROOTN
***
OPST = OPST + 4
***
270 CONTINUE
*
* Failure to find eigenvector in N iterations
*
INFO = 1
*
280 CONTINUE
*
* Normalize eigenvector.
*
VNORM = ZERO
DO 290 I = 1, N
VNORM = MAX( VNORM, ABS( VR( I ) )+ABS( VI( I ) ) )
290 CONTINUE
CALL SSCAL( N, ONE / VNORM, VR, 1 )
CALL SSCAL( N, ONE / VNORM, VI, 1 )
***
OPST = OPST + ( 4*N+1 )
***
*
END IF
*
***
* Compute final op count
OPS = OPS + OPST
***
RETURN
*
* End of SLAEIN
*
END
| old/lapack-test/lapack-timing/EIG/EIGSRC/slaein.f |
use sim
implicit none
type(SeismicAnalysis_) :: seismic
type(FEMDomain_),target :: cube,original
type(IO_) :: f,response,history_A,history_V,history_U,input_wave
type(Math_) :: math
real(real64),allocatable :: disp_z(:,:)
real(real64) :: wave(200,2),T,Duration,dt
integer(int32) :: i,j,cases,stack_id,num_of_cases
num_of_cases = 4
! create Domain
call cube%create(meshtype="Cube3D",x_num=4,y_num=4,z_num=20)
call cube%resize(x=1.0d0,y=1.0d0,z=5.0d0)
call cube%move(z=-5.0d0)
! create Wave
T = 0.300d0
Duration = T * 10.0d0 ! sec.
dt = Duration/dble(size(wave,1))!/10.0d0
wave(:,:) = 0.0d0
do i=1,size(wave,1)
wave(i,1) = dt*dble(i)
wave(i,2) = sin(2.0d0*math%pi/T*wave(i,1) )
enddo
call input_wave%open("input_wave.txt" )
call input_wave%write(wave )
call input_wave%close()
original = cube
! set domain
seismic%femdomain => cube
! set wave
seismic%wave = wave
seismic%dt = dt
! run simulation
call seismic%init()
!call seismic%fixDisplacement(z_max = -4.99d0,direction="x")
call seismic%fixDisplacement(z_max = -4.99d0,direction="y")
call seismic%fixDisplacement(z_max = -4.99d0,direction="z")
call seismic%fixDisplacement(y_max = 0.0d0,direction="y")
call seismic%fixDisplacement(y_min = 1.0d0,direction="y")
call seismic%fixDisplacement(direction="z")
call seismic%femdomain%vtk("mesh_init" )
call seismic%loadWave(z_max=-4.50d0,direction="x",wavetype=WAVE_ACCEL)
seismic%Density(:) = 17000.0d0 !(N/m/m/m)
seismic%PoissonRatio(:) = 0.330d0
seismic%YoungModulus(:) = 25372853.0 !(N/m/m) Vs=121 m/s
!seismic%alpha = 0.0d0
seismic%a = 0.0d0
seismic%v = 0.0d0
seismic%u = 0.0d0
do i=1,199
!seismic%beta = 0.0d0
call history_A%open("history_A"//str(i)//".txt","w")
call history_V%open("history_V"//str(i)//".txt","w")
call history_U%open("history_U"//str(i)//".txt","w")
call seismic%run(timestep=[i,i+1],AccelLimit=10.0d0**8)
do j=1,seismic%femdomain%nn()
if(seismic%femdomain%position_x(j)/=0.0d0) cycle
if(seismic%femdomain%position_y(j)/=0.0d0) cycle
write(history_A%fh,*) real(dble(i)*dt),&
seismic%femdomain%position_z(j), real(seismic%A( (j-1)*3 + 1 ))
enddo
do j=1,seismic%femdomain%nn()
if(seismic%femdomain%position_x(j)/=0.0d0) cycle
if(seismic%femdomain%position_y(j)/=0.0d0) cycle
write(history_V%fh,*) real(dble(i)*dt),&
seismic%femdomain%position_z(j), real(seismic%V( (j-1)*3 + 1 ))
enddo
do j=1,seismic%femdomain%nn()
if(seismic%femdomain%position_x(j)/=0.0d0) cycle
if(seismic%femdomain%position_y(j)/=0.0d0) cycle
write(history_U%fh,*) real(dble(i)*dt),&
seismic%femdomain%position_z(j), real(seismic%U( (j-1)*3 + 1 ))
enddo
call history_A%close()
call history_V%close()
call history_U%close()
enddo
!print *, maxval(seismic%U)
seismic%femdomain%mesh%nodcoord = seismic%femdomain%mesh%nodcoord + (10.0d0**0)*&
reshape(seismic%a, seismic%femdomain%nn(),seismic%femdomain%nd() )
call seismic%femdomain%vtk("result")
!call response%open("T_A"//str(cases)//".txt")
!call response%write(T,seismic%maxA(1))
!call response%close()
end | Tutorial/sim/SeismicAnalysis.f90 |
!
! common routines for testing
!
module test_common
implicit none
integer, parameter, public :: dp = kind(1.d0) ! Common in the test routines.
character(len=*), parameter :: SAMPLE_DIR = '../samples'
character(len=*), parameter :: DEF_FNAME_OUT = SAMPLE_DIR//'/test_out.txt'
contains
! Print the stats info at the end of each subroutine-level testing
subroutine print_teststats(subname, nsuccess, ifailed)
character(*), intent(in) :: subname
integer, intent(in) :: nsuccess ! Number of succesful trials, i-th failure
integer, intent(in), optional :: ifailed ! i-th failure
if (present(ifailed)) then
write(*, '(" Tests(", a, "): Only succeeded in ", i3, " tests before failed at ", i3, "-th.")') &
trim(subname), nsuccess, ifailed
else
write(*, '(" Tests(", a, "): Succeeded in all ", i3, " tests.")') &
trim(subname), nsuccess
end if
end subroutine print_teststats
end module test_common
module test_alpin_misc_utils
use alpin_unittest
use alpin_err_exit
use test_common
use alpin_misc_utils
implicit none
contains
! run tests of routines in alpin_misc_utils.f90
!
! Returns 1 if error is raised (0 otherwise)
integer function run_test_alpin_misc_utils() result(ret_status)
character(*), parameter :: Subname = 'run_test_alpin_misc_utils'
integer, parameter :: TOT_NTESTS = 39
logical, dimension(TOT_NTESTS) :: ress
integer :: iloc
ret_status = 0 ! normal ends (n.b., returned value)
ress = [ &
assert_in_delta(180.0d0, rad2deg(PI), 1.0e5, Subname, ' rad2deg(PI)') &
, assert_in_delta(PI, deg2rad(180.0d0), 1.0e5, Subname, ' deg2rad(180.0)') &
, assert_equal ('00000001', dump_int_binary(1_1), Subname, 'dump_int_binary') &
, assert_equal ('01111111', dump_int_binary(127_1), Subname, 'dump_int_binary') &
, assert_equal ('11111111', dump_int_binary(-1_1), Subname, 'dump_int_binary') &
, assert_equal (3, int4_to_unsigned1(3), Subname, 'for (3(int4=>1))') &
, assert_equal(-1, int4_to_unsigned1(255), Subname, 'for (255(int4=>1))') &
, assert_equal(255, unsigned1_to_int4(-1_1), Subname, 'for (255(int1=>4))') &
, assert_equal ('00000000_00000000_00000000_01111111', dump_int_binary(127_4), Subname, 'dump_int_binary(127)') &
, assert_equal ('00000000_00000000_00000001_01111111', dump_int_binary(383_4), Subname, 'dump_int_binary(383)') &
, assert_equal ('11111111_11111111_11111111_11111111', dump_int_binary(-1_4), Subname, 'dump_int_binary(-1)') &
, assert_equal('c.d', trim(basename('/a/b/c.d')), Subname, 'basename(/a/b/c.d)') &
, assert_equal('c.d', trim(basename('c.d')), Subname, 'basename(c.d)') &
, assert_equal('abc', trim(basename('/x/abc/')), Subname, 'basename(/x/abc/)') &
, assert_equal('abc', trim(basename('/x/abc///')), Subname, 'basename(/x/abc///)') &
, assert_equal('/', trim(basename('/')), Subname, 'basename(/)') &
, assert_equal('/', trim(basename('//')), Subname, 'basename(//)') &
, assert_equal('0', trim(ladjusted_int(0_1)), Subname, 'ladjusted_int(0_1)') &
, assert_equal('-123', trim(ladjusted_int(-123_1)), Subname, 'ladjusted_int(-123_1)') &
, assert_equal('-123', trim(ladjusted_int(-123_2)), Subname, 'ladjusted_int(-123_2)') &
, assert_equal('-123', trim(ladjusted_int(-123_4)), Subname, 'ladjusted_int(-123_4)') &
, assert_equal('-123', trim(ladjusted_int(-123_8)), Subname, 'ladjusted_int(-123_8)') &
, assert_equal('-12345', trim(ladjusted_int(-12345_2)),Subname, 'ladjusted_int(-12345_2)') &
, assert_equal('-123456', trim(ladjusted_int(-123456)), Subname, 'ladjusted_int(-123456)') &
, assert_equal('-123456', trim(ladjusted_int(-123456)), Subname, 'ladjusted_int(-123456)') &
, assert_equal('''ab'', ''cdef'', ''ghi''', join_ary(['ab ','cdef','ghi ']), Subname, 'join_ary_chars()') &
, assert_equal('$ab$, $cdef$, $ghi$', join_ary(['ab ','cdef','ghi '],quote='$'), Subname, 'join_ary_chars()') &
, assert_equal('-123, 4, -56', join_ary([-123, 4, -56]), Subname, 'join_ary_int4()') &
, assert_equal('-123; 4; -56', join_ary([-123_2, 4_2, -56_2], '; '), Subname, 'join_ary_int2()') &
, assert_equal(1, findloc1(['X','Y','X'],'X'), Subname, 'findloc1_char') &
, assert_equal(3, findloc1(['X','Y','X'],'X',MASK=[.false.,.true.,.true.]), Subname, 'findloc1_char-mask') &
, assert_equal(3, findloc1(['X','Y','X'],'X',BACK=.true.), Subname, 'findloc1_char-back') &
, assert_equal(1, findloc1(['X','Y','X'],'X',MASK=[.true.,.true.,.false.],BACK=.true.), Subname, 'findloc1_char-ma-ba') &
, assert_equal(2, findloc1([9,8,7,6],8), Subname, 'findloc1_int4') &
, assert_equal(2, findloc1(int([9,8,7,6],kind=2),8), Subname, 'findloc1_int2_4') &
, assert_equal(2, findloc1(real([16,32,0,0,-1],kind=4),32.0), Subname, 'findloc1_real4') &
, assert_equal(2, findloc1(real([16,32,0,0,-1],kind=4),32.d0), Subname, 'findloc1_real4-2') &
, assert_equal(2, findloc1(real([16,32,0,0,-1],kind=8),32.0), Subname, 'findloc1_real8-1') &
, assert_equal(2, findloc1(real([16,32,0,0,-1],kind=8),32.d0), Subname, 'findloc1_real8-2') &
]
iloc = findloc1(ress, .false.) ! Similar to the standard way, but scalar: ilocs(:)=findloc(ress, .false.)
if (iloc == 0) then ! All passed
call print_teststats(Subname, nsuccess=TOT_NTESTS)
return
end if
! Failed
call print_teststats(Subname, nsuccess=iloc-1, ifailed=iloc)
ret_status = 1
end function run_test_alpin_misc_utils
end module test_alpin_misc_utils
module test_alpin_hash
use alpin_unittest
use alpin_err_exit
use test_common
use alpin_misc_utils
use alpin_hash
implicit none
contains
! run tests of routines in alpin_misc_utils.f90
!
! Returns 1 if error is raised (0 otherwise)
integer function run_test_alpin_hash() result(ret_status)
character(*), parameter :: Subname = 'run_test_alpin_hash'
integer, parameter :: TOT_NTESTS = 11
logical, dimension(TOT_NTESTS) :: ress
integer :: iloc
type(t_alpin_hash_logical), dimension(2) :: arlogi
type(t_alpin_hash_char), dimension(2) :: archar
type(t_alpin_hash_int4), dimension(2) :: arint4
type(t_alpin_hash_real8), dimension(2) :: arreal8
logical, dimension(2) :: is_undef
character(len=LEN_T_ALPIN_HASH), dimension(2) :: valchs
ret_status = 0 ! normal ends (n.b., returned value)
arlogi = [t_alpin_hash_logical(key='k1', val=.false.), t_alpin_hash_logical(key='k2', val=.true.)]
archar = [t_alpin_hash_char( key='k1', val='v1'), t_alpin_hash_char( key='k2', val='v2')]
arint4 = [t_alpin_hash_int4( key='k1', val=11), t_alpin_hash_int4( key='k2', val=22)]
arreal8= [t_alpin_hash_real8(key='k1', val=16.0), t_alpin_hash_real8(key='k2', val=32.0)]
call hashval_status('k2', archar, valchs(1), is_undef(1))
call hashval_status('naiyo', archar, valchs(2), is_undef(2))
ress = [ &
assert_not(is_undef(1), Subname, ' hashval_status()-1') &
, assert( is_undef(2), Subname, ' hashval_status()-2') &
, assert_equal('v2', valchs(1), Subname, ' hashval_status("k2")') &
, assert_equal('v2', trim(fetch_hashval('k2', archar)), Subname, ' fetch_hashval("k2")') & ! NOTE: without trim(), this causes either "malloc: *** set a breakpoint in malloc_error_break to debug" or "SIGSEGV: Segmentation fault - invalid memory reference."
! It seems that if a character as a returned value from a function is passed directly (i.e., without trim()) to a different function, it may cause a memory-related error.
, assert_equal('@', trim(fetch_hashval('naiyo', archar, undef='@')), Subname, ' fetch_hashval("naiyo","@")') &
, assert_equal('', trim(fetch_hashval('naiyo', archar)), Subname, ' fetch_hashval("naiyo")') &
, assert_equal(22, fetch_hashval('k2', arint4), Subname, ' fetch_hashval_i4("k2")') &
, assert_equal(79, fetch_hashval('naiyo', arint4, undef=79), Subname, ' fetch_hashval_i4("k2",79)') &
, assert(fetch_hashval('k2', arlogi), Subname, ' fetch_hashval_logi("k2")') &
, assert_in_delta(32.d0, fetch_hashval('k2', arreal8), 1e-8, Subname, ' fetch_hashval_real8("k2")') &
, assert_in_delta(79.d0, fetch_hashval('naiyo', arreal8, undef=79.d0), 1e-8, Subname, ' fetch_hashval_real8("k2",79)') &
]
iloc = findloc1(ress, .false.) ! Similar to the standard way, but scalar: ilocs(:)=findloc(ress, .false.)
if (iloc == 0) then ! All passed
call print_teststats(Subname, nsuccess=TOT_NTESTS)
return
end if
! Failed
call print_teststats(Subname, nsuccess=iloc-1, ifailed=iloc)
ret_status = 1
end function run_test_alpin_hash
end module test_alpin_hash
! -------------------------------------------------------------------
program testalpin
use test_alpin_misc_utils
use test_alpin_hash
implicit none
integer :: status = 0
status = status + run_test_alpin_misc_utils()
status = status + run_test_alpin_hash()
if (status .ne. 0) then
call EXIT(status) ! for gfortran, Lahey Fujitsu Fortran 95, etc
end if
end program testalpin
| test/testalpin.f90 |
subroutine zgefa(a,lda,n,ipvt,info)
integer lda,n,ipvt(1),info
complex*16 a(lda,1)
c
c zgefa factors a complex*16 matrix by gaussian elimination.
c
c zgefa is usually called by zgeco, but it can be called
c directly with a saving in time if rcond is not needed.
c (time for zgeco) = (1 + 9/n)*(time for zgefa) .
c
c on entry
c
c a complex*16(lda, n)
c the matrix to be factored.
c
c lda integer
c the leading dimension of the array a .
c
c n integer
c the order of the matrix a .
c
c on return
c
c a an upper triangular matrix and the multipliers
c which were used to obtain it.
c the factorization can be written a = l*u where
c l is a product of permutation and unit lower
c triangular matrices and u is upper triangular.
c
c ipvt integer(n)
c an integer vector of pivot indices.
c
c info integer
c = 0 normal value.
c = k if u(k,k) .eq. 0.0 . this is not an error
c condition for this subroutine, but it does
c indicate that zgesl or zgedi will divide by zero
c if called. use rcond in zgeco for a reliable
c indication of singularity.
c
c linpack. this version dated 08/14/78 .
c cleve moler, university of new mexico, argonne national lab.
c
c subroutines and functions
c
c blas zaxpy,zscal,izamax
c fortran dabs
c
c internal variables
c
complex*16 t
integer izamax,j,k,kp1,l,nm1
c
complex*16 zdum
double precision cabs1
double precision dreal,dimag
complex*16 zdumr,zdumi
dreal(zdumr) = zdumr
dimag(zdumi) = (0.0d0,-1.0d0)*zdumi
cabs1(zdum) = dabs(dreal(zdum)) + dabs(dimag(zdum))
c
c gaussian elimination with partial pivoting
c
info = 0
nm1 = n - 1
if (nm1 .lt. 1) go to 70
do 60 k = 1, nm1
kp1 = k + 1
c
c find l = pivot index
c
l = izamax(n-k+1,a(k,k),1) + k - 1
ipvt(k) = l
c
c zero pivot implies this column already triangularized
c
if (cabs1(a(l,k)) .eq. 0.0d0) go to 40
c
c interchange if necessary
c
if (l .eq. k) go to 10
t = a(l,k)
a(l,k) = a(k,k)
a(k,k) = t
10 continue
c
c compute multipliers
c
t = -(1.0d0,0.0d0)/a(k,k)
call zscal(n-k,t,a(k+1,k),1)
c
c row elimination with column indexing
c
do 30 j = kp1, n
t = a(l,j)
if (l .eq. k) go to 20
a(l,j) = a(k,j)
a(k,j) = t
20 continue
call zaxpy(n-k,t,a(k+1,k),1,a(k+1,j),1)
30 continue
go to 50
40 continue
info = k
50 continue
60 continue
70 continue
ipvt(n) = n
if (cabs1(a(n,n)) .eq. 0.0d0) info = n
return
end
| scipy/integrate/linpack_lite/zgefa.f |
! This file is part of toml-f.
!
! Copyright (C) 2019-2020 Sebastian Ehlert
!
! Licensed under either of Apache License, Version 2.0 or MIT license
! at your option; you may not use this file except in compliance with
! the License.
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
!> Version information on TOML-Fortran
module tomlf_version
implicit none
private
public :: tomlf_version_string, tomlf_version_compact
!> String representation of the TOML-Fortran version
character(len=*), parameter :: tomlf_version_string = "0.2.0"
!> Major version number of the above TOML-Fortran version
integer, parameter :: major = 0
!> Minor version number of the above TOML-Fortran version
integer, parameter :: minor = 2
!> Patch version number of the above TOML-Fortran version
integer, parameter :: patch = 0
!> Compact numeric representation of the TOML-Fortran version
integer, parameter :: tomlf_version_compact = major*10000 + minor*100 + patch
end module tomlf_version
| src/tomlf/version.f90 |
SUBROUTINE WIND (ILFN) MLu
C
CHARACTER CA*1 MLu
C
DO 20 I=1,30000 MLu
READ (ILFN,10,ERR=100,END=100) CA MLu
10 FORMAT (A) MLu
20 CONTINUE MLu
C
100 CONTINUE MLu
BACKSPACE ILFN M
RETURN MLu
END MLu
| heclib/heclib_f/src/Support/wind.f |
! -*- Mode: Fortran; -*-
!
! (C) 2014 by Argonne National Laboratory.
! See COPYRIGHT in top-level directory.
!
subroutine MPI_Status_set_elements_f08(status, datatype, count, ierror)
use, intrinsic :: iso_c_binding, only : c_loc, c_associated
use, intrinsic :: iso_c_binding, only : c_int, c_ptr
use :: mpi_f08, only : MPI_Status, MPI_Datatype
use :: mpi_f08, only : MPI_STATUS_IGNORE, MPIR_C_MPI_STATUS_IGNORE, assignment(=)
use :: mpi_c_interface, only : c_Datatype
use :: mpi_c_interface, only : c_Status
use :: mpi_c_interface, only : MPIR_Status_set_elements_c
implicit none
type(MPI_Status), intent(inout), target :: status
type(MPI_Datatype), intent(in) :: datatype
integer, intent(in) :: count
integer, optional, intent(out) :: ierror
type(c_Status), target :: status_c
integer(c_Datatype) :: datatype_c
integer(c_int) :: count_c
integer(c_int) :: ierror_c
if (c_int == kind(0)) then
if (c_associated(c_loc(status), c_loc(MPI_STATUS_IGNORE))) then
ierror_c = MPIR_Status_set_elements_c(MPIR_C_MPI_STATUS_IGNORE, datatype%MPI_VAL, count)
else
ierror_c = MPIR_Status_set_elements_c(c_loc(status), datatype%MPI_VAL, count)
end if
else
datatype_c = datatype%MPI_VAL
count_c = count
if (c_associated(c_loc(status), c_loc(MPI_STATUS_IGNORE))) then
ierror_c = MPIR_Status_set_elements_c(MPIR_C_MPI_STATUS_IGNORE, datatype_c, count_c)
else
ierror_c = MPIR_Status_set_elements_c(c_loc(status_c), datatype_c, count_c)
status = status_c
end if
end if
if (present(ierror)) ierror = ierror_c
end subroutine MPI_Status_set_elements_f08
| src/binding/fortran/use_mpi_f08/wrappers_f/status_set_elements_f08ts.f90 |
program scatter_vector
include 'mpif.h'
integer ndims,xmax,ymax,nnodes,myid,totelem
parameter(ndims=2)
parameter(xmax=1000,ymax=1000)
parameter(niters=1)
parameter (totelem=xmax*ymax)
integer comm,ierr
integer status(MPI_STATUS_SIZE)
double precision,allocatable,dimension(:,:) :: A
double precision,allocatable,dimension(:) :: V,dindex1,dindex2,gV
integer,allocatable,dimension(:) :: index1,index2
integer,allocatable,dimension(:) :: lindex1,lindex2
!distribute each array into nnodes processors except gV and index1 and index2
! these last 3 arrays are global arrays. gv will hold the all local V's
! index1 and index2 will hold all the local lindex1's and lindex2's
! respectively
integer xb,yb,i,j,nitems,xbv
comm=MPI_COMM_WORLD
call MPI_init(ierr)
call MPI_COMM_RANK(comm,myid,ierr)
call MPI_COMM_SIZE(comm,nnodes,ierr)
!initialize the input matrixes A and allocate necessary spaces for A,B
!partition the matrix a in (block ,*) way
xb = xmax/nnodes
xbv = totelem/nnodes
!allocate necessary arrays
allocate(A(xb,ymax))
allocate(V(xbv))
allocate(gV(totelem))
allocate(index1(totelem))
allocate(index2(totelem))
allocate(dindex1(totelem))
allocate(dindex2(totelem))
allocate(lindex1(xbv))
allocate(lindex2(xbv))
!last processor is generating random index vectors index1 and index2
! and partition them onto processors and send to correspoding processor
!also last processor is generating random data vector V for each processor
if (myid == nnodes -1) then
call random_number(dindex1)
call random_number(dindex2)
index1 = xmax*dindex1 + 1
index2 = ymax*dindex2 + 1
do np = 0,nnodes-1
call random_number(V)
V = 1000000.0*V
if (np < nnodes-1) then
call MPI_SEND(V,xbv,MPI_DOUBLE_PRECISION,np,0,comm,ierr)
call MPI_SEND(index1(xbv*np+1),xbv,MPI_INTEGER,np,0,comm,ierr)
call MPI_SEND(index1(xbv*np+1),xbv,MPI_INTEGER,np,0,comm,ierr)
endif
enddo
lindex1 = index1((nnodes-1)*xbv+1:totelem)
lindex2 = index2((nnodes-1)*xbv+1:totelem)
else
call MPI_RECV(V,xbv,MPI_DOUBLE_PRECISION,nnodes-1,0,comm,status,ierr)
call MPI_RECV(lindex1,xbv,MPI_INTEGER,nnodes-1,0,comm,status,ierr)
call MPI_RECV(lindex1,xbv,MPI_INTEGER,nnodes-1,0,comm,status,ierr)
endif
!start timer .....
time_begin = MPI_Wtime()
do iter = 1,niters
!collect all the local V's in gV
call MPI_ALLGATHER(V,xbv,MPI_DOUBLE_PRECISION, &
gV,xbv,MPI_DOUBLE_PRECISION,comm,ierr)
!collect all the local arrays index1's and index2's in index1 and index2
call MPI_ALLGATHER(lindex1,xbv,MPI_INTEGER,index1,&
xbv,MPI_INTEGER,comm,ierr)
call MPI_ALLGATHER(lindex2,xbv,MPI_INTEGER,index2,&
xbv,MPI_INTEGER,comm,ierr)
ilb = myid*xbv+1
iub = (myid+1)*xbv
do i=1,totelem
!If I am holding the vector index 'index1(i)' in my local array
!I will get the gV(i)
if ((index1(i) .ge. ilb).and.(index1(i).le.iub)) then
A(index1(i)-ilb+1,index2(i)) = gV(i)
endif
enddo
enddo
! Stop timer
time_end = MPI_Wtime()
if (myid == 0) then
print *,'Elapsed time ',niters,'iterations for scatter'
print *,'For matrix with dimensions',xmax,ymax ,'is'
print *,time_end-time_begin ,'seconds'
endif
deallocate(a)
deallocate(v)
deallocate(gv)
deallocate(index1)
deallocate(index2)
deallocate(lindex1)
deallocate(lindex2)
deallocate(dindex1)
deallocate(dindex2)
call MPI_FINALIZE(ierr)
end
SUBROUTINE all_to_all_int(myprocid,nnodes,comm,fx,global_fx,xbv,totelem)
integer xbv,totelem
integer fx(xbv),global_fx(totelem)
integer myprocid,nnodes,comm
include 'mpif.h'
integer dest,source,nproc,dest_id,ierr
integer status(MPI_STATUS_SIZE)
do j=1,xbv
global_fx(xbv*myprocid+1+j) = fx(j)
enddo
nproc = nnodes
kcnt = myprocid
dest = mod(myprocid+1,nproc)
source = mod(myprocid-1+nproc,nproc)
do i=1,nproc-1
if (mod (myprocid,2) .eq. 0) then
call MPI_SEND(global_fx(kcnt*xbv+1),xbv,&
MPI_INTEGER,dest,0,comm,ierr)
else
ikcnt = mod(kcnt-1+nproc,nproc)
call MPI_RECV(global_fx(ikcnt*xbv+1),xbv, &
MPI_INTEGER,source,0,comm,status,ierr)
endif
if (mod (myprocid,2) .eq. 1) then
call MPI_SEND(global_fx(kcnt*xbv+1),xbv,&
MPI_INTEGER,dest,0,comm,ierr)
else
ikcnt = mod(kcnt-1+nproc,nproc)
call MPI_RECV(global_fx(ikcnt*xbv+1),xbv, &
MPI_INTEGER,source,0,comm,status,ierr)
endif
kcnt = ikcnt
enddo
return
end
SUBROUTINE all_to_all_float(myprocid,nnodes,comm,fx,global_fx,xbv,totelem)
integer xbv,totelem
double precision fx(xbv),global_fx(totelem)
integer myprocid,nnodes,comm
include 'mpif.h'
integer dest,source,nproc,dest_id,ierr
integer status(MPI_STATUS_SIZE)
do j=1,xbv
global_fx(xbv*myprocid+1+j) = fx(j)
enddo
nproc = nnodes
kcnt = myprocid
dest = mod(myprocid+1,nproc)
source = mod(myprocid-1+nproc,nproc)
do i=1,nproc-1
if (mod (myprocid,2) .eq. 0) then
call MPI_SEND(global_fx(kcnt*xbv+1),xbv,&
MPI_DOUBLE_PRECISION,dest,0,comm,ierr)
else
ikcnt = mod(kcnt-1+nproc,nproc)
call MPI_RECV(global_fx(ikcnt*xbv+1),xbv, &
MPI_DOUBLE_PRECISION,source,0,comm,status,ierr)
endif
if (mod (myprocid,2) .eq. 1) then
call MPI_SEND(global_fx(kcnt*xbv+1),xbv,&
MPI_DOUBLE_PRECISION,dest,0,comm,ierr)
else
ikcnt = mod(kcnt-1+nproc,nproc)
call MPI_RECV(global_fx(ikcnt*xbv+1),xbv, &
MPI_DOUBLE_PRECISION,source,0,comm,status,ierr)
endif
kcnt = ikcnt
enddo
return
end
| files/mpi/scatter_with_mpi.f |
c
c -------------------------------------------------------
c
subroutine fluxad(xfluxm,xfluxp,yfluxm,yfluxp,
1 svdflx,mptr,mitot,mjtot,
2 nvar,lenbc,lratiox,lratioy,ng,dtf,dx,dy)
c
implicit double precision (a-h,o-z)
include "call.i"
c :::::::::::::::::::: FLUXAD ::::::::::::::::::::::::::::::::::
c save fine grid fluxes at the border of the grid, for fixing
c up the adjacent coarse cells. at each edge of the grid, only
c save the plus or minus fluxes, as necessary. For ex., on
c left edge of fine grid, it is the minus xfluxes that modify the
c coarse cell.
c :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
dimension xfluxm(mitot,mjtot,nvar), yfluxm(mitot,mjtot,nvar)
dimension xfluxp(mitot,mjtot,nvar), yfluxp(mitot,mjtot,nvar)
dimension svdflx(nvar,lenbc)
nx = mitot-2*ng
ny = mjtot-2*ng
nyc = ny/lratioy
nxc = nx/lratiox
c ::::: left side saved first
lind = 0
do 100 j=1,nyc
lind = lind + 1
jfine = (j-1)*lratioy + ng
do 110 ivar = 1, nvar
do 120 l=1,lratioy
svdflx(ivar,lind) = svdflx(ivar,lind) +
1 xfluxm(ng+1,jfine+l,ivar)*dtf*dy
c write(dbugunit,900)lind,xfluxm(1,jfine+l,ivar),
c . xfluxp(1,jfine+l,ivar)
900 format(' lind ', i4,' m & p ',2e15.7,' svd ',e15.7)
120 continue
110 continue
100 continue
c ::::: top side
c write(dbugunit,*)" saving top side "
do 200 i=1,nxc
lind = lind + 1
ifine = (i-1)*lratiox + ng
do 210 ivar = 1, nvar
do 220 l=1,lratiox
svdflx(ivar,lind) = svdflx(ivar,lind) +
1 yfluxp(ifine+l,mjtot-ng+1,ivar)*dtf*dx
c write(dbugunit,900)lind,yfluxm(ifine+l,mjtot-ng+1,
c . ivar),yfluxp(ifine+l,mjtot-ng+1,ivar),
c . svdflx(ivar,lind)
220 continue
210 continue
200 continue
c ::::: right side
do 300 j=1,nyc
lind = lind + 1
jfine = (j-1)*lratioy + ng
do 310 ivar = 1, nvar
do 320 l=1,lratioy
svdflx(ivar,lind) = svdflx(ivar,lind) +
1 xfluxp(mitot-ng+1,jfine+l,ivar)*dtf*dy
c write(dbugunit,900)lind,xfluxm(mitot-ng+1,jfine+l,
c ivar),xfluxp(mitot-ng+1,jfine+l,ivar)
320 continue
310 continue
300 continue
c ::::: bottom side
c write(dbugunit,*)" saving bottom side "
do 400 i=1,nxc
lind = lind + 1
ifine = (i-1)*lratiox + ng
do 410 ivar = 1, nvar
do 420 l=1,lratiox
svdflx(ivar,lind) = svdflx(ivar,lind) +
1 yfluxm(ifine+l,ng+1,ivar)*dtf*dx
c write(dbugunit,900)lind,yfluxm(ifine+l,ng+1,ivar),
c . yfluxp(ifine+l,ng+1,ivar),svdflx(ivar,lind)
420 continue
410 continue
400 continue
return
end
| amrclaw/2d/lib/fluxad.f |
SUBROUTINE gather_real(SEND,RECV,SIZE,root)
IMPLICIT NONE
include 'mpif.h'
INTEGER SIZE, ROOT
REAL*8 SEND(*), RECV(*)
INTEGER IERR
CALL MPI_GATHER(send,size,MPI_DOUBLE_PRECISION,
& recv,size,MPI_DOUBLE_PRECISION,ROOT,MPI_COMM_WORLD,IERR)
RETURN
END SUBROUTINE
SUBROUTINE gatherv_real( SEND, ssize, RECV,
& rsize, rdisp, root )
IMPLICIT NONE
include 'mpif.h'
INTEGER ssize, ROOT
INTEGER rsize(*), rdisp(*)
REAL*8 SEND(*), RECV(*)
INTEGER IERR
CALL MPI_GATHERV( send, ssize, MPI_DOUBLE_PRECISION,
& recv, rsize, rdisp, MPI_DOUBLE_PRECISION, ROOT,
& MPI_COMM_WORLD, IERR )
RETURN
END SUBROUTINE
| comm/gather.f |
c Wrappers allowing to link MacOSX's Accelerate framework to
c gfortran compiled code
c Accelerate BLAS is cblas (http://www.netlib.org/blas/blast-forum/cblas.tgz);
c these wrappers call the cblas functions via the C-functions defined
c in veclib_cabi.c
REAL FUNCTION WSDOT( N, SX, INCX, SY, INCY )
INTEGER INCX, INCY, N
REAL SX(*), SY(*)
REAL RESULT
EXTERNAL ACC_SDOT
CALL ACC_SDOT( N, SX, INCX, SY, INCY, RESULT )
WSDOT = RESULT
END FUNCTION
REAL FUNCTION WSDSDOT( N, SB, SX, INCX, SY, INCY )
REAL SB
INTEGER INCX, INCY, N
REAL SX(*), SY(*)
REAL RESULT
EXTERNAL ACC_SDSDOT
CALL ACC_SDSDOT( N, SB, SX, INCX, SY, INCY, RESULT )
WSDSDOT = RESULT
END FUNCTION
REAL FUNCTION WSASUM( N, SX, INCX )
INTEGER INCX, N
REAL SX(*)
REAL RESULT
EXTERNAL ACC_SASUM
CALL ACC_SASUM( N, SX, INCX, RESULT )
WSASUM = RESULT
END FUNCTION
REAL FUNCTION WSNRM2( N, SX, INCX )
INTEGER INCX, N
REAL SX(*)
REAL RESULT
EXTERNAL ACC_SNRM2
CALL ACC_SNRM2( N, SX, INCX, RESULT )
WSNRM2 = RESULT
END FUNCTION
REAL FUNCTION WSCASUM( N, CX, INCX )
INTEGER INCX, N
COMPLEX CX(*)
REAL RESULT
EXTERNAL ACC_SCASUM
CALL ACC_SCASUM( N, CX, INCX, RESULT )
WSCASUM = RESULT
END FUNCTION
REAL FUNCTION WSCNRM2( N, CX, INCX )
INTEGER INCX, N
COMPLEX CX(*)
REAL RESULT
EXTERNAL ACC_SCNRM2
CALL ACC_SCNRM2( N, CX, INCX, RESULT )
WSCNRM2 = RESULT
END FUNCTION
c The LAPACK in the Accelerate framework is a CLAPACK
c (www.netlib.org/clapack) and has hence a different interface than the
c modern Fortran LAPACK libraries. These wrappers here help to link
c Fortran code to Accelerate.
c This wrapper files covers all Lapack functions that are in all versions
c before Lapack 3.2 (Lapack 3.2 adds CLANHF and SLANSF that would be
c problematic, but those do not exist in OSX <= 10.6, and are actually not
c used in scipy)
REAL FUNCTION WCLANGB( NORM, N, KL, KU, AB, LDAB, WORK )
CHARACTER NORM
INTEGER KL, KU, LDAB, N
REAL WORK( * )
COMPLEX AB( LDAB, * )
EXTERNAL CLANGB
DOUBLE PRECISION CLANGB
WCLANGB = REAL(CLANGB( NORM, N, KL, KU, AB, LDAB, WORK ))
END FUNCTION
REAL FUNCTION WCLANGE( NORM, M, N, A, LDA, WORK )
CHARACTER NORM
INTEGER LDA, M, N
REAL WORK( * )
COMPLEX A( LDA, * )
EXTERNAL CLANGE
DOUBLE PRECISION CLANGE
WCLANGE = REAL(CLANGE( NORM, M, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WCLANGT( NORM, N, DL, D, DU )
CHARACTER NORM
INTEGER N
COMPLEX D( * ), DL( * ), DU( * )
EXTERNAL CLANGT
DOUBLE PRECISION CLANGT
WCLANGT = REAL(CLANGT( NORM, N, DL, D, DU ))
END FUNCTION
REAL FUNCTION WCLANHB( NORM, UPLO, N, K, AB, LDAB, WORK )
CHARACTER NORM, UPLO
INTEGER K, LDAB, N
REAL WORK( * )
COMPLEX AB( LDAB, * )
EXTERNAL CLANHB
DOUBLE PRECISION CLANHB
WCLANHB = REAL(CLANHB( NORM, UPLO, N, K, AB, LDAB, WORK ))
END FUNCTION
REAL FUNCTION WCLANHE( NORM, UPLO, N, A, LDA, WORK )
CHARACTER NORM, UPLO
INTEGER LDA, N
REAL WORK( * )
COMPLEX A( LDA, * )
EXTERNAL CLANHE
DOUBLE PRECISION CLANHE
WCLANHE = REAL(CLANHE( NORM, UPLO, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WCLANHP( NORM, UPLO, N, AP, WORK )
CHARACTER NORM, UPLO
INTEGER N
REAL WORK( * )
COMPLEX AP( * )
EXTERNAL CLANHP
DOUBLE PRECISION CLANHP
WCLANHP = REAL(CLANHP( NORM, UPLO, N, AP, WORK ))
END FUNCTION
REAL FUNCTION WCLANHS( NORM, N, A, LDA, WORK )
CHARACTER NORM
INTEGER LDA, N
REAL WORK( * )
COMPLEX A( LDA, * )
EXTERNAL CLANHS
DOUBLE PRECISION CLANHS
WCLANHS = REAL(CLANHS( NORM, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WCLANHT( NORM, N, D, E )
CHARACTER NORM
INTEGER N
REAL D( * )
COMPLEX E( * )
EXTERNAL CLANHT
DOUBLE PRECISION CLANHT
WCLANHT = REAL(CLANHT( NORM, N, D, E ))
END FUNCTION
REAL FUNCTION WCLANSB( NORM, UPLO, N, K, AB, LDAB, WORK )
CHARACTER NORM, UPLO
INTEGER K, LDAB, N
REAL WORK( * )
COMPLEX AB( LDAB, * )
EXTERNAL CLANSB
DOUBLE PRECISION CLANSB
WCLANSB = REAL(CLANSB( NORM, UPLO, N, K, AB, LDAB, WORK ))
END FUNCTION
REAL FUNCTION WCLANSP( NORM, UPLO, N, AP, WORK )
CHARACTER NORM, UPLO
INTEGER N
REAL WORK( * )
COMPLEX AP( * )
EXTERNAL CLANSP
DOUBLE PRECISION CLANSP
WCLANSP = REAL(CLANSP( NORM, UPLO, N, AP, WORK ))
END FUNCTION
REAL FUNCTION WCLANSY( NORM, UPLO, N, A, LDA, WORK )
CHARACTER NORM, UPLO
INTEGER LDA, N
REAL WORK( * )
COMPLEX A( LDA, * )
EXTERNAL CLANSY
DOUBLE PRECISION CLANSY
WCLANSY = REAL(CLANSY( NORM, UPLO, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WCLANTB( NORM, UPLO, DIAG, N, K, AB, LDAB, WORK )
CHARACTER DIAG, NORM, UPLO
INTEGER K, LDAB, N
REAL WORK( * )
COMPLEX AB( LDAB, * )
EXTERNAL CLANTB
DOUBLE PRECISION CLANTB
WCLANTB = REAL(CLANTB( NORM, UPLO, DIAG, N, K, AB, LDAB, WORK ))
END FUNCTION
REAL FUNCTION WCLANTP( NORM, UPLO, DIAG, N, AP, WORK )
CHARACTER DIAG, NORM, UPLO
INTEGER N
REAL WORK( * )
COMPLEX AP( * )
EXTERNAL CLANTP
DOUBLE PRECISION CLANTP
WCLANTP = REAL(CLANTP( NORM, UPLO, DIAG, N, AP, WORK ))
END FUNCTION
REAL FUNCTION WCLANTR( NORM, UPLO, DIAG, M, N, A, LDA, WORK )
CHARACTER DIAG, NORM, UPLO
INTEGER LDA, M, N
REAL WORK( * )
COMPLEX A( LDA, * )
EXTERNAL CLANTR
DOUBLE PRECISION CLANTR
WCLANTR = REAL(CLANTR( NORM, UPLO, DIAG, M, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WSCSUM1( N, CX, INCX )
INTEGER INCX, N
COMPLEX CX( * )
EXTERNAL SCSUM1
DOUBLE PRECISION SCSUM1
WSCSUM1 = REAL(SCSUM1( N, CX, INCX ))
END FUNCTION
REAL FUNCTION WSLANGB( NORM, N, KL, KU, AB, LDAB, WORK )
CHARACTER NORM
INTEGER KL, KU, LDAB, N
REAL AB( LDAB, * ), WORK( * )
EXTERNAL SLANGB
DOUBLE PRECISION SLANGB
WSLANGB = REAL(SLANGB( NORM, N, KL, KU, AB, LDAB, WORK ))
END FUNCTION
REAL FUNCTION WSLANGE( NORM, M, N, A, LDA, WORK )
CHARACTER NORM
INTEGER LDA, M, N
REAL A( LDA, * ), WORK( * )
EXTERNAL SLANGE
DOUBLE PRECISION SLANGE
WSLANGE = REAL(SLANGE( NORM, M, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WSLANGT( NORM, N, DL, D, DU )
CHARACTER NORM
INTEGER N
REAL D( * ), DL( * ), DU( * )
EXTERNAL SLANGT
DOUBLE PRECISION SLANGT
WSLANGT = REAL(SLANGT( NORM, N, DL, D, DU ))
END FUNCTION
REAL FUNCTION WSLANHS( NORM, N, A, LDA, WORK )
CHARACTER NORM
INTEGER LDA, N
REAL A( LDA, * ), WORK( * )
EXTERNAL SLANHS
DOUBLE PRECISION SLANHS
WSLANHS = REAL(SLANHS( NORM, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WSLANSB( NORM, UPLO, N, K, AB, LDAB, WORK )
CHARACTER NORM, UPLO
INTEGER K, LDAB, N
REAL AB( LDAB, * ), WORK( * )
EXTERNAL SLANSB
DOUBLE PRECISION SLANSB
WSLANSB = REAL(SLANSB( NORM, UPLO, N, K, AB, LDAB, WORK ))
END FUNCTION
REAL FUNCTION WSLANSP( NORM, UPLO, N, AP, WORK )
CHARACTER NORM, UPLO
INTEGER N
REAL AP( * ), WORK( * )
EXTERNAL SLANSP
DOUBLE PRECISION SLANSP
WSLANSP = REAL(SLANSP( NORM, UPLO, N, AP, WORK ))
END FUNCTION
REAL FUNCTION WSLANST( NORM, N, D, E )
CHARACTER NORM
INTEGER N
REAL D( * ), E( * )
EXTERNAL SLANST
DOUBLE PRECISION SLANST
WSLANST = REAL(SLANST( NORM, N, D, E ))
END FUNCTION
REAL FUNCTION WSLANSY( NORM, UPLO, N, A, LDA, WORK )
CHARACTER NORM, UPLO
INTEGER LDA, N
REAL A( LDA, * ), WORK( * )
EXTERNAL SLANSY
DOUBLE PRECISION SLANSY
WSLANSY = REAL(SLANSY( NORM, UPLO, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WSLANTB( NORM, UPLO, DIAG, N, K, AB, LDAB, WORK )
CHARACTER DIAG, NORM, UPLO
INTEGER K, LDAB, N
REAL AB( LDAB, * ), WORK( * )
EXTERNAL SLANTB
DOUBLE PRECISION SLANTB
WSLANTB = REAL(SLANTB( NORM, UPLO, DIAG, N, K, AB, LDAB, WORK ))
END FUNCTION
REAL FUNCTION WSLANTP( NORM, UPLO, DIAG, N, AP, WORK )
CHARACTER DIAG, NORM, UPLO
INTEGER N
REAL AP( * ), WORK( * )
EXTERNAL SLANTP
DOUBLE PRECISION SLANTP
WSLANTP = REAL(SLANTP( NORM, UPLO, DIAG, N, AP, WORK ))
END FUNCTION
REAL FUNCTION WSLANTR( NORM, UPLO, DIAG, M, N, A, LDA, WORK )
CHARACTER DIAG, NORM, UPLO
INTEGER LDA, M, N
REAL A( LDA, * ), WORK( * )
EXTERNAL SLANTR
DOUBLE PRECISION SLANTR
WSLANTR = REAL(SLANTR( NORM, UPLO, DIAG, M, N, A, LDA, WORK ))
END FUNCTION
REAL FUNCTION WSLAPY2( X, Y )
REAL X, Y
EXTERNAL SLAPY2
DOUBLE PRECISION SLAPY2
WSLAPY2 = REAL(SLAPY2( X, Y ))
END FUNCTION
REAL FUNCTION WSLAPY3( X, Y, Z )
REAL X, Y, Z
EXTERNAL SLAPY3
DOUBLE PRECISION SLAPY3
WSLAPY3 = REAL(SLAPY3( X, Y, Z ))
END FUNCTION
REAL FUNCTION WSLAMCH( CMACH )
CHARACTER CMACH
EXTERNAL SLAMCH
DOUBLE PRECISION SLAMCH
WSLAMCH = REAL(SLAMCH( CMACH ))
END FUNCTION
REAL FUNCTION WSLAMC3( A, B )
REAL A, B
EXTERNAL SLAMC3
DOUBLE PRECISION SLAMC3
WSLAMC3 = REAL(SLAMC3( A, B ))
END FUNCTION
| scipy/_build_utils/src/wrap_accelerate_f.f |
! Copyright (c) 2021-2022, University of Colorado Denver. All rights reserved.
!
! This file is part of <T>LAPACK.
! <T>LAPACK is free software: you can redistribute it and/or modify it under
! the terms of the BSD 3-Clause license. See the accompanying LICENSE file.
subroutine ssymm ( &
layout, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc )
use, intrinsic :: iso_c_binding
use constants, &
only: wp => sp, &
blas_size
implicit none
character :: layout, side, uplo
integer(blas_size) :: m, n, lda, ldb, ldc
real(wp) :: alpha, beta
real(wp), target :: A, B, C
character(c_char) :: c_layout, c_side, c_uplo
include "tblas.fi"
c_layout = layout
c_side = side
c_uplo = uplo
call ssymm_ ( &
c_layout, c_side, c_uplo, m, n, alpha, &
c_loc(A), lda, c_loc(B), ldb, beta, c_loc(C), ldc )
end subroutine
| src/blas/symm.f90 |
c read a few eigenvectors, a spectrum, and try to fit z
program fitz
include 'specarray.h'
parameter(NMAXVECTS=12)
parameter(NMAXSTEP=2*NLOGWMAX)
c scale sky by estimating read and photon noise ?
parameter (IFSCALENOISE=1)
c plot intermediate steps?
parameter (IFPLOTALL=0)
c read spectrum names from a file?
parameter (IFFILE=1)
c overplot the actual z, when known?
parameter (IFREALZ=1)
c max number of minima to find and zestimates to return
parameter (NMAXEST=12)
c real evects(NMAXVECTS,NLOGWMAX)
integer koffset,nvmax,nwlmax
real z
common /vectorfit/ koffset,z,nvmax,nwlmax,
$ evects(NMAXVECTS,NLOGWMAX)
real spec1(NWAVEMAX),espec1(NWAVEMAX)
real spec2(NLOGWMAX),espec2(NLOGWMAX)
real spec3(NLOGWMAX),espec3(NLOGWMAX)
real tmpspec(NLOGWMAX),wavelog(NLOGWMAX),wavelin(NWAVEMAX)
integer ifit(NLOGWMAX)
real wfit(NLOGWMAX),sfit(NLOGWMAX),efit(NLOGWMAX)
real rifit(NLOGWMAX),fitvect(NLOGWMAX)
real waverest1(NLOGWMAX)
real wrestlin(NWAVEMAX)
real zp1log(NMAXSTEP),zarr(NMAXSTEP)
real rnparr(NMAXSTEP)
integer indkarr(NMAXEST)
real diffarr(NMAXEST),zestarr(NMAXEST)
c real xpl(2),ypl(2)
c real zout(NLOGWMAX),zchisq(NLOGWMAX)
character sname*60,esname*60,vname*60
character answ*3,tlabel*60,xlabel*60
character fsname*60,fename*60,fzname*60
integer isize(7)
c stuff for svdfit
real uu(NLOGWMAX,NMAXVECTS)
real vv(NMAXVECTS,NMAXVECTS),ww(NMAXVECTS)
real acoeff(NMAXVECTS),evals(NMAXVECTS)
real chifit(NMAXSTEP),rchifit(NMAXSTEP)
external funcs
include 'pcredshift.h'
c call pgbeg(0,'?',2,2)
call pgbeg(0,'?',1,1)
call pgscf(2)
call pgsch(1.3)
write(*,'("Full continuum fit subtraction [1,y-yes]? ",$)')
read(*,'(a1)') answ
if (answ(1:1) .eq. '0' .or. answ(1:1) .eq. 'n' .or.
$ answ(1:1) .eq. 'N') then
ifcontsub = 0
else
ifcontsub = 1
end if
write(*,'("Do mean subtraction [1,y-yes]? ",$)')
read(*,'(a1)') answ
if (answ(1:1) .eq. '0' .or. answ(1:1) .eq. 'n' .or.
$ answ(1:1) .eq. 'N') then
ifmeansub = 0
else
ifmeansub = 1
end if
100 write(*,
$ '("Diameter for median smoothing, pixels [0,1=none]: ",$)')
read(*,'(a3)') answ
if (answ(1:3) .eq. ' ') then
ndiamed = 0
else
read(answ,*,err=100) ndiamed
end if
c write(*,
c $ '("Restwave spectrum region to use in PCA, min, max: ",$)')
c read(*,*) pcawmin,pcawmax
c pwminlog = log10(pcawmin)
c pwmaxlog = log10(pcawmax)
nvmax=NMAXVECTS
nwlmax=NLOGWMAX
c open file and read eigenvectors. nvects is returned as
c the # of vectors to use, nw is the actual # of wavelength pixels
call readevects(evects,nvmax,nwlmax,waverest1,nv,nw)
nwlog = nw
c figure out w0 and dw for the eigenvectors. This is in log w
c There is no check yet to make sure it's evenly spaced.
dwrlog = (waverest1(nw) - waverest1(1)) / (nwlog-1.)
w0rlog = waverest1(1) - dwrlog
do i=1,nwlog
wrestlin(i) = 10**waverest1(i)
end do
c write(*,*) "w0rlog, dwrlog = ", w0rlog,dwrlog
c plot the eigenvectors
call pgsubp(2,2)
do i=1,nv
do j=1,nwlog
tmpspec(j) = evects(i,j)
end do
call showspec(nwlog,waverest1,tmpspec)
write(tlabel,'(a,1x,i3)') "eigenvector",i-1
call pglabel("log wavelength"," ",tlabel)
end do
c call pgsubp(1,1)
call pgsubp(2,2)
200 continue
if (IFFILE .eq. 1) then
write(*,'("File with spectrum names: ",$)')
read(*,'(a)') fsname
open(10,file=fsname,status='old',err=200)
write(*,'("File with sky/rms names: ",$)')
read(*,'(a)') fename
open(11,file=fename,status='old',err=200)
if (IFREALZ .eq. 1) then
write(*,'("File with actual zs for plot [none]: ",$)')
read(*,'(a)') fzname
if (fzname(1:3) .ne. ' ') then
open(12,file=fzname,status='old',err=202)
ifzfile=1
else
c no actual z file
ifzfile=0
end if
202 continue
end if
end if
open(2,file='fitz.out',status='unknown')
open(3,file='fitz.out1',status='unknown')
open(4,file='fitz.out2',status='unknown')
220 continue
c open files and read spec and error, with wavelength calib.
if (IFFILE .eq. 1) then
read(10,'(a)',err=666,end=666) sname
read(11,'(a)',err=666,end=666) esname
zreal=1.0e6
if (IFREALZ .eq. 1 .and. ifzfile .eq. 1) then
read(12,*,err=222,end=222) zreal
end if
222 continue
else
write(*,'("fits file with spectrum [quit]: ",$)')
read(*,'(a)') sname
if (sname(1:3) .eq. ' ') go to 666
write(*,'("fits file with sky/rms [quit]: ",$)')
read(*,'(a)') esname
if (esname(1:3) .eq. ' ') go to 666
if (IFREALZ .eq. 1) then
write(*,'("actual z for plotting [none]: ",$)')
read(*,'(a)') fzname
zreal=1.0e6
if (fzname(1:3) .ne. ' ') then
read(fzname,*,err=232) zreal
end if
232 continue
end if
end if
call imopen(sname,1,imgs,ier)
if (ier .ne. 0) go to 220
call imgsiz(imgs,isize,idim,itype,ier)
c trim a buffer at end to get rid of the region where Marc encoded
c the slit number
ibuff2 = 25
nwspec = isize(1) - ibuff2
call imopen(esname,1,imge,ier)
c call imgsiz(imge,isize,idim,itype,ier)
if (ier .ne. 0) go to 220
call imgl1r(imgs,spec1,ier)
call imgl1r(imge,espec1,ier)
c find wavelength of pixel 0, and dw/dpix
call imgkwr(imgs,'CRPIX1',refpix,ier)
c if (ier .ne. 0) refpix = badset
if (ier .ne. 0) then
ier=0
refpix = 0.
end if
call imgkwr(imgs,'CRVAL1',refw,ier)
if (ier .ne. 0) refw = badset
call imgkwr(imgs,'CDELT1',dwsp,ier)
if (ier .ne. 0 .or. abs(dwsp) .lt. 1.e-3) then
ier=0
call imgkwr(imgs,'CD1_1',dwsp,ier)
if (ier .ne. 0) dwsp = badset
end if
if (refpix .gt. bad .and. refw .gt. bad .and. dwsp .gt. bad)
$ then
w0sp = refw - refpix*dwsp
c dws = dwsp
else
c we should really do something here
c w0s = badset
c dws = badset
write(*,
$ '("Couldnt get w0 and dw for ",a," enter w0,dw: ",$)') sname
read(*,*) w0sp,dwsp
end if
write(*,*) "w0sp, dwsp = ", w0sp,dwsp
call imclos(imgs,ier)
call imclos(imge,ier)
c zero out anything beyond the actual spectrum
do i=nwspec+1,nw
spec1(i) = 0.0
espec1(i) = 0.0
end do
c try to clean out bad values
badmax = 5000.
do i=1,nw
if(spec1(i) .lt. bad .or. spec1(i) .gt. badmax)
$ spec1(i) = badset
if(espec1(i) .lt. bad .or. espec1(i) .gt. badmax)
$ espec1(i) = badset
end do
c Figure out the ref wavelength for the log rebinning so that
c it falls on the wl scale of the eigenvectors.
tmp = log10(w0sp)
itmp = int( (tmp-w0rlog)/dwrlog )
w0log = w0rlog + dwrlog*itmp
c k0offset is the offset in integer index of log wavelength
c from the beginning of the eigenvectors to the spectrum to be fit.
k0offset = itmp
dwlog = dwrlog
c write(*,*) "w0log, dwlog = ", w0log,dwlog
c convert sky spectrum into std.dev spectrum. This might be better
c done after smoothing and log rebinning?
c Placeholder assumptions: 2x30 min exposures, 5 pixel diam
c extraction window.
if (IFSCALENOISE .eq. 1) then
nexp = 2
exptime = 30.*60.
c dpix = 5.
dpix = 1.
call scalenoise(espec1,nwspec,nexp,exptime,dpix,espec2)
else
c or if the sky spectrum is actually a rms/per pixel spectrum
c we could do nothing, or scale down by a factor of
c sqrt(#pixels). #pixels is most likely 7.
do i=1,nwspec
espec2(i) = espec1(i) / sqrt(7.0)
end do
end if
do i=1,nw
wavelin(i) = w0sp+i*dwsp
wavelog(i) = log10(wavelin(i))
end do
if (IFPLOTALL .ne. 0) then
call showspec(nwspec,wavelin,spec1)
call pgqci(indexc)
call pgsci(3)
call pgline(nwspec,wavelin,espec2)
call pgsci(indexc)
call pglabel("wavelength","counts","spectrum and error")
end if
c blank out? blankoutsky is supposed to run on a 2-d array
call blankoutsky(spec1,1,1,nwspec,wavelin)
cc find region of good data
c call findends(nwspec,spec1,imin,imax)
c imingood = imin
c nwspecgood = imax-imin+1
c median smooth
if (ndiamed .gt. 1) then
call medsmooth(nwspec,spec1,ndiamed,spec2)
c call medsmooth(nwspecgood,spec1(imingood),ndiamed,
c $ spec2(imingood))
c attempt to compensate the errors. I divided ndiamed by 2 as
c a hack since adjacent pixels are not independent (assume the #
C of indep measurements is about pixels/2 if well sampled)
tmp = sqrt(max(ndiamed/2.,1.))
do i=1,nwspec
espec2(i) = espec2(i) / tmp
end do
else
do i=1,nwspec
spec2(i) = spec1(i)
espec2(i) = espec2(i)
end do
end if
if (IFPLOTALL .ne. 0) then
call showspec(nwspec,wavelin,spec2)
call pglabel("wavelength","counts","median smoothed")
call pgqci(indexc)
call pgsci(3)
call pgline(nwspec,wavelin,espec2)
call pgsci(indexc)
end if
c log rebin both. log rebinning the std dev the same way is a
c total hack, thus it is better done on the variance
call logrebin(spec2,nwspec,w0sp,dwsp,nwlog,w0log,dwlog,spec3)
c call logrebin(spec2(imingood),nwspecgood,w0sp,dwsp,
c $ nwlog,w0log,dwlog,spec3)
c convert std dev to variance
do i=1,nwlog
espec3(i) = espec2(i)**2
end do
call logrebin(espec3,nwspec,w0sp,dwsp,nwlog,w0log,dwlog,espec2)
c call logrebin(espec3(imingood),nwspecgood,w0sp,dwsp,
c $ nwlog,w0log,dwlog,espec2)
c convert back
do i=1,nwlog
espec3(i) = sqrt(max(espec2(i),1.e-2))
end do
if (IFPLOTALL .ne. 0) then
call showspec(nwlog,wavelog,spec3)
call pglabel("log wavelength","counts","log rebinned")
call pgqci(indexc)
call pgsci(3)
call pgline(nwlog,wavelog,espec3)
call pgsci(indexc)
end if
c find&clean ends
call findends(nwlog,spec3,imin,imax)
call cleanends(nwlog,spec3,imin,imax)
write(*,*) "imin, imax = ", imin,imax
c continuum subtract
if (ifcontsub .ne. 0) then
contwrad = 100.*dwlog
call contsubmed(spec3,nwlog,dwlog,contwrad)
else
call contsubconst(spec3,nwlog)
end if
if (IFPLOTALL .ne. 0) then
call showspec(nwlog,wavelog,spec3)
call pgqci(indexc)
call pgsci(3)
call pgline(nwlog,wavelog,espec3)
call pgsci(indexc)
call pglabel("log wavelength","counts","continuum subtracted")
end if
c copy wave and spec to temp array, cleaning out bad points
npfit=0
do i=1,nwlog
if(spec3(i) .gt. bad .and. espec3(i) .gt. bad) then
npfit=npfit+1
ifit(npfit) = i
rifit(npfit) = real(i)
wfit(npfit) = w0log + i*dwlog
sfit(npfit) = spec3(i)
efit(npfit) = espec3(i)
end if
end do
write (*,*) npfit, " points to fit"
c if (IFPLOTALL .ne. 0) then
call showspec(npfit,wfit,sfit)
call pgqci(indexc)
call pgsci(3)
call pgline(npfit,wfit,efit)
call pgsci(indexc)
call pglabel("log wavelength","counts",
$ "spectrum and error to fit, "//sname)
c end if
c What are the good data regions? The spectrum was
c good from imin to imax (before cleanends). Eigenvector 1
c (actually the mean) is good from jmin to jmax.
do j=1,nwlog
spec2(j) = evects(1,j)
end do
call findends(nwlog,spec2,jmin,jmax)
c write(*,*) 'imin,imax,jmin,jmax, k0off: ',imin,imax,jmin,jmax,
c $ k0offset
c loop over steps in log w. the spectrum, indexed by i,
c is offset to the red of the eigenvectors, indexed by j,
c by k steps: j+k = i, k = i-j
c and note that the two scales are offset by k0offset, so when
c z=0, i=j-k0offset. Typically the spectrum starts redder
c than the eigenv. so k0offset>0. If we started at
c z=0, k would start at -koffset.
c log w = log wrest + log(1+z), so k*dwlog = log(1+z)
c Start with an offset of z=-0.01
kmin = int(log10(1-0.01)/dwlog) - k0offset
c For pos. redshift, i+k0offset>j (i is position in spectrum, j in evect)
c Go to the point where only 10 pts overlap, which doesn't
c depend on k0offset.
kmax = imax-10-jmin
nk=kmax-kmin+1
c write(*,*) "kmin, kmax: ",kmin,kmax
tmp1 = (kmin+k0offset)*dwlog
tmp2 = (kmax+k0offset)*dwlog
c write(*,*) "log(1+z): ",tmp1,tmp2," z: ",
c $ 10**tmp1-1.0,10**tmp2-1.0
c open(2,file='fitz.out1',status='unknown')
do k=kmin,kmax
c kindex is 1 when k=kmin
kindex = k-kmin+1
c for passing k to the funcs subroutine
koffset=k
zp1log(kindex) = (k+k0offset)*dwlog
zarr(kindex) = 10**zp1log(kindex) - 1.0
z = zarr(kindex)
c we should only use the data that overlaps the eigenvectors,
c the eigenvectors extend from jmin to jmax, and i=j+k.
c But, since we cleaned out bad points, the spectrum to fit
c is no longer evenly spaced in dwlog, so ifitmax is not
c trivial to calculate. Bummer!
c that is, what I've been calling "i" is the index of spec3(i),
c and the contents of ifit() and rifit(), but it is not the
c index of ifit
iminorig = jmin+k
imaxorig = jmax+k
c now find the corresponding index of ifit - i.e.
c we want iminfit where ifit(iminfit) >= iminorig. Confused yet?
call findindex(npfit,ifit,iminorig,imaxorig,iminfit,imaxfit)
npfittmp = imaxfit-iminfit+1
rnparr(kindex) = real(npfittmp)
c write(*,*) "iminfit,imaxfit: ",iminfit,imaxfit,npfittmp
c now we gotta only use the matching points in the eigenvectors,
c which is a PITA. Actually we've solved this through the way
c that funcs() works.
c do fit using svdfit or something like it.
c Each of the functions will be an eigenvector
c call bigsvdfit(wfit,sfit,efit,npfit,acoeff,nv,uu,vv,ww,
c $ nwlmax,nvmax,chisq1,funcs)
c call bigsvdfit(rifit,sfit,efit,npfit,acoeff,nv,uu,vv,ww,
c $ nwlmax,nvmax,chisq1,funcs)
call bigsvdfit(rifit(iminfit),sfit(iminfit),efit(iminfit),
$ npfittmp,acoeff,nv,uu,vv,ww,nwlmax,nvmax,chisq1,funcs)
chifit(kindex) = chisq1
c to get rid of division by zero when there were no points
c to fit.
rchifit(kindex) = chisq1/max(real(npfittmp),1.e-4)
c write(2,*) k,kindex,npfittmp,zp1log(kindex),zarr(kindex),
c $ chifit(kindex),rchifit(kindex)
end do
c close(2)
c find the absolute minimum in chi-squared. there are probably
c better ways to do this in the long run
c call findabsmin(nk,chifit,indkmin,chimin)
c call findabsmin(nk,rchifit,indkrmin,rchimin)
c try finding the point with the biggest drop below "continuum"
c i.e. deepest local minimum
call findlocmin(nk,chifit,indkmin,chimin,chiminavg)
call findlocmin(nk,rchifit,indkrmin,rchimin,rchiminavg)
c find the n deepest local minima in chi squared
nfind=5
call findmultmin(nk,chifit,nfind,indkarr,diffarr)
zmin=zarr(indkmin)
zrmin=zarr(indkrmin)
do i=1,nfind
zestarr(i) = zarr(indkarr(i))
end do
write(*,*) "chisq min at ",indkmin,zmin,chimin,chiminavg
write(*,*) "reduced chisq min at ",indkrmin,zrmin,rchimin,
$ rchiminavg
c write stuff to output files.
c 2 - fitz.out gets # of z-estimates, z-estimates, spec name
c 3 - fitz.out1 gets specname(truncated), z(deepest chisq min) ,
c z(deepest rchisq min), chi-min, chi-"continuum",
c rchi-min, rchi-"continuum"
c 4 - fitz.out2 gets for each z-est: k-index, z-est, depth in chisq
c write(3,'(a,f7.4,3x,f7.4)') sname,zmin,zrmin
write(3,'(a25,2(3x,f7.4),3x,4(1x,1pe10.3))')
$ sname,zmin,zrmin,chimin,chiminavg,rchimin,rchiminavg
write(2,'(i2,$)') nfind
do i=1,nfind
write(2,'(2x,f7.4$)') zestarr(i)
write(4,'(i5,2x,f7.4,2x,f9.1,$)') indkarr(i),zestarr(i),
$ diffarr(i)
end do
write(2,'(2x,a25)') sname
write(4,'(2x,a25)') sname
c plot
c call showspec(nk,zp1log,chifit)
c call plotz(log10(1.+zreal),log10(1.+zmin),log10(1+zrmin))
c write(xlabel,1010) "log(1+z)",zreal,zmin,zrmin
c call pglabel(xlabel,"chi-squared",sname)
call showspec(nk,zarr,chifit)
call plotz(zreal,zmin,zrmin)
write(xlabel,1010) "z",zreal,zmin,zrmin
call pglabel(xlabel,"chi-squared",sname)
call showspec(nk,zarr,rchifit)
call plotz(zreal,zmin,zrmin)
write(xlabel,1010) "z",zreal,zmin,zrmin
call pglabel(xlabel,"reduced chi-squared",sname)
1010 format(a,", z=",f7.4," zest1=",f7.4," zest2=",f7.4)
c call showspec(nk,zarr,rnparr)
c call pglabel("z","number of points in fit",sname)
c calculate the fit at chimin. Redo the fit to get the coeffs
c for the best-fit spectrum
koffset=indkmin+kmin-1
call findindex(npfit,ifit,jmin+koffset,jmax+koffset,
$ iminfit,imaxfit)
npfittmp=imaxfit-iminfit+1
c write(*,*) "iminfit,imaxfit: ",iminfit,imaxfit,npfittmp
c call bigsvdfit(rifit,sfit,efit,npfit,acoeff,nv,uu,vv,ww,
c $ nwlmax,nvmax,chisq1,funcs)
call bigsvdfit(rifit(iminfit),sfit(iminfit),efit(iminfit),
$ npfittmp,acoeff,nv,uu,vv,ww,nwlmax,nvmax,chisq1,funcs)
write(*,*) "coeffs ",(acoeff(i),i=1,nv)
do i=1,npfit
call funcs(rifit(i),evals,nv)
fitvect(i) = 0.0
do j=1,nv
fitvect(i) = fitvect(i) + acoeff(j)*evals(j)
end do
end do
call showspec(npfit,wfit,sfit)
call pglabel("log wavelength","counts"," ")
call pgmtxt('T',2.5,0.0,0.0,sname)
call pgmtxt('T',1.5,0.0,0.0,"spectrum and best fits")
call pgqci(indexc)
call pgsci(3)
call pgline(npfit,wfit,fitvect)
write(tlabel,'(a,f7.4)') "chi-sq, z=",zmin
call pgmtxt('T',2.5,1.0,1.0,tlabel)
call pgsci(indexc)
c calculate the fit at rchimin
koffset=indkrmin+kmin-1
call findindex(npfit,ifit,jmin+koffset,jmax+koffset,
$ iminfit,imaxfit)
npfittmp=imaxfit-iminfit+1
c call bigsvdfit(rifit,sfit,efit,npfit,acoeff,nv,uu,vv,ww,
c $ nwlmax,nvmax,chisq1,funcs)
call bigsvdfit(rifit(iminfit),sfit(iminfit),efit(iminfit),
$ npfittmp,acoeff,nv,uu,vv,ww,nwlmax,nvmax,chisq1,funcs)
c write(*,*) "coeffs ",(acoeff(i),i=1,nv)
do i=1,npfit
call funcs(rifit(i),evals,nv)
fitvect(i) = 0.0
do j=1,nv
fitvect(i) = fitvect(i) + acoeff(j)*evals(j)
end do
end do
call pgqci(indexc)
call pgsci(2)
call pgline(npfit,wfit,fitvect)
write(tlabel,'(a,f7.4)') "red.chisq, z=",zrmin
call pgmtxt('T',1.5,1.0,1.0,tlabel)
call pgsci(indexc)
go to 220
666 continue
close(2)
close(3)
close(4)
close(10)
close(11)
if (ifzfile .ne. 0) close(12)
call pgend()
end
cccccccccccccccccccc
c funcs returns the values of the nv eigenvectors
c evaluated at position xfit, in the array evals
c if svdfit is called with argument wfit, xfit is the
c log wavelength.
c if svdfit is called with argument rifit, xfit is the
c index in the log wavelength array, as a real.
c
subroutine funcs(xfit,evals,nv)
include 'specarray.h'
c having NMAXVECTS in here as well as fitz is a bad kludge
parameter(NMAXVECTS=12)
real evals(nv)
common /vectorfit/ koffset,z,nvmax,nwlmax,
$ evects(NMAXVECTS,NLOGWMAX)
c find the index corresponding to the position xfit
c and retrieve the eigenvector values
c this is for use with rifit
ispec = nint(xfit)
jvect = ispec-koffset
if(jvect .ge. 1 .and. jvect .le. nwlmax) then
do i=1,nv
evals(i) = evects(i,jvect)
end do
else
do i=1,nv
evals(i) = 0.0
end do
end if
return
end
cccccccccccccccccccccccccccccccccccccccc
c Draw vertical lines for the actual z and z-estimates
c on the chi-squared plots.
subroutine plotz(zreal,zest1,zest2)
real xpl(2),ypl(2)
integer indexc,indexls
ypl(1) = -100.
ypl(2) = 1.0e10
call pgqci(indexc)
call pgqls(indexls)
c call pgsls(1)
xpl(1) = zreal
xpl(2) = zreal
call pgsci(4)
call pgsls(5)
call pgline(2,xpl,ypl)
xpl(1) = zest1
xpl(2) = zest1
call pgsci(3)
call pgsls(4)
call pgline(2,xpl,ypl)
xpl(1) = zest2
xpl(2) = zest2
call pgsci(2)
call pgsls(3)
call pgline(2,xpl,ypl)
call pgsci(indexc)
call pgsls(indexls)
return
end
| fitz.f |
!
! Copyright 2018 SALMON developers
!
! Licensed under the Apache License, Version 2.0 (the "License");
! you may not use this file except in compliance with the License.
! You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
!
!-----------------------------------------------------------------------------------------
subroutine eh_finalize(grid,tmp)
use inputoutput, only: utime_from_au,ulength_from_au,uenergy_from_au,unit_system,iperiodic,&
ae_shape1,ae_shape2,e_impulse,sysname,nt_em,nenergy,de, &
directory,iobs_num_em,iobs_samp_em
use salmon_parallel, only: nproc_id_global
use salmon_communication, only: comm_is_root
use salmon_maxwell, only:fdtd_grid,fdtd_tmp
implicit none
type(fdtd_grid) :: grid
type(fdtd_tmp) :: tmp
integer :: ii
real(8),parameter :: pi=3.141592653589793d0
character(128) :: save_name
!output linear response(matter dipole pm and current jm are outputted: pm = -dip and jm = -curr)
if(ae_shape1=='impulse'.or.ae_shape2=='impulse') then
if(iperiodic==0) then
!output time-dependent dipole data
if(comm_is_root(nproc_id_global)) then
save_name=trim(adjustl(directory))//'/'//trim(adjustl(sysname))//'_p.data'
open(tmp%ifn,file=save_name)
select case(unit_system)
case('au','a.u.')
write(tmp%ifn,'(A)') "# time[a.u.], dipoleMoment(x,y,z)[a.u.]"
case('A_eV_fs')
write(tmp%ifn,'(A)') "# time[fs], dipoleMoment(x,y,z)[Ang.]"
end select
do ii=1,nt_em
write(tmp%ifn, '(E13.5)',advance="no") tmp%time_lr(ii)*utime_from_au
write(tmp%ifn, '(3E16.6e3)',advance="yes") -tmp%dip_lr(ii,:)*ulength_from_au
end do
close(tmp%ifn)
end if
!output lr data
call eh_fourier(nt_em,nenergy,grid%dt,de,tmp%time_lr,tmp%dip_lr(:,1),tmp%fr_lr(:,1),tmp%fi_lr(:,1))
call eh_fourier(nt_em,nenergy,grid%dt,de,tmp%time_lr,tmp%dip_lr(:,2),tmp%fr_lr(:,2),tmp%fi_lr(:,2))
call eh_fourier(nt_em,nenergy,grid%dt,de,tmp%time_lr,tmp%dip_lr(:,3),tmp%fr_lr(:,3),tmp%fi_lr(:,3))
if(comm_is_root(nproc_id_global)) then
save_name=trim(adjustl(directory))//'/'//trim(adjustl(sysname))//'_lr.data'
open(tmp%ifn,file=save_name)
select case(unit_system)
case('au','a.u.')
write(tmp%ifn,'(A)') "# energy[a.u.], Re[alpha](x,y,z)[a.u.], Im[alpha](x,y,z)[a.u.], df/dE(x,y,z)[a.u.]"
case('A_eV_fs')
write(tmp%ifn,'(A)') "# energy[eV], Re[alpha](x,y,z)[Ang.**3], Im[alpha](x,y,z)[Ang.**3], df/dE(x,y,z)[1/eV]"
end select
do ii=0,nenergy
write(tmp%ifn, '(E13.5)',advance="no") dble(ii)*de*uenergy_from_au
write(tmp%ifn, '(3E16.6e3)',advance="no") tmp%fr_lr(ii,:)/(-e_impulse)*(ulength_from_au**3.0d0)
write(tmp%ifn, '(3E16.6e3)',advance="no") tmp%fi_lr(ii,:)/(-e_impulse)*(ulength_from_au**3.0d0)
write(tmp%ifn, '(3E16.6e3)',advance="yes") 2.0d0*dble(ii)*de/pi*tmp%fi_lr(ii,:)/(-e_impulse)/uenergy_from_au
end do
close(tmp%ifn)
end if
elseif(iperiodic==3) then
!output time-dependent dipole data
if(comm_is_root(nproc_id_global)) then
save_name=trim(adjustl(directory))//'/'//trim(adjustl(sysname))//'_current.data'
open(tmp%ifn,file=save_name)
select case(unit_system)
case('au','a.u.')
write(tmp%ifn,'(A)') "# time[a.u.], current(x,y,z)[a.u.]"
case('A_eV_fs')
write(tmp%ifn,'(A)') "# time[fs], current(x,y,z)[A/Ang.^2]"
end select
do ii=1,nt_em
write(tmp%ifn, '(E13.5)',advance="no") tmp%time_lr(ii)*utime_from_au
write(tmp%ifn, '(3E16.6e3)',advance="yes") -tmp%curr_lr(ii,:)*tmp%uAperm_from_au/ulength_from_au
end do
close(tmp%ifn)
end if
!output lr data
call eh_fourier(nt_em,nenergy,grid%dt,de,tmp%time_lr,tmp%curr_lr(:,1),tmp%fr_lr(:,1),tmp%fi_lr(:,1))
call eh_fourier(nt_em,nenergy,grid%dt,de,tmp%time_lr,tmp%curr_lr(:,2),tmp%fr_lr(:,2),tmp%fi_lr(:,2))
call eh_fourier(nt_em,nenergy,grid%dt,de,tmp%time_lr,tmp%curr_lr(:,3),tmp%fr_lr(:,3),tmp%fi_lr(:,3))
if(comm_is_root(nproc_id_global)) then
save_name=trim(adjustl(directory))//'/'//trim(adjustl(sysname))//'_lr.data'
open(tmp%ifn,file=save_name)
select case(unit_system)
case('au','a.u.')
write(tmp%ifn,'(A)') "# energy[a.u.], Re[epsilon](x,y,z), Im[epsilon](x,y,z)"
case('A_eV_fs')
write(tmp%ifn,'(A)') "# energy[eV], Re[epsilon](x,y,z), Im[epsilon](x,y,z)"
end select
do ii=1,nenergy
write(tmp%ifn, '(E13.5)',advance="no") dble(ii)*de*uenergy_from_au
write(tmp%ifn, '(3E16.6e3)',advance="no") 1.0d0-4.0d0*pi*tmp%fi_lr(ii,:)/(-e_impulse)/(dble(ii)*de)
write(tmp%ifn, '(3E16.6e3)',advance="yes") 4.0d0*pi*tmp%fr_lr(ii,:)/(-e_impulse)/(dble(ii)*de)
end do
end if
end if
end if
!observation
if(iobs_num_em>0) then
if(comm_is_root(nproc_id_global)) then
!make information file
open(tmp%ifn,file=trim(directory)//"/obs0_info.data")
write(tmp%ifn,'(A,A14)') 'unit_system =',trim(unit_system)
write(tmp%ifn,'(A,I14)') 'iperiodic =',iperiodic
write(tmp%ifn,'(A,ES14.5)') 'dt_em =',grid%dt*utime_from_au
write(tmp%ifn,'(A,I14)') 'nt_em =',(tmp%iter_end-tmp%iter_sta+1)
write(tmp%ifn,'(A,ES14.5,A,ES14.5,A,ES14.5)') 'al_em =',&
grid%rlsize(1)*ulength_from_au,', ',&
grid%rlsize(2)*ulength_from_au,', ',&
grid%rlsize(3)*ulength_from_au
write(tmp%ifn,'(A,ES14.5,A,ES14.5,A,ES14.5)') 'dl_em =',&
grid%hgs(1)*ulength_from_au,', ',&
grid%hgs(2)*ulength_from_au,', ',&
grid%hgs(3)*ulength_from_au
write(tmp%ifn,'(A,I14,A,I14,A,I14)') 'lg_sta =',&
grid%lg_sta(1),', ',grid%lg_sta(2),', ',grid%lg_sta(3)
write(tmp%ifn,'(A,I14,A,I14,A,I14)') 'lg_end =',&
grid%lg_end(1),', ',grid%lg_end(2),', ',grid%lg_end(3)
write(tmp%ifn,'(A,I14)') 'iobs_num_em =',iobs_num_em
write(tmp%ifn,'(A,I14)') 'iobs_samp_em =',iobs_samp_em
write(tmp%ifn,'(A,ES14.5)') 'e_max =',tmp%e_max
write(tmp%ifn,'(A,ES14.5)') 'h_max =',tmp%h_max
close(tmp%ifn)
end if
end if
!deallocate
deallocate(tmp%ex_y,tmp%c1_ex_y,tmp%c2_ex_y,tmp%ex_z,tmp%c1_ex_z,tmp%c2_ex_z,&
tmp%ey_z,tmp%c1_ey_z,tmp%c2_ey_z,tmp%ey_x,tmp%c1_ey_x,tmp%c2_ey_x,&
tmp%ez_x,tmp%c1_ez_x,tmp%c2_ez_x,tmp%ez_y,tmp%c1_ez_y,tmp%c2_ez_y,&
tmp%hx_y,tmp%c1_hx_y,tmp%c2_hx_y,tmp%hx_z,tmp%c1_hx_z,tmp%c2_hx_z,&
tmp%hy_z,tmp%c1_hy_z,tmp%c2_hy_z,tmp%hy_x,tmp%c1_hy_x,tmp%c2_hy_x,&
tmp%hz_x,tmp%c1_hz_x,tmp%c2_hz_x,tmp%hz_y,tmp%c1_hz_y,tmp%c2_hz_y)
!write end
if(comm_is_root(nproc_id_global)) then
write(*,*) "-------------------------------------------------------"
write(*,*) "**************************"
write(*,*) "FDTD end"
write(*,*) "**************************"
end if
end subroutine eh_finalize
!=========================================================================================
!= Fourier transformation in eh ==========================================================
subroutine eh_fourier(nt,ne,dt,de,ti,ft,fr,fi)
use inputoutput, only: wf_em
implicit none
integer,intent(in) :: nt,ne
real(8),intent(in) :: dt,de
real(8),intent(in) :: ti(nt),ft(nt)
real(8),intent(out) :: fr(0:ne),fi(0:ne)
integer :: ie,it
real(8) :: ft_wf(nt)
real(8) :: hw
complex(8),parameter :: zi=(0.d0,1.d0)
complex(8) :: zf
!apply window function
if(wf_em=='y') then
do it=1,nt
ft_wf(it)=ft(it)*( 1.0d0 -3.0d0*(ti(it)/maxval(ti(:)))**2.0d0 +2.0d0*(ti(it)/maxval(ti(:)))**3.0d0 )
end do
else
ft_wf(:)=ft(:)
end if
!Fourier transformation
do ie=0,ne
hw=dble(ie)*de; zf=(0.0d0,0.0d0);
!$omp parallel
!$omp do private(it) reduction( + : zf )
do it=1,nt
zf=zf+exp(zi*hw*ti(it))*ft_wf(it)
end do
!$omp end do
!$omp end parallel
zf=zf*dt; fr(ie)=real(zf,8); fi(ie)=aimag(zf)
end do
end subroutine eh_fourier
| src/maxwell/eh_finalize.f90 |
subroutine ed_gf_cluster_scalar(zeta,gf)
complex(8) :: zeta
complex(8),dimension(Nlat,Nlat,Nspin,Nspin,Norb,Norb),intent(inout) :: gf
complex(8) :: green
integer :: ispin
integer :: ilat,jlat
integer :: iorb,jorb
integer :: iexc,Nexc
integer :: ichan,Nchannel,istate,Nstates
integer :: i,is,js
complex(8) :: weight,de
real(8) :: chan4
!
if(.not.allocated(impGmatrix))stop "ed_gf_cluster ERROR: impGmatrix not allocated!"
!
if(ed_gf_symmetric)then
chan4=0.d0
else
chan4=1.d0
endif
gf = zero
!
do ilat=1,Nlat
do jlat=1,Nlat
do iorb=1,Norb
do jorb=1,Norb
do ispin=1,Nspin
!
green = zero
Nstates = size(impGmatrix(ilat,jlat,ispin,ispin,iorb,jorb)%state)
do istate=1,Nstates
Nchannel = size(impGmatrix(ilat,jlat,ispin,ispin,iorb,jorb)%state(istate)%channel)
do ichan=1,Nchannel
Nexc = size(impGmatrix(ilat,jlat,ispin,ispin,iorb,jorb)%state(istate)%channel(ichan)%poles)
if(Nexc .ne. 0)then
do iexc=1,Nexc
weight = impGmatrix(ilat,jlat,ispin,ispin,iorb,jorb)%state(istate)%channel(ichan)%weight(iexc)
de = impGmatrix(ilat,jlat,ispin,ispin,iorb,jorb)%state(istate)%channel(ichan)%poles(iexc)
green = green + weight/(zeta-de)
enddo
endif
enddo
enddo
gf(ilat,jlat,ispin,ispin,iorb,jorb) = green
enddo
enddo
enddo
enddo
enddo
do ispin=1,Nspin
do iorb=1,Norb
do jorb=1,Norb
do ilat=1,Nlat
do jlat=1,Nlat
if(ilat==jlat .and. iorb==jorb)cycle
gf(ilat,jlat,ispin,ispin,iorb,jorb) = 0.5d0*(gf(ilat,jlat,ispin,ispin,iorb,jorb) &
- (one-chan4*xi)*gf(ilat,ilat,ispin,ispin,iorb,iorb) - (one-chan4*xi)*gf(jlat,jlat,ispin,ispin,jorb,jorb))
enddo
enddo
enddo
enddo
enddo
!
end subroutine ed_gf_cluster_scalar
subroutine ed_gf_cluster_array(zeta,gf)
complex(8),dimension(:) :: zeta
complex(8),dimension(Nlat,Nlat,Nspin,Nspin,Norb,Norb,size(zeta)),intent(inout) :: gf
complex(8),dimension(Nlat,Nlat,Nspin,Nspin,Norb,Norb) :: green
integer :: ispin
integer :: ilat,jlat
integer :: iorb,jorb
integer :: iexc,Nexc
integer :: ichan,Nchannel,istate,Nstates
integer :: i,is,js
real(8) :: weight,de
!
if(.not.allocated(impGmatrix))stop "ed_gf_cluster ERROR: impGmatrix not allocated!"
!
gf = zero
do i=1,size(zeta)
call ed_gf_cluster_scalar(zeta(i),green)
gf(:,:,:,:,:,:,i) = green
enddo
!
end subroutine ed_gf_cluster_array
| ED_IO/gf_cluster.f90 |
module model_initialiser
contains
! remesher:
! Function based on the origianl REMESH function
! Input (in COMMON blocks):
! H(,) - array of independent variables (in unnamed COMMON)
! DH(,) - list of changes in independent variables (in unnamed COMMON)
! KH - current number of meshpoints in H(,)
! Input options:
! KH2 - new number of meshpoints for this model
! JCH - switch to determine whether to construct new mesh spacing function
! and initialise composition or not.
! BMS - Total mass in the binary (EV)
! TM - New mass of the star
! P1 - New rotational period of the star (solid body)
! ECC - New eccentricity of the binary
! OA - New orbital angular momentum
! JSTAR - Labels which if the stars to initislise variables for
! JF - Switch to decide which variables to recompute
! TODO: this could be split up into different subroutines for each of the
! individual tasks.
subroutine remesher( kh2, jch, bms, tm, p1, ecc, oa, jstar, jf )
use real_kind
use constants
use mesh
use init_dat
use settings
use control
use atomic_data
use test_variables
use eostate_types
use structure_functions
use current_model_properties
use structure_variables
use accretion_abundances
use indices
implicit none
integer, intent(in) :: kh2, jch, jstar, jf
real(double), intent(in) :: bms, tm, p1, ecc, oa
integer :: nm_current, nm_next, nm_target
integer :: ik, ikk, ih, i
integer :: jo
integer :: ksv, kt5
type(init_dat_settings) :: initdat
real(double) :: nh(nvar,nm), ndh(nvar,nm), nndh(nvar,nm)
real(double) :: q1, q2, dk, dty, vd, dtb, ageb, pcrit, wcrit, w1
real(double) :: si, vma, hpc
logical :: equilibrium
logical :: newmesh
real(double) :: var(nvar), dvar(nvar), fn1(nfunc)
real(double) :: qa(NM)
type(eostate) :: eos
real(double) :: xh0, xhe0, xc0, xn0, xo0, xne0, xmg0, xsi0, xfe0
real(double) :: che
real(double) :: xh, xhe, xc, xn, xo, xne, xmg, xsi, xfe
real(double) :: r
real(double) :: qq ! Determines mesh-point metric: mesh-point interval
real(double) :: qm ! Determines mesh-point metric: derivative of mesh spacing function wrt mass
real(double) :: phim ! Derivative of gravitational potential with respect to m**(2/3)
real(double) :: gmr ! Effective gravity at the surface(?)
real(double) :: m3 ! m^(1/3), m is the mass coordinate
! Backup current settings so we can restore them when we're done
dtb = dt
ageb = age
call push_init_dat(initdat, kh2, ksv, kt5, jch)
! Change settings to a reasonable set of defaults
call load_basic_init_dat(ik, ksv, kt5, ik)
kop = initdat%kop
kx = 0; ky = 0; kz = 0; kth = 0
cmi = 0.0
crd = 0.0d0
kt1 = 100
kt2 = 0
kt3 = 0
kt4 = 100
kt5 = 100
ksv = 100
joc = 1
jter = 0
! Set initial composition.
! The composition variables are NOT the actual mass fractions if we
! use non-integer atomic masses, so we have to compute what they are
! The composition variables used in the code are baryon number fractions
! We calculate this even if we don't want to do a ZAMS run because we need to
! know the baryon number densities of Fe, Si and Mg.
! Note that the actual abundances of Si and Fe are forced to by non-zero.
! This is because the EoS becomes poorly defined if there are not enough free
! electrons. It has no impact on the opacity and only a small impact on the
! mean molecular weight and the mass loss rate.
che = 1.0d0 - ch - czs
cn = 1.0d0 - cc - co - cne - cmg - csi - cfe
xh0 = ch*cbn(1)/can(1)
xhe0 = che*cbn(2)/can(2)
xc0 = cc*czs*cbn(3)/can(3)
xn0 = cn*czs*cbn(4)/can(4)
xo0 = co*czs*cbn(5)/can(5)
xne0 = cne*czs*cbn(6)/can(6)
xmg0 = cmg*czs*cbn(7)/can(7)
xsi0 = csi*czs*cbn(8)/can(8)
xfe0 = cfe*czs*cbn(9)/can(9)
xh = xh0
xhe = xhe0
xc = xc0
xn = xn0
xo = xo0
xne = xne0
xmg = xmg0
xsi = max(xsi0, csi*1.0d-4)
xfe = max(xfe0, cfe*1.0d-4)
vma = xh + xhe + xc + xn + xo + xne + xmg + xsi + xfe
xh = xh / vma
xhe = xhe / vma
xc = xc / vma
xn = xn / vma
xo = xo / vma
xne = xne / vma
xfe = xfe / vma
xsi = xsi / vma
xmg = xmg / vma
! Initialise composition variables
h(VAR_MG24, 1:kh) = xmg
h(VAR_SI28, 1:kh) = xsi
h(VAR_FE56, 1:kh) = xfe
if ( jch >= 4 ) then
h(VAR_H1,1:kh) = xh
h(VAR_O16,1:kh) = xo
h(VAR_HE4,1:kh) = xhe
h(VAR_C12,1:kh) = xc
h(VAR_NE20,1:kh) = xne
h(VAR_N14,1:kh) = xn
end if
! We should always do this for Mg24, since that's never stored
if (use_mg24_eqn) then
do ik=1, kh
xmg = h(VAR_H1,ik) + h(VAR_HE4, ik) + h(VAR_C12, ik) + h(VAR_O16, ik) + h(VAR_NE20, ik) + h(VAR_N14, ik) + xfe + xsi
h(VAR_MG24,ik) = max(0.0d0, 1.0 - xmg)
end do
end if
! Now we must also convert the abundances of the accreted material. If not
! set from init.dat, set from initial abundances.
!> \todo FIXME: this will cause problems if we ever need to call REMESH twice in
!! the same run
!<
x1ac = x1ac*cbn(1)/can(1)
x4ac = x4ac*cbn(2)/can(2)
x12ac = x12ac*cbn(3)/can(3)
x14ac = x14ac*cbn(4)/can(4)
x16ac = x16ac*cbn(5)/can(5)
x20ac = x20ac*cbn(6)/can(6)
x24ac = x24ac*cbn(7)/can(7)
if (x1ac < 0.0) x1ac = xh0
if (x4ac < 0.0) x4ac = xhe0
if (x12ac < 0.0) x12ac = xc0
if (x14ac < 0.0) x14ac = xn0
if (x16ac < 0.0) x16ac = xo0
if (x20ac < 0.0) x20ac = xne0
if (x24ac < 0.0) x24ac = xmg0
vma = x1ac + x4ac + x12ac + x14ac + x16ac + x20ac + x24ac + xfe + xsi
x1ac = x1ac / vma
x4ac = x4ac / vma
x12ac = x12ac / vma
x14ac = x14ac / vma
x16ac = x16ac / vma
x20ac = x20ac / vma
x24ac = x24ac / vma
! make sure XH is 1-everything else and abundancies sum to 1
x1ac = max(0.0d0, 1.0d0-(x4ac+x12ac+x14ac+x16ac+x20ac+x24ac+xfe0+xsi0))
! Initialise accretion abundances for both stars
xac(1, 1:2) = x1ac
xac(2, 1:2) = x4ac
xac(3, 1:2) = x12ac
xac(4, 1:2) = x14ac
xac(5, 1:2) = x16ac
xac(6, 1:2) = x20ac
xac(7, 1:2) = x24ac
! Set initial values of some other variables
! Typical mass-scale for the interior (needed for mesh spacing function)
mc(jstar) = tm ! New mass after remesh
var(:) = h(:, kh)
dvar(:) = 0.0d0
call funcs1 ( kh, -2, var(:), dvar(:), fn1(:), eos, px=sx(:,2))
hpc = sqrt(eos%p/(cg * eos%rho * eos%rho))
mc(jstar) = 3.5d-33 * eos%rho * hpc**3
! Initialise binary (orbital) parameters
h(VAR_HORB, 1:kh) = oa ! New orbital angular momentum
h(VAR_ECC, 1:kh) = ecc ! New eccentricity
h(VAR_BMASS, 1:kh) = bms ! New total binary mass
! First: change the number of meshpoints or the mesh spacing function
! Determine if we need to calculate a new mesh (independent of the number
! of meshpoints)
newmesh = .false.
if (jch>3) newmesh = .true.
! Set new number of meshpoints
nm_current = kh
nm_target = kh2
nm_next = nm_target
print *, 'nremesh from', nm_current, 'to', nm_target
do while(newmesh .or. nm_current /= nm_next)
newmesh = .false.
print *, 'trying ', nm_next
! Store old model, so we can go back if needed
nh(:,1:nm_current) = h(:,1:nm_current)
ndh(:,1:nm_current) = dh(:,1:nm_current)
! Find values of mesh spacing function
do ik=1, nm_current
var(:) = h(:, ik)
call funcs1 ( ik, -2, var(:), dvar(:), fn1(:)) ! Calculate stuff
qa(ik) = qq ! Store mesh spacing function
end do
! Interpolate model onto new mesh
! Find values of mesh spacing function at the external points
! Needed to calculate the new mesh, where the meshspacing gradient is
! constant.
q1 = qa(1)
q2 = (nm_next - 1.0d0)/(qa(nm_current) - qa(1))
do ik = 1, nm_current
qa(ik) = (qa(ik) - q1)*q2 + 1.0d0 ! Adjust meshspacing
end do
ih = 1
do ik = 1, nm_next
dk = 0.0d0
if ( ik == nm_next ) ih = nm_current
if ( ik /= 1 .and. ik /= nm_next ) then
! Find the proper value for the meshspacing function at
! this meshpoint
do i = 1, 50
! Sanity check: abort if we're running out of the mesh
! boundary
if ( ih+1 > nm_current) then
write (0, *) &
'remesh running outside mesh boundary, aborting'
stop
end if
if ( ik >= qa(ih + 1) ) ih = ih + 1
if ( ik < qa(ih + 1) ) exit ! Break loop
end do
dk = (ik - qa(ih))/(qa(ih + 1) - qa(ih))
end if
! Linear interpolation for new H and DH
h(:, ik) = nh(:, ih) + dk*(nh(:, ih + 1) - nh(:, ih))
nndh(:, ik) = ndh(:, ih) + dk*(ndh(:, ih + 1) - ndh(:, ih))
end do
!H(6, 1:KH) = 1.0/Q2 ! Gradient of mesh spacing
! Now see if the model will converge properly if we let the code iterate
dty = dt/csy
jo = 0
jnn = 0
kh = nm_next
call printb ( jo, 1, 22 )
age = age - dty
call nextdt ( dty, jo, 22 )
jnn = 1
dh(:, 1:nm_next) = 0.0d0
call solver(20, id, kt5, jo)
if (jo == 0) then
print *, 'converged ok'
! If yes, pick next number of meshpoints
nm_current = nm_next
nm_next = nm_target
h(:,1:nm_current) = h(:,1:nm_current) + dh(:,1:nm_current)
else
! If no, pick a smaller number of meshpoints in between the current value
! and the target and try again.
nm_next = (nm_current+nm_next)/2
print *, 'cannot converge, reduce to ', nm_next
! Restore backup copies of H and DH
h(:,1:nm_current) = nh(:,1:nm_current)
dh(:,1:nm_current) = ndh(:,1:nm_current)
end if
end do
print *, 'nremesh finished with ', nm_current, '(wanted ', nm_target,')'
if (nm_current < nm_target) then
print *, '*** nremesh failed ***'
stop
end if
dh(:, 1:nm_current) = nndh(:,1:nm_current)
dh(:, 1:nm_current) = 0.0
kh = nm_current
! Second: scale the mass
vd = tm/h(VAR_MASS, 1)
vd = 1.0
print *, 'scaling mass by factor', vd
do while (abs(1.0d0 - vd) > 0.1)
vd = max(0.9d0,min(vd, 1.1d0))
h(VAR_MASS, 1:kh) = vd*h(VAR_MASS, 1:kh) ! Scale mass
kth = 1
jhold = 4
equilibrium = equilibrate_model(kt5)
if (.not. equilibrium) then !H(:,1:nm_current) = NH(:,1:nm_current)
print *, '*** failed ***'
stop
end if
vd = tm/h(VAR_MASS, 1)
end do
h(VAR_MASS, 1:kh) = vd*h(VAR_MASS, 1:kh) ! Scale mass
! Third: scale the surface rotation rate
! Make the whole star rotate with the surface rate, if desired
! Convert rotational period -> rotation rate
forall (ik=1:kh) h(VAR_OMEGA, ik) = 2.0*cpi/(h(VAR_OMEGA, ik) * csday)
if (start_with_rigid_rotation) h(VAR_OMEGA,2:kh) = h(VAR_OMEGA,1)
! Now scale the surface rate, similar to the way the mass is scaled
! If we forced the star to rigid rotation before then this will set the
! rotation profile throughout the entire star
wcrit = sqrt(cg*tm/exp(3*h(VAR_LNR, 1)))
pcrit = 2.0*cpi/wcrit/csday
w1 = 2.0*cpi/p1/csday
print *, 'scaling rotation rate by factor', w1/h(13, 1)
! For rotation rates within 1/4 of critical be a bit more careful. Here we
! need to approach the desired rate smoothly, adjusting the structure of
! the star at each step.
!> \todo FIXME: This should be more akin to the bit that updates the code on the
!! new mesh, ie, not necessarily bring the star into equilibrium.
!<
if (wcrit/w1 < 4.0) then
call set_solid_rotation
print *, 'Period', p1, 'close to critical rate', pcrit
vd = 0.25*wcrit/h(VAR_OMEGA,1)
h(VAR_OMEGA, 1:kh) = vd*h(VAR_OMEGA, 1:kh) ! Scale rotation rate
kth = 1
equilibrium = converge_model(kt5)
do while (equilibrium .and. abs(w1 - h(VAR_OMEGA,1)) > 1.0d-6)
vd = max(0.9d0,min(vd, 1.1d0))
h(VAR_OMEGA, 1:kh) = vd*h(VAR_OMEGA, 1:kh)
jhold = 4
equilibrium = converge_model(kt5)
vd = w1/h(VAR_OMEGA, 1)
if (.not. equilibrium) then
print *, '*** failed ***'
stop
end if
end do
end if
vd = w1/h(VAR_OMEGA, 1)
h(VAR_OMEGA, 1:kh) = vd*h(VAR_OMEGA, 1:kh) ! Scale rotational period
! Compute moment of inertia and surface potential
if (jf /= 2) then
q2 = h(VAR_QK,1)
h(VAR_QK, 1:kh) = 1.0d0
h(VAR_INERT, 1:kh) = 1.0d0 ! Moment of Inertia
h(VAR_PHI, 1:kh) = 0.0d0 ! Gravitational potential
do ik = 2, kh
ikk = kh + 2 - ik
var(:) = h(:, ik)
call funcs1 ( ik, -2, var(:), dvar(:), fn1(:), px=sx(:,ikk))
qq = sx(85, ikk)
qm = sx(86, ikk)
phim = sx(87, ikk)
m3 = sx(89, ikk)
r = sqrt(abs(exp(2.0d0*var(7)) - ct(8)))
h(VAR_INERT, ik) = h(VAR_INERT, ik - 1) + r*r*m3/(abs(qm))
h(VAR_PHI, ik) = h(VAR_PHI, ik - 1) + phim/abs(qm)
end do
gmr = sx(88, kh+1)
h(VAR_QK, 1:kh) = q2
h(VAR_PHIS, 1:kh) = - gmr ! Potential at the stellar surface
si = h(VAR_INERT, kh) ! Total moment of inertia
do ik = 1, kh
h(VAR_INERT, ik) = (si - h(VAR_INERT, ik))*abs(q2) ! Moment of inertia of interior
h(VAR_PHI, ik) = - gmr - h(VAR_PHI, ik)*abs(q2) ! Gravitational potential
end do
end if
! Total angular momentum integration
h(VAR_TAM, 1:kh) = h(VAR_INERT, 1:kh)*h(VAR_OMEGA, 1)
if (relax_loaded_model) then
kth = 1
jhold = 4
print *, 'equilibrating...'
equilibrium = equilibrate_model(kt5)
if (.not. equilibrium) then
print *, '*** failed ***'
stop
end if
print *, 'done'
dh(:, 1:kh) = 0.0
end if
! Restore old init.dat
call pop_init_dat(initdat, ik, ksv, kt5, ik)
dt = dtb
age = ageb
print *, 'Remesh done'
end subroutine remesher
function converge_model(kt5)
use real_kind
use mesh
use constants
use test_variables
implicit none
logical :: converge_model
integer, intent(in) :: kt5
real(double) :: dty
integer :: jo
jo = 0
dty = dt/csy
call solver(20, id, kt5, jo)
if (jo == 0) then
age = 0.0d0
call printb ( jo, 1, 22 )
h(:,1:kh) = h(:,1:kh) + dh(:,1:kh)
call nextdt ( dty, jo, 22 )
end if
converge_model = (jo == 0)
end function converge_model
function equilibrate_model(kt5)
use real_kind
use mesh
use constants
use test_variables
implicit none
logical :: equilibrate_model
integer, intent(in) :: kt5
real(double) :: dty
integer :: i, jo
jo = 0
do i=1, 40
dty = dt/csy
call solver(20, id, kt5, jo)
if (jo /= 0) exit
age = 0.0d0
call printb ( jo, 1, 22 )
h(:,1:kh) = h(:,1:kh) + dh(:,1:kh)
call nextdt ( dty, jo, 22 )
if (abs(lth) < 1.0d-8 .or. lth < 0.0d0) exit
end do
equilibrate_model = .false.
if (lth < 1.0d-6 .and. jo == 0) equilibrate_model = .true.
end function equilibrate_model
end module model_initialiser
| src/amuse/community/evtwin/src/trunk/code/nremesh.f90 |
SUBROUTINE MF_LGTORI
& (xintg,r,drdc,nderiv)
implicit complex (a-h,o-z)
real omega,wavenr,
& rmax,xmgsq,cthrsh,cmgsq,delta(4)
common/mf_flag/iexact,iovflo,kexact,lowg,nodivd,noevct,
& nofinl,nointg,nomesh,notlin
& /mf_lgfl/lgflag(4)
& /mf_mode/theta,c,s,csq,ssq,omega,wavenr,ideriv
& /mf_rmtx/x(4),dxdc(4),dxdh(4),dhdxdc(4)
dimension xintg(8),r(4),drdc(4)
data delta/1.0,0.0,0.0,1.0/,cthrsh/0.03/,rmax/50.0/
cmgsq=REAL(c)**2+AIMAG(c)**2
do i=1,4
if (lgflag(i) .eq. 0) then
xmgsq=REAL(xintg(i))**2+AIMAG(xintg(i))**2
if ((xmgsq .gt. rmax**2 .and. cmgsq .ge. cthrsh**2)
& .or.
& (xmgsq .gt. 1.e3*rmax**2 .and. cmgsq .lt. cthrsh**2))
& then
iovflo=1
RETURN
end if
x(i)=xintg(i)
if (nderiv .eq. 1) dxdc(i)=xintg(i+4)
else
if (ABS(REAL(xintg(i))) .gt. 10.) then
iovflo=1
RETURN
end if
r(i)=EXP(xintg(i))
x(i)=(r(i)+delta(i))/c
if (nderiv .eq. 1) then
dlnrdc=xintg(i+4)
drdc(i)=r(i)*dlnrdc
dxdc(i)=(drdc(i)-x(i))/c
end if
end if
end do
RETURN
END ! MF_LGTORI
| LWPCv21/lib/mf_lgtori.for |
C$Procedure ZZRYTPDT ( DSK, ray touches planetodetic element )
SUBROUTINE ZZRYTPDT ( VERTEX, RAYDIR, BOUNDS,
. CORPAR, MARGIN, NXPTS, XPT )
C$ Abstract
C
C SPICE Private routine intended solely for the support of SPICE
C routines. Users should not call this routine directly due to the
C volatile nature of this routine.
C
C Find nearest intersection to a given ray's vertex of the ray and
C a planetodetic volume element. If the vertex is inside the
C element, the vertex is considered to be the solution.
C
C In the computation performed by this routine, ellipsoidal
C surfaces are used, instead of surfaces of constant altitude, to
C define boundaries of planetodetic volume elements. The element
C defined by the input boundaries is contained in the element
C bounded by the input latitude and longitude boundaries and by the
C ellipsoidal surfaces.
C
C$ Disclaimer
C
C THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C DSK
C
C$ Keywords
C
C GEOMETRY
C INTERCEPT
C INTERSECTION
C RAY
C SURFACE
C TOPOGRAPHY
C
C$ Declarations
IMPLICIT NONE
INCLUDE 'dsktol.inc'
DOUBLE PRECISION VERTEX ( 3 )
DOUBLE PRECISION RAYDIR ( 3 )
DOUBLE PRECISION BOUNDS ( 2, 3 )
DOUBLE PRECISION CORPAR ( * )
DOUBLE PRECISION MARGIN
INTEGER NXPTS
DOUBLE PRECISION XPT ( 3 )
INTEGER LONIDX
PARAMETER ( LONIDX = 1 )
INTEGER LATIDX
PARAMETER ( LATIDX = 2 )
INTEGER ALTIDX
PARAMETER ( ALTIDX = 3 )
C$ Brief_I/O
C
C VARIABLE I/O DESCRIPTION
C -------- --- --------------------------------------------------
C VERTEX I Ray's vertex.
C RAYDIR I Ray's direction vector.
C BOUNDS I Bounds of planetodetic volume element.
C CORPAR I Coordinate parameters.
C MARGIN I Margin used for element expansion.
C NXPTS O Number of intercept points.
C XPT O Intercept.
C LONIDX P Longitude index.
C LATIDX P Latitude index.
C ALTIDX P Altitude index.
C
C$ Detailed_Input
C
C VERTEX,
C RAYDIR are, respectively, the vertex and direction vector of
C the ray to be used in the intercept computation.
C
C Both the vertex and ray direction must be represented
C in the reference frame to which the planetodetic
C volume element boundaries correspond. The vertex is
C considered to be an offset from the center of the
C reference frame associated with the element.
C
C BOUNDS is a 2x3 array containing the bounds of a planetodetic
C volume element. Normally this is the coverage boundary
C of a DSK segment. In the element
C
C BOUNDS(I,J)
C
C J is the coordinate index. J is one of
C
C { LONIDX, LATIDX, ALTIDX }
C
C I is the bound index.
C
C I = 1 -> lower bound
C I = 2 -> upper bound
C
C If the longitude upper bound is not greater than the
C longitude lower bound, a value greater than the upper
C bound by 2*pi is used for the comparison.
C
C RE,
C F are, respectively, the equatorial radius and
C flattening coefficient associated with the
C planetodetic coordinate system in which the input
C volume element is described.
C
C
C MARGIN is a scale factor used to effectively expand the
C segment boundaries so as to include intersections
C that lie slightly outside the volume element.
C
C
C$ Detailed_Output
C
C XPT is the intercept of the ray on the surface described
C by the segment, if such an intercept exists. If the
C ray intersects the surface at multiple points, the
C one closest to the ray's vertex is selected. XPT is
C valid if and only if FOUND is .TRUE.
C
C XPT is expressed in the reference frame associated
C with the inputs VERTEX and RAYDIR. XPT represents
C an offset from the origin of the coordinate system.
C
C XPT is valid only if NXPTS is set to 1.
C
C
C NXPTS is the number of intercept points of the ray and
C the volume element.
C
C Currently there are only two possible values for
C NXPTS:
C
C 1 for an intersection
C 0 for no intersection
C
C If the vertex is inside the element, NXPTS is
C set to 1.
C
C$ Parameters
C
C LONIDX is the index of longitude in the second dimension of
C BOUNDS.
C
C LATIDX is the index of latitude in the second dimension of
C BOUNDS.
C
C ALTIDX is the index of altitude in the second dimension of
C BOUNDS.
C$ Exceptions
C
C 1) If MARGIN is negative, the error SPICE(VALUEOUTOFRANGE)
C is signaled.
C
C 2) If the input ray direction vector is zero, the error
C SPICE(ZEROVECTOR) will be signaled.
C
C 3) Any errors that occur while calculating the ray-surface
C intercept will be signaled by routines in the call tree
C of this routine.
C
C$ Files
C
C None. However, the input segment boundaries normally have
C been obtained from a loaded DSK file.
C
C$ Particulars
C
C This routine sits on top of data DSK type-specific ray-segment
C intercept routines such as DSKX02.
C
C$ Examples
C
C See usage in ZZDSKBUX.
C
C$ Restrictions
C
C This is a private routine. It is meant to be used only by the DSK
C subsystem.
C
C$ Literature_References
C
C None.
C
C$ Author_and_Institution
C
C N.J. Bachman (JPL)
C
C$ Version
C
C- SPICELIB Version 1.0.0, 19-JAN-2017 (NJB)
C
C-&
C$ Index_Entries
C
C find intercept of ray on planetodetic volume element
C
C-&
C
C SPICELIB functions
C
DOUBLE PRECISION DPMAX
DOUBLE PRECISION HALFPI
DOUBLE PRECISION VDIST
DOUBLE PRECISION VDOT
DOUBLE PRECISION VNORM
DOUBLE PRECISION VSEP
LOGICAL FAILED
LOGICAL RETURN
LOGICAL VZERO
LOGICAL ZZPDPLTC
C
C Local parameters
C
C
C Altitude expansion factor:
C
DOUBLE PRECISION RADFAC
PARAMETER ( RADFAC = 1.1D0 )
C
C Element boundary indices:
C
INTEGER WEST
PARAMETER ( WEST = 1 )
INTEGER EAST
PARAMETER ( EAST = 2 )
INTEGER SOUTH
PARAMETER ( SOUTH = 1 )
INTEGER NORTH
PARAMETER ( NORTH = 2 )
INTEGER LOWER
PARAMETER ( LOWER = 1 )
INTEGER UPPER
PARAMETER ( UPPER = 2 )
INTEGER NONE
PARAMETER ( NONE = 0 )
C
C Local variables
C
DOUBLE PRECISION AMNALT
DOUBLE PRECISION AMXALT
DOUBLE PRECISION ANGLE
DOUBLE PRECISION APEX ( 3 )
DOUBLE PRECISION DIST
DOUBLE PRECISION EASTB ( 3 )
DOUBLE PRECISION EBACK ( 3 )
DOUBLE PRECISION EMAX
DOUBLE PRECISION EMIN
DOUBLE PRECISION ENDPT2 ( 3 )
DOUBLE PRECISION F
DOUBLE PRECISION LONCOV
DOUBLE PRECISION MAXALT
DOUBLE PRECISION MAXLAT
DOUBLE PRECISION MAXLON
DOUBLE PRECISION MAXR
DOUBLE PRECISION MINALT
DOUBLE PRECISION MINLAT
DOUBLE PRECISION MINLON
DOUBLE PRECISION MNDIST
DOUBLE PRECISION NEGDIR ( 3 )
DOUBLE PRECISION PMAX
DOUBLE PRECISION PMIN
DOUBLE PRECISION RE
DOUBLE PRECISION RP
DOUBLE PRECISION S
DOUBLE PRECISION SRFX ( 3 )
DOUBLE PRECISION UDIR ( 3 )
DOUBLE PRECISION VTXANG
DOUBLE PRECISION VTXLVL
DOUBLE PRECISION VTXOFF ( 3 )
DOUBLE PRECISION WBACK ( 3 )
DOUBLE PRECISION WESTB ( 3 )
DOUBLE PRECISION XPT2 ( 3 )
DOUBLE PRECISION XINCPT
DOUBLE PRECISION YINCPT
DOUBLE PRECISION Z ( 3 )
INTEGER NX
LOGICAL FOUND
LOGICAL INSIDE
LOGICAL XIN
LOGICAL XVAL1
LOGICAL XVAL2
C
C Saved variables
C
SAVE Z
C
C Initial values
C
DATA Z / 0.D0, 0.D0, 1.D0 /
IF ( RETURN() ) THEN
RETURN
END IF
CALL CHKIN ( 'ZZRYTPDT' )
IF ( MARGIN .LT. 0.D0 ) THEN
CALL SETMSG ( 'Margin must be non-negative but was #.' )
CALL ERRDP ( '#', MARGIN )
CALL SIGERR ( 'SPICE(VALUEOUTOFRANGE)' )
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( VZERO(RAYDIR) ) THEN
CALL SETMSG ( 'The ray''s direction was the zero vector.' )
CALL SIGERR ( 'SPICE(ZEROVECTOR)' )
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
C
C Determine whether the vertex is inside the element.
C
CALL ZZINPDT ( VERTEX, BOUNDS, CORPAR, MARGIN, NONE, INSIDE )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( INSIDE ) THEN
C
C We know the answer.
C
NXPTS = 1
CALL VEQU ( VERTEX, XPT )
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
C
C Get semi-axis lengths of the reference spheroid.
C
RE = CORPAR(1)
F = CORPAR(2)
RP = RE * ( 1.D0 - F )
C
C Extract the segment's coordinate bounds into easily
C readable variables.
C
MINALT = BOUNDS( LOWER, ALTIDX )
MAXALT = BOUNDS( UPPER, ALTIDX )
C
C Normalize the longitude bounds. After this step, the bounds will
C be in order and differ by no more than 2*pi.
C
CALL ZZNRMLON( BOUNDS(WEST,LONIDX), BOUNDS(EAST,LONIDX), ANGMRG,
. MINLON, MAXLON )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
MINLAT = BOUNDS( SOUTH, LATIDX )
MAXLAT = BOUNDS( NORTH, LATIDX )
C
C Compute adjusted altitude bounds, taking margin into
C account.
C
AMNALT = MINALT - MARGIN * ABS(MINALT)
AMXALT = MAXALT + MARGIN * ABS(MAXALT)
C
C Generate semi-axis lengths of inner and outer bounding
C ellipsoids.
C
IF ( RE .GE. RP ) THEN
C
C The reference spheroid is oblate.
C
CALL ZZELLBDS ( RE, RP, AMXALT, AMNALT,
. EMAX, PMAX, EMIN, PMIN )
ELSE
C
C The reference spheroid is prolate.
C
CALL ZZELLBDS ( RP, RE, AMXALT, AMNALT,
. PMAX, EMAX, PMIN, EMIN )
END IF
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
C
C The vertex is outside the element.
C
C Indicate no intersection to start.
C
NXPTS = 0
C
C We'll use a unit length copy of the ray's direction vector.
C
CALL VHAT ( RAYDIR, UDIR )
C
C Initialize the distance to the closest solution. We'll keep track
C of this quantity in order to compare competing solutions.
C
MNDIST = DPMAX()
C
C Find the intersection of the ray and outer bounding ellipsoid, if
C possible. Often this intersection is the closest to the vertex.
C If the intersection exists and is on the boundary of the element,
C it's a winner.
C
CALL SURFPT ( VERTEX, UDIR, EMAX, EMAX, PMAX, SRFX, FOUND )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( .NOT. FOUND ) THEN
C
C There are no intersections. The ray cannot hit the volume
C element.
C
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
C
C The ray hits the outer bounding ellipsoid. See whether
C the longitude and latitude are within bounds, taking
C the margin into account. Exclude the altitude coordinate
C from testing.
C
CALL ZZINPDT ( SRFX, BOUNDS, CORPAR, MARGIN, ALTIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
C
C This solution is a candidate.
C
CALL VEQU ( SRFX, XPT )
NXPTS = 1
C
C Find the level surface parameter of the vertex relative
C to the adjusted outer bounding ellipsoid.
C
VTXLVL = ( VERTEX(1)/EMAX )**2
. + ( VERTEX(2)/EMAX )**2
. + ( VERTEX(3)/PMAX )**2
IF ( VTXLVL .GT. 1.D0 ) THEN
C
C The vertex is outside this ellipsoid, and the DSK segment
C lies within the ellipsoid.
C
C No other intersection can be closer to the vertex;
C we don't need to check the other surfaces.
C
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
ELSE
C
C We have a possible solution.
C
MNDIST = VDIST( VERTEX, XPT )
END IF
END IF
C
C So far there may be a candidate solution. We'll try the latitude
C boundaries next.
C
C For testing intersections with the latitude boundaries, we'll
C need a far endpoint for the line segment on which to perform the
C test.
C
MAXR = MAX ( EMAX, PMAX )
S = VNORM(VERTEX) + RADFAC * MAXR
CALL VLCOM ( 1.D0, VERTEX, S, UDIR, ENDPT2 )
C
C Now try the upper latitude bound. We can skip this test
C if the upper bound is pi/2 radians.
C
IF ( MAXLAT .LT. HALFPI() ) THEN
C
C Let ANGLE be the angular separation of the surface of latitude
C MAXLAT and the +Z axis. Note that the surface might be the
C lower nappe of the cone.
C
ANGLE = MAX ( 0.D0, HALFPI() - MAXLAT )
C
C Compute the Z coordinate of the apex of the latitude cone.
C
CALL ZZELNAXX ( RE, RP, MAXLAT, XINCPT, YINCPT )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
APEX(1) = 0.D0
APEX(2) = 0.D0
APEX(3) = YINCPT
C
C Find the offset of the ray's vertex from the cone's apex,
C and find the angular separation of the offset from the +Z
C axis. This separation enables us to compare the latitude of
C the vertex to the latitude boundary without making a RECGEO
C call to compute the planetodetic coordinates of the vertex.
C
C (The comparison will be done later.)
C
CALL VSUB ( VERTEX, APEX, VTXOFF )
VTXANG = VSEP ( VTXOFF, Z )
C
C Check for intersection of the ray with the latitude cone.
C
CALL INCNSG ( APEX, Z, ANGLE, VERTEX, ENDPT2, NX, SRFX, XPT2 )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
C
C Unlike the case of latitudinal coordinates, for planetodetic
C coordinates, the surface of the latitude cone does not
C coincide with the set of points having that latitude (which is
C equal to pi/2 - the cone's angular separation from the +Z
C axis). The subset of the cone having the specified latitude is
C truncated by the X-Y plane. If we ignore round-off errors, we
C can assert that the Z-coordinate of a point having the given
C planetodetic latitude must match the direction of the nappe of
C the cone: positive if ANGLE < pi/2, negative if ANGLE > pi/2,
C and 0 if ANGLE = pi/2.
C
C However, we cannot ignore round-off errors. For a cone having
C angle from its central axis of nearly pi/2, it's possible for
C a valid ray-cone intercept to be on the "wrong" side of the
C X-Y plane due to round-off errors. So we use a more robust
C check to determine whether an intercept should be considered
C to have the same latitude as the cone.
C
C Check all intercepts.
C
IF ( NX .GT. 0 ) THEN
C
C Check the first intercept.
C
XVAL1 = ZZPDPLTC( RE, F, SRFX, MAXLAT )
XVAL2 = .FALSE.
IF ( NX .EQ. 2 ) THEN
C
C Check the second intercept.
C
XVAL2 = ZZPDPLTC( RE, F, XPT2, MAXLAT )
END IF
IF ( XVAL1 .AND. ( .NOT. XVAL2 ) ) THEN
NX = 1
ELSE IF ( XVAL2 .AND. (.NOT. XVAL1 ) ) THEN
C
C Only the second solution is valid. Overwrite
C the first.
C
NX = 1
CALL VEQU( XPT2, SRFX )
ELSE IF ( ( .NOT. XVAL1 ) .AND. ( .NOT. XVAL2 ) ) THEN
C
C Neither solution is valid.
C
NX = 0
END IF
END IF
IF ( NX .GE. 1 ) THEN
C
C The ray intercept SRFX lies on the upper latitude boundary.
C
C See whether SRFX meets the longitude and proxy altitude
C constraints.
C
CALL ZZINPDT ( SRFX, BOUNDS, CORPAR, MARGIN, LATIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
C
C SRFX is a candidate solution.
C
DIST = VDIST( VERTEX, SRFX )
IF ( DIST .LT. MNDIST ) THEN
CALL VEQU ( SRFX, XPT )
NXPTS = 1
IF ( VTXANG .LT. ANGLE ) THEN
IF ( ( MAXLAT .LT. 0.D0 )
. .OR. ( VERTEX(3) .GT. 0.D0 ) ) THEN
C
C If MAXLAT is negative, the vertex offset
C being outside the cone is enough to
C guarantee the planetodetic latitude of the
C vertex is greater than that of the cone.
C
C If MAXLAT is non-negative, the angle of the
C vertex offset relative to the +Z axis is not
C enough; we need the vertex to lie above the
C X-Y plane as well.
C
C Getting here means one of these conditions
C was met.
C
C Since the latitude of the vertex is greater
C than MAXLAT, this is the best solution, since
C the volume element is on the other side of the
C maximum latitude boundary.
C
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
END IF
C
C This is the best solution seen so far, but we
C need to check the remaining boundaries.
C
MNDIST = DIST
END IF
END IF
IF ( NX .EQ. 2 ) THEN
C
C Check the second solution as well.
C
CALL ZZINPDT ( XPT2, BOUNDS, CORPAR,
. MARGIN, LATIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
C
C XPT2 is a candidate solution.
C
DIST = VDIST( VERTEX, XPT2 )
IF ( DIST .LT. MNDIST ) THEN
CALL VEQU ( XPT2, XPT )
NXPTS = 1
MNDIST = DIST
C
C This is the best solution seen so far.
C However, it's not necessarily the best
C solution. So we continue.
C
END IF
END IF
END IF
C
C We've handled the second root, if any.
C
END IF
C
C We're done with the upper latitude boundary.
C
END IF
C
C Try the lower latitude bound. We can skip this test if the lower
C bound is -pi/2 radians.
C
IF ( MINLAT .GT. -HALFPI() ) THEN
C
C Let ANGLE be the angular separation of the surface
C of latitude MINLAT and the +Z axis. Note that the
C surface might be the lower nappe of the cone.
C
ANGLE = HALFPI() - MINLAT
C Compute the Z coordinate of the apex of the latitude cone.
C
CALL ZZELNAXX ( RE, RP, MINLAT, XINCPT, YINCPT )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
APEX(1) = 0.D0
APEX(2) = 0.D0
APEX(3) = YINCPT
CALL INCNSG ( APEX, Z, ANGLE, VERTEX,
. ENDPT2, NX, SRFX, XPT2 )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
C
C Find the offset of the ray's vertex from the cone's apex,
C and find the angular separation of the offset from the +Z
C axis. This separation enables us to compare the latitude of
C the vertex to the latitude boundary without making a RECGEO
C call to compute the planetodetic coordinates of the vertex.
C
C (The comparison will be done later.)
C
CALL VSUB ( VERTEX, APEX, VTXOFF )
VTXANG = VSEP ( VTXOFF, Z )
C
C Check whether the latitude of the intercept can be
C considered to match that of the cone.
C
IF ( NX .GT. 0 ) THEN
C
C Check the first intercept.
C
XVAL1 = ZZPDPLTC( RE, F, SRFX, MINLAT )
XVAL2 = .FALSE.
IF ( NX .EQ. 2 ) THEN
C
C Check the second intercept.
C
XVAL2 = ZZPDPLTC( RE, F, XPT2, MINLAT )
END IF
IF ( XVAL1 .AND. ( .NOT. XVAL2 ) ) THEN
NX = 1
ELSE IF ( XVAL2 .AND. (.NOT. XVAL1 ) ) THEN
C
C Only the second solution is valid. Overwrite
C the first.
C
NX = 1
CALL VEQU( XPT2, SRFX )
ELSE IF ( ( .NOT. XVAL1 ) .AND. ( .NOT. XVAL2 ) ) THEN
C
C Neither solution is valid.
C
NX = 0
END IF
END IF
IF ( NX .GE. 1 ) THEN
C
C The ray intercept SRFX lies on the lower latitude boundary.
C
C See whether SRFX meets the longitude and proxy altitude
C constraints.
C
CALL ZZINPDT ( SRFX, BOUNDS, CORPAR, MARGIN, LATIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
C
C SRFX is a candidate solution.
C
DIST = VDIST( VERTEX, SRFX )
IF ( DIST .LT. MNDIST ) THEN
CALL VEQU ( SRFX, XPT )
NXPTS = 1
IF ( VTXANG .GT. ANGLE ) THEN
IF ( ( MINLAT .GT. 0.D0 )
. .OR. ( VERTEX(3) .LT. 0.D0 ) ) THEN
C
C If MINLAT is positive, the vertex offset
C being outside the cone is enough to
C guarantee the planetodetic latitude of the
C vertex is less than that of the cone.
C
C If MINLAT is non-positive, the angle of the
C vertex offset relative to the +Z axis is not
C enough; we need the vertex to lie below the
C X-Y plane as well.
C
C Getting here means one of these conditions
C was met.
C
C Since the latitude of the vertex is less than
C than MINLAT, this is the best solution, since
C the volume element is on the other side of the
C minimum latitude boundary.
C
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
END IF
C
C This is the best solution seen so far, but we
C need to check the remaining boundaries.
MNDIST = DIST
END IF
END IF
IF ( NX .EQ. 2 ) THEN
C
C Check the second solution as well.
C
CALL ZZINPDT ( XPT2, BOUNDS, CORPAR,
. MARGIN, LATIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
C
C XPT2 is a candidate solution.
C
DIST = VDIST( VERTEX, XPT2 )
IF ( DIST .LT. MNDIST ) THEN
CALL VEQU ( XPT2, XPT )
NXPTS = 1
MNDIST = DIST
C
C This is the best solution seen so far.
C However, it's not necessarily the best
C solution. So we continue.
C
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
END IF
END IF
END IF
C
C We're done with the lower latitude boundary.
C
END IF
C
C Perform longitude boundary checks if the coverage is not
C 2*pi radians. Note that MAXLON > MINLON at this point.
C
LONCOV = MAXLON - MINLON
IF ( COS(LONCOV) .LT. 1.D0 ) THEN
C
C We have distinct longitude boundaries. Go to work.
C
C
C Check the longitude boundaries. Try the plane of western
C longitude first.
C
CALL VPACK ( SIN(MINLON), -COS(MINLON), 0.D0, WESTB )
S = RADFAC * ( VNORM(VERTEX) + MAXR )
CALL ZZINRYPL ( VERTEX, UDIR, WESTB, 0.D0, S, NX, SRFX )
IF ( NX .EQ. 1 ) THEN
C
C We have one point of intersection. Determine whether it's a
C candidate solution. Don't use longitude in the following
C inclusion test. Note that we'll perform a separate check
C later in place of the longitude check.
C
CALL ZZINPDT ( SRFX, BOUNDS, CORPAR, MARGIN, LONIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
C
C Make sure the intercept is not too far on the
C "wrong" side of the Z axis.
C
CALL UCRSS ( WESTB, Z, WBACK )
IF ( VDOT(SRFX, WBACK) .LT. (MARGIN*MAXR) ) THEN
C
C The intercept is either on the same side of the Z
C axis as the west face of the segment, or is very
C close to the Z axis.
C
DIST = VDIST( VERTEX, SRFX )
IF ( DIST .LT. MNDIST ) THEN
C
C Record the intercept, distance, and surface index.
C
CALL VEQU ( SRFX, XPT )
NXPTS = 1
MNDIST = DIST
END IF
END IF
END IF
END IF
C
C We're done with the western boundary.
C
C
C Try the plane of eastern longitude next.
C
CALL VPACK ( -SIN(MAXLON), COS(MAXLON), 0.D0, EASTB )
CALL ZZINRYPL ( VERTEX, UDIR, EASTB, 0.D0, S, NX, SRFX )
IF ( NX .EQ. 1 ) THEN
C
C We have one point of intersection. Determine whether it's a
C candidate solution.
C
CALL ZZINPDT ( SRFX, BOUNDS, CORPAR, MARGIN, LONIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
C
C Make sure the intercept is not too far on the "wrong"
C side of the Z axis.
C
CALL UCRSS ( Z, EASTB, EBACK )
IF ( VDOT(SRFX, EBACK) .LT. (MARGIN*MAXR) ) THEN
C
C The intercept is either on the same side of the Z
C axis as the east face of the segment, or is very
C close to the Z axis.
C
DIST = VDIST( VERTEX, SRFX )
IF ( DIST .LT. MNDIST ) THEN
C
C Record the intercept, distance, and surface index.
C
CALL VEQU ( SRFX, XPT )
NXPTS = 1
MNDIST = DIST
END IF
END IF
END IF
END IF
END IF
C
C End of longitude boundary checks.
C
C
C Find the intersection of the ray and lower bounding
C ellipsoid, if possible.
C
CALL SURFPT ( VERTEX, UDIR, EMIN, EMIN, PMIN, SRFX, FOUND )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( FOUND ) THEN
C
C See whether this solution is in the element.
C
CALL ZZINPDT ( SRFX, BOUNDS, CORPAR, MARGIN, ALTIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
DIST = VDIST( VERTEX, SRFX )
IF ( DIST .LT. MNDIST ) THEN
C
C Record the intercept, distance, and surface index.
C
CALL VEQU ( SRFX, XPT )
NXPTS = 1
MNDIST = DIST
END IF
END IF
END IF
C
C Unlike the outer ellipsoid, either intersection of the ray with
C the inner ellipsoid might be a valid solution. We'll test for the
C case where the intersection farther from the ray's vertex is the
C correct one.
C
CALL VMINUS( UDIR, NEGDIR )
CALL SURFPT ( ENDPT2, NEGDIR, EMIN, EMIN, PMIN, SRFX, FOUND )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( FOUND ) THEN
CALL ZZINPDT ( SRFX, BOUNDS, CORPAR, MARGIN, ALTIDX, XIN )
IF ( FAILED() ) THEN
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END IF
IF ( XIN ) THEN
DIST = VDIST( VERTEX, SRFX )
IF ( DIST .LT. MNDIST ) THEN
C
C Record the intercept, distance, and surface index.
C
CALL VEQU ( SRFX, XPT )
NXPTS = 1
C
C There's no need to update MNDIST at this point.
C
END IF
END IF
END IF
C
C NXPTS and XPT are set.
C
CALL CHKOUT ( 'ZZRYTPDT' )
RETURN
END
| source/nasa_f/zzrytpdt.f |
SUBROUTINE TG_VI2F ( vdtm, idtm, fdtm, lnth, iret )
C************************************************************************
C* DE_VI2F *
C* *
C* This subroutine converts a forecast valid time of the form *
C* YYMMDD/HHNN and an initial GEMPAK time of the form yymmdd/hhnn *
C* into a proper GEMPAK forecast time stamp of the form *
C* yymmdd/hhnnFhhhnn. *
C* *
C* TG_VI2F ( VDTM, IDTM, FDTM, LNTH, IRET ) *
C* *
C* Input parameters: *
C* VDTM CHAR* Valid GEMPAK time, YYMMDD/HHNN *
C* IDTM CHAR* Init. GEMPAK time, yymmdd/hhnn *
C* *
C* Output parameters: *
C* FDTM CHAR* Forecast time, yymmdd/hhnn *
C* LNTH INTEGER Length of string FDTM *
C* IRET INTEGER Return code *
C* 0 = normal return *
C* -1 = invalid date or time *
C* -3 = invalid forecast time *
C** *
C* Log: *
C* T. Lee/SAIC 1/05 *
C************************************************************************
CHARACTER*(*) vdtm, idtm, fdtm
CHARACTER sfh*3, snn*2
C------------------------------------------------------------------------
iret = 0
lnth = 0
C
C* Return if VDTM or IDTM is blank,
C
IF ( ( vdtm .eq. ' ' ) .or. ( idtm .eq. ' ' ) ) THEN
iret = -1
fdtm = ' '
RETURN
END IF
C
C* Compute the difference between valid time and initial time.
C
CALL TG_DIFF ( vdtm, idtm, nmin, iret )
IF ( iret .ne. 0 ) RETURN
C
IF ( ( nmin .lt. 0 ) .or. ( nmin .ge. 60000 ) ) THEN
iret = -3
RETURN
END IF
C
ifh = nmin / 60
nn = MOD ( nmin, 60 )
WRITE ( sfh, 50, IOSTAT = ier ) ifh
50 FORMAT ( I3.3 )
WRITE ( snn, 60, IOSTAT = ier ) nn
60 FORMAT ( I2.2 )
C
C* Construct the forecast time stamp.
C
CALL ST_LSTR ( idtm, lstr, ier )
fdtm = idtm ( :lstr ) // 'F' // sfh // snn
C
CALL ST_LSTR ( fdtm, lnth, ier )
C*
RETURN
END
| gempak/source/gemlib/tg/tgvi2f.f |
! Copyright (c) 2013, NVIDIA CORPORATION. All rights reserved.
!
! Licensed under the Apache License, Version 2.0 (the "License");
! you may not use this file except in compliance with the License.
! You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
!
! Tests F2003 defined I/O (recursive read)
module person_module
logical rslt(10), expect(10)
integer :: cnt
type :: person
character(len=20) :: name
integer :: age
contains
procedure :: my_read => rf
procedure :: my_write => wf
generic :: READ(FORMATTED) => my_read
generic :: WRITE(FORMATTED) => my_write
end type
type, extends(person) :: employee
integer id
real salary
contains
procedure :: my_read => rf2
procedure :: my_write => wf2
end type
contains
recursive subroutine rf(dtv, unit, iotype, vlist, iostat, iomsg)
class(person), intent(inout) :: dtv
integer, intent(in) :: unit
character(len=*),intent(in) :: iotype
integer, intent(in) :: vlist(:)
integer, intent(out) :: iostat
character (len=*), intent(inout) :: iomsg
character(len=9) :: pfmt
read (unit, *, iostat=iostat) dtv%name, dtv%age
if (iostat .eq. 0) then
cnt = cnt + 1
rslt(cnt) = dtv%age .eq. 40+(cnt-1)
read(unit, *) dtv
endif
end subroutine
subroutine wf(dtv, unit, iotype, vlist, iostat, iomsg)
class(person), intent(inout) :: dtv
integer, intent(in) :: unit
character(len=*),intent(in) :: iotype
integer, intent(in) :: vlist(:)
integer, intent(out) :: iostat
character (len=*), intent(inout) :: iomsg
character(len=9) :: pfmt
write (unit, *) dtv%name, dtv%age
end subroutine
subroutine wf2(dtv, unit, iotype, vlist, iostat, iomsg)
class(employee), intent(inout) :: dtv
integer, intent(in) :: unit
character(len=*),intent(in) :: iotype
integer, intent(in) :: vlist(:)
integer, intent(out) :: iostat
character (len=*), intent(inout) :: iomsg
character(len=9) :: pfmt
write (unit, *) dtv%name, dtv%age, dtv%id, dtv%salary
end subroutine
recursive subroutine rf2(dtv, unit, iotype, vlist, iostat, iomsg)
class(employee), intent(inout) :: dtv
integer, intent(in) :: unit
character(len=*),intent(in) :: iotype
integer, intent(in) :: vlist(:)
integer, intent(out) :: iostat
character (len=*), intent(inout) :: iomsg
character(len=9) :: pfmt
read (unit, *, iostat=iostat) dtv%name, dtv%age, dtv%id, dtv%salary
if (iostat .eq. 0) then
cnt = cnt + 1
rslt(cnt) = dtv%id .eq. 100+(cnt-1)
read(unit, *) dtv
endif
end subroutine
end module
use person_module
integer id, members
type(employee) :: chairman
chairman%name='myname'
chairman%age=40
chairman%id = 100
chairman%salary = 0
rslt = .false.
expect = .true.
open(11, file='io16.output', status='replace')
do i=1,10
write(11, *) chairman
chairman%id = chairman%id + 1
enddo
cnt = 0
open(11, file='io16.output', position='rewind')
read(11, *) chairman
close(11)
call check(rslt, expect, 10)
end
| test/f90_correct/src/io16.f90 |
subroutine blue(value,hexrep,bfrac)
C%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
C %
C Copyright (C) 1996, The Board of Trustees of the Leland Stanford %
C Junior University. All rights reserved. %
C %
C The programs in GSLIB are distributed in the hope that they will be %
C useful, but WITHOUT ANY WARRANTY. No author or distributor accepts %
C responsibility to anyone for the consequences of using them or for %
C whether they serve any particular purpose or work at all, unless he %
C says so in writing. Everyone is granted permission to copy, modify %
C and redistribute the programs in GSLIB, but only under the condition %
C that this notice and the above copyright notice remain intact. %
C %
C%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
c-----------------------------------------------------------------------
c
c Provided with a real value ``value'' this subroutine returns the blue
c portion of the color specification.
c
c Note common block "color" and call to "hexa"
c
c-----------------------------------------------------------------------
real value
character hexrep*2,hexa*2
common /color/ cmin,cmax,cint(4),cscl
hexrep = '00'
if(value.lt.cint(2))then
c
c Scale it between (255,255):
c
integ = 255
else if((value.ge.cint(2)).and.(value.lt.cint(3)))then
c
c Scale it between (255,0):
c
integ = int((cint(3)-value)/(cint(3)-cint(2))*255.)
if(integ.gt.255) integ = 255
if(integ.lt.0) integ = 0
else if(value.ge.cint(3))then
c
c Scale it between (0,0):
c
integ = 0
end if
c
c Establish coding and return:
c
bfrac = real(integ) / 255.
hexrep = hexa(integ)
return
end
| visim/visim_src/gslib/blue.f |
SUBROUTINE DEG2CHR(DEGS,LATLON,CHAR)
C******************************************************************
C# SUB DEG2CHR(DEGS,LATLON,CHAR) Degrees to CHARACTER (xxxNxx'xx")
C Convert degrees to characters for output.
C DEGS = input degrees (may be -180 to 180 or 0 to 360)
C LATLON=0= latitude format xxxNxx'xx"
C =1= longitude format xxxExx'xx"
c =2= latitude format xx.xxN
c =3= longitude format xxx.xxE
C CHAR = CHARACTER*10 output
C******************************************************************
CHARACTER*(*) CHAR
CHARACTER*1 NSEW
DEG=DEGS
IF(DEG.GT.180.) DEG=DEG-360.
modd=mod(latlon,2)
IF(modd.EQ.0 .AND. DEG.GE.0.) NSEW='N'
IF(modd.EQ.0 .AND. DEG.LT.0.) NSEW='S'
IF(modd.NE.0 .AND. DEG.GE.0.) NSEW='E'
IF(modd.NE.0 .AND. DEG.LT.0.) NSEW='W'
D=ABS(DEG)
IDEG=D
D=(D-IDEG)*60.
MIN=D
ISEC=(D-MIN)*60. + .5
IF(ISEC.LT.60) GO TO 10
ISEC=0
MIN=MIN+1
IF(MIN.LT.60) GO TO 10
MIN=MIN-60
IDEG=IDEG+1
10 if(latlon.le.1) then
WRITE(CHAR,11) IDEG,NSEW,MIN,ISEC
11 format(i3,a1,i2,1h',i2,1h")
else
WRITE(CHAR,'(f6.2,a1)') abs(DEG),NSEW
end if
RETURN
END
| src/voa_lib/deg2chr.for |
!
! Copyright 2019-2020 SALMON developers
!
! Licensed under the Apache License, Version 2.0 (the "License");
! you may not use this file except in compliance with the License.
! You may obtain a copy of the License at
!
! http://www.apache.org/licenses/LICENSE-2.0
!
! Unless required by applicable law or agreed to in writing, software
! distributed under the License is distributed on an "AS IS" BASIS,
! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
! See the License for the specific language governing permissions and
! limitations under the License.
!
module jellium
implicit none
contains
!===========================================================================================
!= check condition =========================================================================
subroutine check_condition_jm
use salmon_global, only: yn_md, yn_opt, yn_out_pdos, yn_out_tm, yn_out_rvf_rt, nelem, natom, nelec, spin, xc, &
yn_periodic, layout_multipole, shape_file_jm, num_jm, sphere_nion_jm, &
method_singlescale
use parallelization, only: nproc_id_global
use communication, only: comm_is_root
implicit none
call condition_yn_jm(yn_md, 'yn_md', 'n')
call condition_yn_jm(yn_opt, 'yn_opt', 'n')
call condition_yn_jm(yn_out_pdos, 'yn_out_pdos', 'n')
call condition_yn_jm(yn_out_tm, 'yn_out_tm', 'n')
call condition_yn_jm(yn_out_rvf_rt,'yn_out_rvf_rt','n')
call condition_int_jm(nelem,'nelem',1)
call condition_int_jm(natom,'natom',1)
if(yn_periodic=='n'.and.layout_multipole/=1) then
if(comm_is_root(nproc_id_global)) &
write(*,'("For yn_jm = y and yn_periodic = n, layout_multipole must be 1.")')
stop
end if
if(mod(nelec,2)/=0) then
if(comm_is_root(nproc_id_global)) write(*,'("For yn_jm = y, nelec must be even number.")')
stop
end if
if(trim(spin)/='unpolarized') then
if(comm_is_root(nproc_id_global)) write(*,'("For yn_jm = y, spin must be even unpolarized.")')
stop
end if
if(trim(xc)/='pz') then
if(comm_is_root(nproc_id_global)) write(*,'("For yn_jm = y, xc must be pz.")')
stop
end if
if(trim(method_singlescale)/='3d') then
if(comm_is_root(nproc_id_global)) write(*,'("For yn_jm = y, method_singlescale must be 3d.")')
stop
end if
if (trim(shape_file_jm)=='none' .and. nelec/=sum(sphere_nion_jm(:)))then
if(comm_is_root(nproc_id_global)) &
write(*,'("For yn_jm = y and shape_file_jm = none, nelec must be sum(sphere_nion_jm).")')
stop
end if
if(num_jm<1) then
if(comm_is_root(nproc_id_global)) write(*,'("For yn_jm = y, num_jm must be larger than 0.")')
stop
end if
return
contains
!+ CONTAINED IN check_condition_jm +++++++++++++++++++++++++++++++++++++++++++++++++++++++
!+ check condition for y/n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
subroutine condition_yn_jm(tar,name,ans)
implicit none
character(1),intent(in) :: tar
character(*),intent(in) :: name
character(1),intent(in) :: ans
if (tar/=ans) then
if(comm_is_root(nproc_id_global)) write(*,'("For yn_jm = y, ",A," must be ",A,".")') name,ans
stop
end if
return
end subroutine condition_yn_jm
!+ CONTAINED IN check_condition_jm +++++++++++++++++++++++++++++++++++++++++++++++++++++++
!+ check condition for integer +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
subroutine condition_int_jm(tar,name,ans)
implicit none
integer, intent(in) :: tar
character(*),intent(in) :: name
integer, intent(in) :: ans
if (tar/=ans) then
if(comm_is_root(nproc_id_global)) write(*,'("For yn_jm = y, ",A," must be ",I4,".")') name,ans
stop
end if
return
end subroutine condition_int_jm
end subroutine check_condition_jm
!===========================================================================================
!= meke positive back ground charge density ================================================
subroutine make_rho_jm(lg,mg,info,system,rho_jm)
use salmon_global, only: shape_file_jm, num_jm, rs_bohr_jm, sphere_nion_jm, sphere_loc_jm, &
yn_charge_neutral_jm, yn_output_dns_jm, yn_periodic, nelec, unit_system
use inputoutput, only: ulength_from_au
use structures, only: s_rgrid, s_dft_system, s_parallel_info, s_scalar, allocate_scalar
use parallelization, only: nproc_id_global, nproc_group_global
use communication, only: comm_is_root, comm_summation
use common_maxwell, only: input_shape_em
use write_file3d, only: write_cube
use math_constants, only: pi
implicit none
type(s_rgrid), intent(in) :: lg, mg
type(s_parallel_info), intent(in) :: info
type(s_dft_system), intent(in) :: system
type(s_scalar), intent(inout) :: rho_jm
type(s_scalar) :: work_l1,work_l2
integer,allocatable :: imedia(:,:,:)
integer :: ii, ix, iy, iz, nelec_sum, mod_nelec
real(8),allocatable :: dens(:), radi(:), mod_rs_bohr_jm(:)
real(8) :: rab, charge_sum, charge_error
character(60) :: suffix
character(30) :: phys_quantity
!set density
allocate(dens(num_jm)); dens(:)=0.0d0;
do ii=1,num_jm
dens(ii) = 1.0d0/(4.0d0*pi/3.0*(rs_bohr_jm(ii)**3.0d0))
end do
!make rho_jm
if (trim(shape_file_jm)=='none')then
!**************************************************************************************!
!*** rho_jm is generated by spherecal shapes ******************************************!
!**************************************************************************************!
!allocate radius
allocate(radi(num_jm)); radi(:)=0.0d0;
!make spheres
do ii=1,num_jm
!set radius
radi(ii) = ( dble(sphere_nion_jm(ii))/dens(ii)/(4.0d0*pi/3.0) )**(1.0d0/3.0d0)
!make ii-th sphere
do iz=mg%is(3),mg%ie(3)
do iy=mg%is(2),mg%ie(2)
do ix=mg%is(1),mg%ie(1)
rab = sqrt( (lg%coordinate(ix,1)-sphere_loc_jm(ii,1))**2.0d0 &
+(lg%coordinate(iy,2)-sphere_loc_jm(ii,2))**2.0d0 &
+(lg%coordinate(iz,3)-sphere_loc_jm(ii,3))**2.0d0 )
if(rab<=radi(ii)) rho_jm%f(ix,iy,iz)=dens(ii)
end do
end do
end do
end do
!set total electron number
nelec_sum = sum(sphere_nion_jm(:))
else
!**************************************************************************************!
!*** rho_jm is generated by cube file *************************************************!
!**************************************************************************************!
!input shape
allocate(imedia(mg%is(1):mg%ie(1),mg%is(2):mg%ie(2),mg%is(3):mg%ie(3))); imedia(:,:,:)=0;
if(comm_is_root(nproc_id_global)) write(*,*)
if(comm_is_root(nproc_id_global)) write(*,*) "**************************"
if(index(shape_file_jm,".cube", back=.true.)/=0) then
if(comm_is_root(nproc_id_global)) then
write(*,*) "shape file is inputed by .cube format."
end if
call input_shape_em(shape_file_jm,600,mg%is,mg%ie,lg%is,lg%ie,0,imedia,'cu')
elseif(index(shape_file_jm,".mp", back=.true.)/=0) then
if(comm_is_root(nproc_id_global)) then
write(*,*) "shape file is inputed by .mp format."
write(*,*) "This version works for only .cube format.."
end if
stop
else
if(comm_is_root(nproc_id_global)) then
write(*,*) "shape file must be .cube or .mp formats."
end if
stop
end if
if(comm_is_root(nproc_id_global)) write(*,*) "**************************"
!make rho_jm from shape file
do iz=mg%is(3),mg%ie(3)
do iy=mg%is(2),mg%ie(2)
do ix=mg%is(1),mg%ie(1)
if(imedia(ix,iy,iz)>0) rho_jm%f(ix,iy,iz)=dens(imedia(ix,iy,iz))
end do
end do
end do
!set total electron number
nelec_sum = nelec
end if
!check charge neutrality
call check_neutral_jm(charge_sum,charge_error,nelec_sum)
!propose modified parameter & stop
!or modify parameters
allocate(mod_rs_bohr_jm(num_jm)); mod_rs_bohr_jm(:)=0.0d0;
if(charge_error>=2.0d0/dble(nelec))then
!stop & propose modified parameter
mod_nelec = int(charge_sum)
if(mod(mod_nelec,2)/=0) mod_nelec=mod_nelec+1
if(comm_is_root(nproc_id_global))then
write(*,*)
write(*,'("Charge nertrality error is",E23.15E3,".")') charge_error
write(*,'("To improve charge nertrality, change nelec to",I9,".")') mod_nelec
end if
stop
else
!modify parameters and recheck neutrality
if(yn_charge_neutral_jm=='y')then
rho_jm%f(:,:,:) = rho_jm%f(:,:,:) * ( dble(nelec)/charge_sum )
dens(:) = dens(:) * ( dble(nelec)/charge_sum )
mod_rs_bohr_jm(:) = ( 1.0d0/(4.0d0*pi/3.0*dens(:)) )**(1.0d0/3.0d0)
call check_neutral_jm(charge_sum,charge_error,nelec_sum)
end if
end if
!output cube file
if(yn_output_dns_jm=='y') then
call allocate_scalar(lg,work_l1); call allocate_scalar(lg,work_l2);
do iz=mg%is(3),mg%ie(3)
do iy=mg%is(2),mg%ie(2)
do ix=mg%is(1),mg%ie(1)
work_l1%f(ix,iy,iz) = rho_jm%f(ix,iy,iz)
end do
end do
end do
call comm_summation(work_l1%f,work_l2%f,lg%num(1)*lg%num(2)*lg%num(3),nproc_group_global)
suffix = "dns_jellium"; phys_quantity = "pbcd";
call write_cube(lg,103,suffix,phys_quantity,work_l2%f,system)
end if
!write information
if(comm_is_root(nproc_id_global))then
write(*,*)
write(*,*) '****************** Jellium information ******************'
if(trim(shape_file_jm)=='none')then
write(*,'(" Positive background charge density is generated by spherecal shapes:")')
do ii=1,num_jm
write(*, '(A,I3,A,E23.15E3)') ' Radius of sphere(',ii,') =', radi(ii)*ulength_from_au
end do
write(*,*) " in the unit system, ",trim(unit_system),"."
else
write(*,'(" Positive background charge density is generated by shape file.")')
end if
if(sum(mod_rs_bohr_jm(:))==0.0d0) then
write(*,'(" Wigner-Seitz radius is set as follows:")')
do ii=1,num_jm
write(*, '(A,I3,A,E23.15E3)') ' rs_bohr_jm(',ii,') =', rs_bohr_jm(ii)
end do
else
write(*,'(" To keep charge neutrality, Wigner-Seitz radius is modified as follows:")')
do ii=1,num_jm
write(*, '(A,I3,A,E23.15E3)') ' mod_rs_bohr_jm(',ii,') =', mod_rs_bohr_jm(ii)
end do
end if
write(*,*) " in the atomic unit(Bohr)."
write(*,'(A,E23.15E3," %")') ' Chrge neutrality error =', charge_error
if(yn_periodic=='y') then
write(*,*)
write(*,'(" For yn_jm = y and yn_periodic=y, this version still cannot output Total Energy.")')
write(*,*)
end if
write(*,*) '*********************************************************'
write(*,*)
end if
!change sign in view of electron density
rho_jm%f(:,:,:) = -rho_jm%f(:,:,:)
return
contains
!+ CONTAINED IN make_rho_jm ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
!+ check charge neutrality +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
subroutine check_neutral_jm(sum_c,err,num_e)
implicit none
real(8), intent(inout) :: sum_c
real(8), intent(out) :: err
integer, intent(in) :: num_e
real(8) :: sum_tmp
sum_tmp = 0.0d0; sum_c = 0.0d0;
!$omp parallel
!$omp do private(ix,iy,iz) reduction( + : sum_tmp )
do iz=mg%is(3),mg%ie(3)
do iy=mg%is(2),mg%ie(2)
do ix=mg%is(1),mg%ie(1)
sum_tmp = sum_tmp + rho_jm%f(ix,iy,iz)
end do
end do
end do
!$omp end do
!$omp end parallel
call comm_summation(sum_tmp,sum_c,info%icomm_r)
sum_c = sum_c * system%hvol
err = abs( (sum_c - dble(num_e)) / dble(num_e) )
return
end subroutine check_neutral_jm
end subroutine make_rho_jm
end module jellium
| src/atom/jellium.f90 |
! Loop recovery fails. Might be due to semantics not providing the
! necessary preconditions
c%2.3
subroutine s234 (ntimes,ld,n,ctime,dtime,a,b,c,d,e,aa,bb,cc)
c
c loop interchange
c if loop to do loop, interchanging with if loop necessary
c
integer ntimes, ld, n, i, nl, j
real a(n), b(n), c(n), d(n), e(n), aa(ld,n), bb(ld,n), cc(ld,n)
real t1, t2, second, chksum, ctime, dtime, cs2d
! call init(ld,n,a,b,c,d,e,aa,bb,cc,'s234 ')
! t1 = second()
do 1 nl = 1,ntimes/n
i = 1
11 if(i.gt.n) goto 10
j = 2
21 if(j.gt.n) goto 20
aa(i,j) = aa(i,j-1) + bb(i,j-1) * cc(i,j-1)
j = j + 1
goto 21
20 i = i + 1
goto 11
10 continue
! call dummy(ld,n,a,b,c,d,e,aa,bb,cc,1.)
1 continue
! t2 = second() - t1 - ctime - ( dtime * float(ntimes/n) )
! chksum = cs2d(n,aa)
! call check (chksum,(ntimes/n)*n*(n-1),n,t2,'s234 ')
return
end
| packages/PIPS/validation/Transformations/S234.f |
!*==ctrevc3.f90 processed by SPAG 7.51RB at 20:08 on 3 Mar 2022
!> \brief \b CTREVC3
!
! =========== DOCUMENTATION ===========
!
! Online html documentation available at
! http://www.netlib.org/lapack/explore-html/
!
!> \htmlonly
!> Download CTREVC3 + dependencies
!> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/ctrevc3.f">
!> [TGZ]</a>
!> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/ctrevc3.f">
!> [ZIP]</a>
!> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/ctrevc3.f">
!> [TXT]</a>
!> \endhtmlonly
!
! Definition:
! ===========
!
! SUBROUTINE CTREVC3( SIDE, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR,
! LDVR, MM, M, WORK, LWORK, RWORK, LRWORK, INFO)
!
! .. Scalar Arguments ..
! CHARACTER HOWMNY, SIDE
! INTEGER INFO, LDT, LDVL, LDVR, LWORK, M, MM, N
! ..
! .. Array Arguments ..
! LOGICAL SELECT( * )
! REAL RWORK( * )
! COMPLEX T( LDT, * ), VL( LDVL, * ), VR( LDVR, * ),
! $ WORK( * )
! ..
!
!
!> \par Purpose:
! =============
!>
!> \verbatim
!>
!> CTREVC3 computes some or all of the right and/or left eigenvectors of
!> a complex upper triangular matrix T.
!> Matrices of this type are produced by the Schur factorization of
!> a complex general matrix: A = Q*T*Q**H, as computed by CHSEQR.
!>
!> The right eigenvector x and the left eigenvector y of T corresponding
!> to an eigenvalue w are defined by:
!>
!> T*x = w*x, (y**H)*T = w*(y**H)
!>
!> where y**H denotes the conjugate transpose of the vector y.
!> The eigenvalues are not input to this routine, but are read directly
!> from the diagonal of T.
!>
!> This routine returns the matrices X and/or Y of right and left
!> eigenvectors of T, or the products Q*X and/or Q*Y, where Q is an
!> input matrix. If Q is the unitary factor that reduces a matrix A to
!> Schur form T, then Q*X and Q*Y are the matrices of right and left
!> eigenvectors of A.
!>
!> This uses a Level 3 BLAS version of the back transformation.
!> \endverbatim
!
! Arguments:
! ==========
!
!> \param[in] SIDE
!> \verbatim
!> SIDE is CHARACTER*1
!> = 'R': compute right eigenvectors only;
!> = 'L': compute left eigenvectors only;
!> = 'B': compute both right and left eigenvectors.
!> \endverbatim
!>
!> \param[in] HOWMNY
!> \verbatim
!> HOWMNY is CHARACTER*1
!> = 'A': compute all right and/or left eigenvectors;
!> = 'B': compute all right and/or left eigenvectors,
!> backtransformed using the matrices supplied in
!> VR and/or VL;
!> = 'S': compute selected right and/or left eigenvectors,
!> as indicated by the logical array SELECT.
!> \endverbatim
!>
!> \param[in] SELECT
!> \verbatim
!> SELECT is LOGICAL array, dimension (N)
!> If HOWMNY = 'S', SELECT specifies the eigenvectors to be
!> computed.
!> The eigenvector corresponding to the j-th eigenvalue is
!> computed if SELECT(j) = .TRUE..
!> Not referenced if HOWMNY = 'A' or 'B'.
!> \endverbatim
!>
!> \param[in] N
!> \verbatim
!> N is INTEGER
!> The order of the matrix T. N >= 0.
!> \endverbatim
!>
!> \param[in,out] T
!> \verbatim
!> T is COMPLEX array, dimension (LDT,N)
!> The upper triangular matrix T. T is modified, but restored
!> on exit.
!> \endverbatim
!>
!> \param[in] LDT
!> \verbatim
!> LDT is INTEGER
!> The leading dimension of the array T. LDT >= max(1,N).
!> \endverbatim
!>
!> \param[in,out] VL
!> \verbatim
!> VL is COMPLEX array, dimension (LDVL,MM)
!> On entry, if SIDE = 'L' or 'B' and HOWMNY = 'B', VL must
!> contain an N-by-N matrix Q (usually the unitary matrix Q of
!> Schur vectors returned by CHSEQR).
!> On exit, if SIDE = 'L' or 'B', VL contains:
!> if HOWMNY = 'A', the matrix Y of left eigenvectors of T;
!> if HOWMNY = 'B', the matrix Q*Y;
!> if HOWMNY = 'S', the left eigenvectors of T specified by
!> SELECT, stored consecutively in the columns
!> of VL, in the same order as their
!> eigenvalues.
!> Not referenced if SIDE = 'R'.
!> \endverbatim
!>
!> \param[in] LDVL
!> \verbatim
!> LDVL is INTEGER
!> The leading dimension of the array VL.
!> LDVL >= 1, and if SIDE = 'L' or 'B', LDVL >= N.
!> \endverbatim
!>
!> \param[in,out] VR
!> \verbatim
!> VR is COMPLEX array, dimension (LDVR,MM)
!> On entry, if SIDE = 'R' or 'B' and HOWMNY = 'B', VR must
!> contain an N-by-N matrix Q (usually the unitary matrix Q of
!> Schur vectors returned by CHSEQR).
!> On exit, if SIDE = 'R' or 'B', VR contains:
!> if HOWMNY = 'A', the matrix X of right eigenvectors of T;
!> if HOWMNY = 'B', the matrix Q*X;
!> if HOWMNY = 'S', the right eigenvectors of T specified by
!> SELECT, stored consecutively in the columns
!> of VR, in the same order as their
!> eigenvalues.
!> Not referenced if SIDE = 'L'.
!> \endverbatim
!>
!> \param[in] LDVR
!> \verbatim
!> LDVR is INTEGER
!> The leading dimension of the array VR.
!> LDVR >= 1, and if SIDE = 'R' or 'B', LDVR >= N.
!> \endverbatim
!>
!> \param[in] MM
!> \verbatim
!> MM is INTEGER
!> The number of columns in the arrays VL and/or VR. MM >= M.
!> \endverbatim
!>
!> \param[out] M
!> \verbatim
!> M is INTEGER
!> The number of columns in the arrays VL and/or VR actually
!> used to store the eigenvectors.
!> If HOWMNY = 'A' or 'B', M is set to N.
!> Each selected eigenvector occupies one column.
!> \endverbatim
!>
!> \param[out] WORK
!> \verbatim
!> WORK is COMPLEX array, dimension (MAX(1,LWORK))
!> \endverbatim
!>
!> \param[in] LWORK
!> \verbatim
!> LWORK is INTEGER
!> The dimension of array WORK. LWORK >= max(1,2*N).
!> For optimum performance, LWORK >= N + 2*N*NB, where NB is
!> the optimal blocksize.
!>
!> 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] RWORK
!> \verbatim
!> RWORK is REAL array, dimension (LRWORK)
!> \endverbatim
!>
!> \param[in] LRWORK
!> \verbatim
!> LRWORK is INTEGER
!> The dimension of array RWORK. LRWORK >= max(1,N).
!>
!> If LRWORK = -1, then a workspace query is assumed; the routine
!> only calculates the optimal size of the RWORK array, returns
!> this value as the first entry of the RWORK array, and no error
!> message related to LRWORK 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
!> \endverbatim
!
! Authors:
! ========
!
!> \author Univ. of Tennessee
!> \author Univ. of California Berkeley
!> \author Univ. of Colorado Denver
!> \author NAG Ltd.
!
!> \date November 2017
!
! @generated from ztrevc3.f, fortran z -> c, Tue Apr 19 01:47:44 2016
!
!> \ingroup complexOTHERcomputational
!
!> \par Further Details:
! =====================
!>
!> \verbatim
!>
!> The algorithm used in this program is basically backward (forward)
!> substitution, with scaling to make the the code robust against
!> possible overflow.
!>
!> Each eigenvector is normalized so that the element of largest
!> magnitude has magnitude 1; here the magnitude of a complex number
!> (x,y) is taken to be |x| + |y|.
!> \endverbatim
!>
! =====================================================================
SUBROUTINE CTREVC3(Side,Howmny,Select,N,T,Ldt,Vl,Ldvl,Vr,Ldvr,Mm, &
& M,Work,Lwork,Rwork,Lrwork,Info)
IMPLICIT NONE
!*--CTREVC3250
!
! -- LAPACK computational routine (version 3.8.0) --
! -- LAPACK is a software package provided by Univ. of Tennessee, --
! -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
! November 2017
!
! .. Scalar Arguments ..
CHARACTER Howmny , Side
INTEGER Info , Ldt , Ldvl , Ldvr , Lwork , Lrwork , M , Mm , N
! ..
! .. Array Arguments ..
LOGICAL Select(*)
REAL Rwork(*)
COMPLEX T(Ldt,*) , Vl(Ldvl,*) , Vr(Ldvr,*) , Work(*)
! ..
!
! =====================================================================
!
! .. Parameters ..
REAL ZERO , ONE
PARAMETER (ZERO=0.0E+0,ONE=1.0E+0)
COMPLEX CZERO , CONE
PARAMETER (CZERO=(0.0E+0,0.0E+0),CONE=(1.0E+0,0.0E+0))
INTEGER NBMIN , NBMAX
PARAMETER (NBMIN=8,NBMAX=128)
! ..
! .. Local Scalars ..
LOGICAL allv , bothv , leftv , lquery , over , rightv , somev
INTEGER i , ii , is , j , k , ki , iv , maxwrk , nb
REAL ovfl , remax , scale , smin , smlnum , ulp , unfl
COMPLEX cdum
! ..
! .. External Functions ..
LOGICAL LSAME
INTEGER ILAENV , ICAMAX
REAL SLAMCH , SCASUM
EXTERNAL LSAME , ILAENV , ICAMAX , SLAMCH , SCASUM
! ..
! .. External Subroutines ..
EXTERNAL XERBLA , CCOPY , CLASET , CSSCAL , CGEMM , CGEMV , &
& CLATRS , CLACPY , SLABAD
! ..
! .. Intrinsic Functions ..
INTRINSIC ABS , REAL , CMPLX , CONJG , AIMAG , MAX
! ..
! .. Statement Functions ..
REAL CABS1
! ..
! .. Statement Function definitions ..
CABS1(cdum) = ABS(REAL(cdum)) + ABS(AIMAG(cdum))
! ..
! .. Executable Statements ..
!
! Decode and test the input parameters
!
bothv = LSAME(Side,'B')
rightv = LSAME(Side,'R') .OR. bothv
leftv = LSAME(Side,'L') .OR. bothv
!
allv = LSAME(Howmny,'A')
over = LSAME(Howmny,'B')
somev = LSAME(Howmny,'S')
!
! Set M to the number of columns required to store the selected
! eigenvectors.
!
IF ( somev ) THEN
M = 0
DO j = 1 , N
IF ( Select(j) ) M = M + 1
ENDDO
ELSE
M = N
ENDIF
!
Info = 0
nb = ILAENV(1,'CTREVC',Side//Howmny,N,-1,-1,-1)
maxwrk = N + 2*N*nb
Work(1) = maxwrk
Rwork(1) = N
lquery = (Lwork==-1 .OR. Lrwork==-1)
IF ( .NOT.rightv .AND. .NOT.leftv ) THEN
Info = -1
ELSEIF ( .NOT.allv .AND. .NOT.over .AND. .NOT.somev ) THEN
Info = -2
ELSEIF ( N<0 ) THEN
Info = -4
ELSEIF ( Ldt<MAX(1,N) ) THEN
Info = -6
ELSEIF ( Ldvl<1 .OR. (leftv .AND. Ldvl<N) ) THEN
Info = -8
ELSEIF ( Ldvr<1 .OR. (rightv .AND. Ldvr<N) ) THEN
Info = -10
ELSEIF ( Mm<M ) THEN
Info = -11
ELSEIF ( Lwork<MAX(1,2*N) .AND. .NOT.lquery ) THEN
Info = -14
ELSEIF ( Lrwork<MAX(1,N) .AND. .NOT.lquery ) THEN
Info = -16
ENDIF
IF ( Info/=0 ) THEN
CALL XERBLA('CTREVC3',-Info)
RETURN
ELSEIF ( lquery ) THEN
RETURN
ENDIF
!
! Quick return if possible.
!
IF ( N==0 ) RETURN
!
! Use blocked version of back-transformation if sufficient workspace.
! Zero-out the workspace to avoid potential NaN propagation.
!
IF ( over .AND. Lwork>=N+2*N*NBMIN ) THEN
nb = (Lwork-N)/(2*N)
nb = MIN(nb,NBMAX)
CALL CLASET('F',N,1+2*nb,CZERO,CZERO,Work,N)
ELSE
nb = 1
ENDIF
!
! Set the constants to control overflow.
!
unfl = SLAMCH('Safe minimum')
ovfl = ONE/unfl
CALL SLABAD(unfl,ovfl)
ulp = SLAMCH('Precision')
smlnum = unfl*(N/ulp)
!
! Store the diagonal elements of T in working array WORK.
!
DO i = 1 , N
Work(i) = T(i,i)
ENDDO
!
! Compute 1-norm of each column of strictly upper triangular
! part of T to control overflow in triangular solver.
!
Rwork(1) = ZERO
DO j = 2 , N
Rwork(j) = SCASUM(j-1,T(1,j),1)
ENDDO
!
IF ( rightv ) THEN
!
! ============================================================
! Compute right eigenvectors.
!
! IV is index of column in current block.
! Non-blocked version always uses IV=NB=1;
! blocked version starts with IV=NB, goes down to 1.
! (Note the "0-th" column is used to store the original diagonal.)
iv = nb
is = M
DO ki = N , 1 , -1
IF ( somev ) THEN
IF ( .NOT.Select(ki) ) CYCLE
ENDIF
smin = MAX(ulp*(CABS1(T(ki,ki))),smlnum)
!
! --------------------------------------------------------
! Complex right eigenvector
!
Work(ki+iv*N) = CONE
!
! Form right-hand side.
!
DO k = 1 , ki - 1
Work(k+iv*N) = -T(k,ki)
ENDDO
!
! Solve upper triangular system:
! [ T(1:KI-1,1:KI-1) - T(KI,KI) ]*X = SCALE*WORK.
!
DO k = 1 , ki - 1
T(k,k) = T(k,k) - T(ki,ki)
IF ( CABS1(T(k,k))<smin ) T(k,k) = smin
ENDDO
!
IF ( ki>1 ) THEN
CALL CLATRS('Upper','No transpose','Non-unit','Y',ki-1,T,&
& Ldt,Work(1+iv*N),scale,Rwork,Info)
Work(ki+iv*N) = scale
ENDIF
!
! Copy the vector x or Q*x to VR and normalize.
!
IF ( .NOT.over ) THEN
! ------------------------------
! no back-transform: copy x to VR and normalize.
CALL CCOPY(ki,Work(1+iv*N),1,Vr(1,is),1)
!
ii = ICAMAX(ki,Vr(1,is),1)
remax = ONE/CABS1(Vr(ii,is))
CALL CSSCAL(ki,remax,Vr(1,is),1)
!
DO k = ki + 1 , N
Vr(k,is) = CZERO
ENDDO
!
ELSEIF ( nb==1 ) THEN
! ------------------------------
! version 1: back-transform each vector with GEMV, Q*x.
IF ( ki>1 ) CALL CGEMV('N',N,ki-1,CONE,Vr,Ldvr, &
& Work(1+iv*N),1,CMPLX(scale), &
& Vr(1,ki),1)
!
ii = ICAMAX(N,Vr(1,ki),1)
remax = ONE/CABS1(Vr(ii,ki))
CALL CSSCAL(N,remax,Vr(1,ki),1)
!
ELSE
! ------------------------------
! version 2: back-transform block of vectors with GEMM
! zero out below vector
DO k = ki + 1 , N
Work(k+iv*N) = CZERO
ENDDO
!
! Columns IV:NB of work are valid vectors.
! When the number of vectors stored reaches NB,
! or if this was last vector, do the GEMM
IF ( (iv==1) .OR. (ki==1) ) THEN
CALL CGEMM('N','N',N,nb-iv+1,ki+nb-iv,CONE,Vr,Ldvr, &
& Work(1+(iv)*N),N,CZERO,Work(1+(nb+iv)*N),N)
! normalize vectors
DO k = iv , nb
ii = ICAMAX(N,Work(1+(nb+k)*N),1)
remax = ONE/CABS1(Work(ii+(nb+k)*N))
CALL CSSCAL(N,remax,Work(1+(nb+k)*N),1)
ENDDO
CALL CLACPY('F',N,nb-iv+1,Work(1+(nb+iv)*N),N,Vr(1,ki)&
& ,Ldvr)
iv = nb
ELSE
iv = iv - 1
ENDIF
ENDIF
!
! Restore the original diagonal elements of T.
!
DO k = 1 , ki - 1
T(k,k) = Work(k)
ENDDO
!
is = is - 1
ENDDO
ENDIF
!
IF ( leftv ) THEN
!
! ============================================================
! Compute left eigenvectors.
!
! IV is index of column in current block.
! Non-blocked version always uses IV=1;
! blocked version starts with IV=1, goes up to NB.
! (Note the "0-th" column is used to store the original diagonal.)
iv = 1
is = 1
DO ki = 1 , N
!
IF ( somev ) THEN
IF ( .NOT.Select(ki) ) CYCLE
ENDIF
smin = MAX(ulp*(CABS1(T(ki,ki))),smlnum)
!
! --------------------------------------------------------
! Complex left eigenvector
!
Work(ki+iv*N) = CONE
!
! Form right-hand side.
!
DO k = ki + 1 , N
Work(k+iv*N) = -CONJG(T(ki,k))
ENDDO
!
! Solve conjugate-transposed triangular system:
! [ T(KI+1:N,KI+1:N) - T(KI,KI) ]**H * X = SCALE*WORK.
!
DO k = ki + 1 , N
T(k,k) = T(k,k) - T(ki,ki)
IF ( CABS1(T(k,k))<smin ) T(k,k) = smin
ENDDO
!
IF ( ki<N ) THEN
CALL CLATRS('Upper','Conjugate transpose','Non-unit','Y',&
& N-ki,T(ki+1,ki+1),Ldt,Work(ki+1+iv*N),scale, &
& Rwork,Info)
Work(ki+iv*N) = scale
ENDIF
!
! Copy the vector x or Q*x to VL and normalize.
!
IF ( .NOT.over ) THEN
! ------------------------------
! no back-transform: copy x to VL and normalize.
CALL CCOPY(N-ki+1,Work(ki+iv*N),1,Vl(ki,is),1)
!
ii = ICAMAX(N-ki+1,Vl(ki,is),1) + ki - 1
remax = ONE/CABS1(Vl(ii,is))
CALL CSSCAL(N-ki+1,remax,Vl(ki,is),1)
!
DO k = 1 , ki - 1
Vl(k,is) = CZERO
ENDDO
!
ELSEIF ( nb==1 ) THEN
! ------------------------------
! version 1: back-transform each vector with GEMV, Q*x.
IF ( ki<N ) CALL CGEMV('N',N,N-ki,CONE,Vl(1,ki+1),Ldvl, &
& Work(ki+1+iv*N),1,CMPLX(scale), &
& Vl(1,ki),1)
!
ii = ICAMAX(N,Vl(1,ki),1)
remax = ONE/CABS1(Vl(ii,ki))
CALL CSSCAL(N,remax,Vl(1,ki),1)
!
ELSE
! ------------------------------
! version 2: back-transform block of vectors with GEMM
! zero out above vector
! could go from KI-NV+1 to KI-1
DO k = 1 , ki - 1
Work(k+iv*N) = CZERO
ENDDO
!
! Columns 1:IV of work are valid vectors.
! When the number of vectors stored reaches NB,
! or if this was last vector, do the GEMM
IF ( (iv==nb) .OR. (ki==N) ) THEN
CALL CGEMM('N','N',N,iv,N-ki+iv,CONE,Vl(1,ki-iv+1), &
& Ldvl,Work(ki-iv+1+(1)*N),N,CZERO, &
& Work(1+(nb+1)*N),N)
! normalize vectors
DO k = 1 , iv
ii = ICAMAX(N,Work(1+(nb+k)*N),1)
remax = ONE/CABS1(Work(ii+(nb+k)*N))
CALL CSSCAL(N,remax,Work(1+(nb+k)*N),1)
ENDDO
CALL CLACPY('F',N,iv,Work(1+(nb+1)*N),N,Vl(1,ki-iv+1),&
& Ldvl)
iv = 1
ELSE
iv = iv + 1
ENDIF
ENDIF
!
! Restore the original diagonal elements of T.
!
DO k = ki + 1 , N
T(k,k) = Work(k)
ENDDO
!
is = is + 1
ENDDO
ENDIF
!
!
! End of CTREVC3
!
END SUBROUTINE CTREVC3
| src/complex/ctrevc3.f90 |
active component C {
async command C opcode "abc"
}
| compiler/tools/fpp-check/test/command/bad_opcode.fpp |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 3