コード例 #1
0
        public Vector <double>[] bvpsolver_zzz(Func <double, Vector <double>, Vector <double> > system,
                                               double ya, double yb,
                                               double xa, double xb,
                                               int N)
        {
            //先求解方程得到初始斜率的估计值,再进行打靶法迭代。--zzz
            Vector <double>[] res;
            Vector <double>   y0;

            double s_guess, s_guess_pre;
            double fais, fais_pre;
            double dfai, ds;
            int    count = 0;

            //计算20组s_guess和fais,然后样条插值得到连续函数,再通过解方程,得到使fais=0的初始s_guess
            int M = 50;

            double[] sLst = Vector <double> .Build.Dense(M, i => yb / M *i).ToArray();

            double[] faisLst = new double[M];
            count = 0;
            while (count < M)
            {
                y0 = Vector <double> .Build.DenseOfArray(new[] { ya, sLst[count] });

                // observer_pr ob_pr = this->write_targetFunc_end;
                res            = RungeKutta.FourthOrder(y0, xa, xb, N, system);
                faisLst[count] = res[N - 1][0] - yb;
                count++;
            }
            //样条插值得到连续函数
            var cubicSpl = CubicSpline.InterpolateNatural(sLst, faisLst);

            /*如果初始值离解太远,牛顿法会不收敛。故采用Mathnet包中的RobustNewtonRaphson
             * double s_cur = 0, s_next;
             * count = 0;
             * while (count < 1000)
             * {
             *  fais = cubicSpl.Interpolate(s_cur);
             *  dfaids = cubicSpl.Differentiate(s_cur);
             *  if (fais < 1e-5 && fais > -1e-5)
             *  {
             *      break;
             *  }
             *
             *  s_next = s_cur - fais / dfaids;
             *  s_cur = s_next;
             *  count += 1;
             * }*/

            //解方程fais=0,得到初始斜率s_guess。该法先尝试牛顿法,如失败会采用二分法(bisection)。
            s_guess = RobustNewtonRaphson.FindRoot(cubicSpl.Interpolate, cubicSpl.Differentiate, 0, yb, 1e-5);

            //利用解得的s_guess,构造s_guess_pre,目的是求导数dfai/ds。
            if (s_guess == 0)
            {
                s_guess_pre = 1e-2;
            }
            else
            {
                s_guess_pre = s_guess * 0.99;
            }
            //求s_guess_pre对应的fais_pre,目的是求导数dfai/ds。
            y0 = Vector <double> .Build.DenseOfArray(new[] { ya, s_guess_pre });

            res      = RungeKutta.FourthOrder(y0, xa, xb, N, system);
            fais_pre = res[N - 1][0] - yb;

            count = 0;
            while (count < 50)
            {
                y0 = Vector <double> .Build.DenseOfArray(new[] { ya, s_guess });

                res  = RungeKutta.FourthOrder(y0, xa, xb, N, system);
                fais = res[N - 1][0] - yb;

                dfai = fais - fais_pre;
                ds   = s_guess - s_guess_pre;
                if (fais < 1e-5 && fais > -1e-5)
                {
                    break;
                }

                fais_pre    = fais;
                s_guess_pre = s_guess;
                s_guess     = s_guess - fais * ds / dfai;
                count++;
            }

            return(res);
        }
