diff --git a/docs/examples/regression_solovev_ideal_example/equil.in b/docs/examples/regression_solovev_ideal_example/equil.in index 994a522b..0f9d6a26 100644 --- a/docs/examples/regression_solovev_ideal_example/equil.in +++ b/docs/examples/regression_solovev_ideal_example/equil.in @@ -9,7 +9,8 @@ grid_type="ldp" ! Radial grid packing of equilibrium quantities. Accepts rho, ldp, pow1, pow2, or original. ldp packs points near the core and edge. pow* packs near the edge. psilow=1e-4 ! Minimum value of psi, normalized from 0 to 1 - psihigh=0.99999 ! Maximum value of psi, normalized from 0 to 1 + ! Kinetic data end here; extrapolating T to the LCFS gives invalid logLambda. + psihigh=0.997995992 ! Last supplied kinetic.txt surface (positive logLambda) mpsi=16 ! Number of radial grid intervals for equilibrium quantities mtheta=256 ! Number of equally spaced poloidal grid intervals for all splines newq0=0 ! Grad-Shafranov solution invariant adjustment of the q profile to give the specified value of q at the axis. Default 0 uses input file value. diff --git a/docs/examples/regression_solovev_kinetic_example/equil.in b/docs/examples/regression_solovev_kinetic_example/equil.in index 3ac583bd..e0424335 100644 --- a/docs/examples/regression_solovev_kinetic_example/equil.in +++ b/docs/examples/regression_solovev_kinetic_example/equil.in @@ -9,7 +9,8 @@ grid_type="ldp" ! Radial grid packing of equilibrium quantities. Accepts rho, ldp, pow1, pow2, or original. ldp packs points near the core and edge. pow* packs near the edge. psilow=1e-1 ! Minimum value of psi, normalized from 0 to 1 - psihigh=0.99999 ! Maximum value of psi, normalized from 0 to 1 + ! Kinetic data end here; extrapolating T to the LCFS gives invalid logLambda. + psihigh=0.997995992 ! Last supplied kinetic.txt surface (positive logLambda) mpsi=16 ! Number of radial grid intervals for equilibrium quantities mtheta=256 ! Number of equally spaced poloidal grid intervals for all splines newq0=0 ! Grad-Shafranov solution invariant adjustment of the q profile to give the specified value of q at the axis. Default 0 uses input file value. diff --git a/docs/namelists.rst b/docs/namelists.rst index b04b1d7f..30dcd14b 100644 --- a/docs/namelists.rst +++ b/docs/namelists.rst @@ -32,8 +32,10 @@ This namelist sets the inputs, controls the behavior, and determines the outputs The PENTRC Namelist ==================== -This namelist sets the inputs, controls the behavior, and determines the outputs of the GPEC code. +This namelist sets the inputs, controls the behavior, and determines the outputs of PENTRC. .. include:: ../input/pentrc.in :literal: +.. include:: pentrc_supplied_rates.rst + diff --git a/docs/pentrc_supplied_rates.rst b/docs/pentrc_supplied_rates.rst new file mode 100644 index 00000000..6d481045 --- /dev/null +++ b/docs/pentrc_supplied_rates.rst @@ -0,0 +1,66 @@ +PENTRC supplied collision rates +============================== + +``kinetic_format = "rates-v1"`` in ``PENT_INPUT`` selects a nine-column +``kinetic_file``. The default ``"legacy"`` retains the six-column format and +its existing main-ion/impurity collision approximation. The columns are:: + + psi_n n_i n_e T_i T_e OmegaE logLambda nu_i nu_e + +Densities are in m^-3, temperatures in eV, physical electric rotation +``OmegaE`` in rad/s, the Coulomb logarithm dimensionless, and the supplied +base Krook damping rates in s^-1. No 2*pi conversion is applied. All densities, +temperatures, logarithms and rates must be positive and finite. A selected-ion +charge density greater than the total electron density is rejected. Exact +zero rotation is retained in this format. The coordinate orientation is +unchanged: provide ``OmegaE`` in native axes with ``wefac=1``, or declare the +adapter's common-to-native axis conversion through ``wefac``. Supplied-rate +mode requires ``wpfac=1``. + +The supplied rates bypass the legacy impurity-rate formula at both native +query interfaces. Native splines interpolate their logarithms on the input +radial grid, and the generated exponential kernel restores their values and +derivatives. This preserves positivity between positive input samples; +overflow, underflow and nonfinite results are rejected. Primitive drive +profiles retain the existing interpolation. As in legacy mode, ``nfac`` and +``tfac`` alter drive profiles only, leaving supplied collision rates unchanged. + +One native call calculates one population. A common D/T/e mixture therefore +uses an adapter that emits three calls. For D and T, column ``n_i,T_i`` holds +that isotope's density and temperature, and ``mi`` is respectively 2 or 3 +in proton-mass units. Set ``zi=zimp=1``; ``mimp`` may identify the other isotope. +For electrons set ``electron=.true.`` and use the same total ``n_e,T_e``. +All three calls carry the same physical ``OmegaE`` and common ``logLambda``. +Supply each population's rate from the declared full background mixture, +including its densities, temperatures, charges and masses. Keep that mixture +and rate convention in the adapter's provenance record: this profile contains +the selected drive and scalar rates, not the full background distribution. +This is a diagonal scalar response, not a coupled Fokker--Planck solve. + +The existing pitch and energy models are unchanged. Passing particles use +the supplied base rate; trapped particles use the base rate divided by +``2*epsilon``. ``nutype="krook"`` then uses this rate without energy +dependence. ``nutype="harmonic"`` additionally multiplies it by +``(1+ell_eff**2/4)*x**(-3/2)``, with ``x=E/T``, integer ``ell_eff=ell`` for +trapped particles and ``ell_eff=ell+n*q`` for passing particles. ``nufac`` +multiplies the resulting width. Do not include these geometry, harmonic, +energy or ``nufac`` factors in the supplied base columns. An energy-only +``x**(-3/2)`` operator and a geometry-uniform constant operator are not +provided by this interface. ``nutype="zero"`` selects the collisionless model; +``"small"`` retains its numerical width proportional to ``abs(OmegaE)``. + +``pentrc_kinetics.out`` records the format when ``indebug=.true.``. The native +NetCDF output records ``kinetic_format``, the consumed ``collision_model`` and +``collision_multiplier``, along with the existing selected mass, charge, +densities, temperatures, logarithm, base rates and trapped ``nu_eff`` profile. + +Run the focused native reader/query regressions with:: + + cd install + make check-pentrc-collisions + +The supplied-rate oracle checks unequal D/T drive profiles, both ion and +electron rates and their derivatives, physical zero rotation, and invalid +input rejection in both Debug and ``-O3 -ffast-math`` builds. The generated +rate reconstruction is reproducible from ``gen/gen_supplied_rates.f90`` using +FortSym; the checked-in ``pentrc/supplied_rates.inc`` is used by native builds. diff --git a/gen/README.md b/gen/README.md new file mode 100644 index 00000000..ed7fe26f --- /dev/null +++ b/gen/README.md @@ -0,0 +1,15 @@ +Regenerate the supplied-rate exponential and its symbolic derivative with +FortSym. `FORTSYM_PREFIX` points to a verified FortSym build or installation +containing `include/` and `lib/`; supply its exact source revision below. + +```sh +gfortran -I"$FORTSYM_PREFIX/include" gen/gen_supplied_rates.f90 \ + -L"$FORTSYM_PREFIX/lib" -lfortsym -Wl,-rpath,"$FORTSYM_PREFIX/lib" \ + -o gen_supplied_rates +./gen_supplied_rates pentrc/supplied_rates.inc FORTSYM_REVISION +``` + +The generated include is checked in, so normal native builds do not require +FortSym. The reader uses native spline interpolation; this generator owns only +the pointwise exponential reconstruction and its derivative. Independent +profile and invalid-input oracles run through `make check-pentrc-collisions`. diff --git a/gen/gen_supplied_rates.f90 b/gen/gen_supplied_rates.f90 new file mode 100644 index 00000000..ece5ce7e --- /dev/null +++ b/gen/gen_supplied_rates.f90 @@ -0,0 +1,42 @@ +program gen_supplied_rates + use fortsym_arena, only: arena_t + use fortsym_expr, only: expr_t, sym, exp, operator(*) + use fortsym_diff, only: diff + use fortsym_kernel_emit, only: kernel_emit_spec_t, emit_fortran_kernel_ir + use fortsym_kernel_ir, only: kernel_ir_t, lower_kernel_ir + use fortsym_string, only: chars, str, str_t + implicit none + type(arena_t), target :: arena + type(expr_t) :: logarithm, logarithm_derivative, roots(2) + type(kernel_ir_t) :: ir + type(kernel_emit_spec_t) :: spec + type(str_t) :: source + character(2048) :: output, revision + character(:), allocatable :: message + integer :: unit + logical :: ok + + call get_command_argument(1,output) + call get_command_argument(2,revision) + if(len_trim(output)==0.or.len_trim(revision)==0) & + error stop 'usage: gen_supplied_rates OUTPUT FORTSYM_REVISION' + call arena%init() + logarithm=sym(arena,'logarithm') + logarithm_derivative=sym(arena,'logarithm_derivative') + roots(1)=exp(logarithm) + roots(2)=diff(roots(1),logarithm)*logarithm_derivative + call lower_kernel_ir(roots,ir,ok,message) + if(.not.ok) error stop message + spec%name=str('supplied_rate_leaf') + spec%args=[str('logarithm'),str('logarithm_derivative')] + spec%outputs=[str('rate'),str('rate_derivative')] + spec%generator=str('gen/gen_supplied_rates.f90') + spec%generator_revision=str(trim(revision)) + spec%regenerate_command=str( & + 'gen_supplied_rates pentrc/supplied_rates.inc FORTSYM_REVISION') + source=emit_fortran_kernel_ir(ir,spec,ok,message) + if(.not.ok) error stop message + open(newunit=unit,file=trim(output),status='replace') + write(unit,'(a)',advance='no') chars(source) + close(unit) +end program gen_supplied_rates diff --git a/input/pentrc.in b/input/pentrc.in index b1ba6e95..84416c47 100644 --- a/input/pentrc.in +++ b/input/pentrc.in @@ -1,6 +1,7 @@ &PENT_INPUT idconfile = "euler.bin" ! Eigenfunctions output by DCON run kinetic_file = "kinetic.txt" ! Ascii profiles. columns: psi_n, ni(m^-3), ne(m^-3), ti(eV), te(eV), omega_EXB(rad/s) + kinetic_format = "legacy" ! "rates-v1" appends logLambda,nu_i(s^-1),nu_e(s^-1); positive supplied base rates data_dir = "" ! Location of pre-formed fnml matrix used in rlar and clar methods. "default" uses $GPECHOME/pentrc. peq_file = "" ! Ascii displacement. columns: psi_n, m, real(xi^psi), imag(xi^psi), real(xi^alpha), imag(xi^alpha). Default uses "gpec_xclebsch_n#.out" diff --git a/install/DEPENDENCIES.inc b/install/DEPENDENCIES.inc index a7c0d3f4..97ace917 100644 --- a/install/DEPENDENCIES.inc +++ b/install/DEPENDENCIES.inc @@ -95,7 +95,7 @@ ../pentrc/dcon_interface.o: ../equil/bicube.o ../equil/cspline.o ../equil/fspline.o ../equil/spline.o ../pentrc/params.o ../pentrc/utilities.o ../pentrc/diagnostics.o: ../equil/cspline.o ../equil/spline.o ../pentrc/energy.o ../pentrc/params.o ../pentrc/pitch.o ../pentrc/special.o ../pentrc/energy.o: ../pentrc/dcon_interface.o ../pentrc/lsode2.o ../pentrc/params.o ../pentrc/utilities.o -../pentrc/inputs.o: ../equil/bicube.o ../equil/cspline.o ../equil/fspline.o ../equil/spline.o ../pentrc/dcon_interface.o ../pentrc/params.o ../pentrc/utilities.o +../pentrc/inputs.o: ../equil/bicube.o ../equil/cspline.o ../equil/fspline.o ../equil/spline.o ../pentrc/dcon_interface.o ../pentrc/params.o ../pentrc/supplied_rates.inc ../pentrc/utilities.o ../pentrc/lsode1.o: ../equil/local.o ../pentrc/lsode2.o: ../equil/local.o ../pentrc/params.o: ../equil/local.o ../pentrc/version.inc diff --git a/install/TARGETS.inc b/install/TARGETS.inc index e20d9327..576bb8de 100644 --- a/install/TARGETS.inc +++ b/install/TARGETS.inc @@ -431,3 +431,16 @@ mkbin: pentrc dcon rdcon stride match rmatch slayer multi sum gpec cp ../sum/sum $(BINDIR) cp ../gpec/gpec $(BINDIR) $(call print_success,All binaries copied to $(BINDIR)) + +# Native PENTRC profile-reader/query regression; no equilibrium or solver job. +../pentrc/inputs.o: ../pentrc/supplied_rates.inc + +ifeq ($(PLATFORM),Darwin) +GPEC_TEST_LDFLAGS ?= -Wl,-dead_strip +else +GPEC_TEST_LDFLAGS ?= -Wl,--gc-sections +endif +.PHONY: check-pentrc-collisions +check-pentrc-collisions: + GPEC_TEST_LDFLAGS="$(GPEC_TEST_LDFLAGS)" python3 ../regression/test/pentrc_collision_profile.py -v + GPEC_TEST_LDFLAGS="$(GPEC_TEST_LDFLAGS)" python3 ../regression/test/pentrc_supplied_rates.py -v diff --git a/pentrc/inputs.f90 b/pentrc/inputs.f90 index a21b8087..96279151 100644 --- a/pentrc/inputs.f90 +++ b/pentrc/inputs.f90 @@ -15,7 +15,8 @@ module inputs !*PUBLIC DATA MEMBERS: ! ro, real - Major radius (idcon) ! bo, real - Field on axis (determined from sq) - ! kin, spline_type - (psi) Kinetic profiles + ! kin, spline_type - (psi) Primitive profiles; use kin_eval or + ! kin_eval_external for derived collision rates ! xs_m, fspline_type - (psi,theta) First order perturbations ! eqfun, bicube_type - (psi,theta) Equilibrium mod b ! sq, spline_type - (psi,theta) Equilibrium flux functions @@ -29,9 +30,11 @@ module inputs ! EMAIL: nikolas.logan@columbia.edu !----------------------------------------------------------------------- + use, intrinsic :: iso_fortran_env, only: int64 use params, only : r8,xj,mp,me,e,mu0,twopi use utilities, only : get_free_file_unit,readtable,nunique,progressbar,iscdftf,iscdftb - use spline_mod, only : spline_type,spline_alloc,spline_fit,spline_eval,spline_write1 + use spline_mod, only : spline_type,spline_alloc,spline_fit,spline_eval,spline_write1, & + spline_eval_external use cspline_mod, only : cspline_type,cspline_alloc,cspline_dealloc,& cspline_fit,cspline_write,cspline_eval use fspline_mod, only : fspline_eval @@ -50,21 +53,26 @@ module inputs private public & - read_kin, & + read_kin, kin_eval, kin_eval_external, & read_pmodb, & read_peq, & set_peq, & read_gpec_peq,& read_equil, & read_fnml, & - kin, xs_m, dbob_m, divx_m, fnml, & + kin, kin_rate_format, xs_m, dbob_m, divx_m, fnml, & geom,eqfun, sq, rzphi, smats, tmats, xmats, ymats, zmats, & chi1,ro,zo,bo,nn,mfac,mpert,mthsurf, & shotnum,shottime,machine,& verbose ! global variables with defaults + ! Species parameters are immutable during one PENTRC run, like ro and bo. + integer :: kin_zi,kin_zimp,kin_mi,kin_mimp + character(16) :: kin_rate_format='legacy' type(spline_type) :: kin + type(spline_type) :: kin_collision + type(spline_type) :: kin_supplied type(cspline_type) :: dbob_m, divx_m, xs_m(3) type(bicube_type):: fnml !$omp threadprivate(dbob_m, divx_m, kin, xs_m, fnml) @@ -156,7 +164,7 @@ end subroutine read_equil !======================================================================= - subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log) + subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log,format) !----------------------------------------------------------------------- !*DESCRIPTION: ! Read ascii file containing table of kinetic profiles ni, ne, ti, @@ -166,7 +174,9 @@ subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log) ! Assumes table consists of 6 columns: psi_n, n_i(m^-3), n_e(m^-3), ! T_i(eV), T_e(eV), omega_E(rad/s). File can (nearly) arbitrary ! header and/or footer, with the exception that no lines start with - ! a number. + ! a number. Optional format='rates-v1' requires exactly nine columns: + ! the six above, logLambda, nu_i(s^-1), nu_e(s^-1). Rates are positive + ! supplied base damping rates, interpolated through their logarithms. ! !*ARGUMENTS: ! file : character(256) (in) @@ -191,6 +201,7 @@ subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log) implicit none ! declare arguments character(512), intent(in) :: file + character(*), intent(in), optional :: format integer, intent(in) :: zi,zimp,mi,mimp real(r8), intent(in) :: wefac,wpfac,nfac,tfac logical :: write_log @@ -202,12 +213,42 @@ subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log) integer, parameter :: nkin = 100 integer :: i,out_unit, tshape(2) real(r8) :: psi - real(r8), dimension(0:nkin) :: zeff,zpitch,welec,wdian,wdiat,wpefac + real(r8), dimension(0:nkin) :: welec,wdian,wdiat,wpefac type(spline_type) :: tmp + kin_zi=zi + kin_zimp=zimp + kin_mi=mi + kin_mimp=mimp + kin_rate_format='legacy' + if(present(format)) kin_rate_format=format + if(kin_rate_format/='legacy'.and.kin_rate_format/='rates-v1') & + error stop 'PENTRC: kinetic_format must be legacy or rates-v1' + if(min(zi,zimp,mi,mimp)<=0) & + error stop 'PENTRC: positive ion charges and masses required' + call validate_kinetic_values([nfac,tfac,wefac,wpfac]) + if(kin_rate_format=='rates-v1'.and.wpfac/=1._r8) & + error stop 'PENTRC: rates-v1 requires wpfac=1 for physical rotation' + call readtable(file,table,titles,verbose,write_log) tshape = shape(table) if(write_log) print *,"Table shaped ",tshape + if(tshape(2)<6) error stop 'PENTRC: kinetic profile needs six columns' + if(kin_rate_format=='rates-v1') then + if(tshape(2)/=9) & + error stop 'PENTRC: rates-v1 requires exactly nine columns' + do i=1,tshape(1) + call validate_kinetic_values(table(i,:)) + if(any(table(i,2:5)<=0._r8).or.any(table(i,7:9)<=0._r8)) & + error stop 'PENTRC: rates-v1 needs positive n,T,logLambda,rates' + if(zi*table(i,2)>table(i,3)) & + error stop 'PENTRC: selected-ion density exceeds quasineutral total' + end do + call spline_alloc(kin_supplied,tshape(1)-1,3) + kin_supplied%xs=table(:,1) + kin_supplied%fs=log(table(:,7:9)) + call spline_fit(kin_supplied,"extrap") + end if ! temp spline on experimental grid call spline_alloc(tmp,tshape(1)-1,5) @@ -232,26 +273,36 @@ subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log) ! convert temperatures to si units kin%fs(:,3:4) = kin%fs(:,3:4)*1.602e-19 !ev to j - ! collisionalities **assumes si units for n,t** - zeff = zimp-(kin%fs(:,1)/kin%fs(:,2))*zi*(zimp-zi) - zpitch = 1.0+(1.0+mimp)/(2.0*mimp)*zimp*(zeff-1.0)/(zimp-zeff) - kin%fs(:,6) = 17.3-0.5*log(kin%fs(:,2)/1.0e20) & - +1.5*log(kin%fs(:,4)/1.602e-16) - kin%fs(:,7) = (zpitch/3.5e17)*kin%fs(:,1)*kin%fs(:,6) & - /(sqrt(1.0*mi)*(kin%fs(:,3)/1.602e-16)**1.5) - kin%fs(:,8) = (zpitch/3.5e17)*kin%fs(:,2)*kin%fs(:,6) & - /(sqrt(me/mp)*(kin%fs(:,4)/1.602e-16)**1.5) - kin%fs(:,9) = zeff + if(kin_rate_format=='rates-v1') then + ! Preserve supplied-profile validation and initialization. + do i=0,nkin + call supplied_collision_values(kin%xs(i),kin%fs(i,:)) + end do + else + ! Slots 6:8 are reconstructed by kin_eval[_external] at each query. + ! Synthetic interpolation nodes can lie beyond the supplied physical + ! profile, so they must not impose a collision-model domain there. + ! Keep Zeff for GPEC's direct primitive-spline/slayer consumer. + kin%fs(:,6:8)=0._r8 + kin%fs(:,9)=zimp-(kin%fs(:,1)/kin%fs(:,2))*zi*(zimp-zi) + end if call spline_fit(kin,"extrap") if(write_log) print *,"Formed kin spline" + ! Keep collision rates tied to the supplied input profiles, as before + ! nfac/tfac: those optional multipliers act on the drive profiles only. + ! This snapshot is read-only during surface integration. + kin_collision=kin + ! manipulation of N and T profiles kin%fs(:,1:2) = nfac*kin%fs(:,1:2) kin%fs(:,3:4) = tfac*kin%fs(:,3:4) ! manipulation of rotation variables welec(:) = wefac*kin%fs(:,5) ! direct manipulation of omegae + ! Supplied rotation is already physical. Preserve exact zero as well. + if(kin_rate_format/='rates-v1') then ! note dividing by zero makes a nan that then ruins the whole spline warning_printed = .false. do i=0,nkin @@ -268,6 +319,7 @@ subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log) wdiat =-twopi*kin%fs1(:,3)/(e*zi*chi1) wpefac= (wpfac*(welec+wdian+wdiat) - (wdian+wdiat))/welec welec = wpefac*welec ! indirect manipulation of rotation + end if kin%fs(:,5)=welec if(wpfac/=1.0 .and. verbose) then @@ -283,13 +335,152 @@ subroutine read_kin(file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,write_log) if(verbose) print *, "Writing kinetic spline to pentrc_kinetics.out" open(unit=out_unit,file="pentrc_kinetics.out",& status="unknown")!,action="write") - call spline_write1(kin,.true.,.false.,out_unit,0,.true.) + write(out_unit,'(a)') 'kinetic_format: '//trim(kin_rate_format) + write(out_unit,'(/a)') 'node values:' + write(out_unit,'(a,2es17.8)') 'supplied profile domain: ', & + tmp%xs(0),tmp%xs(tmp%mx) + write(out_unit,'(3x,a6,9(4x,a6))') kin%title + do i=0,nkin + psi=kin%xs(i) + if(psitmp%xs(tmp%mx)) cycle + call kin_eval(psi,0) + write(out_unit,'(i5,1p,10e11.3)') i,psi,kin%f + end do + write(out_unit,'(/a)') 'interpolated values (pointwise collision rates):' + do i=0,4*nkin + psi=tmp%xs(0)+(tmp%xs(tmp%mx)-tmp%xs(0))*real(i,r8)/(4*nkin) + call kin_eval(psi,0) + write(out_unit,'(i5,1p,10e11.3)') i,psi,kin%f + end do close(out_unit) endif end subroutine read_kin + subroutine kin_eval(psi,mode) + ! Keep primitive interpolation and gradients unchanged. Nonlinear + ! collision rates must not be independently interpolated as cubics. + real(r8), intent(in) :: psi + integer, intent(in) :: mode + call spline_eval(kin,psi,mode) + if(mode>0) then + call update_collision_values(psi,kin%f,kin%f1) + else + call update_collision_values(psi,kin%f) + end if + end subroutine kin_eval + + subroutine kin_eval_external(psi,ix,f,f1) + ! Reentrant evaluator for the surface integrand and its exported data. + real(r8), intent(in) :: psi + integer, intent(inout) :: ix + real(r8), intent(out) :: f(:),f1(:) + call spline_eval_external(kin,psi,ix,f,f1) + call update_collision_values(psi,f,f1) + end subroutine kin_eval_external + + subroutine update_collision_values(psi,f,f1) + ! The original inputs set collisions even when nfac/tfac modify the + ! drive profiles. Supplied rates bypass the legacy impurity model. + real(r8), intent(in) :: psi + real(r8), intent(inout) :: f(:) + real(r8), intent(inout), optional :: f1(:) + real(r8) :: raw(9),raw1(9) + integer :: ix + ix=0 + call spline_eval_external(kin_collision,psi,ix,raw,raw1) + if(kin_rate_format=='rates-v1') then + call supplied_collision_values(psi,raw,raw1) + else + call kinetic_collisions(raw,raw1) + end if + f(6:9)=raw(6:9) + if(present(f1)) f1(6:9)=raw1(6:9) + end subroutine update_collision_values + + subroutine validate_kinetic_values(values) + ! Inspect binary64 exponent bits: IEEE predicates may be optimized + ! away by -ffast-math, while integer validation remains effective. + real(r8), intent(in) :: values(:) + integer(int64) :: bits(size(values)) + integer(int64), parameter :: exponent_mask=int(z'7ff0000000000000',int64) + if(storage_size(0._r8)/=64) & + error stop 'PENTRC: kinetic validation requires binary64' + bits=transfer(values,bits) + if(any(iand(bits,exponent_mask)==exponent_mask)) & + error stop 'PENTRC: non-finite kinetic profile value' + end subroutine validate_kinetic_values + + subroutine supplied_collision_values(psi,f,f1) + real(r8), intent(in) :: psi + real(r8), intent(inout) :: f(:) + real(r8), intent(inout), optional :: f1(:) + real(r8) :: logarithms(3),derivatives(3),rate_derivatives(3) + integer :: ix,j + call validate_kinetic_values(f(1:5)) + if(any(f(1:4)<=0._r8)) & + error stop 'PENTRC: non-positive supplied-rate drive profile' + if(kin_zi*f(1)>f(2)) & + error stop 'PENTRC: selected-ion density exceeds quasineutral total' + ix=0 + call spline_eval_external(kin_supplied,psi,ix,logarithms,derivatives) + do j=1,3 + call supplied_rate_leaf(logarithms(j),derivatives(j), & + f(j+5),rate_derivatives(j)) + end do + call validate_kinetic_values(f(6:8)) + if(any(f(6:8)<=0._r8)) & + error stop 'PENTRC: supplied-rate interpolation underflow' + ! Main ion plus residual ion charge determines this diagnostic. + ! In the D/T projection zi=zimp=1 gives Zeff=1 without a division. + f(9)=kin_zimp-(f(1)/f(2))*kin_zi*(kin_zimp-kin_zi) + if(present(f1)) then + call validate_kinetic_values(f1(1:5)) + call validate_kinetic_values(rate_derivatives) + f1(6:8)=rate_derivatives + f1(9)=-kin_zi*(kin_zimp-kin_zi) & + *(f1(1)/f(2)-f(1)*f1(2)/f(2)**2) + end if + end subroutine supplied_collision_values + + include 'supplied_rates.inc' + + subroutine kinetic_collisions(f,f1) + ! n_i,n_e in m^-3, T_i,T_e in joules; rates in s^-1. + ! Reconstruct the existing read_kin Coulomb model at the query point. + ! Positive physical primitives and a positive Coulomb logarithm imply + ! positive rates, without flooring or clipping an interpolated rate. + real(r8), intent(inout) :: f(:) + real(r8), intent(inout), optional :: f1(:) + real(r8) :: zpitch,dpitch,fac + if(any(f(1:4)<=0)) & + error stop 'PENTRC: non-positive kinetic density or temperature' + f(6)=17.3-0.5*log(f(2)/1.0e20)+1.5*log(f(4)/1.602e-16) + f(9)=kin_zimp-(f(1)/f(2))*kin_zi*(kin_zimp-kin_zi) + if(kin_zimp<=f(9)) & + error stop 'PENTRC: invalid impurity density in collision model' + fac=(1.0+kin_mimp)/(2.0*kin_mimp)*kin_zimp + zpitch=1.0+fac*(f(9)-1.0)/(kin_zimp-f(9)) + if(f(6)<=0.or.zpitch<=0) & + error stop 'PENTRC: non-positive collision model coefficient' + f(7)=(zpitch/3.5e17)*f(1)*f(6) & + /(sqrt(1.0*kin_mi)*(f(3)/1.602e-16)**1.5) + f(8)=(zpitch/3.5e17)*f(2)*f(6) & + /(sqrt(me/mp)*(f(4)/1.602e-16)**1.5) + if(present(f1)) then + f1(6)=-0.5*f1(2)/f(2)+1.5*f1(4)/f(4) + f1(9)=-kin_zi*(kin_zimp-kin_zi) & + *(f1(1)/f(2)-f(1)*f1(2)/f(2)**2) + dpitch=fac*(kin_zimp-1.0)*f1(9)/(kin_zimp-f(9))**2 + f1(7)=f(7)*(dpitch/zpitch+f1(1)/f(1) & + +f1(6)/f(6)-1.5*f1(3)/f(3)) + f1(8)=f(8)*(dpitch/zpitch+f1(2)/f(2) & + +f1(6)/f(6)-1.5*f1(4)/f(4)) + end if + end subroutine kinetic_collisions + + !======================================================================= subroutine read_pmodb(file,jac_in,jsurf_in,tmag_in,debug,op_powin) !----------------------------------------------------------------------- diff --git a/pentrc/pentrc_interface.f90 b/pentrc/pentrc_interface.f90 index 6814a986..7c1d1d01 100644 --- a/pentrc/pentrc_interface.f90 +++ b/pentrc/pentrc_interface.f90 @@ -143,13 +143,14 @@ module pentrc_interface pmodb_file ="none", & data_dir ="." character(32) :: & + kinetic_format = "legacy",& nutype = "harmonic",& f0type = "maxwellian",& jac_in = "default",& moment = "pressure" ! namelists - namelist/pent_input/kinetic_file, gpec_file, peq_file, pmodb_file, idconfile, & + namelist/pent_input/kinetic_file, kinetic_format, gpec_file, peq_file, pmodb_file, idconfile, & data_dir, zi, zimp, mi, mimp, nl, electron, nutype, f0type, & jac_in, jsurf_in, tmag_in, power_bin, power_bpin, power_rin, power_rcin @@ -238,7 +239,8 @@ subroutine initialize_pentrc(op_kin,op_deq,op_peq) ! read (perturbed) equilibrium inputs if(indebug .and. in_kin) print *," read_kin args: ",trim(kinetic_file),zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,indebug if(in_deq) call read_equil(idconfile) - if(in_kin) call read_kin(kinetic_file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,indebug) + if(in_kin) call read_kin(kinetic_file,zi,zimp,mi,mimp,nfac,tfac, & + wefac,wpfac,indebug,kinetic_format) if(in_peq)then if(peq_file=="")then write(nstr,'(i3)')nn @@ -297,7 +299,8 @@ subroutine get_pentrc(get_nl,get_zi,get_mi,get_wdfac,get_divxfac,& print *,"read_kin args:" print *," ",trim(kinetic_file),zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,tdebug endif - call read_kin(kinetic_file,zi,zimp,mi,mimp,nfac,tfac,wefac,wpfac,indebug) + call read_kin(kinetic_file,zi,zimp,mi,mimp,nfac,tfac, & + wefac,wpfac,indebug,kinetic_format) ! transfer torque function variables to external program get_nl = nl diff --git a/pentrc/supplied_rates.inc b/pentrc/supplied_rates.inc new file mode 100644 index 00000000..99eae324 --- /dev/null +++ b/pentrc/supplied_rates.inc @@ -0,0 +1,17 @@ +! Generated by fortsym. Do not edit. +! Generator: gen/gen_supplied_rates.f90 +! Generator revision: 2f0571e39f36a0606b3ae150c8b3b3df92ce6750 +! Regenerate with: gen_supplied_rates pentrc/supplied_rates.inc FORTSYM_REVISION + +subroutine supplied_rate_leaf(logarithm, logarithm_derivative, rate, rate_derivative) + use, intrinsic :: iso_fortran_env, only: real64 + implicit none + real(real64), intent(in) :: logarithm, logarithm_derivative + real(real64), intent(out) :: rate, rate_derivative + real(real64) :: t2, t5 + + t2 = exp(logarithm) + t5 = (logarithm_derivative * t2) + rate = t2 + rate_derivative = t5 +end subroutine supplied_rate_leaf diff --git a/pentrc/torque.F90 b/pentrc/torque.F90 index a930b619..d55d2374 100644 --- a/pentrc/torque.F90 +++ b/pentrc/torque.F90 @@ -36,10 +36,10 @@ module torque cspline_fit,cspline_int,cspline_eval_external use bicube_mod, only : bicube_eval_external use pitch_integration, only : lambdaintgrl_lsode,kappaintgrl,kappadjsum - use energy_integration, only : xintgrl_lsode,qt + use energy_integration, only : xintgrl_lsode,qt,xnutype,xnufac use dcon_interface, only : issurfint,mpert ! intel < 2018 doesn't like mpert from inputs use inputs, only : eqfun,sq,geom,rzphi,smats,tmats,xmats,ymats,zmats,& - kin,xs_m,dbob_m,divx_m,fnml, & ! equilib and pert. equilib splines + kin,kin_rate_format,kin_eval,kin_eval_external,xs_m,dbob_m,divx_m,fnml, & ! profile queries chi1,ro,zo,bo,mfac,mthsurf,shotnum,shottime, & ! reals or integers verbose, & ! logical machine ! character @@ -307,7 +307,7 @@ subroutine tpsi(tpsi_var,psi,n,l,zi,mi,wdfac,divxfac,electron, & ! flux function variables !!WARNING WHEN MODIFYING: THESE ARE CALCULATED SEPARATELY FOR I/O!! call spline_eval_external(sq,psi,ix,sq_s_f) - call spline_eval_external(kin,psi,ix,kin_f,kin_f1) + call kin_eval_external(psi,ix,kin_f,kin_f1) call spline_eval_external(geom,psi,ix,geom_f) q = sq_s_f(4) welec = kin_f(5) ! electric precession @@ -1121,7 +1121,7 @@ function tintgrl_grid(gtype,psilim,n,nl,zi,mi,wdfac,divxfac,electron,& do i=0,mx x = xs(i+istrt) call spline_eval(sq,x,0) - call spline_eval(kin,x,1) + call kin_eval(x,1) call spline_eval(geom,x,1) gam = tphi_spl%fs(i,:)*twopi/(chrg*chi1*geom%f(1)) if(qt)then @@ -1295,7 +1295,7 @@ function tintgrl_lsode(psilim,n,nl,zi,mi,wdfac,divxfac,electron,method) ! flux/diffusivity profiles call spline_eval(sq,x,0) - call spline_eval(kin,x,1) + call kin_eval(x,1) call spline_eval(geom,x,1) gam = dky*twopi/(chrg*chi1*geom%f(1)) if(qt)then @@ -1898,7 +1898,7 @@ subroutine output_torque_netcdf(n,nl,zi,mi,electron,wdfac) do i=1,sq%mx + 1 psi = sq%xs(i-1) call spline_eval(sq,psi,1) - call spline_eval(kin,psi,1) + call kin_eval(psi,1) call spline_eval(geom,psi,0) q = sq%f(4) ni(i) = kin%f(1) @@ -1929,6 +1929,11 @@ subroutine output_torque_netcdf(n,nl,zi,mi,electron,wdfac) ! store attributes call check( nf90_put_att(ncid, nf90_global, "title", "PENTRC fundamental outputs") ) call check( nf90_put_att(ncid, nf90_global, "version", version)) + call check( nf90_put_att(ncid, nf90_global, "kinetic_format", & + trim(kin_rate_format)) ) + call check( nf90_put_att(ncid, nf90_global, "collision_model", & + trim(xnutype)) ) + call check( nf90_put_att(ncid, nf90_global, "collision_multiplier", xnufac) ) call check( nf90_put_att(ncid, nf90_global, "shot", INT(shotnum) ) ) call check( nf90_put_att(ncid, nf90_global, "time", INT(shottime)) ) call check( nf90_put_att(ncid, nf90_global, "machine", machine) ) diff --git a/regression/test/pentrc_collision_profile.py b/regression/test/pentrc_collision_profile.py new file mode 100644 index 00000000..f47208c0 --- /dev/null +++ b/regression/test/pentrc_collision_profile.py @@ -0,0 +1,242 @@ +"""Native read_kin and torque query must preserve positive physical collision rates. + +Compile the production profile reader, its query routines and the exact query +calls used by torque.F90, with the native spline/table modules. A positive +linear-temperature profile has an independent analytic Coulomb-rate oracle. + +Use the native make check-pentrc-collisions target to select platform linker +flags. Direct invocation accepts GPEC_TEST_LDFLAGS (use -Wl,-dead_strip on Darwin). +""" +import math +import os +from pathlib import Path +import re +import shlex +import struct +import subprocess +import tempfile +import unittest + +ROOT = Path(os.environ.get('GPEC_ROOT') or Path(__file__).resolve().parents[2]) + + +def routine(source, name): + m = re.search(r'^ subroutine ' + name + r'\(.*?^ end subroutine ' + name + r'\b', + source, re.M | re.S | re.I) + return m.group() + '\n' if m else '' + + +class CollisionProfileTests(unittest.TestCase): + def test_native_offgrid_rates_match_positive_coulomb_oracle(self): + source = (ROOT/'pentrc/inputs.f90').read_text() + torque = (ROOT/'pentrc/torque.F90').read_text() + call_external = re.search(r'call (?:kin_eval_external\(|spline_eval_external\(kin,)[^\n]+', torque).group() + call_diagnostic = re.search(r'call (?:kin_eval\(x,1\)|spline_eval\(kin,x,1\))', torque).group() + decl = source[source.index(' integer :: kin_zi'):source.index(' type(cspline_type)')] + parts = ''.join(routine(source, name) for name in + ('read_kin', 'kin_eval', 'kin_eval_external', 'update_collision_values', + 'kinetic_collisions', 'validate_kinetic_values', 'supplied_collision_values')) + inputs = '''module inputs +use, intrinsic :: iso_fortran_env, only: int64 +use params, only: r8,mp,me,e,twopi +use utilities, only: readtable,get_free_file_unit +use spline_mod, only: spline_type,spline_alloc,spline_fit, & + spline_eval,spline_eval_external,spline_write1 +implicit none +logical :: verbose=.false. +real(r8) :: chi1=1.0_r8 +''' + decl + '\ncontains\n' + parts + \ + (ROOT/'pentrc/supplied_rates.inc').read_text() + '\nend module inputs\n' + driver = '''program collision_profile +use params, only: r8 +use inputs +use spline_mod, only: spline_eval,spline_eval_external,spline_dealloc +implicit none +integer :: i,unit,ix,icase +real(r8) :: psi,x,nfac,tfac,kin_f(9),kin_f1(9) +character(512) :: file,mode +call get_command_argument(1,mode) +file='profile.kin' +open(newunit=unit,file=trim(file),status='replace') +write(unit,'(a)') 'psi ni ne ti te omegae' +do i=0,199 + psi=0.99485_r8*i/199 + write(unit,'(6es25.16e3)') psi,1.e19_r8,1.e19_r8, & + 100._r8+72000._r8*(1-psi),1.2_r8*(100._r8+72000._r8*(1-psi)),-3000._r8 +end do +close(unit) +do icase=1,3 + nfac=1._r8 + tfac=1._r8 + if(icase==2) then + nfac=0.5_r8 + tfac=2._r8 + end if + if(icase==3) file='CI_PROFILE_FILE' + call read_kin(file,1,6,2,12,nfac,tfac,1._r8,1._r8,.true.) + if(icase==3.and.trim(mode)=='invalid-query') call kin_eval(1._r8,1) + ix=0 + do i=0,104 + psi=i/100._r8 + if(i==101) psi=0.984411_r8 + if(i==102) psi=0.985957_r8 + if(i==103) psi=0.9756_r8 + if(i==104) psi=0.989_r8 + if(icase==3) then + psi=0.997995992_r8*i/100 + if(i==101) psi=.25_r8 + if(i==102) psi=.5_r8 + if(i==103) psi=.75_r8 + if(i==104) psi=.99_r8 + end if + QUERY_EXTERNAL + call spline_eval(kin,psi,1) + if(abs(kin%f(9)-1._r8)>1.e-12_r8) error stop 'raw slayer Zeff changed' + x=psi + QUERY_DIAGNOSTIC + write(*,'(2i4,1x,28es25.16e3)') icase,i,psi,kin_f,kin%f,kin_f1(7:8),kin_f1(1:5) + end do + call spline_dealloc(kin) + call spline_dealloc(kin_collision) +end do +end program collision_profile +'''.replace('QUERY_EXTERNAL',call_external).replace('QUERY_DIAGNOSTIC',call_diagnostic).replace( + 'CI_PROFILE_FILE',str(ROOT/'docs/examples/regression_solovev_ideal_example/kinetic.txt')) + with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', ROOT)) as tmp: + work=Path(tmp) + (work/'inputs.f90').write_text(inputs) + (work/'driver.f90').write_text(driver) + (work/'version.inc').write_text("character(128), parameter :: version='collision-profile-test'\n") + files=['equil/io.f','equil/local.f','equil/utils.f','equil/spline.f', + 'pentrc/params.f90','pentrc/utilities.f90'] + nf=os.environ.get('NF_CONFIG','nf-config') + netcdf_flags=shlex.split(os.environ['NETCDF_FFLAGS']) if 'NETCDF_FFLAGS' in os.environ else \ + shlex.split(subprocess.check_output([nf,'--fflags'],text=True)) + netcdf_libs=shlex.split(os.environ['NETCDF_FLIBS']) if 'NETCDF_FLIBS' in os.environ else \ + shlex.split(subprocess.check_output([nf,'--flibs'],text=True)) + math_libs=shlex.split(os.environ.get('GPEC_MATH_LIBS','-llapack -lblas')) + linker_flags=shlex.split(os.environ.get('GPEC_TEST_LDFLAGS','-Wl,--gc-sections')) + command=[os.environ.get('FC','gfortran'),'-O0','-fcheck=all','-std=legacy', + '-ffree-line-length-none','-ffixed-line-length-none','-fallow-argument-mismatch', + '-ffunction-sections','-fdata-sections',*netcdf_flags,'-I'+str(work), + *[str(ROOT/f) for f in files],str(work/'inputs.f90'),str(work/'driver.f90'), + *linker_flags,*netcdf_libs,*math_libs,'-o',str(work/'check')] + compiled=subprocess.run(command,cwd=work,text=True,capture_output=True,timeout=90) + self.assertEqual(compiled.returncode,0,compiled.stdout+compiled.stderr) + run=subprocess.run([str(work/'check')],cwd=work,text=True,capture_output=True,timeout=30) + self.assertEqual(run.returncode,0,run.stdout+run.stderr) + invalid=subprocess.run([str(work/'check'),'invalid-query'],cwd=work, + text=True,capture_output=True,timeout=30) + self.assertNotEqual(invalid.returncode,0,'invalid consumed extrapolation accepted') + self.assertIn('PENTRC: non-positive collision model coefficient', + invalid.stdout+invalid.stderr) + # Debug-exported values use the same physical query, too. + debug_rates=[] + for line in (work/'pentrc_kinetics.out').read_text().splitlines(): + tokens=line.split() + if len(tokens)!=11: + continue + try: + fields=list(map(float,tokens)) + except ValueError: + continue + debug_rates.extend(fields[8:10]) + self.assertTrue(debug_rates) + self.assertGreater(min(debug_rates),0.,'debug export retains a negative rate') + minnu=math.inf + maxerr=0. + violations=[] + row_count=0 + maxprimitiveerr=0. + min_ci_loglambda=math.inf + # Native primitive values/gradients from unmodified develop + # 3c0b8f3b, GNU Fortran binary64, using the exact CI input file. + # This parent-code receipt verifies the existing two-stage + # primitive interpolation, including its cold-edge error. + primitive_receipt={ + 0: (1.51795e21,1.4097600405650037e-17,3958.999995, + -1.0625634632084995e21,-4.2292892968672215e-18,-3959.0000556058844), + 100: (4.575143868829413e20,9.373007088720216e-20,7.933867835582145, + -1.0625654363734113e21,-4.65544415687748e-17,-3959.000011093797), + 101: (1.2523087477594865e21,1.2816000366244083e-17,2969.2499995564554, + -1.0625652711557528e21,-6.213818814970546e-18,-3959.001265133593), + 102: (9.866675000002848e20,1.0844307997650295e-17,1979.5000065100269, + -1.0625650002070866e21,-1.0010130403478095e-17,-3958.9997417756244), + 103: (7.210262496942402e20,7.419789684897973e-18,989.7500003888853, + -1.0625649979732148e21,-1.874473135647245e-17,-3959.0005334947086), + 104: (4.660106501937482e20,4.592052280328285e-19,39.590000328186484, + -1.0625651093240409e21,-4.487429506331625e-17,-3959.000030368476), + } + for line in run.stdout.splitlines(): + values=line.split() + if len(values)!=28: + continue + case,index=int(values[0]),int(values[1]) + row_count+=1 + psi=float(values[2]); f=list(map(float,values[3:12])); diagnostic=list(map(float,values[12:21])) + nfac,tfac=(0.5,2.) if case==2 else (1.,1.) + ni=ne=1.e19*nfac + ti=(100.+72000.*(1.-psi))*tfac + te=1.2*ti + if case==3: + # The CI profile is n=n0*(1-.7*psi), n*T proportional to + # 1-psi. Its finite supplied endpoint has logLambda>5; + # extrapolating it to psi=1 violates weak coupling. + ni=ne=1.51795e21*(1-.7*psi) + # Rate coefficients belong to the consumed primitives, + # rather than the analytic profile before interpolation. + ti=f[2]/1.602e-19 + te=f[3]/1.602e-19 + if index in primitive_receipt: + pf=list(map(float,values[23:28])) + actual=(f[0],f[2],f[4],pf[0],pf[2],pf[4]) + for a,b in zip(actual,primitive_receipt[index]): + maxprimitiveerr=max(maxprimitiveerr,abs(a/b-1.)) + self.assertLess(abs(a/b-1.),2.e-10) + self.assertEqual(f[0],f[1]) + self.assertEqual(f[2],f[3]) + # Preserve nfac/tfac semantics: collisions belong to the input + # profiles; these optional multipliers alter drive profiles. + base_ni,base_ne=ni/nfac,ne/nfac + base_ti,base_te=ti/tfac,te/tfac + lnl=17.3-0.5*math.log(base_ne/1.e20)+1.5*math.log(base_te/1.e3) + if case==3: + min_ci_loglambda=min(min_ci_loglambda,f[5]) + # The original reader's unsuffixed constants are binary32 + # literals promoted to binary64; preserve that convention. + native=lambda v: struct.unpack('f',struct.pack('f',v))[0] + native_lnl=native(17.3)-.5*math.log(f[1]/native(1.e20)) \ + +1.5*math.log(f[3]/native(1.602e-16)) + self.assertLess(abs(f[5]/native_lnl-1.),2.e-13) + # Pure deuterium: Zeff=zpitch=1; temperatures here are eV. + nui=base_ni*lnl/(3.5e17*math.sqrt(2.)*(base_ti/1.e3)**1.5) + nue=base_ne*lnl/(3.5e17*math.sqrt(9.1091e-31/1.672614e-27)*(base_te/1.e3)**1.5) + self.assertEqual(f,diagnostic,'integrand and exported profile queries disagree') + df=list(map(float,values[21:23])) + self.assertLess(abs(f[0]/ni-1.),1.e-8 if case==3 else 1.e-9) + if case!=3: + self.assertLess(abs(f[2]/(ti*1.602e-19)-1.),1.e-6) + minnu=min(minnu,f[6],f[7]) + error=max(abs(f[6]/nui-1.),abs(f[7]/nue-1.)) + maxerr=max(maxerr,error) + derivative=(1.5/lnl-1.5)*(-72000.*tfac)/ti + if case==3: + pf=list(map(float,values[23:28])) + nd=pf[0]/f[0] + td=pf[2]/f[2] + derivative=nd+(-.5*nd+1.5*td)/lnl-1.5*td + derivative_error=max(abs(df[0]/(nui*derivative)-1.),abs(df[1]/(nue*derivative)-1.)) + if derivative_error>2.e-6: + violations.append((case,index,psi,'derivative',derivative_error)) + if min(f[6:8])<=0 or error>1.e-6: + violations.append((case,index,psi,f[6],nui,error)) + self.assertTrue(math.isfinite(minnu),'no native rows read') + self.assertEqual(row_count,315,'all three native profile cases must complete') + self.assertGreater(min_ci_loglambda,5.) + print('native collision profile: minnu=',minnu,'maxerr=',maxerr,'violations=',violations[:8]) + print('CI primitive preservation: maxerr=',maxprimitiveerr, + 'minimum logLambda=',min_ci_loglambda) + self.assertFalse(bool(violations),'native collision-rate positivity/Coulomb oracle failed: '+str(violations[:8])) + + +if __name__=='__main__': unittest.main() diff --git a/regression/test/pentrc_supplied_rates.py b/regression/test/pentrc_supplied_rates.py new file mode 100644 index 00000000..e57c9eb0 --- /dev/null +++ b/regression/test/pentrc_supplied_rates.py @@ -0,0 +1,150 @@ +"""Native supplied-rate D/T projection: analytic profile and invalid-input oracles.""" +import math +import os +from pathlib import Path +import shlex +import subprocess +import tempfile +import unittest + +from pentrc_collision_profile import ROOT, routine + + +class SuppliedRateTests(unittest.TestCase): + def test_native_supplied_rates_and_fast_validation(self): + source = (ROOT/'pentrc/inputs.f90').read_text() + declaration = source[source.index(' integer :: kin_zi'):source.index(' type(cspline_type)')] + parts = ''.join(routine(source, name) for name in ( + 'read_kin', 'kin_eval', 'kin_eval_external', 'update_collision_values', + 'kinetic_collisions', 'validate_kinetic_values', 'supplied_collision_values')) + inputs = '''module inputs +use, intrinsic :: iso_fortran_env, only: int64 +use params, only: r8,mp,me,e,twopi +use utilities, only: readtable,get_free_file_unit +use spline_mod, only: spline_type,spline_alloc,spline_fit, & + spline_eval,spline_eval_external,spline_write1 +implicit none +logical :: verbose=.false. +real(r8) :: chi1=1.0_r8 +''' + declaration + '\ncontains\n' + parts + generated = ROOT/'pentrc/supplied_rates.inc' + if generated.exists(): + inputs += generated.read_text() + inputs += '\nend module inputs\n' + driver = '''program supplied_profile +use params, only: r8 +use inputs +use spline_mod, only: spline_dealloc +use, intrinsic :: ieee_arithmetic, only: ieee_value,ieee_quiet_nan,ieee_positive_inf +implicit none +integer :: i,unit,ix,icase,mi,mimp +real(r8) :: psi,nD,nT,td,tt,omega,rows(9),f(9),f1(9) +character(512) :: mode,file +call get_command_argument(1,mode) +file='profile.kin' +do icase=1,2 + open(newunit=unit,file=trim(file),status='replace') + write(unit,'(a)') 'psi ni ne ti te OmegaE logLambda nu_i nu_e' + do i=0,24 + psi=i/24._r8 + nD=2.e19_r8*(1+.1_r8*psi) + nT=1.e19_r8*(1+.2_r8*psi) + td=1200._r8*(1+.3_r8*psi) + tt=2100._r8*(1+.4_r8*psi) + omega=0._r8 + if(icase==2) omega=-3500._r8 + rows=[psi,nD,nD+nT,td,900._r8*(1+.25_r8*psi),omega, & + 17.5_r8,700._r8*exp(2._r8*psi),1500._r8*exp(-1.5_r8*psi)] + if(icase==2) rows(2:4:2)=[nT,tt] + if(i==10) then + select case(trim(mode)) + case('nan-rate'); rows(8)=ieee_value(0._r8,ieee_quiet_nan) + case('inf-rate'); rows(9)=ieee_value(0._r8,ieee_positive_inf) + case('nan-log'); rows(7)=ieee_value(0._r8,ieee_quiet_nan) + case('inf-density'); rows(2)=ieee_value(0._r8,ieee_positive_inf) + case('negative-rate'); rows(8)=-1._r8 + case('zero-rate'); rows(9)=0._r8 + end select + end if + if(trim(mode)=='columns') then + write(unit,'(8es25.16e3)') rows(:8) + else + write(unit,'(9es25.16e3)') rows + end if + end do + close(unit) + mi=2; mimp=3 + if(icase==2) then + mi=3; mimp=2 + end if + call read_kin(file,1,1,mi,mimp,1._r8,1._r8,1._r8,1._r8,.true.,'rates-v1') + ix=0 + do i=0,104 + psi=i/104._r8 + call kin_eval_external(psi,ix,f,f1) + call kin_eval(psi,1) + if(any(abs(f-kin%f)>1.e-12_r8*max(abs(f),abs(kin%f),tiny(1._r8)))) & + error stop 'query values disagree' + if(any(abs(f1-kin%f1)>1.e-12_r8*max(abs(f1),abs(kin%f1),tiny(1._r8)))) & + error stop 'query derivatives disagree' + write(*,'(i4,1x,13es25.16e3)') icase,psi,f,f1(6:8) + end do + call spline_dealloc(kin) + call spline_dealloc(kin_collision) + call spline_dealloc(kin_supplied) +end do +end program supplied_profile +''' + nf=os.environ.get('NF_CONFIG','nf-config') + ff=shlex.split(os.environ.get('NETCDF_FFLAGS') or subprocess.check_output([nf,'--fflags'],text=True)) + libs=shlex.split(os.environ.get('NETCDF_FLIBS') or subprocess.check_output([nf,'--flibs'],text=True)) + linker=shlex.split(os.environ.get('GPEC_TEST_LDFLAGS','-Wl,--gc-sections')) + mathlibs=shlex.split(os.environ.get('GPEC_MATH_LIBS','-llapack -lblas')) + files=['equil/io.f','equil/local.f','equil/utils.f','equil/spline.f', + 'pentrc/params.f90','pentrc/utilities.f90'] + with tempfile.TemporaryDirectory(prefix='.pentrc-rates-',dir=ROOT) as tmp: + work=Path(tmp) + (work/'inputs.f90').write_text(inputs) + (work/'driver.f90').write_text(driver) + (work/'version.inc').write_text("character(128), parameter :: version='supplied-rate-test'\n") + for optimization in (['-O0','-fcheck=all'],['-O3','-ffast-math']): + command=[os.environ.get('FC','gfortran'),*optimization,'-std=legacy', + '-ffree-line-length-none','-ffixed-line-length-none', + '-fallow-argument-mismatch','-ffunction-sections','-fdata-sections', + *ff,'-I'+str(work),*[str(ROOT/f) for f in files], + str(work/'inputs.f90'),str(work/'driver.f90'),*linker,*libs,*mathlibs, + '-o',str(work/'check')] + result=subprocess.run(command,cwd=work,text=True,capture_output=True,timeout=90) + self.assertEqual(result.returncode,0,result.stdout+result.stderr) + run=subprocess.run([str(work/'check')],cwd=work,text=True,capture_output=True,timeout=20) + self.assertEqual(run.returncode,0,run.stdout+run.stderr) + rows=0; maxerr=0. + for line in run.stdout.splitlines(): + tokens=line.split() + if len(tokens)!=14: + continue + case=int(tokens[0]); psi=float(tokens[1]); f=list(map(float,tokens[2:11])) + df=list(map(float,tokens[11:14])) + ni=(2.e19*(1+.1*psi) if case==1 else 1.e19*(1+.2*psi)) + ti=(1200*(1+.3*psi) if case==1 else 2100*(1+.4*psi)) + nu_i=700*math.exp(2*psi); nu_e=1500*math.exp(-1.5*psi) + expected=[ni,3.e19+4.e18*psi,ti*1.602e-19,900*(1+.25*psi)*1.602e-19, + 0. if case==1 else -3500.,17.5,nu_i,nu_e,1.] + if expected[4]==0.: + self.assertEqual(f[4],0.,'zero physical rotation changed') + else: + self.assertLess(abs(f[4]/expected[4]-1.),1.e-14) + error=max(abs(a/b-1.) for i,(a,b) in enumerate(zip(f,expected)) if i!=4) + maxerr=max(maxerr,error,abs(df[1]/(2*nu_i)-1.),abs(df[2]/(-1.5*nu_e)-1.)) + self.assertLess(abs(df[0]),1.e-10) + rows+=1 + self.assertEqual(rows,210,run.stdout[-1600:]) + self.assertLess(maxerr,2.e-6) + print('supplied D/T/e profile',optimization,'rows=',rows,'maxerr=',maxerr) + for mode in ('nan-rate','inf-rate','nan-log','inf-density','negative-rate','zero-rate','columns'): + bad=subprocess.run([str(work/'check'),mode],cwd=work,text=True,capture_output=True,timeout=20) + self.assertNotEqual(bad.returncode,0,optimization[0]+': accepted '+mode) + self.assertIn('PENTRC:',bad.stdout+bad.stderr) + + +if __name__=='__main__': unittest.main()