public IBMAdamsBashforth(
            SpatialOperator standardOperator,
            SpatialOperator boundaryOperator,
            CoordinateMapping fieldsMap,
            CoordinateMapping parametersMap,
            ISpeciesMap ibmSpeciesMap,
            IBMControl control,
            IList <TimeStepConstraint> timeStepConstraints)
            : base(standardOperator, fieldsMap, parametersMap, control.ExplicitOrder, timeStepConstraints, ibmSpeciesMap.SubGrid)    // TO DO: I SIMPLY REMOVED PARAMETERMAP HERE; MAKE THIS MORE PRETTY
        {
            speciesMap = ibmSpeciesMap as ImmersedSpeciesMap;
            if (this.speciesMap == null)
            {
                throw new ArgumentException(
                          "Only supported for species maps of type 'ImmersedSpeciesMap'",
                          "speciesMap");
            }

            this.boundaryOperator          = boundaryOperator;
            this.boundaryParameterMap      = parametersMap;
            agglomerationPatternHasChanged = true;

            // StarUp Phase needs also an IBM time stepper
            RungeKuttaScheme = new IBMSplitRungeKutta(
                standardOperator,
                boundaryOperator,
                fieldsMap,
                parametersMap,
                speciesMap,
                timeStepConstraints);
        }
Beispiel #2
0
 /// <summary>
 /// Check whether Operator, Fields and Parameters fit toghether
 /// </summary>
 /// <param name="spatialOp"></param>
 /// <param name="Fieldsmap"></param>
 /// <param name="Parameters"></param>
 public static void VerifyInput(SpatialOperator spatialOp, CoordinateMapping Fieldsmap, CoordinateMapping Parameters)
 {
     if (!spatialOp.ContainsNonlinear && !(spatialOp.ContainsLinear()))
     {
         throw new ArgumentException("spatial differential operator seems to contain no components.", "spatialOp");
     }
     if (spatialOp.DomainVar.Count != spatialOp.CodomainVar.Count)
     {
         throw new ArgumentException("spatial differential operator must have the same number of domain and codomain variables.", "spatialOp");
     }
     if (Fieldsmap.Fields.Count != spatialOp.CodomainVar.Count)
     {
         throw new ArgumentException("the number of fields in the coordinate mapping must be equal to the number of domain/codomain variables of the spatial differential operator", "fields");
     }
     if (Parameters == null)
     {
         if (spatialOp.ParameterVar.Count != 0)
         {
             throw new ArgumentException("the number of fields in the parameter mapping must be equal to the number of parameter variables of the spatial differential operator", "Parameters");
         }
     }
     else
     {
         if (Parameters.Fields.Count != spatialOp.ParameterVar.Count)
         {
             throw new ArgumentException("the number of fields in the parameter mapping must be equal to the number of parameter variables of the spatial differential operator", "Parameters");
         }
     }
 }
Beispiel #3
0
        /// <summary>
        /// ctor.
        /// </summary>
        public LinearSolver(ISparseSolver solver, MsrMatrix spatialOpMtx, IList <double> spatialOpAffine, CoordinateMapping UnknownsMap)
        {
            // check operator and arguments
            // ----------------------------

            if (spatialOpMtx.NoOfRows != spatialOpMtx.NoOfCols)
            {
                throw new ArgumentException("matrix must be quadratic.", "spatialOpMtx");
            }
            if (spatialOpMtx.NoOfRows != UnknownsMap.GlobalCount)
            {
                throw new ArgumentException("matrix size must be equal to the GlobalCount of fields mapping", "fields,spatialOpMtx");
            }
            if (spatialOpMtx.RowPartitioning.LocalLength != UnknownsMap.LocalLength)
            {
                throw new ArgumentException("number of locally stored matrix rows nust be equal to NUpdate of fields mapping.", "fields,spatialOpMtx");
            }
            if (spatialOpAffine.Count < UnknownsMap.LocalLength)
            {
                throw new ArgumentException("length affine offset vector must be equal or larger than NUpdate of the mapping", "spatialOpAffine");
            }

            m_Solver  = solver;
            m_Mapping = UnknownsMap;


            // finish constructor
            // ------------------
            m_AffineOffset = spatialOpAffine.ToArray();
            ConstructorCommon(spatialOpMtx);
        }
Beispiel #4
0
        /// <summary>
        /// Calculating the level set gradient using the specified scheme in a narrow band around the zero level set, therein the calculions are performed
        /// </summary>
        /// <param name="LS"> The level set function </param>
        /// <param name="LSG"> Gradient of the level set function </param>
        /// <param name="f"> Specifying the method of flux calculation </param>
        /// <param name="Restriction"> The narrow band around the zero level set wherein the calculations are performed </param>
        void CalculateLevelSetGradient(LevelSet LS, VectorField <SinglePhaseField> LSG, string f, SubGrid Restriction)
        {
            SpatialOperator   SO;
            CoordinateMapping CoDom;

            if (m_ctx.SpatialDimension == 2)
            {
                SO = new SpatialOperator(1, 2, QuadOrderFunc.Linear(), new string[] { "LS", "LSG[0]", "LSG[1]" });
                SO.EquationComponents["LSG[0]"].Add(CreateFlux(m_ctx, f, 0));
                SO.EquationComponents["LSG[1]"].Add(CreateFlux(m_ctx, f, 1));
                SO.Commit();
                CoDom = new CoordinateMapping(LSG[0], LSG[1]);
            }
            else if (m_ctx.SpatialDimension == 3)
            {
                SO = new SpatialOperator(1, 3, QuadOrderFunc.Linear(), new string[] { "LS", "LSG[0]", "LSG[1]", "LSG[2]" });
                SO.EquationComponents["LSG[0]"].Add(CreateFlux(m_ctx, f, 0));
                SO.EquationComponents["LSG[1]"].Add(CreateFlux(m_ctx, f, 1));
                SO.EquationComponents["LSG[2]"].Add(CreateFlux(m_ctx, f, 2));
                SO.Commit();
                CoDom = new CoordinateMapping(LSG[0], LSG[1], LSG[2]);
            }
            else
            {
                throw new NotSupportedException();
            }

            SO.Evaluate(1.0, 0.0, LS.Mapping, null, CoDom, sgrd: Restriction, bndMode: SubGridBoundaryModes.OpenBoundary);
        }
