Ejemplo n.º 1
0
def run(args):
    """
    Run the test.
    """
    global nTimeSteps

    # Tolerance to require for agreement with CODE
    TOLERANCE = 2e-2    # 2%
    success = True
    workdir = pathlib.Path(__file__).parent.absolute()

    B, CODEbump = loadCODE('{}/CODE-bumps.mat'.format(workdir))
    B = B[:,0]
    CODEbump = CODEbump[:,0]

    nt     = nTimeSteps
    nB     = B.size
    bumpP  = np.zeros((nB,))
    for i in range(1, nB):
    #for i in [2]:
        print('Checking B = {} T... '.format(B[i]), end="")
        try:
            bumpP[i] = runB(B[i],CODEbump[i])
        except Exception as e:
            print(e)
            bumpP[i] = 0
            return False

        # Compare runaway rates
        Delta = np.abs(bumpP[i] / CODEbump[i] - 1.0)

        print("Delta = {:.3f}%".format(Delta*100))
        if Delta > TOLERANCE:
            dreamtests.print_error("DREAM synchrotron bump location deviates from CODE at B = {} T".format(B[i]))
            dreamtests.print_error("DREAM bump at p = {} mc, CODE bump at p = {} mc".format(bumpP[i], CODEbump[i]))
            success = False

    
    # Save
    if args['save']:
        with h5py.File('{}/DREAM-bumps.h5'.format(workdir), 'w') as f:
            f['B'] = B
            f['bumpP'] = bumpP

    if args['plot']:
        plt.plot(B[1:], bumpP[1:], '*', markersize=10)
        plt.plot(B[1:], CODEbump[1:], 's', markersize=10)

        plt.legend(['DREAM', 'CODE'])
        plt.xlabel('Magnetic field strength (T)')
        plt.ylabel('Bump momentum ($mc$)')

        plt.tight_layout()
        plt.show()

    if success:
        dreamtests.print_ok("All runaway rates match those of CODE.")

    return success
Ejemplo n.º 2
0
def run(args):
    """
    Run the test.
    """
    #testrun()
    #return True


    QUIET = True
    TOLERANCE = 100*sys.float_info.epsilon

    output_const, output_adapt = None, None
    # Save output?
    if args['save']:
        output_const = 'output_ts_adaptive_const.h5'
        output_adapt = 'output_ts_adaptive_adapt.h5'

    # Run with constant time step
    ds_const = genSettings(False)
    if args['save']:
        ds_const.save('settings_ts_adaptive_const.h5')
    do_const = DREAM.runiface(ds_const, output_const, quiet=QUIET)

    ds_adapt = genSettings(True)
    if args['save']:
        ds_adapt.save('settings_ts_adaptive_adapt.h5')
    do_adapt = DREAM.runiface(ds_adapt, output_adapt, quiet=QUIET)

    # Compare results
    err_f = np.abs(do_const.eqsys.f_hot[-1,:] / do_adapt.eqsys.f_hot[-1,:] - 1)
    err_j = np.abs(do_const.eqsys.j_hot[-1,:] / do_adapt.eqsys.j_hot[-1,:] - 1)

    eps_f = np.amax(err_f)
    eps_j = np.amax(err_j)

    success = True
    if eps_f > TOLERANCE:
        dreamtests.print_error("f_hot is too different. eps_f = {:.8e}".format(eps_f))
        success = False
    if eps_j > TOLERANCE:
        dreamtests.print_error("j_hot is too different. eps_j = {:.8e}".format(eps_j))
        success = False

    if success:
        dreamtests.print_ok("Solution from adaptive time stepper agrees exactly with solution from the constant time stepper.")

    return success