コード例 #2
0
    public double[,] rabbit_fox_horizontal_diff_ts(float r, float r_ts, float f, float f_ts, int yr, string r_integ_method, string f_integ_method)
    {
        int ts_factor = 10; //time step factor, to define numer of loops in unit of time, e.g. if ts=0.1 then we will have 10 loops in each unit of time

        float ts;
        if (r_ts > f_ts)
            ts = f_ts;
        else if (r_ts > f_ts)
            ts = r_ts;
        else
            ts = r_ts;

        if (ts >= 0.1)
        {
            ts_factor = 10;
        }
        else if (ts >= 0.009) //>=0.01
        {
            ts_factor = 100;
        }
        else if (ts >= 0.0009) //>=0.001
            ts_factor = 1000;

        //ts_factor = 1000;

        Rabbit rab = new Rabbit();
        Fox fx_m = new Fox();

        RungeKutta rk = new RungeKutta();

        //the system will loop for each time step
        //int lp = Convert.ToInt32(Math.Truncate(yr / 0.1)); //total number of loop due to the defined year
        int lp = yr * ts_factor;

        lp = lp + 1;
           // r_result = new double[lp]; //array for rab
        //f_result = new double[lp]; //array for fox

        double[,] result = new double[lp, 2];

        double[] t = new double[3];
        t[1] = Convert.ToDouble(r_ts.ToString("#.####")); //time step of rabbit
        t[2] = Convert.ToDouble(f_ts.ToString("#.####")); //time step of fox

        int temp_r_ts = Convert.ToInt16(r_ts * ts_factor);
        int temp_f_ts = Convert.ToInt16(f_ts * ts_factor);

        float rx = r;
        float ry = f;
        float fx = r;
        float fy = f;

        for (int i = 1; i < lp; i++)
        {

            int m = i % temp_r_ts; //m for maintaining result of % operation
            if (m == 0 && i > 0) //check if the current time step is valid to run rabit model
            {

                if (r_integ_method == "Runge-Kutta") // Runge-Kutta integration of rabbit model
                {
                    rx = rk.calc_Rabbit_Runge_Kutta(rx, ry, r_ts);

                }
                else
                    rx = rx + rab.rabbit_model(rx, ry) * r_ts;
                //rx = rx + rabbit_with_diff_func(rx, ry) * r_ts;

                r = rx;
            }

            int n = i % temp_f_ts;
            if (n == 0 && i > 0) //check if the current time step is valid to run fox model
            {
                if (m == 0)
                    fx = r;

                if (f_integ_method == "Runge-Kutta") // for Runge-Kutta integration of fox model
                {
                    fy = rk.calc_Fox_Runge_Kutta(fy, fx, f_ts);
                }
                else
                    fy = fy + fx_m.fox_model(fy, fx) * f_ts;
                //fy = fy + fox_with_diff_func(fy, fx) * f_ts;

                f = fy;
                fx = r;
            }

            if (m == 0) //if the time step meets ts of rabbit then copy value of f
                ry = f;

            //r_result[i] = r; // Convert.ToDouble(r.ToString("#.##"));
            result[i,0] = r;

            if (f >= 0)
                //f_result[i] = f;
                result[i, 1] = f;
            else //if fox pop <0 set it to 0
            {
                f = 0;
                //f_result[i] = 0;
                result[i, 1] = 0;
            }

            if (result[i, 0] < 0) // (r_result[i] < 0)
            {
                //r_result[i] = 0;//if rab pop<0 then set the pop value to 0 and quit
                //f_result[i] = 0;
                result[i, 0] = 0;//if rab pop<0 then set the pop value to 0 and quit
                result[i, 1] = 0;
                break;
            }

        }

        return result;
    }