Beispiel #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="spatialOp"></param>
        /// <param name="Fieldsmap"></param>
        /// <param name="Parameters">
        /// optional parameter fields, can be null if
        /// <paramref name="spatialOp"/> contains no parameters; must match
        /// the parameter field list of <paramref name="spatialOp"/>, see
        /// <see cref="BoSSS.Foundation.SpatialOperator.ParameterVar"/>
        /// </param>
        /// <param name="sgrdBnd">
        /// Options for the treatment of edges at the boundary of a SubGrid,
        /// <see cref="SubGridBoundaryModes"/></param>
        /// <param name="timeStepConstraints">
        /// optional list of time step constraints <see cref="TimeStepConstraint"/>
        /// </param>
        /// <param name="sgrd">
        /// optional restriction to computational domain
        /// </param>
        public ExplicitEuler(SpatialOperator spatialOp, CoordinateMapping Fieldsmap, CoordinateMapping Parameters, SubGridBoundaryModes sgrdBnd, IList <TimeStepConstraint> timeStepConstraints = null, SubGrid sgrd = null)
        {
            using (new ilPSP.Tracing.FuncTrace()) {
                // verify input
                // ============
                TimeStepperCommon.VerifyInput(spatialOp, Fieldsmap, Parameters);


                Mapping          = Fieldsmap;
                CurrentState     = new CoordinateVector(Mapping);
                ParameterMapping = Parameters;
                IList <DGField> ParameterFields =
                    (ParameterMapping == null) ? (new DGField[0]) : ParameterMapping.Fields;

                this.TimeStepConstraints = timeStepConstraints;

                SubGrid = sgrd ?? new SubGrid(CellMask.GetFullMask(Fieldsmap.First().GridDat));

                // generate Evaluator
                // ==================

                CellMask cm = SubGrid.VolumeMask;
                EdgeMask em = SubGrid.AllEdgesMask;

                Operator    = spatialOp;
                m_Evaluator = new Lazy <IEvaluatorNonLin>(delegate() {
                    spatialOp.EdgeQuadraturSchemeProvider   = g => new EdgeQuadratureScheme(true, em);
                    spatialOp.VolumeQuadraturSchemeProvider = g => new CellQuadratureScheme(true, cm);
                    var op = spatialOp.GetEvaluatorEx(
                        Fieldsmap, ParameterFields, Fieldsmap);
                    op.ActivateSubgridBoundary(SubGrid.VolumeMask, sgrdBnd);
                    return(op);
                });
            }
        }
Beispiel #6
0
        /// <summary>
        /// In a vector <paramref name="vec"/>, this method performs a
        /// polynomial extrapolation from agglomeration target cells to agglomeration source cells.
        /// </summary>
        public void Extrapolate(CoordinateMapping Map)
        {
            //var vecS = GetFrameVectors(vec, Map);

            foreach (var kv in DictAgglomeration) {
                var Species = kv.Key;
                var m_Agglomerator = kv.Value;

                var DgFields = Map.Fields.ToArray();

                DGField[] SubFields = new DGField[DgFields.Count()];
                for (int iFld = 0; iFld < SubFields.Length; iFld++) {
                    DGField f = DgFields[iFld];

                    if (f is ConventionalDGField)
                        SubFields[iFld] = (ConventionalDGField)(f);
                    else if (f is XDGField)
                        SubFields[iFld] = ((XDGField)f).GetSpeciesShadowField(Species);
                    else
                        throw new NotImplementedException();
                }

                if (m_Agglomerator != null) {
                    m_Agglomerator.Extrapolate(new CoordinateMapping(SubFields));
                }

            }
        }
Beispiel #7
0
        public IBMABevolve(
            SpatialOperator standardOperator,
            SpatialOperator boundaryOperator,
            CoordinateMapping fieldsMap,
            CoordinateMapping parametersMap,
            ISpeciesMap ibmSpeciesMap,
            int explicitOrder,
            int levelSetQuadratureOrder,
            XQuadFactoryHelper.MomentFittingVariants momentFittingVariant,
            SubGrid sgrd,
            bool adaptive = false)
            : base(standardOperator, fieldsMap, parametersMap, explicitOrder, adaptive: adaptive, sgrd: sgrd)
        {
            speciesMap = ibmSpeciesMap as ImmersedSpeciesMap;
            if (speciesMap == null)
            {
                throw new ArgumentException(
                          "Only supported for species maps of type 'ImmersedSpeciesMap'",
                          "speciesMap");
            }

            this.boundaryOperator          = boundaryOperator;
            this.boundaryParameterMap      = parametersMap;
            agglomerationPatternHasChanged = true;
        }
