Example #1
0
    public static void Main()
    {
        double A = 0.0;
        double T = 0.0;

        ODE myODE = new ODE(A, T);

        myODE.InitialCondition = 1.0;
        myODE.Expiry           = 1.0;

        // Getting values of coefficients
        double t = 0.5;

        Console.WriteLine("[a(t), f(t)] values: [{0}, {1}]", myODE.a(t), myODE.f(t));

        // Calculate the FD scheme
        int N = 140; // Number of steps

        ExplicitEuler myFDM = new ExplicitEuler(N, myODE);

        myFDM.calculate();
        double val = myFDM.Value;

        Console.WriteLine("fdm value: {0}", val);
    }
Example #2
0
        /// <summary>
        ///
        /// </summary>
        protected override void CreateEquationsAndSolvers(GridUpdateDataVaultBase L)
        {
            diffOp = new SpatialOperator(new string[] { "u" },
                                         Solution.NSECommon.VariableNames.VelocityVector(this.GridData.SpatialDimension),
                                         new string[] { "codom1" },
                                         QuadOrderFunc.Linear());


            switch (this.GridData.SpatialDimension)
            {
            case 2:
                diffOp.EquationComponents["codom1"].Add(new ScalarTransportFlux());
                break;

            case 3:
                diffOp.EquationComponents["codom1"].Add(new ScalarTransportFlux3D());
                break;

            default:
                throw new NotImplementedException("spatial dim. not supported.");
            }
            diffOp.Commit();

            Timestepper = new RungeKutta(RungeKuttaScheme.TVD3,
                                         diffOp,
                                         new CoordinateMapping(u), Velocity.Mapping);

            //Timestepper = new ROCK4(diffOp, u.CoordinateVector, Velocity.Mapping);
        }
Example #3
0
        protected override void CreateEquationsAndSolvers(GridUpdateDataVaultBase L)
        {
            diffOp = new SpatialOperator(
                new string[] { "c" },
                new string[] { "viscosity", "VelocityX", "VelocityY" },
                new string[] { "codom1" },
                QuadOrderFunc.Linear());
            diffOp.EquationComponents["codom1"].Add(new ScalarTransportFlux2D(inflowDirichletValue));
            diffOp.Commit();

            CoordinateMapping coordMap;

            coordMap = new CoordinateMapping(viscosity, Velocity[0], Velocity[1]);

            // 3 sub-grids
            MultidimensionalArray metricOne = MultidimensionalArray.Create(numOfCellsX);
            MultidimensionalArray metricTwo = MultidimensionalArray.Create(numOfCellsX);

            // 3 cells
            //metricOne[0] = 2;
            //metricOne[1] = 1;
            //metricOne[2] = 0.5;

            //metricTwo[0] = 1;
            //metricTwo[1] = 0.5;
            //metricTwo[2] = 2;

            // 4 cells
            metricOne[0] = 2;
            metricOne[1] = 1;
            metricOne[2] = 0.5;
            metricOne[3] = 0.25;

            metricTwo[0] = 0.5;
            metricTwo[1] = 2;
            metricTwo[2] = 0.25;
            metricTwo[3] = 1;

            CustomTimestepConstraint = new SurrogateConstraint(GridData, dtFixed, dtFixed, double.MaxValue, endTime, metricOne, metricTwo);

            timeStepper = new AdamsBashforthLTS(
                diffOp,
                new CoordinateMapping(c),
                coordMap,
                order: ABOrder,
                numOfClusters: this.numOfSubgrids,
                timeStepConstraints: new List <TimeStepConstraint>()
            {
                CustomTimestepConstraint
            },
                fluxCorrection: false,
                reclusteringInterval: 1);

            // Sub-grid visualization
            //AdamsBashforthLTS timeStepper2 = timeStepper as AdamsBashforthLTS;
            //timeStepper2.SubGridField.Identification = "clusterLTS";
            //m_IOFields.Add(timeStepper2.SubGridField);
            //timeStepper = timeStepper2;
        }