def run(args):
    """
    Run the test.
    """
    # Tolerance to require for agreement with CODE
    TOLERANCE = 1e-2
    success = True
    workdir = pathlib.Path(__file__).parent.absolute()

    T, Z, CODEsigma = loadCODE('{}/CODE-conductivities.mat'.format(workdir))

    nZ, nT = T.shape
    sigma = np.zeros((nZ, nT))
    for i in range(0, nZ):
        for j in range(0, nT):
            print('Checking T = {} eV, Z = {:.1f}... '.format(
                T[i, j], Z[i, j]),
                  end="")
            try:
                sigma[i, j] = runTZ(T[i, j], Z[i, j])
            except Exception as e:
                print('\x1B[1;31mFAIL\x1B[0m')
                print(e)
                sigma[i, j] = 0
                #continue
                return False

            # Compare conductivity right away
            Delta = np.abs(sigma[i, j] / CODEsigma[i, j] - 1.0)
            print("Delta = {:.3f}%".format(Delta * 100))
            if Delta > TOLERANCE:
                dreamtests.print_error(
                    "DREAM conductivity deviates from CODE at T = {} eV, Z = {}"
                    .format(T[i, j], Z[i, j]))
                success = False

    # Save
    if args['save']:
        with h5py.File('{}/DREAM-conductivities.h5'.format(workdir), 'w') as f:
            f['T'] = T
            f['Z'] = Z
            f['sigma'] = sigma

    if args['plot']:
        cmap = GeriMap.get()

        # Compare conductivities
        #plt.figure(figsize=(9,6))
        plt.figure(figsize=(5, 3))
        legs = []
        legh = []
        hN = None
        for i in range(0, nT):
            clr = cmap(i / nT)

            h, = plt.semilogy(Z[:, i], CODEsigma[:, i], color=clr, linewidth=2)
            hN, = plt.semilogy(Z[:, i],
                               sigma[:, i],
                               'x',
                               color=clr,
                               markersize=10,
                               markeredgewidth=3)

            if T[0, i] >= 1e3:
                s = r'$T = {:.0f}\,\mathrm{{keV}}$'.format(T[0, i] / 1e3)
            else:
                s = r'$T = {:.0f}\,\mathrm{{eV}}$'.format(T[0, i])

            yfac = 1.2
            plt.text(Z[-2, i] + 4, sigma[-2, i] * yfac, s, color=clr)

            legs.append(s)
            legh.append(h)

        legs.append('$\mathrm{DREAM}$')
        legh.append(hN)

        plt.xlabel(r'$Z$')
        plt.ylabel(r'$\sigma\ \mathrm{(S/m)}$')
        #plt.legend(legh, legs)

        plt.tight_layout()
        plt.show()

    if success:
        dreamtests.print_ok("All conductivities match those of CODE.")

    return success