Beispiel #8
0
        public ImagePanel2()
        {
            InitializeComponent();

            currentDisplayOffsetPt  = new Point(0, 0);
            originalDisplayOffsetPt = new Point(0, 0);
            BorderSize         = 2;
            currentZoomFactor  = 1.0F;
            originalZoomFactor = 1.0F;
            lastMousePosition  = new Point(0, 0);

            // initialize MPR cursor
            this.m_mprCursor = new MPRCursor();
            // initial coordinate system mapping
            this.m_coordinateMapping = new CoordinateMapping();
            // cursor path
            cursorPath = new GraphicsPath();
            cursorPath.Reset();

            // testing
            objectPath     = new GraphicsPath();
            objectLocation = new Point(0, 0);
            objectPath.Reset();
            objectPath.AddEllipse(objectLocation.X - 5.0F, objectLocation.Y - 5.0F, 10.0F, 10.0F);
            objectPath.CloseFigure();

            // Set few control option.
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.DoubleBuffer, true);
            SetStyle(ControlStyles.UserMouse, true);

            // handle resize
            this.Resize += new EventHandler(ImagePanel2_Resize);
        }
Beispiel #9
0
        /// <summary>
        /// Initilializes the History-stack for the Unknown u and the Operator Matrix and Affine Part
        /// </summary>
        /// <param name="Mapping"></param>
        /// <param name="StackLength"></param>
        private void InitStacks(CoordinateMapping Mapping, int StackLength)
        {
            // operator matrix - stack
            // -----------------------

            Stack_OpMatrix = new BlockMsrMatrix[2]; // only required for Crank.Nic. and Expl. Euler,
            Stack_OpAffine = new double[2][];       //      in this case 'theta0' is unequal 0.0.

            Stack_OpMatrix[1] = new BlockMsrMatrix(Mapping);
            Stack_OpAffine[1] = new double[Mapping.LocalLength];


            // Stack for the unknown field
            //----------------------------
            Stack_u = new CoordinateVector[StackLength];
            for (int i = 0; i < StackLength; i++)
            {
                Stack_u[i] = new CoordinateVector(Mapping.Fields.Select(dgf => dgf.CloneAs()).ToArray());
            }
            Stack_u[0].Clear();
            Stack_u[0].AccV(1.0, CurrentState);

            // Initialize the Operator Matrix for TimeStep 0, i.e. Calculate it and Push it to its Position
            UpdateOperatorMatrix();
            PushStacks();
        }
Beispiel #10
0
        /// <summary>
        /// ctor.
        /// </summary>
        /// <param name="temporalOp">
        /// Indicates, for each each equation whether it is
        /// <list type="bullet">
        ///   <item>(false) a auxiliary condition  i.e. a variable where no time derivative occurs in the equation, or</item>
        ///   <item>(true) a differential equation</item>
        /// </list>
        /// At least one equation must be time-dependent;
        /// Otherwise, the <see cref="BoSSS.Solution.Solvers.LinearSolver"/> should be used;
        /// </param>
        /// <param name="spatialOp"></param>
        /// <param name="fields"></param>
        /// <param name="solver">
        /// </param>
        public ImplicitTimeStepper(ISparseSolverExt solver, bool[] temporalOp, SpatialOperator spatialOp, CoordinateMapping fields)
        {
            // check operator and arguments
            if (!spatialOp.IsCommited)
            {
                throw new ArgumentException("operator must be committed first.", "spatialOp");
            }
            if (spatialOp.ContainsNonlinear)
            {
                throw new ArgumentException("spatial differential operator cannot contain nonlinear components for implicit euler.", "spatialOp");
            }
            if (!spatialOp.ContainsLinear())
            {
                throw new ArgumentException("spatial differential operator seems to contain no components.", "spatialOp");
            }
            if (spatialOp.DomainVar.Count != spatialOp.CodomainVar.Count)
            {
                throw new ArgumentException("spatial differential operator must have the same number of domain and codomain variables.", "spatialOp");
            }

            if (fields.Fields.Count != spatialOp.CodomainVar.Count)
            {
                throw new ArgumentException("the number of fields in the coordinate mapping must be equal to the number of domain/codomain variables of the spatial differential operator", "fields");
            }

            m_Solver  = solver;
            m_Mapping = fields;
            //m_AffineOffset1 = new double[fields.LocalLength];
            MsrMatrix eM;

            ImplicitTimeStepper.ComputeMatrix(spatialOp, fields, false, out eM, out m_AffineOffset1);

            //Setup2(eM, temporalOp);
            Setup1(solver, temporalOp, eM, m_AffineOffset1, fields);
        }
Beispiel #11
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;
        }
Beispiel #12
0
 /// <summary>
 /// ctor.
 /// </summary>
 public IBMMassMatrixFactory(ImmersedSpeciesMap speciesMap, CoordinateMapping mapping, string fluidSpeciesName, int quadOrder)
 {
     this.Mapping            = mapping;
     this.SpeciesMap         = speciesMap;
     this.m_FluidSpeciesName = fluidSpeciesName;
     this.m_quadOrder        = quadOrder;
     speciesMap.Tracker.Subscribe(this);
 }
Beispiel #13
0
 /// <summary>
 /// Creates an instance of <see cref="IBMMassMatrixFactory"/> that is
 /// appropriate for the given <paramref name="mapping"/>
 /// </summary>
 /// <param name="mapping"></param>
 /// <returns></returns>
 public IBMMassMatrixFactory GetMassMatrixFactory(CoordinateMapping mapping)
 {
     if (MassMatrixFactory == null || !mapping.Equals(MassMatrixFactory.Mapping))
     {
         MassMatrixFactory = new IBMMassMatrixFactory(this, mapping, Control.FluidSpeciesName, Control.LevelSetQuadratureOrder);
     }
     return(MassMatrixFactory);
 }