コード例 #3
0
ファイル: ReInitialization.cs プロジェクト: xyuan/BoSSS
        /// <summary>
        /// Obtaining the time integrated spatial discretization of the reinitialization equation in a narrow band around the zero level set, based on a Godunov's numerical Hamiltonian calculation
        /// </summary>
        /// <param name="LS"> The level set function </param>
        /// <param name="Restriction"> The narrow band around the zero level set </param>
        /// <param name="NumberOfTimesteps">
        /// maximum number of pseudo-timesteps
        /// </param>
        /// <param name="thickness">
        /// The smoothing width of the signum function.
        /// This is the main stabilization parameter for re-initialization.
        /// It should be set to approximately 3 cells.
        /// </param>
        /// <param name="TimestepSize">
        /// size of the pseudo-timestep
        /// </param>
        public void ReInitialize(LevelSet LS, SubGrid Restriction, double thickness, double TimestepSize, int NumberOfTimesteps)
        {
            using (var tr = new FuncTrace()) {
                // log parameters:
                tr.Info("thickness: " + thickness.ToString(NumberFormatInfo.InvariantInfo));
                tr.Info("TimestepSize: " + TimestepSize.ToString(NumberFormatInfo.InvariantInfo));
                tr.Info("NumberOfTimesteps: " + NumberOfTimesteps);

                ExplicitEuler TimeIntegrator;

                SpatialOperator SO;
                Func <int[], int[], int[], int> QuadratureOrder = QuadOrderFunc.NonLinear(3);
                if (m_ctx.SpatialDimension == 2)
                {
                    SO = new SpatialOperator(1, 5, 1, QuadratureOrder, new string[] { "LS", "LSCGV", "LSDG[0]", "LSUG[0]", "LSDG[1]", "LSUG[1]", "Result" });
                    SO.EquationComponents["Result"].Add(new GodunovHamiltonian(m_ctx, thickness));
                    SO.Commit();
                    TimeIntegrator = new RungeKutta(m_Scheme, SO, new CoordinateMapping(LS), new CoordinateMapping(LSCGV, LSDG[0], LSUG[0], LSDG[1], LSUG[1]), sgrd: Restriction);
                }
                else
                {
                    SO = new SpatialOperator(1, 7, 1, QuadratureOrder, new string[] { "LS", "LSCGV", "LSDG[0]", "LSUG[0]", "LSDG[1]", "LSUG[1]", "LSDG[2]", "LSUG[2]", "Result" });
                    SO.EquationComponents["Result"].Add(new GodunovHamiltonian(m_ctx, thickness));
                    SO.Commit();
                    TimeIntegrator = new RungeKutta(m_Scheme, SO, new CoordinateMapping(LS), new CoordinateMapping(LSCGV, LSDG[0], LSUG[0], LSDG[1], LSUG[1], LSDG[2], LSUG[2]), sgrd: Restriction);
                }



                // Calculating the gradients in each sub-stage of a Runge-Kutta integration procedure
                ExplicitEuler.ChangeRateCallback EvalGradients = delegate(double t1, double t2) {
                    LSUG.Clear();
                    CalculateLevelSetGradient(LS, LSUG, "Upwind", Restriction);

                    LSDG.Clear();
                    CalculateLevelSetGradient(LS, LSDG, "Downwind", Restriction);

                    LSCG.Clear();
                    CalculateLevelSetGradient(LS, LSCG, "Central", Restriction);

                    LSCGV.Clear();
                    var VolMask = (Restriction != null) ? Restriction.VolumeMask : null;
                    LSCGV.ProjectAbs(1.0, VolMask, LSCG.ToArray());
                };
                TimeIntegrator.OnBeforeComputeChangeRate += EvalGradients;


                {
                    EvalGradients(0, 0);
                    var GodunovResi = new SinglePhaseField(LS.Basis, "Residual");
                    SO.Evaluate(1.0, 0.0, LS.Mapping, TimeIntegrator.ParameterMapping.Fields, GodunovResi.Mapping, Restriction);

                    //Tecplot.Tecplot.PlotFields(ArrayTools.Cat<DGField>( LSUG, LSDG, LS, GodunovResi), "Residual", 0, 3);
                }



                // pseudo-timestepping
                // ===================
                double   factor     = 1.0;
                double   time       = 0;
                LevelSet prevLevSet = new LevelSet(LS.Basis, "prevLevSet");

                CellMask RestrictionMask = (Restriction == null) ? null : Restriction.VolumeMask;

                for (int i = 0; (i < NumberOfTimesteps); i++)
                {
                    tr.Info("Level set reinitialization pseudo-timestepping, timestep " + i);

                    // backup old Levelset
                    // -------------------
                    prevLevSet.Clear();
                    prevLevSet.Acc(1.0, LS, RestrictionMask);

                    // time integration
                    // ----------------
                    double dt = TimestepSize * factor;
                    tr.Info("dt = " + dt.ToString(NumberFormatInfo.InvariantInfo) + " (factor = " + factor.ToString(NumberFormatInfo.InvariantInfo) + ")");
                    TimeIntegrator.Perform(dt);
                    time += dt;

                    // change norm
                    // ------

                    prevLevSet.Acc(-1.0, LS, RestrictionMask);
                    double ChangeNorm = prevLevSet.L2Norm(RestrictionMask);
                    Console.WriteLine("Reinit: PseudoTime: {0}  - Changenorm: {1}", i, ChangeNorm);

                    //Tecplot.Tecplot.PlotFields(new SinglePhaseField[] { LS }, m_ctx, "Reinit-" + i, "Reinit-" + i, i, 3);
                }

                //*/
            }
        }