Ejemplo n.º 4
0
def run(args):
    """
    Run the test.
    """
    global nTimeSteps

    # Tolerance required for agreement with DREAM data.
    # The simulations are slightly underrresolved to speed up the test,
    # so we allow a 5% margin.
    # Resolution bottlenecks appear to be Nxi, Np and pOverPc.
    TOLERANCE = 5e-2
    success = True

    # Path to reference data file
    workdir = pathlib.Path(__file__).parent.absolute()
    filename = '{}/DREAM-avalanche-data.h5'.format(workdir)

    # Define electric fields and densities to scan over
    EOverEcs = np.array([5, 30, 100])
    nDs = np.array([1e19, 1e21])
    nZs = np.array([1e18, 1e20])
    nE = EOverEcs.size
    nnD = nDs.size
    nnZ = nZs.size

    nt = nTimeSteps

    # Unless run with --save, load reference data to compare with
    if args['save']:
        GammaRef = np.zeros((nE, nnD, nnD, nnZ, nnZ))
    else:
        with h5py.File(filename, 'r') as f:
            GammaRef = f['GammaNum'][:]
            nDsRef = f['nD'][:]
            nZsRef = f['nZ'][:]
            EOverEcsRef = f['EOverEcTot'][:]

        # The plasma parameters must equal the saved reference data
        dataIsConsistent = np.array_equal(nDs, nDsRef) and np.array_equal(
            nZs, nZsRef) and np.array_equal(EOverEcs, EOverEcsRef)
        if not dataIsConsistent:
            dreamtests.print_error(
                "Reference plasma parameters does not equal test parameters.")

    #                         E,  D0,  D1,  Ar,  Ne,  t
    GammaNum = np.zeros((nE, nnD, nnD, nnZ, nnZ))
    GammaNumFull = np.zeros((nE, nnD, nnD, nnZ, nnZ, nt))
    GammaAn1 = np.zeros((nE, nnD, nnD, nnZ, nnZ))
    GammaAn2 = np.zeros((nE, nnD, nnD, nnZ, nnZ))
    for i in range(0, nE):
        for j in range(0, nnD):
            for k in range(0, nnD):
                for m in range(0, nnZ):
                    for n in range(0, nnZ):
                        EOverEc = EOverEcs[i]
                        nD0 = nDs[j]
                        nD1 = nDs[k]
                        nAr = nZs[m]
                        nNe = nZs[n]
                        print(
                            'Checking E/Ectot = {}, nD0 = {} m-3, nD1 = {} m-3, nAr = {} m-3, nNe = {} m-3. '
                            .format(EOverEc, nD0, nD1, nAr, nNe))
                        try:
                            GammaNum[i, j, k, m, n], GammaNumFull[
                                i, j, k, m,
                                n:], GammaAn1[i, j, k, m, n], GammaAn2[
                                    i, j, k, m, n] = runNE(args,
                                                           EOverEcTot=EOverEc,
                                                           nD0=nD0,
                                                           nD1=nD1,
                                                           nAr=nAr,
                                                           nNe=nNe)
                        except Exception as e:
                            print(e)
                            traceback.print_exc()
                            GammaNum[i, j, k, m, n], GammaNumFull[
                                i, j, k, m,
                                n:], GammaAn1[i, j, k, m,
                                              n], GammaAn2[i, j, k, m,
                                                           n] = 0, 0, 0, 0
                            return False
                        if args['verbose']:
                            print(
                                'GammaNum = {:.3f}, GammaAva = {:.3f}, GammaAvaAlt = {:.3f}'
                                .format(GammaNum[i, j, k, m,
                                                 n], GammaAn1[i, j, k, m, n],
                                        GammaAn2[i, j, k, m, n]))

                        # Compare growth rates
                        Delta = np.abs(GammaNum[i, j, k, m, n] /
                                       GammaAn1[i, j, k, m, n] - 1.0)
                        DeltaAlt = np.abs(GammaNum[i, j, k, m, n] /
                                          GammaAn2[i, j, k, m, n] - 1.0)

                        if args['save']:
                            if args['verbose']:
                                print("Delta = {:.2f}%, DeltaAlt = {:.2f}%".
                                      format(Delta * 100, DeltaAlt * 100))
                        else:
                            DeltaRef = np.abs(GammaNum[i, j, k, m, n] /
                                              GammaRef[i, j, k, m, n] - 1.0)
                            if DeltaRef > TOLERANCE:
                                dreamtests.print_error(
                                    "DREAM kinetic avalanche growth rate deviates from DREAM reference data"
                                )
                                success = False
                            if args['verbose']:
                                print(
                                    "DeltaRef = {:.2f}%, Delta = {:.2f}%, DeltaAlt = {:.2f}%"
                                    .format(DeltaRef * 100, Delta * 100,
                                            DeltaAlt * 100))
                            else:
                                print("DeltaRef = {:.2f}%".format(DeltaRef *
                                                                  100))

    # Plot or save results if requested
    if args['plot']:
        plotResults(GammaNum, GammaAn1, GammaAn2, EOverEcs, nDs, nZs, nE, nnD,
                    nnZ)
    if args['save']:
        with h5py.File(filename, 'w') as f:
            f['GammaNum'] = GammaNum
            f['EOverEcTot'] = EOverEcs
            f['nD'] = nDs
            f['nZ'] = nZs
            dreamtests.print_ok(
                "Test data saved to file as the future reference.")
    else:
        if success:
            dreamtests.print_ok(
                "DREAM growth rate matches DREAM reference data.")

    return success