Beispiel #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="spatialOp"></param>
        /// <param name="Fieldsmap"></param>
        /// <param name="Parameters">
        /// optional parameter fields, can be null if
        /// <paramref name="spatialOp"/> contains no parameters; must match
        /// the parameter field list of <paramref name="spatialOp"/>, see
        /// <see cref="BoSSS.Foundation.SpatialOperator.ParameterVar"/>
        /// </param>
        /// <param name="sgrdBnd">
        /// Options for the treatment of edges at the boundary of a SubGrid,
        /// <see cref="SpatialOperator.SubGridBoundaryModes"/></param>
        /// <param name="timeStepConstraints">
        /// optional list of time step constraints <see cref="TimeStepConstraint"/>
        /// </param>
        /// <param name="sgrd">
        /// optional restriction to computational domain
        /// </param>
        public ExplicitEuler(SpatialOperator spatialOp, CoordinateMapping Fieldsmap, CoordinateMapping Parameters, SpatialOperator.SubGridBoundaryModes sgrdBnd, IList <TimeStepConstraint> timeStepConstraints = null, SubGrid sgrd = null)
        {
            using (new ilPSP.Tracing.FuncTrace()) {
                // verify input
                // ============

                if (!spatialOp.ContainsNonlinear && !(spatialOp.ContainsLinear()))
                {
                    throw new ArgumentException("spatial differential operator seems to contain no components.", "spatialOp");
                }
                if (spatialOp.DomainVar.Count != spatialOp.CodomainVar.Count)
                {
                    throw new ArgumentException("spatial differential operator must have the same number of domain and codomain variables.", "spatialOp");
                }
                if (Fieldsmap.Fields.Count != spatialOp.CodomainVar.Count)
                {
                    throw new ArgumentException("the number of fields in the coordinate mapping must be equal to the number of domain/codomain variables of the spatial differential operator", "fields");
                }
                if (Parameters == null)
                {
                    if (spatialOp.ParameterVar.Count != 0)
                    {
                        throw new ArgumentException("the number of fields in the parameter mapping must be equal to the number of parameter variables of the spatial differential operator", "Parameters");
                    }
                }
                else
                {
                    if (Parameters.Fields.Count != spatialOp.ParameterVar.Count)
                    {
                        throw new ArgumentException("the number of fields in the parameter mapping must be equal to the number of parameter variables of the spatial differential operator", "Parameters");
                    }
                }

                Mapping          = Fieldsmap;
                DGCoordinates    = new CoordinateVector(Mapping);
                ParameterMapping = Parameters;
                IList <DGField> ParameterFields =
                    (ParameterMapping == null) ? (new DGField[0]) : ParameterMapping.Fields;

                this.TimeStepConstraints = timeStepConstraints;

                SubGrid = sgrd ?? new SubGrid(CellMask.GetFullMask(Fieldsmap.First().GridDat));

                // generate Evaluator
                // ==================

                CellMask cm = SubGrid.VolumeMask;
                EdgeMask em = SubGrid.AllEdgesMask;

                Operator    = spatialOp;
                m_Evaluator = new Lazy <SpatialOperator.Evaluator>(() => spatialOp.GetEvaluatorEx(
                                                                       Fieldsmap, ParameterFields, Fieldsmap,
                                                                       new EdgeQuadratureScheme(true, em),
                                                                       new CellQuadratureScheme(true, cm),
                                                                       SubGrid,
                                                                       sgrdBnd));
            }
        }
Beispiel #15
0
 /// <summary>
 /// ctor.
 /// </summary>
 public ROCK4(SpatialOperator op, CoordinateVector V, CoordinateMapping ParamFields)
 {
     this.CurrentState = V;
     this.OpEv         = op.GetEvaluatorEx(this.Mapping,
                                           ParamFields != null ? ParamFields.Fields : new DGField[0],
                                           this.Mapping);
     this.nfevals   = 0;
     this.nrejected = 0;
 }
Beispiel #16
0
        /// <summary>
        /// Factory for residual loggers. The instantiated objects depend on the
        /// defined <paramref name="loggerType"/>.
        /// </summary>
        /// <param name="loggerType">
        /// The type of logger to be instantiated
        /// </param>
        /// <param name="program">
        /// The program requesting the residual logger.
        /// </param>
        /// <param name="config">Configuration options</param>
        /// <param name="differentialOperator">
        /// The differential operator that defines the system of equations to
        /// be solved. May be null if <paramref name="loggerType"/> does
        /// <b>not</b> contain <see cref="ResidualLoggerTypes.Rigorous"/>.
        /// </param>
        /// <returns>
        /// A list of residual loggers, see <see cref="ResidualLogger"/>.
        /// </returns>
        public static IEnumerable <IResidualLogger> Instantiate <T>(
            this ResidualLoggerTypes loggerType,
            Application <T> program,
            CompressibleControl config,
            SpatialOperator differentialOperator,
            DGField[] consVars,
            CoordinateMapping paramMap)
            where T : CompressibleControl, new()
        {
            if (loggerType.HasFlag(ResidualLoggerTypes.ChangeRate) &&
                loggerType.HasFlag(ResidualLoggerTypes.Rigorous))
            {
                throw new Exception(
                          "Residual types \"changeRate\" and \"rigorous\" are mutually exclusive");
            }

            if (loggerType == ResidualLoggerTypes.None)
            {
                yield return(new NullResidualLogger(
                                 program.ResLogger, program.CurrentSessionInfo, consVars));
            }
            else
            {
                if (loggerType.HasFlag(ResidualLoggerTypes.ChangeRate))
                {
                    loggerType ^= ResidualLoggerTypes.ChangeRate;
                    yield return(new ChangeRateResidualLogger(
                                     program.ResLogger, program.CurrentSessionInfo, consVars, config.ResidualInterval));
                }

                if (loggerType.HasFlag(ResidualLoggerTypes.Rigorous))
                {
                    loggerType ^= ResidualLoggerTypes.Rigorous;
                    yield return(new RigorousResidualLogger <T>(
                                     program,
                                     consVars,
                                     paramMap,
                                     config.ResidualInterval,
                                     differentialOperator));
                }

                if (loggerType.HasFlag(ResidualLoggerTypes.Query))
                {
                    loggerType ^= ResidualLoggerTypes.Query;
                    yield return(new QueryLogger(
                                     program.ResLogger, program));
                }

                if (loggerType != ResidualLoggerTypes.None)
                {
                    throw new NotImplementedException(
                              "Residual logging for residual type " + loggerType + " not implemented");
                }
            }
        }
        /// <summary>
        /// <see cref="ResidualLogger"/>
        /// </summary>
        /// <param name="program"></param>
        /// <param name="residualInterval">
        /// <see cref="ResidualLogger"/>
        /// </param>
        /// <param name="differentialOperator">
        /// The spatial differential operator defining (the spatial part of)
        /// the system of equations that are solved.
        /// </param>
        public RigorousResidualLogger(Application <T> program, DGField[] consVars, CoordinateMapping paramMap, int residualInterval, SpatialOperator differentialOperator)
            : base(program.ResLogger, program.CurrentSessionInfo, consVars, residualInterval)
        {
            CoordinateMapping           domainMapping   = new CoordinateMapping(consVars);
            UnsetteledCoordinateMapping codomainMapping = new UnsetteledCoordinateMapping(
                consVars.Select((field) => field.Basis).ToArray());

            evaluator = differentialOperator.GetEvaluatorEx(
                domainMapping,
                paramMap,
                codomainMapping);
        }