コード例 #4
0
    private static void Main()
    //****************************************************************************80
    //
    //  Purpose:
    //
    //    MAIN is the main program for LORENZ_ODE.
    //
    //  Discussion:
    //
    //    Thanks to Ben Whitney for pointing out an error in specifying a loop,
    //    24 May 2016.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    24 May 2016
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        const string  command_filename = "lorenz_ode_commands.txt";
        List <string> command_unit     = new();
        const string  data_filename    = "lorenz_ode_data.txt";
        List <string> data_unit        = new();
        int           j;
        const int     m = 3;
        const int     n = 200000;

        Console.WriteLine("");
        Console.WriteLine("LORENZ_ODE");
        Console.WriteLine("  Compute solutions of the Lorenz system.");
        Console.WriteLine("  Write data to a file for use by gnuplot.");
        //
        //  Data
        //
        double t_final = 40.0;
        double dt      = t_final / n;

        //
        //  Store the initial conditions in entry 0.
        //
        double[] t = typeMethods.r8vec_linspace_new(n + 1, 0.0, t_final);
        double[] x = new double[m * (n + 1)];
        x[0 + 0 * m] = 8.0;
        x[0 + 1 * m] = 1.0;
        x[0 + 2 * m] = 1.0;
        //
        //  Compute the approximate solution at equally spaced times.
        //
        for (j = 0; j < n; j++)
        {
            double[] xnew = RungeKutta.rk4vec(t[j], m, x, dt, Lorenz.lorenz_rhs, index: +j * m);
            int      i;
            for (i = 0; i < m; i++)
            {
                x[i + (j + 1) * m] = xnew[i];
            }
        }

        //
        //  Create the plot data file.
        //
        for (j = 0; j <= n; j += 50)
        {
            data_unit.Add("  " + t[j].ToString(CultureInfo.InvariantCulture).PadLeft(14)
                          + "  " + x[0 + j * m].ToString(CultureInfo.InvariantCulture).PadLeft(14)
                          + "  " + x[1 + j * m].ToString(CultureInfo.InvariantCulture).PadLeft(14)
                          + "  " + x[2 + j * m].ToString(CultureInfo.InvariantCulture).PadLeft(14) + "");
        }

        File.WriteAllLines(data_filename, data_unit);

        Console.WriteLine("  Created data file \"" + data_filename + "\".");

        /*
         * Create the plot command file.
         */
        command_unit.Add("# " + command_filename + "");
        command_unit.Add("#");
        command_unit.Add("# Usage:");
        command_unit.Add("#  gnuplot < " + command_filename + "");
        command_unit.Add("#");
        command_unit.Add("set term png");
        command_unit.Add("set output 'xyz_time.png'");
        command_unit.Add("set xlabel '<--- T --->'");
        command_unit.Add("set ylabel '<--- X(T), Y(T), Z(T) --->'");
        command_unit.Add("set title 'X, Y and Z versus Time'");
        command_unit.Add("set grid");
        command_unit.Add("set style data lines");
        command_unit.Add("plot '" + data_filename
                         + "' using 1:2 lw 3 linecolor rgb 'blue',"
                         + "'' using 1:3 lw 3 linecolor rgb 'red',"
                         + "'' using 1:4 lw 3 linecolor rgb 'green'");
        command_unit.Add("set output 'xyz_3d.png'");
        command_unit.Add("set xlabel '<--- X(T) --->'");
        command_unit.Add("set ylabel '<--- Y(T) --->'");
        command_unit.Add("set zlabel '<--- Z(T) --->'");
        command_unit.Add("set title '(X(T),Y(T),Z(T)) trajectory'");
        command_unit.Add("set grid");
        command_unit.Add("set style data lines");
        command_unit.Add("splot '" + data_filename
                         + "' using 2:3:4 lw 1 linecolor rgb 'blue'");
        command_unit.Add("quit");

        File.WriteAllLines(command_filename, command_unit);

        Console.WriteLine("  Created command file '" + command_filename + "'");

        Console.WriteLine("");
        Console.WriteLine("LORENZ_ODE:");
        Console.WriteLine("  Normal end of execution.");
        Console.WriteLine("");
    }