Ejemplo n.º 5
0
def run(args):
    """
    Run the test.
    """
    global nTimeSteps

    # Tolerance to require for agreement with CODE
    TOLERANCE = 5e-2  # 5%
    success = True
    workdir = pathlib.Path(__file__).parent.absolute()

    T, E, CODErr = loadCODE('{}/CODE-rates.mat'.format(workdir))

    nElong = 30

    nt = nTimeSteps
    nE, nT = T.shape
    rr = np.zeros((nE, nT))
    rrCH = np.zeros((nE, nT))
    rrFull = np.zeros((nE, nT, nt))
    rrCH_E = np.zeros((nE, nT, nElong))
    rrCH = np.zeros((nE, nT, nElong))
    for i in range(0, nE):
        for j in range(0, nT):
            print('Checking T = {} eV, E = {:.4f} V/m... '.format(
                T[i, j], E[i, j]),
                  end="")
            try:
                rr[i, j], rrFull[i, j, :], rrCH[i, j] = runTE(T[i, j], E[i, j])
            except Exception as e:
                print(e)
                rr[i, j], rrFull[i, j, :] = 0, 0
                return False

            # Compare runaway rates
            Delta = 0
            if CODErr[i, j] < 1:
                # Some of the runaway rates are so small that they're unreliable,
                # so just compare to zero
                Delta = np.abs(rr[i, j])
            else:
                Delta = np.abs(rr[i, j] / CODErr[i, j] - 1.0)

            print("Delta = {:.3f}%".format(Delta * 100))
            if Delta > TOLERANCE:
                dreamtests.print_error(
                    "DREAM runaway rate deviates from CODE at T = {} eV, E = {}"
                    .format(T[i, j], E[i, j]))
                success = False

            # Calculate Connor-Hastie rate
            rrCH_E[i, j, :] = np.linspace(E[0, j], E[-1, j], nElong)
            rrCH[i, j, :] = getConnorHastieRate(T[0, j], rrCH_E[i, j])

    # Save
    if args['save']:
        with h5py.File('{}/DREAM-rates.h5'.format(workdir), 'w') as f:
            f['T'] = T
            f['E'] = E
            f['rr'] = rr

    if args['plot']:
        cmap = GeriMap.get()

        # Compare runaway rates
        plt.figure(figsize=(5, 3.33))
        legs = []
        legh = []
        hN = None
        for i in range(0, nT):
            clr = cmap(i / nT)

            plt.loglog(rrCH_E[0, i, :], rrCH[0, i, :], color=clr, linewidth=2)

            h, = plt.loglog(E[:, i],
                            CODErr[:, i],
                            'o',
                            color=clr,
                            fillstyle='none',
                            markersize=14,
                            markeredgewidth=2)
            hN, = plt.loglog(E[:, i],
                             rr[:, i],
                             'x',
                             color=clr,
                             markersize=10,
                             markeredgewidth=3)

            s = r'$T = {:.0f}\,\mathrm{{eV}}$'.format(T[0, i])

            #legs.append(s)
            #legh.append(h)

        #legs.append('$\mathrm{DREAM}$')
        #legh.append(hN)

        plt.xlabel(r'Electric field $E_\parallel$ (V/m)')
        plt.ylabel(r'Runaway rate $\gamma\ \mathrm{(s)}^{-1}$')
        #plt.legend(legh, legs)

        plt.ylim([1e-28, 1e28])

        plt.tight_layout()
        plt.show()

    if success:
        dreamtests.print_ok("All runaway rates match those of CODE.")

    return success
Ejemplo n.º 6
0
def run(args):
    """
    Run the test.
    """
    global NR

    # Tolerance to require for agreement with CODE
    TOLERANCE = 1e-2
    success = True
    workdir = pathlib.Path(__file__).parent.absolute()

    T = np.array([1e1,1e2,1e3,1e4])
    nT = T.size
    jKinetic = np.zeros((nT, NR))
    jFluid   = np.zeros((nT, NR))
    for i in range(0, nT):
        print('Checking T = {} eV... '.format(T[i]), end="")
        try:
            jKinetic[i,:], jFluid[i,:], eps = runT(T[i])
        except Exception as e:
            print('\x1B[1;31mFAIL\x1B[0m')
            print(e)
            #continue
            return False

        # Compare conductivity right away
        Delta = np.amax(np.abs(jKinetic[i,:] / jFluid[i,:] - 1.0))
        print("Delta = {:.3f}%".format(Delta*100))
        if Delta > TOLERANCE:
            dreamtests.print_error("DREAM conductivity deviates from CODE at T = {} eV".format(T[i]))
            success = False
    
    # Save
    if args['save']:
        with h5py.File('{}/DREAM-conductivities-trapping.h5'.format(workdir), 'w') as f:
            f['T'] = T
            f['jFluid']   = jFluid
            f['jKinetic'] = jKinetic

    if args['plot']:
        cmap = GeriMap.get()

        # Compare conductivities
        #plt.figure(figsize=(9,6))
        plt.figure(figsize=(5,3))
        legs = []
        legh = []
        hN = None
        for i in range(0, nT):
            clr = cmap(i/nT)

            h,  = plt.semilogy(eps, jKinetic[:,i], color=clr, linewidth=2)
            hN, = plt.semilogy(eps, jFluid[:,i], 'x', color=clr, markersize=10, markeredgewidth=3)

            if T[i] >= 1e3:
                s = r'$T = {:.0f}\,\mathrm{{keV}}$'.format(T[0,i]/1e3)
            else:
                s = r'$T = {:.0f}\,\mathrm{{eV}}$'.format(T[0,i])

            yfac = .6
            plt.text(0.5, jKinetic[0,i]*yfac, s, color=clr)

            legs.append(s)
            legh.append(h)

        legs.append('$\mathrm{DREAM}$')
        legh.append(hN)

        plt.xlabel(r'$Z$')
        plt.ylabel(r'$\sigma\ \mathrm{(S/m)}$')
        #plt.legend(legh, legs)

        plt.tight_layout()
        plt.show()

    if success:
        dreamtests.print_ok("All conductivities match those of CODE.")

    return success