Beispiel #18
0
        /// <summary>
        ///  Constructor for an explicit Euler scheme operating on subgrids supporting parameters.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="subgridMapping">Coordinate Mapping on the subgrid</param>
        /// <param name="Parameters">Optional parameters which have to match the matrix dimensions</param>
        /// <param name="operatorMatrix">Matrix of the differential operator</param>
        /// <param name="affine">Affine part of the operator matrix</param>
        public ExplicitEulerSubgrid(Context ctx, SubgridCoordinateMapping subgridMapping, CoordinateMapping Parameters, MsrMatrix operatorMatrix, double[] affine)
        {
            using (new ilPSP.Tracing.FuncTrace()) {
                m_Context        = ctx;
                m_SubgridMapping = subgridMapping;
                m_DGCoordinates  = subgridMapping.subgridCoordinates;
                m_Parameters     = Parameters;
                IList <Field> ParameterFields = (m_Parameters == null) ? (new Field[0]) : m_Parameters.Fields;

                m_SubgridMapping.SetupSubmatrix(affine, operatorMatrix, out subgridAffine, out subgridMatrix);
            }
        }
Beispiel #19
0
        public static IBMRungeKutta CreateRungeKuttaTimeStepper(
            this TimesteppingStrategies strategy,
            IBMControl control,
            OperatorFactory equationSystem,
            CNSFieldSet fieldSet,
            CoordinateMapping parameterMap,
            ISpeciesMap speciesMap,
            IList <TimeStepConstraint> timeStepConstraints)
        {
            ImmersedSpeciesMap ibmSpeciesMap = speciesMap as ImmersedSpeciesMap;

            if (ibmSpeciesMap == null)
            {
                throw new ArgumentException(
                          "Only supported for species maps of type 'ImmersedSpeciesMap'",
                          "speciesMap");
            }

            IBMOperatorFactory ibmFactory = equationSystem as IBMOperatorFactory;

            if (ibmFactory == null)
            {
                throw new Exception();
            }

            CoordinateMapping variableMap = new CoordinateMapping(fieldSet.ConservativeVariables);

            switch (strategy)
            {
            case TimesteppingStrategies.LieSplitting:
            case TimesteppingStrategies.StrangSplitting:
                return(new IBMSplitRungeKutta(
                           equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                           ibmFactory.GetImmersedBoundaryOperator().ToSpatialOperator(fieldSet),
                           variableMap,
                           parameterMap,
                           ibmSpeciesMap,
                           timeStepConstraints));

            case TimesteppingStrategies.MovingFrameFlux:
                return(new IBMMovingFrameRungeKutta(
                           equationSystem.GetJoinedOperator().ToSpatialOperator(fieldSet),
                           ibmFactory.GetImmersedBoundaryOperator().ToSpatialOperator(fieldSet),
                           variableMap,
                           parameterMap,
                           ibmSpeciesMap,
                           timeStepConstraints));

            default:
                throw new System.NotImplementedException();
            }
        }
Beispiel #20
0
        /// <summary>
        /// <see cref="ResidualLogger"/>
        /// </summary>
        /// <param name="program"></param>
        /// <param name="residualInterval">
        /// <see cref="ResidualLogger"/>
        /// </param>
        /// <param name="differentialOperator">
        /// The spatial differential operator defining (the spatial part of)
        /// the system of equations that are solved.
        /// </param>
        public RigorousResidualLogger(Program <T> program, int residualInterval, SpatialOperator differentialOperator)
            : base(program.ResLogger, program.CurrentSessionInfo, program.WorkingSet, residualInterval)
        {
            DGField[]                   primalFields    = program.WorkingSet.ConservativeVariables;
            CoordinateMapping           domainMapping   = new CoordinateMapping(primalFields);
            UnsetteledCoordinateMapping codomainMapping = new UnsetteledCoordinateMapping(
                primalFields.Select((field) => field.Basis).ToArray());

            evaluator = differentialOperator.GetEvaluatorEx(
                domainMapping,
                program.ParameterMapping,
                codomainMapping);
        }