Example #4
0
        protected override void CreateEquationsAndSolvers(GridUpdateDataVaultBase L)
        {
            SpatialOperator diffOp = new SpatialOperator(1, 0, 1, QuadOrderFunc.MaxDegTimesTwo(), "u", "codom1");

            diffOp.EquationComponents["codom1"].Add(new ScalarTransportFlux());
            diffOp.Commit();

            CustomTimestepConstraint = new SurrogateConstraint(GridData, dt_input, dt_input, double.MaxValue, endTime);

            if (LTS)
            {
                AdamsBashforthLTS ltsTimeStepper = new AdamsBashforthLTS(
                    diffOp,
                    new CoordinateMapping(u),
                    null,
                    ABorder,
                    numOfSubgrids,
                    fluxCorrection: true,
                    reclusteringInterval: 0,
                    timeStepConstraints: new List <TimeStepConstraint>()
                {
                    CustomTimestepConstraint
                });
                timeStepper = ltsTimeStepper;
            }
            else if (ALTS)
            {
                AdamsBashforthLTS ltsTimeStepper = new AdamsBashforthLTS(
                    diffOp,
                    new CoordinateMapping(u),
                    null,
                    ABorder,
                    numOfSubgrids,
                    fluxCorrection: false,
                    reclusteringInterval: 1,
                    timeStepConstraints: new List <TimeStepConstraint>()
                {
                    CustomTimestepConstraint
                });
                timeStepper = ltsTimeStepper;
            }
            else
            {
                timeStepper = new AdamsBashforth(diffOp, new CoordinateMapping(u), null, ABorder);
                //timeStepper = new RungeKutta(RungeKutta.RungeKuttaScheme.Heun, diffOp, new CoordinateMapping(u),null);
                //timeStepper = RungeKutta.Factory(ABorder, diffOp, new CoordinateMapping(u));
            }
        }
Example #5
0
        static void LoktaVolterraHardoded()
        {
            var logger     = new NoLogger();
            var model      = new DAEProblem();
            var integrator = new ExplicitEuler();

            integrator.StepSize = 0.1;
            integrator.EndTime  = 200;

            var N1  = new Variable("N1", 5);
            var N2  = new Variable("N2", 10);
            var dN1 = new Variable("dN1dt", 0);
            var dN2 = new Variable("dN2dt", 0);
            var e1  = new Variable("e1", 0.09);
            var g1  = new Variable("g1", 0.01);
            var e2  = new Variable("e2", 0.04);
            var g2  = new Variable("g2", 0.01);

            var eq1 = new Equation(N1 * (e1 - g1 * N2) - dN1);
            var eq2 = new Equation(-N2 * (e2 - g2 * N1) - dN2);


            model.AlgebraicVariables.Add(N1);
            model.AlgebraicVariables.Add(N2);
            model.DifferentialVariables.Add(dN1);
            model.DifferentialVariables.Add(dN2);
            model.Equations.Add(eq1);
            model.Equations.Add(eq2);
            model.Mapping.Add(dN1, N1);
            model.Mapping.Add(dN2, N2);
            model.Initialize(new NoLogger());

            var results = integrator.Integrate(model, logger);

            using (var sw = new StreamWriter(Environment.CurrentDirectory + "\\results.csv"))
            {
                sw.WriteLine("time;" + string.Join("; ", model.AlgebraicVariables.Select(v => v.Name)));

                foreach (var result in results)
                {
                    sw.WriteLine(result.ToString());
                }
            }
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        protected override void CreateEquationsAndSolvers()
        {
            SpatialOperator diffOp = new SpatialOperator(1, 0, 1, "u", "codom1");


            switch (base.GridDat.Grid.SpatialDimension)
            {
            case 2: diffOp.EquationComponents["codom1"].Add(new ScalarTransportFlux()); break;

            case 3: diffOp.EquationComponents["codom1"].Add(new ScalarTransportFlux3D()); break;

            default:
                throw new NotImplementedException("spatial dim. not supported.");
            }
            diffOp.Commit();

            eEule = new RungeKutta(
                RungeKutta.RungeKuttaScheme.TVD3,
                diffOp,
                new CoordinateMapping(u), null);
        }
        /// <summary>
        /// Creating the time integrated DG-FEM discretization of the level set advection equation
        /// </summary>
        /// <param name="LevelSet"></param>
        /// <param name="ExtensionVelocity"></param>
        /// <param name="e"></param>
        void CreateAdvectionSpatialOperator(SinglePhaseField LevelSet, SinglePhaseField ExtensionVelocity, ExplicitEuler.ChangeRateCallback e, SubGrid subGrid)
        {
            SpatialOperator SO;
            Func <int[], int[], int[], int> QuadOrderFunction = QuadOrderFunc.Linear();
            int D = LevelSet.GridDat.SpatialDimension;

            //FieldFactory<SinglePhaseField> fac = new FieldFactory<SinglePhaseField>(SinglePhaseField.Factory);
            //VectorField<SinglePhaseField> LevelSetGradient = new VectorField<SinglePhaseField>(D,
            //    LevelSet.Basis,fac);

            SO = new SpatialOperator(1, 1, 1, QuadOrderFunction, new string[] { "LS", "S", "Result" });
            double PenaltyBase = ((double)((LevelSet.Basis.Degree + 1) * (LevelSet.Basis.Degree + D))) / ((double)D);

            SO.EquationComponents["Result"].Add(new ScalarVelocityAdvectionFlux(GridDat, PenaltyBase));
            SO.Commit();
            this.TimeIntegrator = new RungeKutta(RungeKuttaScheme.ExplicitEuler, SO, new CoordinateMapping(LevelSet), new CoordinateMapping(ExtensionVelocity), subGrid);

            // Performing the task e
            if (e != null)
            {
                this.TimeIntegrator.OnBeforeComputeChangeRate += e;
            }
        }
Example #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,
                    forceReclustering: control.forceReclustering,
                    logging: control.WriteLTSLog,
                    consoleOutput: control.WriteLTSConsoleOutput);
                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,
                    forceReclustering: control.forceReclustering,
                    logging: control.WriteLTSLog,
                    consoleOutput: control.WriteLTSConsoleOutput);
                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.CNSShockSensor != 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.CNSShockSensor.UpdateSensorValues(
                        program.WorkingSet.AllFields,
                        program.SpeciesMap,
                        explicitEulerBasedTimestepper.SubGrid.VolumeMask);
                    // Note: When being called, artificial viscosity is updated in the _ENTIRE_ (fluid) domain
                    var avField = program.WorkingSet.DerivedFields[CNSVariables.ArtificialViscosity];
                    CNSVariables.ArtificialViscosity.UpdateFunction(avField, program.SpeciesMap.SubGrid.VolumeMask, program);

                    // Test
                    //double sensorNorm = program.WorkingSet.DerivedFields[CNSVariables.ShockSensor].L2Norm();
                    //double avNorm = program.WorkingSet.DerivedFields[CNSVariables.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.WorkingSet.ConservativeVariables, program.WorkingSet.DerivedFields.Values);
            }

            return(timeStepper);
        }