コード例 #5
0
 /// <summary>
 /// Método Runge Kutta de Segunda ordem para equações diferenciais
 /// </summary>
 /// <param name="y0">Valor Inicial</param>
 /// <param name="start">Tempo Inicial</param>
 /// <param name="end">Tempo Final</param>
 /// <param name="dydx">Equação diferencial a ser calculada</param>
 /// <returns></returns>
 public double RungeKutta2(double y0, double start, double end, Func <double, double, double> dydx)
 {
     return(RungeKutta.SecondOrder(y0, start, end, 10, dydx)[9]);
 }
コード例 #6
0
 /// <summary>
 /// Método Runge Kutta de Quarta ordem para equações diferenciais
 /// </summary>
 /// <param name="y0">Valor Inicial</param>
 /// <param name="start">Tempo Inicial</param>
 /// <param name="end">Tempo Final</param>
 /// <param name="dydx">Equação diferencial a ser calculada</param>
 /// <returns></returns>
 public double RungeKutta4(double y0, double start, double end, Func <double, double, double> dydx)
 {
     return(RungeKutta.FourthOrder(y0, start, end, 10, dydx)[9]);
 }
コード例 #7
0
ファイル: HorizontalSameTs.cs プロジェクト: getachewf/mdmif
    public double[,] rabbit_fox_horizontal_same_ts(float r, float f, int yr, float ts, string r_integ_method, string f_integ_method)
    {
        int ts_factor = 10; //time step factor, to define numer of loops in unit of time, e.g. if ts=0.1 then we will have 10 loops in each unit of time
        if (ts >= 0.1)
        {
            ts_factor = 10;
        }
        else if (ts >= 0.009) //>=0.01
        {
            ts_factor = 100;
        }
        else if (ts >= 0.0009) //>=0.001
            ts_factor = 1000;

        //ts_factor = 1000;

        Rabbit rab = new Rabbit();
        Fox fx = new Fox();

        RungeKutta rk = new RungeKutta();

        //the system will loop according to the defined time step
        //int lp = Convert.ToInt16(Math.Truncate(yr / ts)); //total number of loop due to the defined time step
        //int lp = Convert.ToInt32(Math.Truncate(yr / 0.1)); //10 timestep in 1 year
        int lp = yr * ts_factor;

        lp = lp + 2;
        double[,] result = new double[lp, 2];

        float fr = r; //rabbit population for fox model

        for (int i = 1; i < lp; i++)
        {

            //if (i % (Convert.ToInt16(Math.Truncate(ts * 10))) == 0)
            if (i % (Convert.ToInt16(ts * ts_factor)) == 0)
            {
                //run rabbit model
                if (r_integ_method == "Runge-Kutta") // for Runge-Kutta integration of rabbit
                {
                    r = rk.calc_Rabbit_Runge_Kutta(r, f, ts);
                }
                else
                  //for euler integration
                    r = r + rab.rabbit_model(r, f) * ts;
                // r = r + rabbit_with_diff_func(r, f) * ts; //rabbit with px/(q+x) function than bx

                //run fox model
                if (f_integ_method == "Runge-Kutta") // for Runge-Kutta integration of fox model
                {
                    f = rk.calc_Fox_Runge_Kutta(f, fr, ts);
                }
                else
                    f = f + fx.fox_model(f, fr) * ts;
                //f = f + fox_with_diff_func(f, fr) * ts; //fox with px/(q+x) function than bx

                fr = r; //update current rabbit population for fox model

                if (r < 0)
                    result[i, 0] = 0;
                else
                    result[i, 0] = r;   //Convert.ToDouble(r.ToString("#.##"));

                if (f < 0)
                    result[i, 1] = 0;
                else
                    result[i, 1] = f;   // Convert.ToDouble(f.ToString("#.##"));

                if (result[i, 0] < 0) //(result[i, 0] < 1)
                {
                    result[i, 0] = 0; //if pop<0 then set the pop value to 0
                    result[i, 1] = 0;
                    break;
                }
            }
            else
            {
                if (r < 0) //(result[i, 0] < 1)
                {
                    result[i, 0] = 0; //if pop<0 then set the pop value to 0
                    result[i, 1] = 0;
                    break;
                }
                else
                {
                    result[i, 0] = r;
                    result[i, 1] = f;
                }

            }
        }

        return result;
    }