Beispiel #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="spatialOp">Spatial operator</param>
        /// <param name="Fieldsmap"></param>
        /// <param name="scheme">Runge-Kutta scheme</param>
        /// <param name="Parameters">
        /// Optional parameter fields, can be null if
        /// <paramref name="spatialOp"/> contains no parameters;
        /// must match the parameter field list of
        /// <paramref name="spatialOp"/>, see
        /// <see cref="BoSSS.Foundation.SpatialOperator.ParameterVar"/>
        /// </param>
        /// <param name="timeStepConstraints">
        /// optional list of time step constraints <see cref="TimeStepConstraint"/>
        /// </param>
        /// <param name="sgrd">
        /// optional restriction to computational domain
        /// </param>
        public RungeKutta(RungeKuttaScheme scheme, SpatialOperator spatialOp, CoordinateMapping Fieldsmap, CoordinateMapping Parameters, IList <TimeStepConstraint> timeStepConstraints, SubGrid sgrd = null)
            : base(spatialOp, Fieldsmap, Parameters, timeStepConstraints, sgrd)
        {
            using (new ilPSP.Tracing.FuncTrace()) {
                m_Scheme = scheme;

                m_Scheme.Verify();
                if (!m_Scheme.IsExplicit)
                {
                    throw new ArgumentException("Implicit Runge-Kutta -- schemes are not supported.");
                }
            }
        }
Beispiel #22
0
 public IBMRungeKutta(
     SpatialOperator standardOperator,
     SpatialOperator boundaryOperator,
     CoordinateMapping fieldsMap,
     CoordinateMapping parametersMap,
     ImmersedSpeciesMap speciesMap,
     IList <TimeStepConstraint> timeStepConstraints)
     : base(RungeKutta.GetDefaultScheme(speciesMap.Control.ExplicitOrder), standardOperator, fieldsMap, parametersMap, timeStepConstraints, speciesMap.SubGrid)
 {
     this.speciesMap           = speciesMap;
     this.boundaryOperator     = boundaryOperator;
     this.boundaryParameterMap = parametersMap;
 }
Beispiel #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="spatialOp"></param>
        /// <param name="fields"></param>
        /// <param name="matrix"></param>
        /// <param name="affineOffset"></param>
        /// <param name="OnlyAffine">
        /// if true, only the <paramref name="affineOffset"/>
        /// is computed and <paramref name="matrix"/> is null on exit.
        /// </param>
        public static void ComputeMatrix(SpatialOperator spatialOp, CoordinateMapping fields, bool OnlyAffine, out MsrMatrix matrix, out double[] affineOffset)
        {
            // Check operator and arguments
            if (!spatialOp.IsCommited)
            {
                throw new ArgumentException("operator must be committed first.", "spatialOp");
            }
            if (spatialOp.ContainsNonlinear)
            {
                throw new ArgumentException("spatial differential operator cannot contain nonlinear components for implicit euler.", "spatialOp");
            }
            if (!spatialOp.ContainsLinear())
            {
                throw new ArgumentException("spatial differential operator seems to contain no components.", "spatialOp");
            }
            if (spatialOp.DomainVar.Count != spatialOp.CodomainVar.Count)
            {
                throw new ArgumentException("spatial differential operator must have the same number of domain and codomain variables.", "spatialOp");
            }
            if (fields.Fields.Count != spatialOp.CodomainVar.Count)
            {
                throw new ArgumentException("the number of fields in the coordinate mapping must be equal to the number of domain/codomain variables of the spatial differential operator", "fields");
            }

            // Assemble matrix and affine offset
            IPartitioning matrixPartition = fields;


            if (!OnlyAffine)
            {
                matrix = new MsrMatrix(matrixPartition);
            }
            else
            {
                matrix = null;
            }
            affineOffset = new double[fields.LocalLength];

            var b = spatialOp.GetMatrixBuilder(fields, null, fields);

            if (OnlyAffine)
            {
                b.ComputeAffine(affineOffset);
            }
            else
            {
                b.ComputeMatrix(matrix, affineOffset);
            }
        }
Beispiel #24
0
        public IBMAdamsBashforthLTS(SpatialOperator standardOperator, SpatialOperator boundaryOperator, CoordinateMapping fieldsMap, CoordinateMapping boundaryParameterMap, ISpeciesMap ibmSpeciesMap, IBMControl control, IList <TimeStepConstraint> timeStepConstraints, int reclusteringInterval, bool fluxCorrection)
            : base(standardOperator, fieldsMap, boundaryParameterMap, control.ExplicitOrder, control.NumberOfSubGrids, true, timeStepConstraints, reclusteringInterval: reclusteringInterval, fluxCorrection: fluxCorrection, subGrid: ibmSpeciesMap.SubGrid)
        {
            this.speciesMap = ibmSpeciesMap as ImmersedSpeciesMap;
            if (this.speciesMap == null)
            {
                throw new ArgumentException(
                          "Only supported for species maps of type 'ImmersedSpeciesMap'",
                          "speciesMap");
            }
            this.standardOperator     = standardOperator;
            this.boundaryOperator     = boundaryOperator;
            this.boundaryParameterMap = boundaryParameterMap;
            this.fieldsMap            = fieldsMap;
            this.control = control;

            agglomerationPatternHasChanged = true;

            cutCells          = speciesMap.Tracker.Regions.GetCutCellMask();
            cutAndTargetCells = cutCells.Union(speciesMap.Agglomerator.AggInfo.TargetCells);

            // Normal LTS constructor
            NumberOfLocalTimeSteps = new List <int>(control.NumberOfSubGrids);

            clusterer = new Clusterer(this.gridData, this.TimeStepConstraints);

            CurrentClustering = clusterer.CreateClustering(control.NumberOfSubGrids, speciesMap.SubGrid);
            CurrentClustering = CalculateNumberOfLocalTS(CurrentClustering); // Might remove sub-grids when time step sizes are too similar

            ABevolver = new IBMABevolve[CurrentClustering.NumberOfClusters];

            for (int i = 0; i < ABevolver.Length; i++)
            {
                ABevolver[i] = new IBMABevolve(standardOperator, boundaryOperator, fieldsMap, boundaryParameterMap, speciesMap, control.ExplicitOrder, control.LevelSetQuadratureOrder, control.CutCellQuadratureType, sgrd: CurrentClustering.Clusters[i], adaptive: this.adaptive);
                ABevolver[i].OnBeforeComputeChangeRate += (t1, t2) => this.RaiseOnBeforeComputechangeRate(t1, t2);
            }

            GetBoundaryTopology();

#if DEBUG
            for (int i = 0; i < CurrentClustering.NumberOfClusters; i++)
            {
                Console.WriteLine("IBM AB LTS ctor: id=" + i + " -> sub-steps=" + NumberOfLocalTimeSteps[i] + " and elements=" + CurrentClustering.Clusters[i].GlobalNoOfCells);
            }
#endif

            // Start-up phase needs an IBM Runge-Kutta time stepper
            RungeKuttaScheme = new IBMSplitRungeKutta(standardOperator, boundaryOperator, fieldsMap, boundaryParameterMap, speciesMap, timeStepConstraints);
        }