Example #9
0
        static void LotkaVolterraParsed()
        {
            string input =
                @"class LotkaVolterra
                    Real N1 = 10;
                    Real N2 = 5;
                    parameter Real e1 = 0.09;
                    parameter Real g1 = 0.01;
                    parameter Real e2 = 0.04;
                    parameter Real g2 = 0.01;
                    equation
                        der(N1) = N1*(e1-g1*N2);
                        der(N2) = -N2*(e2-g2*N1);                        
                 end LotkaVolterra;
                 ";

            var parser = new ModelicaParser();



            var printer    = new ModelicaTreePrinter();
            var translator = new ModelTranslatorV1();

            var status = parser.TryParseProgram(input, out var prog, out var error, out var position);

            if (status)
            {
                var ast = printer.Transform(prog);
                // Console.WriteLine(ast);
                var logger = new NoLogger();
                var model  = translator.Translate(prog.ClassDefinitions.Last());

                var integrator = new ExplicitEuler();
                integrator.Discretize(model);
                integrator.StepSize = 1;
                integrator.EndTime  = 800;
                model.Initialize(new NoLogger());

                Stopwatch w = new Stopwatch();
                w.Start();
                var results = integrator.Integrate(model, logger);
                w.Stop();
                Console.WriteLine("Integration took " + w.ElapsedMilliseconds + "ms");

                using (var sw = new StreamWriter(Environment.CurrentDirectory + "\\results.csv"))
                {
                    sw.WriteLine("time;" + string.Join("; ", model.AlgebraicVariables.Select(v => v.Name)));

                    foreach (var result in results)
                    {
                        sw.WriteLine(result.ToString());
                        // Console.WriteLine(result.ToString());
                    }
                }
            }
            else
            {
                Console.WriteLine(error);
            }
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine(e.Message);
            //}
        }