コード例 #8
0
        /// <summary>
        /// Creates the appropriate time-stepper for a given
        /// <paramref name="timeStepperType"/>
        /// </summary>
        /// <param name="timeStepperType">
        /// The type of the time-stepper (e.g., Runge-Kutta) to be created
        /// </param>
        /// <param name="control">
        /// Configuration options
        /// </param>
        /// <param name="equationSystem">
        /// The equation system to be solved
        /// </param>
        /// <param name="fieldSet">
        /// Fields affected by the time-stepper
        /// </param>
        /// <param name="parameterMap">
        /// Fields serving as parameter for the time-stepper.
        /// </param>
        /// <param name="speciesMap">
        /// Mapping of different species inside the domain
        /// </param>
        /// <param name="program"></param>
        /// <returns>
        /// Depending on <paramref name="timeStepperType"/>, an appropriate
        /// implementation of <see cref="ITimeStepper"/>.
        /// </returns>
        /// <remarks>
        /// Currently limiting is not supported for Adams-Bashforth methods
        /// </remarks>
        public static ITimeStepper Instantiate <T>(
            this ExplicitSchemes timeStepperType,
            CNSControl control,
            OperatorFactory equationSystem,
            CNSFieldSet fieldSet,
            CoordinateMapping parameterMap,
            ISpeciesMap speciesMap,
            IProgram <T> program)
            where T : CNSControl, new()
        {
            CoordinateMapping variableMap = new CoordinateMapping(fieldSet.ConservativeVariables);

            IBMControl         ibmControl = control as IBMControl;
            IBMOperatorFactory ibmFactory = equationSystem as IBMOperatorFactory;

            if (control.DomainType != DomainTypes.Standard &&
                (ibmFactory == null || ibmControl == null))
            {
                throw new Exception();
            }

            ITimeStepper timeStepper;

            switch (timeStepperType)
            {
            case ExplicitSchemes.RungeKutta when control.DomainType == DomainTypes.Standard:
                timeStepper = new RungeKutta(
                    RungeKutta.GetDefaultScheme(control.ExplicitOrder),
                    equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                    variableMap,
                    parameterMap,
                    equationSystem.GetJoinedOperator().CFLConstraints);
                break;

            case ExplicitSchemes.RungeKutta:
                timeStepper = ibmControl.TimesteppingStrategy.CreateRungeKuttaTimeStepper(
                    ibmControl,
                    equationSystem,
                    fieldSet,
                    parameterMap,
                    speciesMap,
                    equationSystem.GetJoinedOperator().CFLConstraints);
                break;

            case ExplicitSchemes.AdamsBashforth when control.DomainType == DomainTypes.Standard:
                timeStepper = new AdamsBashforth(
                    equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                    variableMap,
                    parameterMap,
                    control.ExplicitOrder,
                    equationSystem.GetJoinedOperator().CFLConstraints);
                break;

            case ExplicitSchemes.AdamsBashforth:
                timeStepper = new IBMAdamsBashforth(
                    ibmFactory.GetJoinedOperator().ToSpatialOperator(fieldSet),
                    ibmFactory.GetImmersedBoundaryOperator().ToSpatialOperator(fieldSet),
                    variableMap,
                    parameterMap,
                    speciesMap,
                    ibmControl,
                    equationSystem.GetJoinedOperator().CFLConstraints);
                break;

            case ExplicitSchemes.LTS when control.DomainType == DomainTypes.Standard:
                timeStepper = new AdamsBashforthLTS(
                    equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                    variableMap,
                    parameterMap,
                    control.ExplicitOrder,
                    control.NumberOfSubGrids,
                    equationSystem.GetJoinedOperator().CFLConstraints,
                    reclusteringInterval: control.ReclusteringInterval,
                    fluxCorrection: control.FluxCorrection,
                    saveToDBCallback: program.SaveToDatabase,
                    maxNumOfSubSteps: control.maxNumOfSubSteps);
                break;

            case ExplicitSchemes.LTS:
                timeStepper = new IBMAdamsBashforthLTS(
                    equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                    ibmFactory.GetImmersedBoundaryOperator().ToSpatialOperator(fieldSet),
                    variableMap,
                    parameterMap,
                    speciesMap,
                    ibmControl,
                    equationSystem.GetJoinedOperator().CFLConstraints,
                    reclusteringInterval: control.ReclusteringInterval,
                    fluxCorrection: control.FluxCorrection,
                    maxNumOfSubSteps: control.maxNumOfSubSteps);
                break;

            case ExplicitSchemes.Rock4 when control.DomainType == DomainTypes.Standard:
                timeStepper = new ROCK4(equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet), new CoordinateVector(variableMap), null);
                break;

            case ExplicitSchemes.SSP54 when control.DomainType == DomainTypes.Standard:
                timeStepper = new RungeKutta(
                    RungeKuttaScheme.SSP54,
                    equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                    variableMap,
                    parameterMap,
                    equationSystem.GetJoinedOperator().CFLConstraints);
                break;

            case ExplicitSchemes.RKC84 when control.DomainType == DomainTypes.Standard:
                timeStepper = new RungeKutta(
                    RungeKuttaScheme.RKC84,
                    equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                    variableMap,
                    parameterMap,
                    equationSystem.GetJoinedOperator().CFLConstraints);
                break;

            case ExplicitSchemes.None:
                throw new System.ArgumentException("Cannot instantiate empty scheme");

            default:
                throw new NotImplementedException(String.Format(
                                                      "Explicit time stepper type '{0}' not implemented for domain type '{1}'",
                                                      timeStepperType,
                                                      control.DomainType));
            }

            // Make sure shock sensor is updated before every flux evaluation
            if (control.ShockSensor != null)
            {
                ExplicitEuler explicitEulerBasedTimestepper = timeStepper as ExplicitEuler;
                if (explicitEulerBasedTimestepper == null)
                {
                    throw new Exception(String.Format(
                                            "Shock-capturing currently not implemented for time-steppers of type '{0}'",
                                            timeStepperType));
                }

                explicitEulerBasedTimestepper.OnBeforeComputeChangeRate += delegate(double absTime, double relTime) {
                    // Note: Only shock sensor is updated, _NOT_ the corresponding variable
                    program.Control.ShockSensor.UpdateSensorValues(
                        program.WorkingSet,
                        program.SpeciesMap,
                        explicitEulerBasedTimestepper.SubGrid.VolumeMask);
                    // Note: When being called, artificial viscosity is updated in the _ENTIRE_ (fluid) domain
                    var avField = program.WorkingSet.DerivedFields[Variables.ArtificialViscosity];
                    Variables.ArtificialViscosity.UpdateFunction(avField, program.SpeciesMap.SubGrid.VolumeMask, program);

                    // Test
                    //double sensorNorm = program.WorkingSet.DerivedFields[Variables.ShockSensor].L2Norm();
                    //double avNorm = program.WorkingSet.DerivedFields[Variables.ArtificialViscosity].L2Norm();
                    //Console.WriteLine("\r\nThis is OnBeforeComputeChangeRate");
                    //Console.WriteLine("SensorNeu: {0}", sensorNorm);
                    //Console.WriteLine("AVNeu: {0}", avNorm);
                };
            }

            // Make sure limiter is applied after each modification of conservative variables
            if (control.Limiter != null)
            {
                ExplicitEuler explicitEulerBasedTimestepper = timeStepper as ExplicitEuler;
                if (explicitEulerBasedTimestepper == null)
                {
                    throw new Exception(String.Format(
                                            "Limiting currently not implemented for time-steppers of type '{0}~",
                                            timeStepperType));
                }

                explicitEulerBasedTimestepper.OnAfterFieldUpdate +=
                    (t, f) => control.Limiter.LimitFieldValues(program);
            }

            return(timeStepper);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: xMattAdams/MyProjects
        static void Main(string[] args)
        {
            RungeKutta Result = new RungeKutta();

            Result.Wynik();
        }