Beispiel #25
0
        /// <summary>
        /// common to more than one constructor
        /// </summary>
        protected void ConstructorCommon2(CoordinateMapping UnknownsMap, SpatialOperator rhsOperator, CoordinateMapping rhsDomainFields)
        {
            // verify input
            // ------------

            if (m_Mapping.Fields.Count != rhsOperator.CodomainVar.Count)
            {
                throw new ArgumentException("spatial differential operator and RHS obperator must have the same number of domain variables.", "rhsOperator");
            }

            // construct evaluator
            // -------------------

            m_rhsEvaluator = rhsOperator.GetEvaluatorEx(rhsDomainFields, null, UnknownsMap);
        }
Beispiel #26
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="spatialOp">Spatial operator</param>
        /// <param name="Fieldsmap"><see cref="CoordinateMapping"/> of the fields</param>
        /// <param name="Parameters">Optional parameter fields, can be null if <paramref name="spatialOp"/> contains no parameters. Must match the parameter field list of <paramref name="spatialOp"/>, see <see cref="BoSSS.Foundation.SpatialOperator.ParameterVar"/>
        /// </param>
        /// <param name="order">Order of the LTS algorithm</param>
        /// <param name="adaptive"><see cref="adaptive"/></param>
        /// <param name="sgrd">Sub-grid in which the local Adams-Bashforth step is evaluated</param>
        /// <remarks>Result of the local sub-step is saved in historyDGC, not directly in m_DGCoordinates</remarks>
        public ABevolve(SpatialOperator spatialOp, CoordinateMapping Fieldsmap, CoordinateMapping Parameters, int order, bool adaptive = false, SubGrid sgrd = null)
            : base(spatialOp, Fieldsmap, Parameters, order, null, sgrd)
        {
            this.ABSubGrid      = sgrd;
            HistoryDGCoordinate = new Queue <double[]>(order);
            RungeKuttaScheme    = null; // Instance of RungeKutta not needed
            jSub2jCell          = sgrd.SubgridIndex2LocalCellIndex;

            numOfEdges             = Fieldsmap.Fields.First().GridDat.iGeomEdges.Count;
            HistoryBoundaryFluxes  = new Queue <double[]>(order - 1);
            CompleteBoundaryFluxes = new double[numOfEdges * Fieldsmap.Count];

            historyTimePerCell = new Queue <double[]>(order - 1);

            this.adaptive = adaptive;
        }
Beispiel #27
0
        /// <summary>
        /// Constructor for (A)LTS with IBM
        /// </summary>
        public AdamsBashforthLTS(SpatialOperator spatialOp, CoordinateMapping Fieldsmap, CoordinateMapping Parameters, int order, int numOfClusters, bool IBM, IList <TimeStepConstraint> timeStepConstraints = null, SubGrid subGrid = null, bool fluxCorrection = true, int reclusteringInterval = 0)
            : base(spatialOp, Fieldsmap, Parameters, order, timeStepConstraints, subGrid)
        {
            this.gridData       = Fieldsmap.Fields.First().GridDat;
            this.fluxCorrection = fluxCorrection;

            if (reclusteringInterval != 0)
            {
                numberOfClustersInitial = numOfClusters;
                this.adaptive           = true;
            }
            this.reclusteringInterval = reclusteringInterval;

            // Add OnBeforeComputeChangeRate (AV) to start-up phase time stepper
            RungeKuttaScheme.OnBeforeComputeChangeRate += (t1, t2) => this.RaiseOnBeforeComputechangeRate(t1, t2);
        }
Beispiel #28
0
        /// <summary>
        /// Creates an instance of <see cref="IBMMassMatrixFactory"/> that is
        /// appropriate for the given <paramref name="mapping"/>
        /// </summary>
        /// <param name="mapping"></param>
        /// <returns></returns>
        public IBMMassMatrixFactory GetMassMatrixFactory(CoordinateMapping mapping)
        {
            if (MaMaFactCache_TrackerVersion != Tracker.VersionCnt)
            {
                MaMaFactCache.Clear();
                MaMaFactCache_TrackerVersion = Tracker.VersionCnt;
            }

            int[] degCodes = mapping.BasisS.Select(bs => bs.Degree).ToArray();
            if (!MaMaFactCache.ContainsKey(degCodes))
            {
                var mmf = new IBMMassMatrixFactory(this, mapping, Control.FluidSpeciesName, Control.LevelSetQuadratureOrder);
                MaMaFactCache.Add(degCodes, mmf);
            }

            return(MaMaFactCache[degCodes]);
        }