コード例 #10
0
    private static void test01()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    TEST01 tests RK1_TI_STEP.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    06 July 2010
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        const double t0 = 0.0;
        const double tn = 1.0;

        Console.WriteLine("");
        Console.WriteLine("TEST01");
        Console.WriteLine("  RK1_TI_STEP uses a first order RK method");
        Console.WriteLine("  for a problem whose right hand side does not");
        Console.WriteLine("  depend explicitly on time.");

        const int n = 10;

        double[]     x    = new double[n + 1];
        const double h    = (tn - t0) / n;
        const double q    = 1.0;
        int          seed = 123456789;

        int    i = 0;
        double t = t0;

        x[i] = 0.0;

        Console.WriteLine("");
        Console.WriteLine("         I           T             X");
        Console.WriteLine("");
        Console.WriteLine("  " + i.ToString().PadLeft(8)
                          + "  " + t.ToString(CultureInfo.InvariantCulture).PadLeft(14)
                          + "  " + x[i].ToString(CultureInfo.InvariantCulture).PadLeft(14) + "");

        for (i = 1; i <= n; i++)
        {
            t = ((n - i) * t0
                 + i * tn)
                / n;

            x[i] = RungeKutta.rk1_ti_step(x[i - 1], t, h, q, fi, gi, ref seed);

            Console.WriteLine("  " + i.ToString().PadLeft(8)
                              + "  " + t.ToString(CultureInfo.InvariantCulture).PadLeft(14)
                              + "  " + x[i].ToString(CultureInfo.InvariantCulture).PadLeft(14) + "");
        }
    }
コード例 #11
0
ファイル: ODE.cs プロジェクト: KernelA/control-task
 public Vector <double>[] Integrate(IReadOnlyList <double> Control)
 {
     _params = Control;
     return(RungeKutta.FourthOrder(_x0, 0, _tMax, _sizeOfRes, OdeFunction));
 }