Beispiel #29
0
        //################# Hack for saving to database in every (A)LTS sub-step

        /// <summary>
        /// Standard constructor for the (adaptive) local time stepping algorithm
        /// </summary>
        /// <param name="spatialOp">Spatial operator</param>
        /// <param name="Fieldsmap">Coordinate mapping for the variable fields</param>
        /// <param name="Parameters">optional parameter fields, can be null if <paramref name="spatialOp"/> contains no parameters; must match the parameter field list of <paramref name="spatialOp"/>, see <see cref="BoSSS.Foundation.SpatialOperator.ParameterVar"/></param>
        /// <param name="order">LTS/AB order</param>
        /// <param name="numOfClusters">Amount of sub-grids/clusters to be used for LTS</param>
        /// <param name="timeStepConstraints">Time step constraints for later usage as metric</param>
        /// <param name="subGrid">Sub-grids, e.g., from previous time steps</param>
        /// <param name="fluxCorrection">Bool for triggering the fluss correction</param>
        /// <param name="reclusteringInterval">Interval for potential reclustering</param>
        /// <param name="saveToDBCallback">Hack for plotting all sub-steps</param>
        /// <remarks>Uses the k-Mean clustering, see <see cref="BoSSS.Solution.Utils.Kmeans"/>, to generate the element groups</remarks>
        public AdamsBashforthLTS(SpatialOperator spatialOp, CoordinateMapping Fieldsmap, CoordinateMapping Parameters, int order, int numOfClusters, IList <TimeStepConstraint> timeStepConstraints = null, SubGrid subGrid = null, bool fluxCorrection = true, int reclusteringInterval = 0, Action <TimestepNumber, double> saveToDBCallback = null, int initialTimestepNumber = 1)
            : base(spatialOp, Fieldsmap, Parameters, order, timeStepConstraints, subGrid)
        {
            if (reclusteringInterval != 0)
            {
                numberOfClustersInitial = numOfClusters;
                this.timestepNumber     = initialTimestepNumber;
                this.adaptive           = true;
            }

            // Add OnBeforeComputeChangeRate (AV) to start-up phase time stepper
            RungeKuttaScheme.OnBeforeComputeChangeRate += (t1, t2) => this.RaiseOnBeforeComputechangeRate(t1, t2);

            this.reclusteringInterval = reclusteringInterval;
            this.gridData             = Fieldsmap.Fields.First().GridDat;
            this.fluxCorrection       = fluxCorrection;

            NumberOfLocalTimeSteps = new List <int>(numOfClusters);

            clusterer         = new Clusterer(this.gridData, this.TimeStepConstraints);
            CurrentClustering = clusterer.CreateClustering(numOfClusters, this.SubGrid); // Might remove clusters when their centres are too close
            CurrentClustering = CalculateNumberOfLocalTS(CurrentClustering);             // Might remove clusters when time step sizes are too similar

            ABevolver = new ABevolve[CurrentClustering.NumberOfClusters];

            for (int i = 0; i < ABevolver.Length; i++)
            {
                ABevolver[i] = new ABevolve(spatialOp, Fieldsmap, Parameters, order, adaptive: this.adaptive, sgrd: CurrentClustering.Clusters[i]);
                ABevolver[i].OnBeforeComputeChangeRate += (t1, t2) => this.RaiseOnBeforeComputechangeRate(t1, t2);
            }

            GetBoundaryTopology();

#if DEBUG
            for (int i = 0; i < CurrentClustering.NumberOfClusters; i++)
            {
                Console.WriteLine("AB LTS Ctor: id=" + i + " -> sub-steps=" + NumberOfLocalTimeSteps[i] + " and elements=" + CurrentClustering.Clusters[i].GlobalNoOfCells);
            }
#endif

            // Saving time steps in subgrids
            //this.saveToDBCallback = saveToDBCallback;
        }
Beispiel #30
0
        /// <summary>
        /// ctor.
        /// </summary>
        public LinearSolver(ISparseSolver solver, SpatialOperator spatialOp, CoordinateMapping UnknownsMap)
        {
            // verify input
            // ------------
            if (!spatialOp.IsCommited)
            {
                throw new ArgumentException("operator must be committed first.", "spatialOp");
            }
            if (spatialOp.ContainsNonlinear)
            {
                throw new ArgumentException("spatial differential operator cannot contain nonlinear components for linear solver.", "spatialOp");
            }
            if (!spatialOp.ContainsLinear())
            {
                throw new ArgumentException("spatial differential operator seems to contain no components.", "spatialOp");
            }
            if (spatialOp.DomainVar.Count != spatialOp.CodomainVar.Count)
            {
                throw new ArgumentException("spatial differential operator must have the same number of domain and codomain variables.", "spatialOp");
            }

            if (UnknownsMap.Fields.Count != spatialOp.CodomainVar.Count)
            {
                throw new ArgumentException("the number of fields in the coordinate mapping must be equal to the number of domain/codomain variables of the spatial differential operator", "fields");
            }

            m_Mapping = UnknownsMap;
            m_Solver  = solver;

            // matrix assembly
            // ---------------
            MsrMatrix eM;

            {
                eM             = new MsrMatrix(m_Mapping);
                m_AffineOffset = new double[m_Mapping.LocalLength];

                //spatialOp.ComputeMatrixEx(m_Mapping, null, m_Mapping, eM, m_AffineOffset);
                spatialOp.GetMatrixBuilder(m_Mapping, null, m_Mapping).ComputeMatrix(eM, m_AffineOffset);
            }

            ConstructorCommon(eM);
        }