Exemple #1
0
		public void ChangeDimensionAndScale()
		{
			var grid = new Grid2D(new Size(2), Vector2D.Half);
			grid.Dimension = new Size(4);
			grid.GridScale = 2;
			Assert.AreEqual(2, grid.GridScale);
		}
Exemple #2
0
		public void InactivatingInactivatesLines()
		{
			var grid = new Grid2D(new Size(2), Vector2D.Half);
			grid.IsActive = false;
			foreach (var line in grid.lines)
				Assert.IsFalse(line.IsActive);
		}
        public static void Calculate(IntVector2 viewerLocation, int visionRange, Grid2D<bool> visibilityMap, IntSize2 mapSize,
			Func<IntVector2, bool> blockerDelegate)
        {
            visibilityMap.Clear();

            if (blockerDelegate(viewerLocation) == true)
                return;

            for (int y = -visionRange; y <= visionRange; ++y)
            {
                for (int x = -visionRange; x <= visionRange; ++x)
                {
                    var dst = viewerLocation + new IntVector2(x, y);

                    if (mapSize.Contains(dst) == false)
                    {
                        visibilityMap[x, y] = false;
                        continue;
                    }

                    bool vis = FindLos(viewerLocation, dst, blockerDelegate);
                    visibilityMap[x, y] = vis;
                }
            }
        }
Exemple #4
0
        /// <summary>
        ///     Returns the number of unique paths along the lattice lines of a 2d grid,
        ///     being able to only move down or to the right at each point.
        /// </summary>
        /// <param name="width">Width of the 2d grid.</param>
        /// <param name="height">Height of the 2d grid.</param>
        /// <returns>The number of paths through the lattice points of the grid.</returns>
        public static long NumLatticePaths2DDownAndRight(int width, int height)
        {
            var toCheck = new Dictionary<Grid2D, long>();
            toCheck.Add(new Grid2D {Width = width, Height = height}, 1);

            var pathLength = 0L;
            while (toCheck.Count != 0)
            {
                var gridInfo = toCheck.First();
                var grid = gridInfo.Key;
                var count = gridInfo.Value;

                toCheck.Remove(grid);

                if (grid.Width == 1)
                {
                    pathLength += count * (grid.Height + 1);
                }
                else if (grid.Height == 1)
                {
                    pathLength += count * (grid.Width + 1);
                }
                else
                {
                    var subGrid1 = new Grid2D {Width = grid.Width, Height = grid.Height - 1};
                    var subGrid2 = new Grid2D {Width = grid.Width - 1, Height = grid.Height};

                    toCheck.AddOrIncrement(subGrid1, count, count);
                    toCheck.AddOrIncrement(subGrid2, count, count);
                }
            }

            return pathLength;
        }
Exemple #5
0
		public void RenderQuadraticGridWithSizeOfOne()
		{
			var grid = new Grid2D(new Size(2), Vector2D.Half);
			AssertQuadraticGrid(2, grid);
			foreach (var line in grid.lines)
				Assert.IsTrue(line.IsActive);
		}
Exemple #6
0
            public bool Equals(Grid2D other)
            {
                // If parameter is null return false:
                if (other == null)
                {
                    return false;
                }

                return ((Width == other.Width) && (Height == other.Height))
                       || ((Width == other.Height) && (Height == other.Width));
            }
Exemple #7
0
        static void Main(string[] args)
        {
            Grid2D<int?> grid = new Grid2D<int?>(11, 11, 5, 5);

            var arr = IntPoint2.DiagonalSquareSpiral(new IntPoint2(0, 0), 5).ToArray();
            //var arr = IntPoint2.SquareSpiral(new IntPoint2(0, 0), 5).ToArray();

            Console.WriteLine("num values {0}", arr.Length);

            for (int i = 0; i < arr.Length; ++i)
            {
                var p = arr[i];

                if (grid[p].HasValue)
                    throw new Exception();

                grid[p] = i;
            }

            var sb = new StringBuilder();

            for (int y = 0; y < grid.Height; ++y)
            {
                sb.Clear();

                for (int x = 0; x < grid.Width; ++x)
                {
                    var v = grid[new IntPoint2(x, grid.Height - y - 1) - grid.Origin];

                    if (v.HasValue)
                        sb.AppendFormat("{0:000} ", v.Value);
                    else
                        sb.Append("... ");
                }

                Console.WriteLine(sb.ToString());
            }

            Console.ReadLine();
        }
        public MainWindow()
        {
            m_blockerMap = new Grid2D<bool>(m_visionRange * 2 + 1, m_visionRange * 2 + 1);
            m_visionMap = new Grid2D<bool>(m_visionRange * 2 + 1, m_visionRange * 2 + 1);
            m_visionMap.Origin = new IntVector2(m_visionRange, m_visionRange);

            m_viewerLocation = new IntPoint2(m_visionRange, m_visionRange);

            m_blockerMap.Origin = new IntVector2(m_visionRange, m_visionRange);

            //m_blockerMap[2, 1] = true;

            m_blockerMap[12, 8] = true;
            m_blockerMap[12, 9] = true;

            m_blockerMap[13, 0] = true;
            m_blockerMap[13, 1] = true;

            m_blockerMap[13, 4] = true;

            m_blockerMap[13, 7] = true;
            m_blockerMap[13, 8] = true;
            m_blockerMap[13, 9] = true;

            m_blockerMap[14, 7] = true;
            m_blockerMap[14, 8] = true;
            m_blockerMap[14, 9] = true;

            m_blockerMap[15, 7] = true;
            m_blockerMap[15, 8] = true;
            m_blockerMap[15, 9] = true;

            m_blockerMap.Origin = new IntVector2();

            m_tileSize = 16;

            InitializeComponent();
        }
		public static void Calculate(IntVector2 viewerLocation, int visionRange, Grid2D<bool> visibilityMap, IntSize2 mapSize,
			Func<IntVector2, bool> blockerDelegate)
		{
			visibilityMap.Clear();

			if (blockerDelegate(viewerLocation) == true)
				return;

			visibilityMap[0, 0] = true;

			SCRData data = new SCRData()
			{
				ViewerLocation = viewerLocation,
				VisionRange = visionRange,
				VisionRangeSquared = (visionRange + 1) * (visionRange + 1),	// +1 to get a bit bigger view area
				VisibilityMap = visibilityMap,
				MapSize = mapSize,
				BlockerDelegate = blockerDelegate,
			};

			for (int octant = 0; octant < 8; ++octant)
				Calculate(ref data, 1, octant, 0.0, 1.0, 1);
		}
Exemple #10
0
        public MainWindow()
        {
            m_blockerMap = new Grid2D<bool>(m_mapSize * 2 + 1, m_mapSize * 2 + 1);
            m_blockerMap.Origin = new IntVector2(m_mapSize, m_mapSize);

            m_visionMap = new Grid2D<bool>(m_visionRange * 2 + 1, m_visionRange * 2 + 1);
            m_visionMap.Origin = new IntVector2(m_visionRange, m_visionRange);

            m_viewerLocation = new IntVector2(m_mapSize, m_mapSize);

            m_blockerMap[-1, -4] = true;
            m_blockerMap[1, -4] = true;

            m_blockerMap[2, 8] = true;
            m_blockerMap[2, 9] = true;

            m_blockerMap[3, 0] = true;
            m_blockerMap[3, 1] = true;

            m_blockerMap[3, 4] = true;

            m_blockerMap[3, 7] = true;
            m_blockerMap[3, 8] = true;
            m_blockerMap[3, 9] = true;

            m_blockerMap[4, 7] = true;
            m_blockerMap[4, 8] = true;
            m_blockerMap[4, 9] = true;

            m_blockerMap[5, 7] = true;
            m_blockerMap[5, 8] = true;
            m_blockerMap[5, 9] = true;

            m_blockerMap.Origin = new IntVector2();

            InitializeComponent();
        }
Exemple #11
0
        public static void Calculate(IntVector2 viewerLocation, int visionRange, Grid2D<bool> visibilityMap, IntSize2 mapSize,
			Func<IntVector2, bool> blockerDelegate)
        {
            visibilityMap.Clear();

            if (blockerDelegate(viewerLocation) == true)
                return;

            var g = new IntGrid2(new IntVector2(), mapSize);
            g = g.Offset(-viewerLocation.X, -viewerLocation.Y);
            var vr = new IntVector2(visionRange, visionRange);
            g = g.Intersect(new IntGrid2(vr, -vr));

            int visionRangeSquared = (visionRange + 1) * (visionRange + 1);	// +1 to get a bit bigger view area

            foreach (var dst in g.Range())
            {
                if (dst.X * dst.X + dst.Y * dst.Y > visionRangeSquared)
                    continue;

                bool vis = FindLos(viewerLocation, dst, blockerDelegate);
                visibilityMap[dst] = vis;
            }
        }
        /// <summary>
        /// Testing of particle/wall interactions using a single particle
        /// </summary>
        public static FSI_Control Test_DryParticleCollision(string _DbPath = null, bool MeshRefine = false)
        {
            FSI_Control C = new FSI_Control {
                // basic database options
                // ======================

                DbPath             = _DbPath,
                savetodb           = _DbPath != null,
                saveperiod         = 1,
                ProjectName        = "ParticleCollisionTest",
                ProjectDescription = "Gravity"
            };

            C.SessionName = C.ProjectName;
            C.Tags.Add("with immersed boundary method");
            C.AdaptiveMeshRefinement = true;


            // DG degrees
            // ==========

            C.SetDGdegree(1);

            // grid and boundary conditions
            // ============================

            double[] Xnodes = GenericBlas.Linspace(-1, 1, 21);
            double[] Ynodes = GenericBlas.Linspace(-1, 1, 21);
            double   h      = Math.Min((Xnodes[1] - Xnodes[0]), (Ynodes[1] - Ynodes[0]));

            C.GridFunc = delegate {
                var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: false);
                grd.EdgeTagNames.Add(1, "Wall");
                grd.DefineEdgeTags(delegate(double[] X) {
                    byte et = 1;
                    return(et);
                });

                return(grd);
            };

            C.AddBoundaryValue("Wall");

            // Boundary values for level-set
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0.1 * 2 * Math.PI * -Math.Sin(Math.PI * 2 * 1 * t), (t) =>  0};
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0, (t) => 0 };

            // Initial Values
            // ==============

            // Coupling Properties
            C.Timestepper_LevelSetHandling = LevelSetHandling.Coupled_Once;


            // Fluid Properties
            C.PhysicalParameters.rho_A = 1;
            C.PhysicalParameters.mu_A  = 0.1;


            // Particles
            // =========

            C.pureDryCollisions = true;
            double             particleDensity = 1.0;
            ParticleMotionInit motion          = new ParticleMotionInit(C.gravity, particleDensity, C.pureDryCollisions);

            C.Particles.Add(new Particle_Sphere(motion, 0.15, new double[] { -0.6, +0.1 }, startAngl: 90.0, startTransVelocity: new double[] { 1, 0 }, startRotVelocity: 0));

            C.Particles.Add(new Particle_Sphere(motion, 0.15, new double[] { +0.6, -0.1 }, startAngl: 90.0, startTransVelocity: new double[] { -1, 0 }, startRotVelocity: 0));

            C.collisionModel = FSI_Control.CollisionModel.MomentumConservation;

            double V = 0;

            foreach (var p in C.Particles)
            {
                V = Math.Max(V, p.Motion.GetTranslationalVelocity(0).L2Norm());
            }

            if (V <= 0)
            {
                throw new ArithmeticException();
            }


            // Physical Parameters
            // ===================
            C.PhysicalParameters.IncludeConvection = true;


            // misc. solver options
            // ====================

            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.2;
            C.LevelSetSmoothing = false;
            C.LinearSolver.MaxSolverIterations    = 10;
            C.NonLinearSolver.MaxSolverIterations = 10;
            C.LinearSolver.NoOfMultigridLevels    = 1;
            C.AdaptiveMeshRefinement = MeshRefine;

            // Timestepping
            // ============

            //C.Timestepper_Mode = FSI_Control.TimesteppingMode.Splitting;
            C.Timestepper_Scheme = FSI_Solver.FSI_Control.TimesteppingScheme.BDF2;

            double dt = (h / V) * (MeshRefine ? 0.5 * 0.5 * 0.5 * 0.2 : 0.1);

            C.dtMax = dt;
            C.dtMin = dt;

            C.Endtime       = 100.0 / V;
            C.NoOfTimesteps = 200;

            // haben fertig...
            // ===============

            return(C);
        }
    protected void Awake()
    {
        gridSpace = transform.Find("GridSpace") as RectTransform;

        var size = 100;
        var grid = new Grid2D(size, size);

        grid[5, 5].Weight = float.MaxValue;
        grid[5, 6].Weight = float.MaxValue;
        grid[5, 7].Weight = float.MaxValue;
        grid[5, 8].Weight = float.MaxValue;
        grid[5, 9].Weight = float.MaxValue;
        grid[5, 10].Weight = float.MaxValue;
        grid[5, 11].Weight = float.MaxValue;
        grid[5, 12].Weight = float.MaxValue;
        grid[5, 13].Weight = float.MaxValue;
        grid[5, 14].Weight = float.MaxValue;

        grid[15, 5].Weight = float.MaxValue;
        grid[15, 6].Weight = float.MaxValue;
        grid[15, 7].Weight = float.MaxValue;
        grid[15, 8].Weight = float.MaxValue;
        grid[15, 9].Weight = float.MaxValue;
        grid[15, 10].Weight = float.MaxValue;
        grid[15, 11].Weight = float.MaxValue;
        grid[15, 12].Weight = float.MaxValue;
        grid[15, 13].Weight = float.MaxValue;
        grid[15, 14].Weight = float.MaxValue;

        grid[5, 15].Weight = float.MaxValue;
        grid[6, 15].Weight = float.MaxValue;
        grid[7, 15].Weight = float.MaxValue;
        grid[8, 15].Weight = float.MaxValue;
        grid[9, 15].Weight = float.MaxValue;
        grid[10, 15].Weight = float.MaxValue;
        grid[11, 15].Weight = float.MaxValue;
        grid[12, 15].Weight = float.MaxValue;
        grid[13, 15].Weight = float.MaxValue;
        grid[14, 15].Weight = float.MaxValue;
        grid[15, 15].Weight = float.MaxValue;

        //grid[5,  4].Weight = float.MaxValue;
        //grid[6,  4].Weight = float.MaxValue;
        //grid[7,  4].Weight = float.MaxValue;
        //grid[8,  4].Weight = float.MaxValue;
        //grid[9,  4].Weight = float.MaxValue;
        //grid[10, 4].Weight = float.MaxValue;
        //grid[11, 4].Weight = float.MaxValue;
        //grid[12, 4].Weight = float.MaxValue;
        //grid[13, 4].Weight = float.MaxValue;
        //grid[14, 4].Weight = float.MaxValue;
        //grid[15, 4].Weight = float.MaxValue;

        tiles = new Image[size, size];

        gridSpace.gameObject.AddComponent<Selectable>();

        Vector2 anchorMin, anchorMax;
        for (int i = 0; i < size; i++)
        {
            anchorMin.x = ((float)i / size);
            anchorMax.x = ((float)(i + 1) / size);

            for (int j = 0; j < size; j++)
            {
                anchorMin.y = ((float)j / size);
                anchorMax.y = ((float)(j + 1) / size);

                var obj = new GameObject(string.Format("Node [{0},{1}]", i, j));
                obj.transform.SetParent(gridSpace);

                var trans = obj.AddComponent<RectTransform>();
                trans.anchorMin = anchorMin;
                trans.anchorMax = anchorMax;
                trans.offsetMax = Vector2.zero;
                trans.offsetMin = Vector2.zero;
                trans.localScale = Vector3.one;

                var image = obj.AddComponent<Image>();
                image.color = (Color.blue * anchorMax.x + Color.red * (1 - anchorMax.x)) * anchorMax.y +
                              (Color.yellow * anchorMax.x + Color.green * (1 - anchorMax.x)) * (1 - anchorMax.y);

                var c = 1f / (grid[i, j].Weight);
                image.color = new Color(c, c, c, 1);

                tiles[i, j] = image;
            }
        }

        var search = new Fringe(Grid2D.HeuristicManhattan2);
        var searchA = new AStar(Grid2D.HeuristicManhattan2);
        var start = grid[14, 5];
        var end = grid[90, 90];

        tiles[start.X, start.Y].color = Color.blue + Color.white * .5f;
        tiles[end.X, end.Y].color = Color.yellow + Color.white * .5f;

        //StartCoroutine(search.AdvanceFrontier(start, end, () => {
        //    foreach (Node node in search.mappedNodes.Keys)
        //        if (node != start && node != end)
        //            tiles[node.X, node.Y].color = Color.red + Color.white * .5f;

        //    foreach (Node node in search.frontier)
        //        if (node != start && node != end)
        //            tiles[node.X, node.Y].color = Color.green + Color.white * .5f;

        //    return StartCoroutine(WaitKeyDown(KeyCode.None));
        //}));

        // astar

        var beforea = System.DateTime.Now;
        var pathA = searchA.FindPath(start, end);
        var aftera = System.DateTime.Now;

        Debug.Log((aftera - beforea).Milliseconds);

        //foreach (Node2D node in searchA.mappedNodes.Keys)
        //    if (node != start && node != end)
        //        tiles[node.X, node.Y].color = Color.red + Color.white * .5f;

        //foreach (Node2D node in searchA.frontier)
        //    if (node != start && node != end)
        //        tiles[node.X, node.Y].color = Color.green + Color.white * .5f;

        //foreach (Node2D node in pathA)
        //    if (node != start && node != end)
        //        tiles[node.X, node.Y].color = Color.magenta + Color.white * .5f;

        // fringe

        var before = System.DateTime.Now;
        var path = search.FindPath(start, end);
        var after = System.DateTime.Now;

        Debug.Log((after - before).Milliseconds);

        foreach (Node2D node in search.cache.Keys)
            if (node != start && node != end)
                tiles[node.X, node.Y].color = Color.red + Color.white * .5f;

        foreach (Node2D node in search.fringe)
            if (node != start && node != end)
                tiles[node.X, node.Y].color = Color.green + Color.white * .5f;

        foreach (Node2D node in path)
            if (node != start && node != end)
                tiles[node.X, node.Y].color = Color.magenta + Color.white * .5f;

        //StartCoroutine(search.FindInteractive(start, end, () =>
        //{
        //    foreach (Node2D node in search.cache.Keys)
        //        if (node != start && node != end)
        //            tiles[node.X, node.Y].color = Color.red + Color.white * .5f;

        //    foreach (Node2D node in search.fringe)
        //        if (node != start && node != end)
        //            tiles[node.X, node.Y].color = Color.green + Color.white * .5f;

        //    foreach (Node2D node in search.pathInteractive)
        //        if (node != start && node != end)
        //            tiles[node.X, node.Y].color = Color.magenta + Color.white * .5f;

        //    return StartCoroutine(WaitKeyDown(KeyCode.None));
        //}));
    }
Exemple #14
0
        /// <summary>
        /// Test on a Cartesian grid, with a sinusodial solution.
        /// </summary>
        /// <param name="Res">
        /// Grid resolution
        /// </param>
        /// <param name="Dim">
        /// spatial dimension
        /// </param>
        /// <param name="deg">
        /// polynomial degree
        /// </param>
        /// <param name="solver_name">
        /// Name of solver to use.
        /// </param>
        public static SipControl TestCartesian2(int Res, int Dim, SolverCodes solver_name = SolverCodes.exp_softpcg_mg, int deg = 3)
        {
            if (Dim != 2 && Dim != 3)
            {
                throw new ArgumentOutOfRangeException();
            }

            var R = new SipControl();

            R.ProjectName = "ipPoison/cartesian";
            R.savetodb    = false;

            R.FieldOptions.Add("T", new FieldOpts()
            {
                Degree = deg, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Tex", new FieldOpts()
            {
                Degree = deg * 2
            });
            R.InitialValues_Evaluators.Add("RHS", X => - Math.Sin(X[0]));
            R.InitialValues_Evaluators.Add("Tex", X => Math.Sin(X[0]));
            R.ExactSolution_provided = true;
            R.NoOfMultigridLevels    = int.MaxValue;
            R.solver_name            = solver_name;
            //R.TargetBlockSize = 100;

            R.TracingNamespaces = "BoSSS,ilPSP";

            R.GridFunc = delegate() {
                GridCommons grd = null;
                if (Dim == 2)
                {
                    double[] xNodes = GenericBlas.Linspace(0, 10, Res * 5 + 1);
                    double[] yNodes = GenericBlas.SinLinSpacing(-1, +1, 0.6, Res + 1);

                    grd = Grid2D.Cartesian2DGrid(xNodes, yNodes);
                }
                else if (Dim == 3)
                {
                    double[] xNodes = GenericBlas.Linspace(0, 10, Res * 5 + 1);
                    double[] yNodes = GenericBlas.SinLinSpacing(-1, +1, 0.6, Res + 1);
                    double[] zNodes = GenericBlas.SinLinSpacing(-1, +1, 0.6, Res + 1);

                    grd = Grid3D.Cartesian3DGrid(xNodes, yNodes, zNodes);
                }
                else
                {
                    throw new NotSupportedException();
                }
                grd.EdgeTagNames.Add(1, BoundaryType.Dirichlet.ToString());
                grd.EdgeTagNames.Add(2, BoundaryType.Neumann.ToString());
                grd.DefineEdgeTags(delegate(double[] X) {
                    byte ret;
                    if (Math.Abs(X[0] - 0.0) <= 1.0e-6)
                    {
                        ret = 1;
                    }
                    else
                    {
                        ret = 2;
                    }
                    return(ret);
                });

                return(grd);
            };

            R.AddBoundaryValue(BoundaryType.Dirichlet.ToString(), "T",
                               delegate(double[] X) {
                double x = X[0], y = X[1];

                if (Math.Abs(X[0] - (0.0)) < 1.0e-8)
                {
                    return(0.0);
                }

                throw new ArgumentOutOfRangeException();
            });

            R.AddBoundaryValue(BoundaryType.Neumann.ToString(), "T",
                               delegate(double[] X) {
                if (Math.Abs(X[1] - 1.0) < 1.0e-8 || Math.Abs(X[1] + 1.0) < 1.0e-8)     // y = -1, y = +1
                {
                    return(0);
                }

                if (X.Length > 2 && (Math.Abs(X[2] - 1.0) < 1.0e-8 || Math.Abs(X[2] + 1.0) < 1.0e-8))     // z = -1, z = +1
                {
                    return(0);
                }

                if (Math.Abs(X[0] - (+10.0)) < 1.0e-8)
                {
                    return(Math.Cos(10.0));
                }

                throw new ArgumentOutOfRangeException();
            });



            return(R);
        }
Exemple #15
0
        private static IBMControl ControlTemplate(int dgDegree, int divisions, double levelSetPosition)
        {
            IBMControl c = new IBMControl();

            c.savetodb = false;

            double vortexSpeed = 1.0;

            c.DomainType         = DomainTypes.StaticImmersedBoundary;
            c.ActiveOperators    = Operators.Convection;
            c.ConvectiveFluxType = ConvectiveFluxTypes.Rusanov;
            c.ExplicitScheme     = ExplicitSchemes.RungeKutta;
            c.ExplicitOrder      = 1;
            c.EquationOfState    = IdealGas.Air;

            c.MachNumber = 1.0 / Math.Sqrt(c.EquationOfState.HeatCapacityRatio);

            c.AddVariable(CompressibleVariables.Density, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.xComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.yComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Energy, dgDegree);
            c.AddVariable(IBMVariables.LevelSet, 1);

            c.GridFunc = delegate {
                int         noOfCellsPerDirection = (2 << divisions) * 10;
                GridCommons grid = Grid2D.Cartesian2DGrid(
                    GenericBlas.Linspace(-10.0, 10.0, noOfCellsPerDirection + 1),
                    GenericBlas.Linspace(-10.0, 10.0, noOfCellsPerDirection + 1));
                grid.EdgeTagNames.Add(1, "supersonicInlet");
                grid.DefineEdgeTags((Vector X) => 1);
                return(grid);
            };

            c.LevelSetBoundaryTag = "supersonicInlet";

            IsentropicVortexExactSolution solution = new IsentropicVortexExactSolution(c, vortexSpeed);

            c.InitialValues_Evaluators.Add(CompressibleVariables.Density, X => solution.rho()(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.xComponent, X => solution.u()(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.yComponent, X => solution.v()(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Pressure, X => solution.p()(X, 0.0));

            c.LevelSetFunction = (X, t) => X[1] - levelSetPosition;

            c.AddBoundaryValue("supersonicInlet", CompressibleVariables.Density, solution.rho());
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity[0], solution.u());
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity[1], solution.v());
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Pressure, solution.p());

            c.Queries.Add("L2ErrorDensity", IBMQueries.L2Error(CompressibleVariables.Density, solution.rho()));
            c.Queries.Add("L2ErrorPressure", IBMQueries.L2Error(state => state.Pressure, solution.p()));
            c.Queries.Add("L2ErrorEntropy", IBMQueries.L2Error(state => state.Entropy, (X, t) => 1.0));

            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.CFLFraction   = 0.2;
            c.Endtime       = 0.5;
            c.NoOfTimesteps = 100;

            return(c);
        }
Exemple #16
0
        public static XdgTimesteppingTestControl Heat1D(int degree               = 1,
                                                        int NoOfTimesteps        = 8,
                                                        InterfaceMode tsm        = InterfaceMode.MovingInterface,
                                                        int GridResolutionFactor = 1)
        {
            XdgTimesteppingTestControl R = new XdgTimesteppingTestControl();

            R.ProjectName = "XdgMassMatrixEvolution/Heat1D";
            R.savetodb    = false;
            //R.DbPath = @"\\fdyprime\userspace\kummer\BoSSS-db-XNSE";
            R.DbPath = null;

            // DG config
            // =========

            R.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("u", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vx", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vy", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });

            // grid
            // ====

            R.GridFunc = delegate() {
                double[] Xnodes = GenericBlas.Linspace(-1, 1, 18 * GridResolutionFactor + 1);
                double[] Ynodes = GenericBlas.Linspace(-1, 1, 3);
                var      grd    = Grid2D.Cartesian2DGrid(Xnodes, Ynodes);

                grd.EdgeTagNames.Add(1, "Dirichlet");
                grd.EdgeTagNames.Add(2, "Neumann");

                grd.DefineEdgeTags(delegate(double[] X) {
                    byte ret;
                    if (Math.Abs(X[0] - (-1)) <= 1.0e-8 || Math.Abs(X[0] - (+1)) <= 1.0e-8)
                    {
                        ret = 1;
                    }
                    else
                    {
                        ret = 2;
                    }
                    return(ret);
                });

                return(grd);
            };

            // exact solution
            // ==============

            double muA = 1;
            double muB = 10;
            Func <double, double> hA = t => 1 - t - t.Pow2();
            Func <double, double> hB = t => - .3125000000 * Math.Sin(.7853981635 + .7853981635 * t) * (t.Pow2() + t - 1.0) / Math.Sin(.2513274123 + .2513274123 * t);
            Func <double, double> oA = t => (0.6250000000e-1 * (16.0 * Math.Cos(.7853981635 + .7853981635 * t) * t.Pow2() * Math.Sin(.2513274123 + .2513274123 * t) - 5.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) * t.Pow2() + 4.045084972 * Math.Sin(.7853981635 + .7853981635 * t) * t.Pow2() + 16.0 * Math.Cos(.7853981635 + .7853981635 * t) * t * Math.Sin(.2513274123 + .2513274123 * t) - 5.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) * t + 4.045084972 * Math.Sin(.7853981635 + .7853981635 * t) * t - 16.0 * Math.Cos(.7853981635 + .7853981635 * t) * Math.Sin(.2513274123 + .2513274123 * t) + 5.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) - 4.045084972 * Math.Sin(.7853981635 + .7853981635 * t))) / Math.Sin(.2513274123 + .2513274123 * t);
            Func <double, double> oB = t => .2528178107 * Math.Sin(.7853981635 + .7853981635 * t) * (t.Pow2() + t - 1.0) / Math.Sin(.2513274123 + .2513274123 * t);


            Func <double, double, double> uA_Ex = (t, x) => oA(t) + hA(t) * Math.Cos(x * Math.PI * 0.5 * 10.0 / 8.0);
            Func <double, double, double> uB_Ex = (t, x) => oB(t) + hB(t) * Math.Cos(x * Math.PI / 5);
            Func <double, double, double> rhsA  = (t, x) => (0.6250000000e-1 * (-11.30973355 * Math.Sin(.7853981635 + .7853981635 * t) * t.Pow2() * Math.Sin(.2513274123 + .2513274123 * t) + 32.0 * Math.Cos(.7853981635 + .7853981635 * t) * t * Math.Sin(.2513274123 + .2513274123 * t) + 0.9424777962e-1 * Math.Cos(.7853981635 + .7853981635 * t) * t.Pow2() * Math.Cos(.2513274123 + .2513274123 * t) - 10.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) * t + 3.177002308 * Math.Cos(.7853981635 + .7853981635 * t) * t.Pow2() + 8.090169943 * Math.Sin(.7853981635 + .7853981635 * t) * t - 11.30973355 * Math.Sin(.7853981635 + .7853981635 * t) * t * Math.Sin(.2513274123 + .2513274123 * t) + 16.0 * Math.Cos(.7853981635 + .7853981635 * t) * Math.Sin(.2513274123 + .2513274123 * t) + 0.9424777962e-1 * Math.Cos(.7853981635 + .7853981635 * t) * t * Math.Cos(.2513274123 + .2513274123 * t) - 5.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) + 3.177002308 * Math.Cos(.7853981635 + .7853981635 * t) * t + 4.045084972 * Math.Sin(.7853981635 + .7853981635 * t) + 11.30973355 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Sin(.2513274123 + .2513274123 * t) - 0.9424777962e-1 * Math.Cos(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) - 3.177002308 * Math.Cos(.7853981635 + .7853981635 * t))) / Math.Sin(.2513274123 + .2513274123 * t) - (0.1570796327e-1 * (16.0 * Math.Cos(.7853981635 + .7853981635 * t) * t.Pow2() * Math.Sin(.2513274123 + .2513274123 * t) - 5.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) * t.Pow2() + 4.045084972 * Math.Sin(.7853981635 + .7853981635 * t) * t.Pow2() + 16.0 * Math.Cos(.7853981635 + .7853981635 * t) * t * Math.Sin(.2513274123 + .2513274123 * t) - 5.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) * t + 4.045084972 * Math.Sin(.7853981635 + .7853981635 * t) * t - 16.0 * Math.Cos(.7853981635 + .7853981635 * t) * Math.Sin(.2513274123 + .2513274123 * t) + 5.0 * Math.Sin(.7853981635 + .7853981635 * t) * Math.Cos(.2513274123 + .2513274123 * t) - 4.045084972 * Math.Sin(.7853981635 + .7853981635 * t))) * Math.Cos(.2513274123 + .2513274123 * t) / Math.Sin(.2513274123 + .2513274123 * t).Pow2() + (-2.0 * t - 1.0) * Math.Cos(1.963495409 * x) + (3.855314220 * (-1.0 * t.Pow2() - 1.0 * t + 1.0)) * Math.Cos(1.963495409 * x);
            Func <double, double, double> rhsB  = (t, x) => - 0.6354004615e-1 * Math.Sin(.7853981635 + .7853981635 * t) * (t.Pow2() + t - 1.0) * Math.Cos(.2513274123 + .2513274123 * t) / Math.Sin(.2513274123 + .2513274123 * t).Pow2() + .1985626442 * Math.Cos(.7853981635 + .7853981635 * t) * (t.Pow2() + t - 1.0) / Math.Sin(.2513274123 + .2513274123 * t) + .2528178107 * Math.Sin(.7853981635 + .7853981635 * t) * (2.0 * t + 1.0) / Math.Sin(.2513274123 + .2513274123 * t) + 0.7853981635e-1 * Math.Sin(.7853981635 + .7853981635 * t) * (t.Pow2() + t - 1.0) * Math.Cos(.6283185308 * x) * Math.Cos(.2513274123 + .2513274123 * t) / Math.Sin(.2513274123 + .2513274123 * t).Pow2() - .2454369261 * Math.Cos(.7853981635 + .7853981635 * t) * (t.Pow2() + t - 1.0) * Math.Cos(.6283185308 * x) / Math.Sin(.2513274123 + .2513274123 * t) - .3125000000 * Math.Sin(.7853981635 + .7853981635 * t) * (2.0 * t + 1.0) * Math.Cos(.6283185308 * x) / Math.Sin(.2513274123 + .2513274123 * t) - 1.233700550 * Math.Sin(.7853981635 + .7853981635 * t) * (t.Pow2() + t - 1.0) * Math.Cos(.6283185308 * x) / Math.Sin(.2513274123 + .2513274123 * t);

            R.uA_Ex = ((X, t) => uA_Ex(t, X[0]));
            R.uB_Ex = ((X, t) => uB_Ex(t, X[0]));

            R.rhsA = ((X, t) => rhsA(t, X[0]));
            R.rhsB = ((X, t) => rhsB(t, X[0]));

            R.Eq  = Equation.HeatEq;
            R.muA = muA;
            R.muB = muB;

            const double S = 0.4;

            R.S   = ((double[] X, double t) => S);
            R.Phi = ((double[] X, double t) => X[0].Pow2() - (0.4 + t * S).Pow2());

            R.InitialValues_Evaluators.Add("Phi", X => R.Phi(X, 0.0));
            R.InitialValues_Evaluators.Add("u#A", X => R.uA_Ex(X, 0));
            R.InitialValues_Evaluators.Add("u#B", X => R.uB_Ex(X, 0));

            // restart
            // =======

            //R.RestartInfo = new Tuple<Guid, Foundation.IO.TimestepNumber>(new Guid("aff36e92-1546-4fdf-a7bc-fbeff1e67f49"), 58);
            //R.InitialValues_Evaluators.Clear();

            // anderes zeugs
            // =============

            R.TimeSteppingScheme = TimeSteppingScheme.BDF4;
            R.InterfaceMode      = tsm;

            R.Endtime       = 0.4;
            R.NoOfTimesteps = NoOfTimesteps;
            R.dtFixed       = R.Endtime / R.NoOfTimesteps;

            R.AgglomerationThreshold = 0.1;

            // return
            // ======

            return(R);
        }
Exemple #17
0
        public static XdgTimesteppingTestControl Gerade(
            double angle = 5 *Math.PI / 180.0, int degree = 0, int GridResolutionFactor = 1, double t_offset = 0.0)
        {
            XdgTimesteppingTestControl R = new XdgTimesteppingTestControl();

            R.ProjectName = "XdgMassMatrixEvolution/Gerade";
            R.DbPath      = null;
            R.savetodb    = false;



            // DG degree
            // =========

            R.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 3,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("u", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vx", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vy", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });

            // grid
            // ====

            R.GridFunc = delegate() {
                var grd = Grid2D.Cartesian2DGrid(
                    GenericBlas.Linspace(-7, 7, 7 * GridResolutionFactor + 1),
                    GenericBlas.Linspace(-7, 7, 7 * GridResolutionFactor + 1)
                    );
                grd.EdgeTagNames.Add(1, "Inflow");
                grd.DefineEdgeTags(X => (byte)1);
                return(grd);
            };

            // level-set over time
            // ===================

            const double S = 0.9;

            R.S = ((double[] X, double t) => S);

            double Nx = Math.Cos(angle);
            double Ny = Math.Sin(angle);

            R.Phi = ((double[] X, double t) => (X[0] - Nx * S * (t + t_offset)) * Nx + (X[1] - Ny * S * (t + t_offset)) * Ny);

            // exact solution
            // ==============

            R.uA_Ex = ((X, t) => 0.8);
            R.uB_Ex = ((X, t) => 1.66);

            // Initial Values
            // ==============
            R.InitialValues_Evaluators.Add("Phi", X => R.Phi(X, 0.0));
            R.InitialValues_Evaluators.Add("Vx", X => Nx * S);
            R.InitialValues_Evaluators.Add("Vy", X => Ny * S);
            R.InitialValues_Evaluators.Add("u#A", X => R.uA_Ex(X, 0.0));
            R.InitialValues_Evaluators.Add("u#B", X => R.uB_Ex(X, 0.0));

            // Boundary values
            // ===============

            R.AddBoundaryCondition("Inflow", "u", (X, t) => 0.8);

            // Timestepping config
            // ===================

            R.NoOfTimesteps = 1;
            R.Endtime       = 2;
            R.dtFixed       = R.Endtime / R.NoOfTimesteps;


            R.TimeSteppingScheme     = TimeSteppingScheme.ExplicitEuler;
            R.InterfaceMode          = InterfaceMode.MovingInterface;
            R.AgglomerationThreshold = 0.1;

            // return
            // ======

            return(R);
        }
Exemple #18
0
        void Calc(IntVector2 viewerLocation, int visionRange, Grid2D<bool> visibilityMap, IntSize2 mapSize,
			Func<IntVector2, bool> blockerDelegate)
        {
            m_algoDel(viewerLocation, visionRange, visibilityMap, mapSize, blockerDelegate);
        }
Exemple #19
0
        static public IBM_Control PrecTest3dDegenhardt(int precNo = 4, int channel = 1, int name_newton = 1, int k = 3, int cells_x = 4, int cells_yz = 5, int re = 100, int ASparts = 3, int ASDepth = 2, int MGLevels = 3, int maxKrDim = 1000, int saveToDB = 1)
        {
            IBM_Control C = new IBM_Control();

            //in SolverFactory die DoF parts ändern

            //Possibilities:
            //channel = 0 --> channel 3D with sphere
            //channel = 1 --> channel 3D empty
            //channel = 2 --> channel 2D with cylinder
            //channel = 3 --> channel 2D empty

            string sessName = "";

            if (channel == 0)
            {
                sessName = "Channel_3D_Sphere";
            }
            else if (channel == 1)
            {
                sessName = "Channel_3D_empty";
            }
            else if (channel == 2)
            {
                sessName = "Channel_2D_Cylinder";
            }
            else if (channel == 3)
            {
                sessName = "Channel_2D_empty";
            }

            string precString = "";

            if (precNo == 0)
            {
                precString = "_noPrec";
            }
            if (precNo == 1)
            {
                precString = "_Schur";
            }
            if (precNo == 2)
            {
                precString = "_Simple";
            }
            if (precNo == 3)
            {
                precString = "_AS-1000";
            }
            if (precNo == 4)
            {
                precString = "_AS-5000";
            }
            if (precNo == 5)
            {
                precString = "_AS-10000";
            }
            if (precNo == 6)
            {
                precString = "_AS-MG";
            }
            if (precNo == 7)
            {
                precString = "_localPrec";
            }



            // basic database options
            // ======================
            // if (saveToDB == 1)
            // C.savetodb = true;
            //else
            //C.savetodb = false;

            C.savetodb = true;

            C.DbPath = @" \\dc1\scratch\Krause\Datenbank_Louis\degenhardt_final";
            //C.DbPath = @"\\hpccluster\hpccluster-scratch\krause\cluster_db";
            //C.DbPath = @"/home/oe11okuz/BoSSS_DB/Lichtenberg_DB";


            //string restartSession = "727da287-1b6a-463e-b7c9-7cc19093b5b3";
            //string restartGrid = "3f8f3445-46f1-47ed-ac0e-8f0260f64d8f";

            C.DynamicLoadBalancing_Period = 1;
            //C.DynamicLoadBalancing_CellCostEstimatorFactory = delegate (IApplication<AppControl> app, int noOfPerformanceClasses) {
            //    Console.WriteLine("i was called");
            //    int[] map = new int[] { 1, 5, 100 };
            //    return new StaticCellCostEstimator(map);
            //};



            if (name_newton == 1)
            {
                C.SessionName        = "Newton_" + sessName + precString + "_k" + k + "_x" + cells_x + "_yz" + cells_yz + "_re" + re + "_asp" + ASparts + "_asd" + ASDepth + "_mgl" + MGLevels + "_kr" + maxKrDim;
                C.ProjectDescription = "Newton_" + sessName + precString + "_k" + k + "_x" + cells_x + "_yz" + cells_yz + "_re" + re + "_asp" + ASparts + "_asd" + ASDepth + "_mgl" + MGLevels + "_kr" + maxKrDim;
            }
            else
            {
                C.SessionName        = "Picard_" + sessName + precString + "_k" + k + "_x" + cells_x + "_yz" + cells_yz + "_re" + re + "_asp" + ASparts + "_asd" + ASDepth + "_mgl" + MGLevels + "_kr" + maxKrDim;
                C.ProjectDescription = "Picard_" + sessName + precString + "_k" + k + "_x" + cells_x + "_yz" + cells_yz + "_re" + re + "_asp" + ASparts + "_asd" + ASDepth + "_mgl" + MGLevels + "_kr" + maxKrDim;
            }

            C.saveperiod = 1;
            //C.SessionName = "Sphere_k" + k + "_h" + h+"Re100";
            C.ProjectName = "iteration-study";
            C.Tags.Add("Prec param study");

            // Create Fields
            C.FieldOptions.Add("VelocityX", new FieldOpts()
            {
                Degree   = k,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("VelocityY", new FieldOpts()
            {
                Degree   = k,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Pressure", new FieldOpts()
            {
                Degree   = k - 1,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("PhiDG", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });

            if (channel == 0 || channel == 1) //3D
            {
                C.FieldOptions.Add("VelocityZ", new FieldOpts()
                {
                    Degree   = k,
                    SaveToDB = FieldOpts.SaveToDBOpt.TRUE
                });
            }



            #region Creates grid () and sets BC
            //// Create Grid
            Console.WriteLine("...generating grid");
            if (channel == 0 || channel == 1) //3D
            {
                #region grid 3D
                C.GridFunc = delegate
                {
                    // x-direction
                    var _xNodes = GenericBlas.Linspace(-0.5, 1.5, cells_x + 1);

                    // y-direction
                    var _yNodes = GenericBlas.Linspace(-0.5, 0.5, cells_yz + 1);

                    // z-direction
                    var _zNodes = GenericBlas.Linspace(-0.5, 0.5, cells_yz + 1);

                    // Cut Out
                    var grd = Grid3D.Cartesian3DGrid(_xNodes, _yNodes, _zNodes, CellType.Cube_Linear, false, true, false);

                    grd.EdgeTagNames.Add(1, "Velocity_inlet");
                    grd.EdgeTagNames.Add(2, "Wall");
                    grd.EdgeTagNames.Add(3, "Pressure_Outlet");

                    grd.DefineEdgeTags(delegate(double[] _X)
                    {
                        var X    = _X;
                        double x = X[0];
                        double y = X[1];
                        double z = X[2];

                        if (Math.Abs(x - (-0.5)) < 1.0e-6)
                        {
                            // inlet
                            return(1);
                        }

                        if (Math.Abs(x - (1.5)) < 1.0e-6)
                        {
                            // outlet
                            return(3);
                        }

                        if (Math.Abs(y - (-0.5)) < 1.0e-6)
                        {
                            // left
                            return(2);
                        }

                        if (Math.Abs(y - (0.5)) < 1.0e-6)
                        {
                            // right
                            return(2);
                        }

                        if (Math.Abs(z - (-0.5)) < 1.0e-6)
                        {
                            // top left
                            return(2);
                        }

                        if (Math.Abs(z - (0.5)) < 1.0e-6)
                        {
                            // top right
                            return(2);
                        }

                        throw new ArgumentOutOfRangeException();
                    });

                    return(grd);
                };
                #endregion
            }
            else
            {
                #region grid 2D
                C.GridFunc = delegate {
                    // x-direction
                    var _xnodes = GenericBlas.Linspace(-0.5, 1.5, cells_x + 1);
                    // y-direction
                    var _ynodes = GenericBlas.Linspace(-0.5, 0.5, cells_yz + 1);

                    var grd = Grid2D.Cartesian2DGrid(_xnodes, _ynodes, CellType.Square_Linear, false, false);

                    grd.EdgeTagNames.Add(1, "Velocity_inlet");
                    grd.EdgeTagNames.Add(2, "Wall");
                    grd.EdgeTagNames.Add(3, "Pressure_Outlet");

                    grd.DefineEdgeTags(delegate(double[] _X)
                    {
                        var X    = _X;
                        double x = X[0];
                        double y = X[1];

                        if (Math.Abs(x - (-0.5)) < 1.0e-6)
                        {
                            // inlet
                            return(1);
                        }

                        if (Math.Abs(x - (1.5)) < 1.0e-6)
                        {
                            // outlet
                            return(3);
                        }

                        if (Math.Abs(y - (-0.5)) < 1.0e-6)
                        {
                            // left
                            return(2);
                        }

                        if (Math.Abs(y - (0.5)) < 1.0e-6)
                        {
                            // right
                            return(2);
                        }

                        throw new ArgumentOutOfRangeException();
                    });

                    return(grd);
                };
                #endregion
            }
            #endregion


            // set initial conditions
            C.InitialValues_Evaluators.Add("Pressure", X => 0);
            C.InitialValues_Evaluators.Add("VelocityY", X => 0);

            if (channel == 0 | channel == 1)  //3D
            {
                //C.InitialValues_Evaluators.Add("VelocityX", X => 1 - 4 * (X[2] * X[2]));
                C.InitialValues_Evaluators.Add("VelocityX", X => 0);

                C.InitialValues_Evaluators.Add("VelocityZ", X => 0);
            }
            else
            {
                //C.InitialValues_Evaluators.Add("VelocityX", X => 1 - 4 * (X[1] * X[1]));
                C.InitialValues_Evaluators.Add("VelocityX", X => 0);
            }



            // Because its a sphere

            if (channel == 0)  //3D channel sphere
            {
                C.particleRadius = 0.1;
                C.InitialValues_Evaluators.Add("Phi", x => - (x[0]).Pow2() + -(x[1]).Pow2() + -(x[2]).Pow2() + C.particleRadius.Pow2());
            }
            else if (channel == 1 || channel == 3)  //3D channel empty or 2D channel empty
            {
                C.InitialValues_Evaluators.Add("Phi", x => - 1);
            }
            else if (channel == 2)   //2D channel cylinder
            {
                var radius = 0.1;
                C.particleRadius = radius;
                C.InitialValues_Evaluators.Add("Phi", X => - (X[0]).Pow2() + -(X[1]).Pow2() + radius.Pow2());
            }



            Console.WriteLine("...starting calculation of Preconditioning test with 3D Channel");
            if (name_newton == 1)
            {
                Console.WriteLine("newton_" + sessName + precString + "_k" + k + "_x" + cells_x + "_yz" + cells_yz + "_re" + re + "_asp" + ASparts + "_asd" + ASDepth + "_mgl" + MGLevels + "_kr" + maxKrDim);
            }
            else
            {
                Console.WriteLine("picard_" + sessName + precString + "_k" + k + "_x" + cells_x + "_yz" + cells_yz + "_re" + re + "_asp" + ASparts + "_asd" + ASDepth + "_mgl" + MGLevels + "_kr" + maxKrDim);
            }


            // Physical values
            C.PhysicalParameters.rho_A = 1;
            // 1/Re
            //C.PhysicalParameters.mu_A = 1.0 / 10.0;
            //C.PhysicalParameters.mu_A = 0.2 / re;

            C.PhysicalParameters.mu_A = 1.0 / re;

            // Boundary conditions
            C.AddBoundaryValue("Velocity_inlet", "VelocityY", (x, t) => 0);
            C.AddBoundaryValue("Wall");
            C.AddBoundaryValue("Pressure_Outlet");

            if (channel == 0 || channel == 1) //3D
            {
                C.AddBoundaryValue("Velocity_inlet", "VelocityX", (x, t) => 1 - 4 * (x[2] * x[2]));
            }
            else
            {
                C.AddBoundaryValue("Velocity_inlet", "VelocityX", (x, t) => 1 - 4 * (x[1] * x[1]));
            }



            // misc. solver options
            // ====================
            C.PhysicalParameters.IncludeConvection        = true;
            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.2;
            C.LevelSetSmoothing = false;
            //C.LinearSolver.MaxKrylovDim = 1000;
            C.LinearSolver.MaxKrylovDim            = maxKrDim;
            C.LinearSolver.MaxSolverIterations     = 100;
            C.LinearSolver.MinSolverIterations     = 1;
            C.NonLinearSolver.MaxSolverIterations  = 100;
            C.NonLinearSolver.MinSolverIterations  = 1;
            C.LinearSolver.ConvergenceCriterion    = 1E-5;
            C.NonLinearSolver.ConvergenceCriterion = 1E-5;
            //C.LinearSolver.ConvergenceCriterion = 1E-6;
            C.VelocityBlockPrecondMode = MultigridOperator.Mode.SymPart_DiagBlockEquilib_DropIndefinite;

            // Choosing the Preconditioner
            ISolverSmootherTemplate Prec;

            if (name_newton == 1)
            {
                C.NonLinearSolver.SolverCode = NonLinearSolverCode.NewtonGMRES;
            }
            else
            {
                C.NonLinearSolver.SolverCode = NonLinearSolverCode.PicardGMRES;
            }


            switch (precNo)
            {
            case 0:
            {
                Prec = null;
                break;
            }

            case 1:
            {
                C.LinearSolver.SolverCode = LinearSolverCode.exp_Schur;
                break;
            }

            case 2:
            {
                C.LinearSolver.SolverCode = LinearSolverCode.exp_Simple;
                break;
            }

            case 3:
            {
                C.LinearSolver.SolverCode          = LinearSolverCode.exp_AS_1000;
                C.LinearSolver.NoOfMultigridLevels = MGLevels;          // 3 // --> grobes MG am Ende nochmal
                break;
            }

            case 4:
            {
                C.LinearSolver.SolverCode          = LinearSolverCode.exp_AS_5000;
                C.LinearSolver.NoOfMultigridLevels = MGLevels;
                break;
            }

            case 5:
            {
                C.LinearSolver.SolverCode          = LinearSolverCode.exp_AS_10000;
                C.LinearSolver.NoOfMultigridLevels = MGLevels;
                break;
            }

            case 6:
            {
                //depth = 2,
                //   Depth = ASDepth,  //--> MG bei der Blockzerlegung --> Resultat ergibt die Blöcke zur Berechnung (kleine Blöcke--> schlecht)
                C.LinearSolver.SolverCode          = LinearSolverCode.exp_AS_MG;
                C.LinearSolver.NoOfMultigridLevels = MGLevels;
                break;
            }

            case 7:
            {
                C.LinearSolver.SolverCode          = LinearSolverCode.exp_localPrec;;
                C.LinearSolver.NoOfMultigridLevels = MGLevels;
                break;
            }

            case 8:
            {
                C.LinearSolver.NoOfMultigridLevels = 5;
                Prec = new Schwarz()
                {
                    m_BlockingStrategy = new Schwarz.METISBlockingStrategy()
                    {
                        //noofparts = 5,
                        NoOfPartsPerProcess = ASparts,
                    },
                    CoarseSolver = new ClassicMultigrid()
                    {
                        CoarserLevelSolver = new ClassicMultigrid()
                        {
                            CoarserLevelSolver = new ClassicMultigrid()
                            {
                                CoarserLevelSolver = new SparseSolver()
                                {
                                    WhichSolver = SparseSolver._whichSolver.MUMPS
                                },
                            },
                        },
                    },
                    Overlap = 1
                };
                break;
            }

            default:
            {
                Prec = new SchurPrecond()
                {
                    SchurOpt = SchurPrecond.SchurOptions.decoupledApprox
                };
                break;
            }
            }


            // For Newton
            //  C.LinearSolver.SolverCoder = Prec;

            ////For Picard
            //C.LinearSolver.SolverCoder = new SoftGMRES()
            //{
            //    MaxKrylovDim = C.LinearSolver.MaxKrylovDim,
            //    Precond_solver = Prec,
            //    m_Tolerance = 1E-6,
            //    m_MaxIterations = 50
            //};



            // Timestepping
            // ============
            C.Timestepper_Scheme = IBM_Control.TimesteppingScheme.BDF2;
            double dt = 1E20;
            C.dtFixed       = dt;
            C.dtMax         = dt;
            C.dtMin         = dt;
            C.Endtime       = 10000000;
            C.NoOfTimesteps = 1;


            return(C);
        }
Exemple #20
0
        /// <summary>
        /// 4:1 Contraction Flow
        /// </summary>
        static public RheologyControl Contraction(string path = null, int degree = 2, int GridLevel = 3)   //int kelem = 4
        {
            RheologyControl C = new RheologyControl();

            //Path für cluster
            //\\dc1\userspace\kikker\cluster\cluster_db\ContractionNYC

            //Path für lokale DB
            //C:\AnnesBoSSSdb\Contraction

            //Solver Options
            C.savetodb    = false;
            C.DbPath      = path;
            C.ProjectName = "Contraction";

            C.NonLinearSolver.SolverCode           = NonLinearSolverCode.Newton;
            C.NonLinearSolver.MaxSolverIterations  = 50;
            C.NonLinearSolver.MinSolverIterations  = 1;
            C.NonLinearSolver.ConvergenceCriterion = 1E-7;

            C.LinearSolver.SolverCode = LinearSolverCode.classic_mumps;
            //C.LinearSolver.SolverCode = LinearSolverCode.exp_Kcycle_schwarz;
            //C.NoOfMultigridLevels = 3;
            //C.LinearSolver.TargetBlockSize = 1000;
            C.LinearSolver.MaxSolverIterations  = 50;
            C.LinearSolver.MinSolverIterations  = 1;
            C.LinearSolver.ConvergenceCriterion = 1E-7;
            C.useFDJacobianForOperatorMatrix    = true;

            C.dt                 = 1E20;
            C.dtMax              = C.dt;
            C.dtMin              = C.dt;
            C.NoOfTimesteps      = 1;
            C.Timestepper_Scheme = RheologyControl.TimesteppingScheme.ImplicitEuler;

            C.ObjectiveParam = 1.0;

            //Debugging and Solver Analysis
            C.SkipSolveAndEvaluateResidual = false;
            C.SetInitialConditions         = true;
            C.SetInitialPressure           = true;
            C.SetParamsAnalyticalSol       = false;
            C.ComputeL2Error         = false;
            C.UsePerssonSensor       = true;
            C.SensorLimit            = 1e-4;
            C.AdaptiveMeshRefinement = true;
            C.RefinementLevel        = 4;
            //C.AMR_startUpSweeps = 1;
            C.UseArtificialDiffusion = false;

            //Physical Params
            C.Stokes = false;
            C.FixedStreamwisePeriodicBC = false;
            C.beta             = 1;// 0.11;
            C.Reynolds         = 1;
            C.Weissenberg      = 1.0;
            C.RaiseWeissenberg = true;
            C.giesekusfactor   = 0.0;

            //Grid Params
            double L      = 20;
            double H      = 2;
            int    cellsX = 40;
            int    cellsY = 8;

            //Penalties
            C.ViscousPenaltyScaling = 1;
            C.Penalty2        = 1;
            C.Penalty1[0]     = 0.0;
            C.Penalty1[1]     = 0.0;
            C.PresPenalty2    = 0;
            C.PresPenalty1[0] = 0.0;
            C.PresPenalty1[1] = 0.0;


            //Exact Solution Contraction

            // Set Initial Conditions
            Func <double[], double, double> VelocityXfunction = (X, t) => (1.0 - (X[1] * X[1]) / (2 * H));
            Func <double[], double, double> VelocityYfunction = (X, t) => (0.0);
            Func <double[], double, double> Pressurefunction  = (X, t) => 2 / (2 * H) * C.Reynolds * (L - X[0]);
            Func <double[], double, double> StressXXfunction  = (X, t) => 2 * C.Weissenberg * (1 - C.beta) * ((-2 / (2 * H) * X[1]) * (-2 / (2 * H) * X[1])); //aim Weissenberg!!!
            Func <double[], double, double> StressXYfunction  = (X, t) => (1 - C.beta) * (-2 / (2 * H) * X[1]);
            Func <double[], double, double> StressYYfunction  = (X, t) => (0.0);

            // Insert Exact Solution
            //C.ExSol_Velocity = new Func<double[], double, double>[] { VelocityXfunction, VelocityYfunction };
            //C.ExSol_Pressure = Pressurefunction;
            //C.ExSol_Stress = new Func<double[], double, double>[] { StressXXfunction, StressXYfunction, StressYYfunction };

            // Create Fields
            C.SetDGdegree(degree);

            // Create Grid

            double[] pt1a = new double[] { L / 2, H / 4 };
            double[] pt1b = new double[] { L, H };

            BoundingBox boundingBox1;

            boundingBox1 = new BoundingBox(pt1a, pt1b);

            double[] pt2a = new double[] { L / 2, -H / 4 };
            double[] pt2b = new double[] { L, -H };

            BoundingBox boundingBox2;

            boundingBox2 = new BoundingBox(pt2a, pt2b);

            BoundingBox[] BoundingBox = new BoundingBox[] { boundingBox1, boundingBox2 };

            C.GridFunc = delegate {
                // UNIFORM CARTESIAN GRID
                var _xNodes = GenericBlas.Linspace(0, L, cellsX + 1);
                var _yNodes = GenericBlas.Linspace(-H, H, (cellsY + 1));
                var grd     = Grid2D.Cartesian2DGrid(_xNodes, _yNodes, CellType.Square_Linear, C.FixedStreamwisePeriodicBC, false, null, boundingBox1, boundingBox2);
                //var grd = Grid2D.Cartesian2DGrid(_xNodes, _yNodes, CellType.Square_9, C.FixedStreamwisePeriodicBC, false, null, boundingBox1, boundingBox2);

                #region grids
                //var _xNodes = GenericBlas.Linspace(0, 10, cells2 + 1);// 10 * GridLevel + 1); //(10 * kelem + 1));
                //var _yNodes = GenericBlas.Linspace(-2, 2, (cells2 / 4) + 1);// (int)(2 * 1.5 * GridLevel) + GridLevel + 1); //(int)((2 * 1.5 * kelem) + kelem + 1));
                //var grd1 = Grid2D.Cartesian2DGrid(_xNodes, _yNodes, CellType.Square_Linear, C.FixedStreamwisePeriodicBC);

                //var _xNodes2 = GenericBlas.Linspace(10, 20, cells2 + 1);// 10 * GridLevel + 1); //(10 * kelem + 1));
                //var _yNodes2 = GenericBlas.Linspace(-0.5, 0.5, (cells2 / 4) + 1);// (int)(2 * 1.5 * GridLevel) + GridLevel + 1); //(int)((2 * 1.5 * kelem) + kelem + 1));
                //var grd2 = Grid2D.Cartesian2DGrid(_xNodes, _yNodes, CellType.Square_Linear, C.FixedStreamwisePeriodicBC);

                //var grdM = GridCommons.MergeLogically(grd1, grd2);
                //var grd = GridCommons.Seal(grdM);

                // NON_UNIFORM CARTESIAN GRID
                //var _xNodes1 = Grid1D.TanhSpacing(0, 10, (cells2 / 4) + 1, 2, false);
                //_xNodes1 = _xNodes1.GetSubVector(0, (_xNodes1.Length - 1));
                //var _xNodes2 = Grid1D.TanhSpacing(10, 20, (cells2 / 4) + 1, 2, true);
                //var _xNodes = ArrayTools.Cat(_xNodes1, _xNodes2);

                //var _yNodes1 = Grid1D.TanhSpacing(0, 0.5, (cells2 / 6) + 1, 1.5, false);
                //_yNodes1 = _yNodes1.GetSubVector(0, (_yNodes1.Length - 1));
                //var _yNodes2 = Grid1D.TanhSpacing(0.5, 2, (6 * cells2 / 16) + 1, 1.5, true);
                ////var _yNodes = ArrayTools.Cat(_yNodes1, _yNodes2);

                //var _yNodes3 = Grid1D.TanhSpacing(-0.5, 0, (cells2 / 6) + 1, 1.5, true);
                //_yNodes3 = _yNodes3.GetSubVector(0, (_yNodes3.Length - 1));
                //var _yNodes4 = Grid1D.TanhSpacing(-2, -0.5, (6 * cells2 / 16) + 1, 1.5, false);
                //_yNodes4 = _yNodes4.GetSubVector(0, (_yNodes4.Length - 1));
                //var _yNodes = ArrayTools.Cat(_yNodes4, _yNodes3, _yNodes1, _yNodes2);



                //// CARTESIAN GRID WITH HANGING NODES REFINEMENT
                //double[] ecke = new double[] { 10, 0.5 };

                //var boxA1_p1 = new double[2] { 0, -2 };
                //var boxA1_p2 = new double[2] { 10, 2 };
                //var boxA1 = new GridCommons.GridBox(boxA1_p1, boxA1_p2, 2 * 40, 2 * 16);

                //var boxA2_p1 = new double[2] { 9, -1 };
                //var boxA2_p2 = new double[2] { 10, 1 };
                ////var boxA2_p1 = new double[2] { ecke[0] - 0.5, ecke[1] - 0.25 };
                ////var boxA2_p2 = new double[2] { ecke[0], ecke[1] + 0.25 };
                //var boxA2 = new GridCommons.GridBox(boxA2_p1, boxA2_p2, 2 * 8, 2 * 16);

                //var boxA3_p1 = new double[2] { 9.5, -0.75 };
                //var boxA3_p2 = new double[2] { 10, 0.75 };
                //var boxA3 = new GridCommons.GridBox(boxA3_p1, boxA3_p2, 2 * 8, 2 * 24);

                //var grdA = Grid2D.HangingNodes2D(boxA1, boxA2, boxA3);

                //var boxB1_p1 = new double[2] { 10, -0.5 };
                //var boxB1_p2 = new double[2] { 20, 0.5 };
                //var boxB1 = new GridCommons.GridBox(boxB1_p1, boxB1_p2, 2 * 40, 2 * 4);

                //var boxB2_p1 = new double[2] { 10, -0.5 };
                //var boxB2_p2 = new double[2] { 11, 0.5 };
                //var boxB2 = new GridCommons.GridBox(boxB2_p1, boxB2_p2, 2 * 8, 2 * 8);

                //var boxB3_p1 = new double[2] { 10, -0.5 };
                //var boxB3_p2 = new double[2] { 10.5, 0.5 };
                //var boxB3 = new GridCommons.GridBox(boxB3_p1, boxB3_p2, 2 * 8, 2 * 16);

                //var grdB = Grid2D.HangingNodes2D(boxB1, boxB2, boxB3);

                //var grdM = GridCommons.MergeLogically(grdA, grdB);
                //var grd = GridCommons.Seal(grdM);

                // COARSE CARTESIAN GRID WITH HANGING NODES REFINEMENT - FOR DEBUGGING!
                //double[] ecke = new double[] { 10, 0.5 };

                //var boxA1_p1 = new double[2] { 0, -2 };
                //var boxA1_p2 = new double[2] { 10, 2 };
                //var boxA1 = new GridCommons.GridBox(boxA1_p1, boxA1_p2, 2 * 10, 2 * 4);

                //var boxA2_p1 = new double[2] { 9, -1 };
                //var boxA2_p2 = new double[2] { 10, 1 };
                ////var boxA2_p1 = new double[2] { ecke[0] - 0.5, ecke[1] - 0.25 };
                ////var boxA2_p2 = new double[2] { ecke[0], ecke[1] + 0.25 };
                //var boxA2 = new GridCommons.GridBox(boxA2_p1, boxA2_p2, 2 * 2, 2 * 4);

                ////var boxA3_p1 = new double[2] { 9.5, -0.75 };
                ////var boxA3_p2 = new double[2] { 10, 0.75 };
                ////var boxA3 = new GridCommons.GridBox(boxA3_p1, boxA3_p2, 2 * 4, 2 * 12);

                //var grdA = Grid2D.HangingNodes2D(boxA1, boxA2);

                //var boxB1_p1 = new double[2] { 10, -0.5 };
                //var boxB1_p2 = new double[2] { 20, 0.5 };
                //var boxB1 = new GridCommons.GridBox(boxB1_p1, boxB1_p2, 2 * 10, 2 * 1);

                //var boxB2_p1 = new double[2] { 10, -0.5 };
                //var boxB2_p2 = new double[2] { 11, 0.5 };
                //var boxB2 = new GridCommons.GridBox(boxB2_p1, boxB2_p2, 2 * 2, 2 * 2);

                ////var boxB3_p1 = new double[2] { 10, -0.5 };
                ////var boxB3_p2 = new double[2] { 10.5, 0.5 };
                ////var boxB3 = new GridCommons.GridBox(boxB3_p1, boxB3_p2, 2 * 4, 2 * 8);

                //var grdB = Grid2D.HangingNodes2D(boxB1, boxB2);

                //var grdM = GridCommons.MergeLogically(grdA, grdB);
                //var grd = GridCommons.Seal(grdM);
                #endregion

                if (!C.FixedStreamwisePeriodicBC)
                {
                    grd.EdgeTagNames.Add(1, "Velocity_inlet");
                    grd.EdgeTagNames.Add(4, "Pressure_Outlet");
                }


                grd.DefineEdgeTags(delegate(double[] _X) {
                    var X    = _X;
                    double x = X[0];
                    double y = X[1];

                    if (!C.FixedStreamwisePeriodicBC)
                    {
                        if (Math.Abs(x - (0)) < 1.0e-6)
                        {
                            //left
                            return("Velocity_inlet");
                        }

                        if (Math.Abs(x - (L)) < 1.0e-6)
                        {
                            //right
                            return("Pressure_Outlet");
                        }
                    }

                    if (Math.Abs(y - (-H)) < 1.0e-6 && x < L / 2 + 1.0e-6)
                    {
                        //bottom front
                        return("Wall_bottom");
                    }

                    //if (Math.Abs(y - (0)) < 1.0e-6)
                    //{
                    //    //symmetry line
                    //    return "Wall_bottom";
                    //}

                    if (Math.Abs(y - (+H)) < 1.0e-6 && x < L / 2 + 1.0e-6)
                    {
                        //top front
                        return("Wall_top");
                    }

                    if (Math.Abs(y - (-H / 4)) < 1.0e-6 && x > L / 2 - 1.0e-6)
                    {
                        // bottom back
                        return("Wall_bottom");
                    }

                    if (Math.Abs(y - (H / 4)) < 1.0e-6 && x > L / 2 - 1.0e-6)
                    {
                        // top back
                        return("Wall_top");
                    }

                    if (Math.Abs(x - (L / 2)) < 1.0e-6 && y < -H / 4 - 1.0e-6)
                    {
                        // bottom contraction
                        return("Wall_Contraction_bottom");
                    }

                    if (Math.Abs(x - (L / 2)) < 1.0e-6 && y > H / 4 - 1.0e-6)
                    {
                        //top contraction
                        return("Wall_Contraction_top");
                    }

                    throw new ArgumentOutOfRangeException("at x = " + x + "and y = " + y);
                });


                return(grd);
            };


            // Analytical Sol for Params
            //if (C.SetParamsAnalyticalSol == true) {
            //    C.VelFunctionU = X => VelocityXfunction(X, 0);
            //    C.VelFunctionV = X => VelocityYfunction(X, 0);
            //    C.PresFunction = X => Pressurefunction(X, 0);
            //}

            // Set Initial Conditions
            if (C.SetInitialConditions == true)
            {
                C.InitialValues_Evaluators.Add("VelocityX", X => VelocityXfunction(X, 0));
                C.InitialValues_Evaluators.Add("VelocityY", X => VelocityYfunction(X, 0));
                C.InitialValues_Evaluators.Add("StressXX", X => StressXXfunction(X, 0));
                C.InitialValues_Evaluators.Add("StressXY", X => StressXYfunction(X, 0));
                C.InitialValues_Evaluators.Add("StressYY", X => StressYYfunction(X, 0));

                if (C.SetInitialPressure == true || C.SkipSolveAndEvaluateResidual == true)
                {
                    C.InitialValues_Evaluators.Add("Pressure", X => Pressurefunction(X, 0));
                }
            }

            C.InitialValues_Evaluators.Add("Phi", X => - 1);

            // Set Boundary Conditions
            C.AddBoundaryValue("Wall_bottom");
            C.AddBoundaryValue("Wall_top");
            //C.AddBoundaryValue("Wall_Contraction_bottom");
            //C.AddBoundaryValue("Wall_Contraction_top");
            //C.AddBoundaryCondition("FreeSlip");


            if (!C.FixedStreamwisePeriodicBC)
            {
                C.AddBoundaryValue("Velocity_inlet", "VelocityX", VelocityXfunction);
                C.AddBoundaryValue("Velocity_inlet", "VelocityY", VelocityYfunction);
                C.AddBoundaryValue("Velocity_inlet", "StressXX", StressXXfunction);
                C.AddBoundaryValue("Velocity_inlet", "StressXY", StressXYfunction);
                C.AddBoundaryValue("Velocity_inlet", "StressYY", StressYYfunction);
                //C.AddBoundaryCondition("Velocity_inlet", "Pressure", Pressurefunction);
                C.AddBoundaryValue("Pressure_Outlet");
            }
            return(C);
        }
Exemple #21
0
        public static IBMControl IBMBump(int noOfCells, int dgDegree, int lsDegree, double CFL, double epsilonX = 0.0, double epsilonY = 0.0)
        {
            IBMControl c = new IBMControl();

            // Solver Settings
            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.Endtime       = 1000.0;
            c.CFLFraction   = CFL;
            c.NoOfTimesteps = 200000;

            c.PrintInterval      = 100;
            c.ResidualInterval   = 100;
            c.ResidualLoggerType = ResidualLoggerTypes.ChangeRate | ResidualLoggerTypes.Query;
            c.ResidualBasedTerminationCriteria.Add("changeRate_L2_abs_rhoE", 1E-8);

            //IBM Settings
            c.LevelSetBoundaryTag     = "adiabaticSlipWall";
            c.LevelSetQuadratureOrder = 2 * dgDegree;
            c.AgglomerationThreshold  = 0.3;

            // NEXT STEP: SET THIS BOOL TO FALSE AND JUST USE IN POSITIVE SUB_VOLUME;
            // THEN TRY BOUNDING BOX APPROACH?
            // WHY THE HELL DOES THIS CONFIGURATION FAIL!??!?!?!?
            c.CutCellQuadratureType             = XQuadFactoryHelper.MomentFittingVariants.Classic;
            c.SurfaceHMF_ProjectNodesToLevelSet = false;
            c.SurfaceHMF_RestrictNodes          = true;
            c.SurfaceHMF_UseGaussNodes          = false;
            c.VolumeHMF_NodeCountSafetyFactor   = 3.0;
            c.VolumeHMF_RestrictNodes           = true;
            c.VolumeHMF_UseGaussNodes           = false;

            //Guid restart = new Guid(" 60688cbc-707d-4777-98e6-d237796ec14c");
            //c.RestartInfo = new Tuple<Guid, BoSSS.Foundation.IO.TimestepNumber>(restart, -1);

            // Session Settings
            c.DbPath = @"\\fdyprime\userspace\kraemer-eis\FDY-Cluster\dbe_bump\";
            //c.DbPath = @"/home/kraemer/GaussianBump/dbev2/";
            c.savetodb           = true;
            c.saveperiod         = 20000;
            c.ProjectName        = "BoxHMF=" + c.CutCellQuadratureType + "_Ma=0.5_(" + 2 * noOfCells + "x" + noOfCells + ")_CFL=" + c.CFLFraction + "_lsQuadOrder=" + c.LevelSetQuadratureOrder + "_p=" + dgDegree + "_agg=" + c.AgglomerationThreshold + "_epsX=" + epsilonX + "_epsY=" + epsilonY;
            c.ProjectDescription = "GaussianBump with Ma=0.5";
            c.Tags.Add("Gaussian Bump");
            c.Tags.Add("IBM Test");

            // Solver Type
            c.DomainType         = DomainTypes.StaticImmersedBoundary;
            c.ActiveOperators    = Operators.Convection;
            c.ConvectiveFluxType = ConvectiveFluxTypes.OptimizedHLLC;

            // Time-Stepping Settings
            c.ExplicitScheme = ExplicitSchemes.RungeKutta;
            c.ExplicitOrder  = 1;

            //Material Settings
            c.EquationOfState = IdealGas.Air;



            // Primary CNSVariables
            c.AddVariable(CompressibleVariables.Density, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.xComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.yComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Energy, dgDegree);

            c.AddVariable(IBMVariables.LevelSet, lsDegree);



            // Grid

            //switch (noOfCells) {
            //    case 8:
            //        c.GridGuid = new Guid("7337e273-542f-4b97-b592-895ac3422621");
            //        break;
            //    case 16:
            //        c.GridGuid = new Guid("32e5a779-2aef-4ea2-bdef-b158ae785f01");
            //        break;
            //    case 32:
            //        c.GridGuid = new Guid("e96c9f83-3486-4e45-aa3b-9a436445a059");
            //        break;
            //    case 64:
            //        c.GridGuid = new Guid("a86f1b67-4fa3-48ed-b6df-dcea370eb2c0");
            //        break;
            //    default:
            //        throw new ArgumentException("Wrong Grid Input");
            //}



            c.GridFunc = delegate {
                double xBoundary = 12.0;
                double yBoundary = 12.0;
                double yBottom   = 0.0;

                double[] xnodes = GenericBlas.Linspace(-xBoundary, xBoundary, 2 * noOfCells + 1);

                //double ySplit = 6.0;
                //int ySplitNoOfCells = (int) (0.5*noOfCells);
                //double[] ynodes1 = GenericBlas.Linspace(yBottom, ySplit, ySplitNoOfCells + 1);
                //double[] ynodes2 = GenericBlas.Linspace(ySplit, yBoundary, noOfCells-ySplitNoOfCells + 1);
                //ynodes1 = ynodes1.GetSubVector(0, ynodes1.Length - 1);
                //double[] ynodes = ArrayTools.Cat(ynodes1, ynodes2);

                double[] ynodes = GenericBlas.Linspace(yBottom, yBoundary, noOfCells + 1);

                GridCommons grid = Grid2D.Cartesian2DGrid(
                    xnodes,
                    ynodes
                    );

                grid.EdgeTagNames.Add(1, "supersonicinlet");
                grid.EdgeTagNames.Add(2, "adiabaticSlipWall");

                Func <double[], byte> func = delegate(double[] x) {
                    if (Math.Abs(x[0] + xBoundary) < 1e-5)   // Inflow
                    {
                        return(1);
                    }
                    else if (Math.Abs(x[0] - xBoundary) < 1e-5)     // Outflow
                    {
                        return(1);
                    }
                    else if (Math.Abs(x[1] - yBoundary) < 1e-5)     // Top
                    {
                        return(1);
                    }
                    else     // Bottom
                    {
                        return(2);
                    }
                };
                grid.DefineEdgeTags(func);
                grid.Name = "IBM-[" + -xBoundary + "," + xBoundary + "]x[" + yBottom + "," + yBoundary + "]_Cells:(" + 2 * noOfCells + "x" + noOfCells + ")";
                return(grid);
            };

            // Functions
            Func <double[], double, double> rho      = (X, t) => 1.0;
            Func <double[], double, double> u0       = (X, t) => 1.0;
            Func <double[], double, double> u1       = (X, t) => 0.0;
            Func <double[], double, double> pressure = (X, t) => 2.8571428571428;

            //Initial Values
            c.InitialValues_Evaluators.Add(CompressibleVariables.Density, X => rho(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.xComponent, X => u0(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.yComponent, X => u1(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Pressure, X => pressure(X, 0.0));

            c.LevelSetFunction = (X, t) => X[1] - epsilonY - 0.01 - 0.3939 * Math.Exp(-0.5 * (X[0] - epsilonX) * (X[0] - epsilonX));

            //BoundaryConditions
            c.AddBoundaryValue("adiabaticSlipWall");
            c.AddBoundaryValue("supersonicInlet", CompressibleVariables.Density, rho);
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity.xComponent, u0);
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity.yComponent, u1);
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Pressure, pressure);


            // Queries

            c.Queries.Add("L2ErrorEntropy", IBMQueries.L2Error(state => state.Entropy, (X, t) => 2.8571428571428));
            return(c);
        }
Exemple #22
0
        public static IBMControl IBMBumpTest(int noOfCells, int dgDegree, int lsDegree, double CFL)
        {
            IBMControl c = new IBMControl();

            // Solver Settings
            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.Endtime       = 1000.0;
            c.CFLFraction   = CFL;
            c.NoOfTimesteps = 250000;

            c.PrintInterval      = 100;
            c.ResidualInterval   = 100;
            c.ResidualLoggerType = ResidualLoggerTypes.ChangeRate | ResidualLoggerTypes.Query;
            c.ResidualBasedTerminationCriteria.Add("changeRate_L2_abs_rhoE", 1E-8);

            //Guid restart = new Guid(" 60688cbc-707d-4777-98e6-d237796ec14c");
            //c.RestartInfo = new Tuple<Guid, BoSSS.Foundation.IO.TimestepNumber>(restart, -1);

            // Session Settings
            c.DbPath = @"C:\bosss_dbv2\GaussianBump_hhlr";
            //c.DbPath = @"\\fdyprime\userspace\kraemer-eis\FDY-Cluster\dbe_bump\";
            //c.DbPath = @"/home/kraemer/GaussianBump/dbev2/";
            c.savetodb           = true;
            c.saveperiod         = 100;
            c.ProjectName        = "TestsCutCells_(" + 2 * noOfCells + "x" + noOfCells + ")_CFL=" + c.CFLFraction + "_ls=" + lsDegree + "_p=" + dgDegree + "_agg=" + 0.53;
            c.ProjectDescription = "GaussianBump with Ma=0.5";
            c.Tags.Add("Gaussian Bump");
            c.Tags.Add("IBM Test");

            // Solver Type
            c.DomainType         = DomainTypes.StaticImmersedBoundary;
            c.ActiveOperators    = Operators.Convection;
            c.ConvectiveFluxType = ConvectiveFluxTypes.OptimizedHLLC;

            // Time-Stepping Settings
            c.ExplicitScheme = ExplicitSchemes.RungeKutta;
            c.ExplicitOrder  = 1;

            //Material Settings
            c.EquationOfState = IdealGas.Air;

            //IBM Settings
            c.LevelSetBoundaryTag     = "adiabaticSlipWall";
            c.LevelSetQuadratureOrder = 2 * lsDegree;
            c.CutCellQuadratureType   = XQuadFactoryHelper.MomentFittingVariants.Classic;
            c.AgglomerationThreshold  = 0.3;

            // Primary CNSVariables
            c.AddVariable(CompressibleVariables.Density, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.xComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.yComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Energy, dgDegree);

            c.AddVariable(IBMVariables.LevelSet, lsDegree);

            c.GridFunc = delegate {
                double xBoundary = 2.0625;
                double yBoundary = 2.0525;
                double yBottom   = -0.01;

                double[] xnodes = GenericBlas.Linspace(-xBoundary, xBoundary, 2 * noOfCells + 1);
                double[] ynodes = GenericBlas.Linspace(yBottom, yBoundary, noOfCells + 1);

                GridCommons grid = Grid2D.Cartesian2DGrid(
                    xnodes,
                    ynodes
                    );

                grid.EdgeTagNames.Add(1, "supersonicinlet");
                grid.EdgeTagNames.Add(2, "adiabaticSlipWall");

                Func <double[], byte> func = delegate(double[] x) {
                    if (Math.Abs(x[0] + xBoundary) < 1e-5)   // Inflow
                    {
                        return(1);
                    }
                    else if (Math.Abs(x[0] - xBoundary) < 1e-5)     // Outflow
                    {
                        return(1);
                    }
                    else if (Math.Abs(x[1] - yBoundary) < 1e-5)     // Top
                    {
                        return(1);
                    }
                    else     // Bottom
                    {
                        return(2);
                    }
                };
                grid.DefineEdgeTags(func);
                grid.Name = "IBM-[" + -xBoundary + "," + xBoundary + "]x[" + yBottom + "," + yBoundary + "]_Cells:(" + 2 * noOfCells + "x" + noOfCells + ")";
                return(grid);
            };

            // Functions
            Func <double[], double, double> rho      = (X, t) => 1.0;
            Func <double[], double, double> u0       = (X, t) => 1.0;
            Func <double[], double, double> u1       = (X, t) => 0.0;
            Func <double[], double, double> pressure = (X, t) => 2.8571428571428;

            //Initial Values
            c.InitialValues_Evaluators.Add(CompressibleVariables.Density, X => rho(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.xComponent, X => u0(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.yComponent, X => u1(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Pressure, X => pressure(X, 0.0));

            c.LevelSetFunction = (X, t) => X[1] - 0.3939 * Math.Exp(-0.5 * X[0] * X[0]);

            //BoundaryConditions
            c.AddBoundaryValue("adiabaticSlipWall");
            c.AddBoundaryValue("supersonicInlet", CompressibleVariables.Density, rho);
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity.xComponent, u0);
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity.yComponent, u1);
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Pressure, pressure);


            // Queries

            c.Queries.Add("L2ErrorEntropy", IBMQueries.L2Error(state => state.Entropy, (X, t) => 2.8571428571428));
            return(c);
        }
Exemple #23
0
        /// <summary>
        /// Gets the fields that have to be followed to come to a specific location.
        /// </summary>
        /// <returns>The path to location.</returns>
        /// <param name="fromLocation">the location from where to start path finding. Must be the same that was passed to PreparePathGrid()</param>
        /// <param name="toLocation">the location to find the path to starting at the unused location.</param>
        /// <param name="gameGrid">Game grid.</param>
        /// <param name="pathGrid">Populated path grid.</param>
        /// <param name="currentActiveTreasure">The current active treasre can always be stepped onto.</param>
        public static List<GridLocation> GetPathToLocation(GameFieldGrid gameGrid, Grid2D<int> pathGrid, GridLocation fromLocation, GridLocation toLocation, TreasureType currentActiveTreasure)
        {
            if(gameGrid == null)
            {
                throw new ArgumentNullException ("gameGrid");
            }

            if(pathGrid == null)
            {
                throw new ArgumentNullException ("pathGrid");
            }

            if(toLocation == null)
            {
                throw new ArgumentNullException ("toLocation");
            }

            // This will hold the reversed path.
            var path = new List<GridLocation> {
                // The target always belongs to the path.
                new GridLocation (toLocation.Row, toLocation.Column)
            };

            // Loop until the path has been completed.
            while(true)
            {
                // From the current target location check all possible moves. The algorithm works its way from the target to the start, so the path will be reversed.
                var checkLocations = AIHelpers.GetAccessibleAdjacentLocations (gameGrid, toLocation, currentActiveTreasure, fromLocation);

                // Loop the possible moves and remember the one with the lowest distance towards the start location.
                int lowestDistance = pathFindingMaxVal;
                GridLocation lowestLocation = null;

                foreach(var adjacentLocation in checkLocations)
                {
                    int distance = pathGrid.GetItem (adjacentLocation);
                    if(distance < lowestDistance)
                    {
                        lowestDistance = distance;
                        lowestLocation = adjacentLocation;
                        // The new target location is the lowest of the possible locations.
                        toLocation = lowestLocation;
                    }
                }

                if(lowestLocation != null)
                {
                    // Insert at 0 to have the path in the correct reversed order.
                    path.Insert(0, lowestLocation);
                    if(lowestLocation.Equals(fromLocation))
                    {
                        // Reached the start location.
                        break;
                    }
                }
                else
                {
                    // No lowest location found. Bail out.
                    break;
                }
            }

            return path;
        }
Exemple #24
0
		public void RenderQuadraticGridWithSizeOfTen()
		{
			var grid = new Grid2D(new Size(10), Vector2D.Half);
			AssertQuadraticGrid(10, grid);
		}
        public static FSI_Control Test_StickyTrap(int k = 2)
        {
            FSI_Control C = new FSI_Control();


            const double BaseSize = 1.0;


            // basic database options
            // ======================

            //C.DbPath = @"\\dc1\userspace\deriabina\bosss_db";
            C.savetodb           = false;
            C.saveperiod         = 1;
            C.ProjectName        = "ParticleCollisionTest";
            C.ProjectDescription = "Gravity";
            C.SessionName        = C.ProjectName;
            C.Tags.Add("with immersed boundary method");
            C.AdaptiveMeshRefinement = false;
            C.RefinementLevel        = 2;
            C.SessionName            = "fjkfjksdfhjk";

            C.pureDryCollisions = true;
            C.SetDGdegree(k);

            // grid and boundary conditions
            // ============================

            C.GridFunc = delegate
            {
                int q, r;

                q = 40;
                r = 40;

                double[] Xnodes = GenericBlas.Linspace(-1.5 * BaseSize, 1.5 * BaseSize, q + 1);
                double[] Ynodes = GenericBlas.Linspace(-1.5 * BaseSize, 1.5 * BaseSize, r + 1);

                var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: false);

                grd.EdgeTagNames.Add(1, "Wall_left");
                grd.EdgeTagNames.Add(2, "Wall_right");
                grd.EdgeTagNames.Add(3, "Pressure_Outlet_lower");
                grd.EdgeTagNames.Add(4, "Pressure_Outlet_upper");


                grd.DefineEdgeTags(delegate(double[] X)
                {
                    byte et = 0;
                    if (Math.Abs(X[0] - (-1.5 * BaseSize)) <= 1.0e-8)
                    {
                        et = 1;
                    }
                    if (Math.Abs(X[0] + (-1.5 * BaseSize)) <= 1.0e-8)
                    {
                        et = 2;
                    }

                    if (Math.Abs(X[1] - (-1.5 * BaseSize)) <= 1.0e-8)
                    {
                        et = 3;
                    }
                    if (Math.Abs(X[1] + (-1.5 * BaseSize)) <= 1.0e-8)
                    {
                        et = 4;
                    }


                    return(et);
                });

                Console.WriteLine("Cells:" + grd.NumberOfCells);

                return(grd);
            };

            C.GridPartType = GridPartType.Hilbert;

            C.AddBoundaryValue("Wall_left");
            C.AddBoundaryValue("Wall_right");
            C.AddBoundaryValue("Pressure_Outlet_lower");
            C.AddBoundaryValue("Pressure_Outlet_upper");

            // Boundary values for level-set
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0.1 * 2 * Math.PI * -Math.Sin(Math.PI * 2 * 1 * t), (t) =>  0};
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0, (t) => 0 };

            // Initial Values
            // ==============

            // Coupling Properties
            C.Timestepper_LevelSetHandling = LevelSetHandling.LieSplitting;

            // Fluid Properties
            C.PhysicalParameters.rho_A = 1.0;
            C.PhysicalParameters.mu_A  = 0.1;
            C.CoefficientOfRestitution = 0;
            C.gravity = new double[] { 0, -9.81 };

            // Particle Properties
            //C.PhysicalParameters.mu_B = 0.1;
            //C.particleMass = 1;
            double             particleDensity1 = 4.0;
            ParticleMotionInit motion1          = new ParticleMotionInit(C.gravity, particleDensity1, C.pureDryCollisions, true);
            double             particleDensity2 = 1.0;
            ParticleMotionInit motion2          = new ParticleMotionInit(C.gravity, particleDensity2, C.pureDryCollisions, true, true);

            C.Particles.Add(new Particle_Sphere(motion1, 0.18, new double[] { 0.0, 0.6 }));
            C.Particles.Add(new Particle_superEllipsoid(motion2, 0.4, 0.2, 4, new double[] { 0.45, 0 }, startAngl: 45));
            C.Particles.Add(new Particle_superEllipsoid(motion2, 0.4, 0.2, 4, new double[] { -0.45, 0 }, startAngl: -45));

            C.InitialValues_Evaluators.Add("VelocityX", X => 0);
            C.InitialValues_Evaluators.Add("VelocityY", X => 0);
            C.PhysicalParameters.IncludeConvection = false;

            // misc. solver options
            // ====================

            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.2;
            C.LevelSetSmoothing = false;
            C.LinearSolver.MaxSolverIterations    = 10;
            C.NonLinearSolver.MaxSolverIterations = 10;
            C.LinearSolver.NoOfMultigridLevels    = 1;
            C.hydrodynamicsConvergenceCriterion   = 1e-2;


            // Timestepping
            // ============

            //C.Timestepper_Mode = FSI_Control.TimesteppingMode.Splitting;
            C.Timestepper_Scheme = FSI_Solver.FSI_Control.TimesteppingScheme.BDF2;
            double dt = 1e-2;

            C.dtMax         = dt;
            C.dtMin         = dt;
            C.Endtime       = 10.0;
            C.NoOfTimesteps = 50;

            // haben fertig...
            // ===============

            return(C);
        }
Exemple #26
0
        private static CNSControl ShockTube_PartTest_Dynamic(int numOfCellsX, int numOfCellsY, int NoOfTimesteps, int NumberOfSubGrids, bool Repart, int RecInt)
        {
            CNSControl c = new CNSControl();

            int    dgDegree    = 0;
            double sensorLimit = 1e-4;
            bool   true1D      = false;
            bool   saveToDb    = false;

            //string dbPath = @"D:\Weber\BoSSS\test_db";
            string dbPath = null;

            c.DbPath   = dbPath;
            c.savetodb = dbPath != null && saveToDb;

            c.GridPartType = GridPartType.Hilbert;

            bool AV = false;

            double xMin = 0;
            double xMax = 1;
            double yMin = 0;
            double yMax = 1;

            c.ExplicitScheme = ExplicitSchemes.LTS;
            c.ExplicitOrder  = 1;

            c.NumberOfSubGrids     = NumberOfSubGrids;
            c.ReclusteringInterval = RecInt;
            c.FluxCorrection       = false;

            if (Repart)
            {
                // Add one balance constraint for each subgrid
                c.DynamicLoadBalancing_On             = true;
                c.DynamicLoadBalancing_CellClassifier = new LTSCellClassifier();
                c.DynamicLoadBalancing_CellCostEstimatorFactories.AddRange(LTSCellCostEstimator.Factory(c.NumberOfSubGrids));
                c.DynamicLoadBalancing_ImbalanceThreshold = 0.0;
                c.DynamicLoadBalancing_Period             = c.ReclusteringInterval;
            }

            c.GridFunc = delegate {
                double[] xNodes = GenericBlas.Linspace(xMin, xMax, numOfCellsX + 1);

                if (true1D)
                {
                    var grid = Grid1D.LineGrid(xNodes, periodic: false);
                    // Boundary conditions
                    grid.EdgeTagNames.Add(1, "AdiabaticSlipWall");

                    grid.DefineEdgeTags(delegate(double[] _X) {
                        return(1);
                    });
                    return(grid);
                }
                else
                {
                    double[] yNodes = GenericBlas.Linspace(yMin, yMax, numOfCellsY + 1);
                    var      grid   = Grid2D.Cartesian2DGrid(xNodes, yNodes, periodicX: false, periodicY: false);
                    // Boundary conditions
                    grid.EdgeTagNames.Add(1, "AdiabaticSlipWall");

                    grid.DefineEdgeTags(delegate(double[] _X) {
                        return(1);
                    });

                    return(grid);
                }
            };

            c.AddBoundaryValue("AdiabaticSlipWall");

            // Initial conditions
            c.InitialValues_Evaluators.Add(Variables.Density, delegate(double[] X) {
                double x = X[0];

                if (true1D == false)
                {
                    double y = X[1];
                }

                if (x <= 0.5)
                {
                    return(1.0);
                }
                else
                {
                    return(0.125);
                }
            });
            c.InitialValues_Evaluators.Add(Variables.Pressure, delegate(double[] X) {
                double x = X[0];

                if (true1D == false)
                {
                    double y = X[1];
                }

                if (x <= 0.5)
                {
                    return(1.0);
                }
                else
                {
                    return(0.1);
                }
            });
            c.InitialValues_Evaluators.Add(Variables.Velocity.xComponent, X => 0.0);
            if (true1D == false)
            {
                c.InitialValues_Evaluators.Add(Variables.Velocity.yComponent, X => 0.0);
            }


            if (AV)
            {
                c.ActiveOperators = Operators.Convection | Operators.ArtificialViscosity;
            }
            else
            {
                c.ActiveOperators = Operators.Convection;
            }
            c.ConvectiveFluxType = ConvectiveFluxTypes.OptimizedHLLC;

            // Shock-capturing
            double epsilon0 = 1.0;
            double kappa    = 0.5;

            if (AV)
            {
                Variable sensorVariable = Variables.Density;
                c.ShockSensor            = new PerssonSensor(sensorVariable, sensorLimit);
                c.ArtificialViscosityLaw = new SmoothedHeavisideArtificialViscosityLaw(c.ShockSensor, dgDegree, sensorLimit, epsilon0, kappa);
            }

            c.EquationOfState = IdealGas.Air;

            c.MachNumber     = 1.0 / Math.Sqrt(c.EquationOfState.HeatCapacityRatio);
            c.ReynoldsNumber = 1.0;
            c.PrandtlNumber  = 0.71;

            c.AddVariable(Variables.Density, dgDegree);
            c.AddVariable(Variables.Momentum.xComponent, dgDegree);
            c.AddVariable(Variables.Energy, dgDegree);
            if (true1D == false)
            {
                c.AddVariable(Variables.Momentum.yComponent, dgDegree);
                c.AddVariable(Variables.Velocity.yComponent, dgDegree);
                if (AV)
                {
                    c.AddVariable(Variables.ArtificialViscosity, 2);
                }
            }
            else
            {
                if (AV)
                {
                    c.AddVariable(Variables.ArtificialViscosity, 1);
                }
            }
            c.AddVariable(Variables.Velocity.xComponent, dgDegree);
            c.AddVariable(Variables.Pressure, dgDegree);
            c.AddVariable(Variables.Entropy, dgDegree);
            c.AddVariable(Variables.LocalMachNumber, dgDegree);
            c.AddVariable(Variables.Rank, 0);

            c.AddVariable(Variables.CFL, 0);
            c.AddVariable(Variables.CFLConvective, 0);
            if (AV)
            {
                c.AddVariable(Variables.CFLArtificialViscosity, 0);
            }
            if (c.ExplicitScheme.Equals(ExplicitSchemes.LTS))
            {
                c.AddVariable(Variables.LTSClusters, 0);
            }


            // Time config
            c.dtMin       = 0.0;
            c.dtMax       = 1.0;
            c.CFLFraction = 0.3;
            c.Endtime     = 0.25;
            //c.dtFixed = 1.5e-3;
            c.NoOfTimesteps = NoOfTimesteps;


            c.ProjectName = String.Format("Shock tube {0} Repartitioning", (Repart ? "with" : "without"));
            if (true1D)
            {
                c.SessionName = String.Format("{3}, 1D, dgDegree = {0}, noOfCellsX = {1}, sensorLimit = {2:0.00E-00}", dgDegree, numOfCellsX, sensorLimit, c.ProjectName);
            }
            else
            {
                c.SessionName = String.Format("{9}, 2D, dgDegree = {0}, noOfCellsX = {1}, noOfCellsX = {2}, sensorLimit = {3:0.00E-00}, CFLFraction = {4:0.00E-00}, ALTS {5}/{6}, GridPartType {7}, NoOfCores {8}", dgDegree, numOfCellsX, numOfCellsY, sensorLimit, c.CFLFraction, c.ExplicitOrder, c.NumberOfSubGrids, c.GridPartType, ilPSP.Environment.MPIEnv.MPI_Size, c.ProjectName);
            }
            return(c);
        }
        private static CNSControl ShockTubeToro1Template(int dgDegree, ExplicitSchemes explicitScheme, int explicitOrder, int noOfCells = 50, double gridStretching = 0.0, bool twoD = false)
        {
            double densityLeft           = 1.0;
            double velocityLeft          = 0.0;
            double pressureLeft          = 1.0;
            double densityRight          = 0.125;
            double velocityRight         = 0.0;
            double pressureRight         = 0.1;
            double discontinuityPosition = 0.5;

            CNSControl c = new CNSControl();

            c.DbPath = null;
            //c.DbPath = @"c:\bosss_db\";
            c.savetodb = false;

            c.ActiveOperators    = Operators.Convection;
            c.ConvectiveFluxType = ConvectiveFluxTypes.OptimizedHLLC;

            c.EquationOfState = IdealGas.Air;
            c.MachNumber      = 1.0 / Math.Sqrt(c.EquationOfState.HeatCapacityRatio);
            c.ReynoldsNumber  = 1.0;
            c.PrandtlNumber   = 0.71;

            c.ExplicitScheme = explicitScheme;
            c.ExplicitOrder  = explicitOrder;

            c.AddVariable(Variables.Density, dgDegree);
            c.AddVariable(Variables.Momentum.xComponent, dgDegree);
            c.AddVariable(Variables.Energy, dgDegree);
            c.AddVariable(Variables.Velocity.xComponent, dgDegree);
            c.AddVariable(Variables.Pressure, dgDegree);
            c.AddVariable(Variables.Rank, 0);

            c.GridFunc = delegate {
                double xMin = 0.0;
                double xMax = 1.0;
                double yMin = 0.0;
                double yMax = 1.0;

                double[] xNodes;
                double[] yNodes;
                if (gridStretching > 0.0)
                {
                    xNodes = Grid1D.TanhSpacing(xMin, xMax, noOfCells + 1, gridStretching, true);
                    yNodes = Grid1D.TanhSpacing(yMin, yMax, 1 + 1, gridStretching, true);
                }
                else
                {
                    xNodes = GenericBlas.Linspace(xMin, xMax, noOfCells + 1);
                    yNodes = GenericBlas.Linspace(yMin, yMax, 1 + 1);
                }

                GridCommons grid;
                if (twoD)
                {
                    grid = Grid2D.Cartesian2DGrid(xNodes, yNodes, periodicX: false, periodicY: false);
                }
                else
                {
                    grid = Grid1D.LineGrid(xNodes, periodic: false);
                }

                // Boundary conditions
                grid.EdgeTagNames.Add(1, "AdiabaticSlipWall");
                grid.DefineEdgeTags(delegate(double[] _X) {
                    return(1);
                });
                return(grid);
            };
            c.AddBoundaryValue("AdiabaticSlipWall");

            Material    material  = c.GetMaterial();
            StateVector stateLeft = StateVector.FromPrimitiveQuantities(
                material, densityLeft, new Vector(velocityLeft, 0.0, 0.0), pressureLeft);
            StateVector stateRight = StateVector.FromPrimitiveQuantities(
                material, densityRight, new Vector(velocityRight, 0.0, 0.0), pressureRight);

            c.InitialValues_Evaluators.Add(
                Variables.Density,
                X => stateLeft.Density + (stateRight.Density - stateLeft.Density) * (X[0] - discontinuityPosition).Heaviside());
            c.InitialValues_Evaluators.Add(
                Variables.Velocity.xComponent,
                X => stateLeft.Velocity.x + (stateRight.Velocity.x - stateLeft.Velocity.x) * (X[0] - discontinuityPosition).Heaviside());
            c.InitialValues_Evaluators.Add(
                Variables.Pressure,
                X => stateLeft.Pressure + (stateRight.Pressure - stateLeft.Pressure) * (X[0] - discontinuityPosition).Heaviside());
            if (twoD)
            {
                c.InitialValues_Evaluators.Add(Variables.Velocity.yComponent, X => 0);
            }

            if (!twoD)
            {
                var riemannSolver = new ExactRiemannSolver(stateLeft, stateRight, new Vector(1.0, 0.0, 0.0));
                riemannSolver.GetStarRegionValues(out double pStar, out double uStar);

                c.Queries.Add("L2ErrorDensity", QueryLibrary.L2Error(
                                  Variables.Density,
                                  (X, t) => riemannSolver.GetState(pStar, uStar, X[0] - discontinuityPosition, t).Density));
                c.Queries.Add("L2ErrorVelocity", QueryLibrary.L2Error(
                                  Variables.Velocity.xComponent,
                                  (X, t) => riemannSolver.GetState(pStar, uStar, X[0] - discontinuityPosition, t).Velocity.x));
                c.Queries.Add("L2ErrorPressure", QueryLibrary.L2Error(
                                  Variables.Pressure,
                                  (X, t) => riemannSolver.GetState(pStar, uStar, X[0] - discontinuityPosition, t).Pressure));
            }

            c.dtMin = 0.0;
            c.dtMax = 1.0;
            //c.dtFixed = 1.0e-6;
            c.CFLFraction   = 0.1;
            c.Endtime       = 0.2;
            c.NoOfTimesteps = int.MaxValue;

            // Use METIS since ParMETIS is not installed on build server
            c.GridPartType = GridPartType.METIS;

            return(c);
        }
Exemple #28
0
        /// <summary>
        /// 2D Manufactured Solution for the compressible Navier-Stokes equations with variable Mach number
        /// and constant viscosity. It is based on primitive variables.
        /// </summary>
        /// <param name="noOfCellsPerDirection"></param>
        /// <param name="dgDegree"></param>
        /// <param name="dbPath"></param>
        /// <returns></returns>
        public static CNSControl Gassner2D_primitive(int noOfCellsPerDirection, int dgDegree, string dbPath = @"c:\bosss_dbv2\exp")
        {
            CNSControl c = new CNSControl();

            // Session Settings
            c.DbPath             = dbPath;
            c.savetodb           = true;
            c.saveperiod         = 10000;
            c.ProjectDescription = "Manufactured Solution with primitive variables. Based on Gassner et al. (2008)";
            c.Tags.Add("MMS");
            c.Tags.Add("Diffusive Test");

            // Solver Type
            c.ActiveOperators    = Operators.Convection | Operators.Diffusion | Operators.CustomSource;
            c.ConvectiveFluxType = ConvectiveFluxTypes.OptimizedHLLC;
            c.DiffusiveFluxType  = DiffusiveFluxTypes.OptimizedSIPG;
            c.SIPGPenaltyScaling = 1.3;

            // Solver Settings
            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.Endtime       = 0.1;
            c.CFLFraction   = 0.25;
            c.NoOfTimesteps = 2000;

            c.PrintInterval      = 100;
            c.ResidualInterval   = 1000;
            c.ResidualLoggerType = ResidualLoggerTypes.ChangeRate | ResidualLoggerTypes.Query;

            // Time-Stepping Settings
            c.ExplicitScheme = ExplicitSchemes.RungeKutta;
            c.ExplicitOrder  = 4;


            //Material Settings
            c.EquationOfState = IdealGas.Air;
            c.ViscosityLaw    = new ConstantViscosity();
            c.PrandtlNumber   = 0.72;
            c.ReynoldsNumber  = 1.0e6;
            c.MachNumber      = 1 / Math.Sqrt(1.4);

            // Primary CNSVariables
            c.AddVariable(CompressibleVariables.Density, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.xComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.yComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Energy, dgDegree);
            // Parameters
            c.AddVariable(CNSVariables.Velocity.xComponent, dgDegree);
            c.AddVariable(CNSVariables.Velocity.yComponent, dgDegree);
            c.AddVariable(CNSVariables.Pressure, dgDegree);
            c.AddVariable(CNSVariables.LocalMachNumber, dgDegree);


            // Grid
            c.GridFunc = delegate {
                double[] nodes = GenericBlas.Linspace(0.0, 1.0, noOfCellsPerDirection + 1);
                var      grid  = Grid2D.Cartesian2DGrid(nodes, nodes, periodicX: true, periodicY: true);
                return(grid);
            };

            // Functions

            double b           = 0.25;
            double c1          = 2.0;
            double k           = 2.0 * Math.PI;
            double omega       = 20.0 * Math.PI;
            double gamma       = c.EquationOfState.HeatCapacityRatio;
            double MachScaling = gamma * c.MachNumber * c.MachNumber;

            double PressureScale = 1.0;

            Func <double[], double, double> rho      = (X, t) => c1 + b * Math.Sin(k * (X[0] + X[1]) - omega * t);
            Func <double[], double, double> u0       = (X, t) => 1.0;
            Func <double[], double, double> u1       = (X, t) => 1.0;
            Func <double[], double, double> pressure = (X, t) => rho(X, t) / PressureScale;

            Func <double[], double, double> m0   = (X, t) => u0(X, t) * rho(X, t);
            Func <double[], double, double> m1   = (X, t) => u1(X, t) * rho(X, t);
            Func <double[], double, double> rhoE = (X, t) => pressure(X, t) / (gamma - 1) + 0.5 * MachScaling * rho(X, t) * (u0(X, t) * u0(X, t) + u1(X, t) * u1(X, t));

            //Initial Values
            //c.InitialValues.Add(Variables.Density, X => rho(X, 0.0));
            //c.InitialValues.Add(Variables.Momentum.xComponent, X => m0(X, 0.0));
            //c.InitialValues.Add(Variables.Momentum.yComponent, X => m1(X, 0.0));
            //c.InitialValues.Add(Variables.Energy, X => rhoE(X, 0.0));

            //c.InitialValues.Add(CNSVariables.Velocity.xComponent, X => u0(X, 0.0));
            //c.InitialValues.Add(CNSVariables.Velocity.yComponent, X => u1(X, 0.0));
            //c.InitialValues.Add(CNSVariables.Pressure, X => pressure(X, 0.0));


            //MMS Sources

            c.CustomContinuitySources.Add(map => new AdHocSourceTerm(map,
                                                                     (X, t, state) => - b * Math.Cos(k * (X[0] + X[1]) - omega * t) * (-omega + 2.0 * k)));
            c.CustomMomentumSources[0].Add(map => new AdHocSourceTerm(map,
                                                                      (X, t, state) => - b * Math.Cos(k * (X[0] + X[1]) - omega * t) * (-omega + 2.0 * k + k / (PressureScale * MachScaling))
                                                                      ));
            c.CustomMomentumSources[1].Add(map => new AdHocSourceTerm(map,
                                                                      (X, t, state) => - b * Math.Cos(k * (X[0] + X[1]) - omega * t) * (-omega + 2.0 * k + k / (PressureScale * MachScaling))
                                                                      ));
            c.CustomEnergySources.Add(map => new AdHocSourceTerm(map,
                                                                 (X, t, state) => - b * Math.Cos(k * (X[0] + X[1]) - omega * t) * (-omega / (PressureScale * (gamma - 1.0)) - MachScaling * omega + 2.0 * k / (PressureScale * (gamma - 1.0)) + 1.0 + MachScaling + 2.0 + k / PressureScale)
                                                                 ));


            // Queries
            int QueryDegree = 10;

            c.Queries.Add("densityError", QueryLibrary.L2Error(CompressibleVariables.Density, rho, QueryDegree));
            c.Queries.Add("momentum0Error", QueryLibrary.L2Error(CompressibleVariables.Momentum.xComponent, m0, QueryDegree));
            c.Queries.Add("energyError", QueryLibrary.L2Error(CompressibleVariables.Energy, rhoE, QueryDegree));
            c.Queries.Add("velocity0Error", QueryLibrary.L2Error(CNSVariables.Velocity.xComponent, u0, QueryDegree));

            c.ProjectName = "MMS-Gassner2D_Mach=" + c.MachNumber + "_Flux=" + c.DiffusiveFluxType + "_h=1/" + noOfCellsPerDirection + "_p=" + dgDegree;


            return(c);
        }
Exemple #29
0
		private static void AssertQuadraticGrid(int expectedDimension, Grid2D grid)
		{
			Assert.AreEqual(new Size(expectedDimension, expectedDimension), grid.Dimension);
		}
        public static FSI_Control Test2ActiveParticle(string _DbPath = null, int k = 2, double VelXBase = 0.0, double stressM = 100)
        {
            FSI_Control C = new FSI_Control();


            const double BaseSize = 1.0;

            //C.Paramstudy_CaseIdentification = new Tuple<string, object>[] {
            //                    new Tuple<string,object>("k", k),
            //                };

            // k = i;

            // basic database options
            // ======================
            //C.DbPath = @"\\hpccluster\hpccluster-scratch\deussen\cluster_db\active_particle_test";
            C.savetodb           = false;
            C.saveperiod         = 5;
            C.ProjectName        = "Active2ParticleTest";
            C.ProjectDescription = "Active2";
            C.SessionName        = C.ProjectName;
            C.Tags.Add("with immersed boundary method");
            C.AdaptiveMeshRefinement = true;
            C.RefinementLevel        = 2;


            // DG degrees
            // ==========

            C.FieldOptions.Add("VelocityX", new FieldOpts()
            {
                Degree   = k,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("VelocityY", new FieldOpts()
            {
                Degree   = k,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Pressure", new FieldOpts()
            {
                Degree   = k - 1,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("PhiDG", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });


            // grid and boundary conditions
            // ============================

            C.GridFunc = delegate {
                int q = new int();
                int r = new int();

                switch (99)
                {
                case 1:
                    q = 60;
                    r = 178;
                    break;

                case 2:
                    q = 41;
                    r = 121;
                    break;

                case 3:
                    q = 31;
                    r = 91;
                    break;

                case 99:
                    q = 80;
                    r = 25;
                    break;

                default:

                    throw new ApplicationException();
                }

                //q = 16;
                //r = 46;

                double[] Xnodes = GenericBlas.Linspace(-5 * BaseSize, 15 * BaseSize, q); //k1: 71; k2:41; k3: 31
                double[] Ynodes = GenericBlas.Linspace(-3 * BaseSize, 3 * BaseSize, r);  //k1: 211; k2:121; k3: 91

                var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: false);

                grd.EdgeTagNames.Add(1, "Velocity_Inlet_left");
                grd.EdgeTagNames.Add(2, "Velocity_Inlet_right");
                grd.EdgeTagNames.Add(3, "Pressure_Outlet_lower");
                grd.EdgeTagNames.Add(4, "Pressure_Outlet_upper");


                grd.DefineEdgeTags(delegate(double[] X) {
                    byte et = 0;
                    if (Math.Abs(X[0] - (-5 * BaseSize)) <= 1.0e-8)
                    {
                        et = 1;
                    }
                    if (Math.Abs(X[0] + (-15 * BaseSize)) <= 1.0e-8)
                    {
                        et = 2;
                    }
                    if (Math.Abs(X[1] - (-3 * BaseSize)) <= 1.0e-8)
                    {
                        et = 3;
                    }
                    if (Math.Abs(X[1] + (-3 * BaseSize)) <= 1.0e-8)
                    {
                        et = 4;
                    }

                    Debug.Assert(et != 0);
                    return(et);
                });

                Console.WriteLine("Cells:" + grd.NumberOfCells);

                return(grd);
            };



            C.AddBoundaryValue("Velocity_Inlet_left", "VelocityX", X => 0.0);
            C.AddBoundaryValue("Velocity_Inlet_right", "VelocityX", X => 0.0);
            C.AddBoundaryValue("Pressure_Outlet_lower");
            C.AddBoundaryValue("Pressure_Outlet_upper");

            // Boundary values for level-set
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0.1 * 2 * Math.PI * -Math.Sin(Math.PI * 2 * 1 * t), (t) =>  0};
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0, (t) => 0 };

            // Initial Values
            // ==============

            // Coupling Properties
            C.Timestepper_LevelSetHandling = LevelSetHandling.Coupled_Once;
            C.includeRotation    = true;
            C.includeTranslation = true;

            // Fluid Properties
            C.PhysicalParameters.rho_A    = 1.0;
            C.PhysicalParameters.mu_A     = 0.25;
            C.PhysicalParameters.Material = true;

            //Defining particles
            C.Particles = new List <Particle>();
            int numOfParticles = 2;

            for (int d = 0; d < numOfParticles; d++)
            {
                C.Particles.Add(new Particle(2, 4, new double[] { 10.0 * d, 0.0 }, startAngl: d *180.0, shape: Particle.ParticleShape.elliptic)
                {
                    radius_P           = 1,
                    rho_P              = 1.0,
                    active_P           = true,
                    stress_magnitude_P = stressM,
                    thickness_P        = 1.0,
                    length_P           = 3.0
                });
            }
            //Define level-set
            Func <double[], double, double> phiComplete = delegate(double[] X, double t)
            {
                int    exp = C.Particles.Count - 1;
                double ret = Math.Pow(-1, exp);
                for (int i = 0; i < C.Particles.Count; i++)
                {
                    ret *= C.Particles[i].phi_P(X, t);
                }
                return(ret);
            };

            C.CutCellQuadratureType = Foundation.XDG.XQuadFactoryHelper.MomentFittingVariants.OneStepGaussAndStokes;


            //Func<double[], double, double> phiComplete = (X, t) => -1 * (C.Particles[0].phi_P(X, t)) * (C.Particles[1].phi_P(X, t));
            //Func<double[], double, double> phiComplete = (X, t) => -1 * (C.Particles[0].phi_P(X, t) * C.Particles[1].phi_P(X, t));
            //for (int i = 0;i<C.Particles.Count; i++) {
            //    phiComplete = (X,t) => phiComplete(X,t)*C.Particles[i].phi_P(X,t);
            //}


            //Func<double[], double, double> phi = (X, t) => -(X[0] - t+X[1]);
            //C.MovementFunc = phi;

            C.InitialValues_Evaluators.Add("Phi", X => phiComplete(X, 0));
            //C.InitialValues_Evaluators.Add("Phi", X => -1);
            //C.InitialValues.Add("VelocityX#B", X => 1);
            C.InitialValues_Evaluators.Add("VelocityX", X => 0);
            C.InitialValues_Evaluators.Add("VelocityY", X => 0);
            //C.InitialValues.Add("Phi", X => -1);
            //C.InitialValues.Add("Phi", X => (X[0] - 0.41));

            // For restart
            //C.RestartInfo = new Tuple<Guid, TimestepNumber>(new Guid("42c82f3c-bdf1-4531-8472-b65feb713326"), 400);
            //C.GridGuid = new Guid("f1659eb6 -b249-47dc-9384-7ee9452d05df");


            // Physical Parameters
            // ===================

            C.PhysicalParameters.IncludeConvection = true;

            // misc. solver options
            // ====================

            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.2;
            C.LevelSetSmoothing   = false;
            C.MaxSolverIterations = 100;
            C.NoOfMultigridLevels = 1;


            // Timestepping
            // ============

            C.Timestepper_Mode   = FSI_Control.TimesteppingMode.Splitting;
            C.Timestepper_Scheme = FSI_Solver.FSI_Control.TimesteppingScheme.BDF2;
            double dt = 0.001;

            C.dtMax         = dt;
            C.dtMin         = dt;
            C.Endtime       = 10;
            C.NoOfTimesteps = 100000;

            // haben fertig...
            // ===============

            return(C);
        }
Exemple #31
0
        public static XdgTimesteppingTestControl Rarefaction(int degree               = 2,
                                                             int NoOfTimesteps        = 20,
                                                             InterfaceMode tsm        = InterfaceMode.MovingInterface,
                                                             int GridResolutionFactor = 2)
        {
            XdgTimesteppingTestControl R = new XdgTimesteppingTestControl();

            R.ProjectName = "XdgMassMatrixEvolution/Rarefaction";
            R.savetodb    = false;
            //R.DbPath = @"\\fdyprime\userspace\kummer\BoSSS-db-XNSE";
            R.DbPath = null;

            // DG config
            // =========

            R.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("u", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vx", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vy", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });

            // grid
            // ====

            R.GridFunc = delegate() {
                double[]    nodes  = GenericBlas.Linspace(-2.7, 2.7, 18 * GridResolutionFactor + 1);
                BoundingBox cutOut = new BoundingBox(new double[] { -0.3, -0.3 }, new double[] { 0.3, 0.3 });
                var         grd    = Grid2D.Cartesian2DGrid(nodes, nodes, CutOuts: cutOut);

                grd.EdgeTagNames.Add(1, "Inflow");
                grd.EdgeTagNames.Add(2, "Outflow");

                grd.DefineEdgeTags(delegate(double[] X) {
                    byte ret = 2;
                    if (Math.Abs(X[0]) <= 0.31 && Math.Abs(X[1]) <= 0.31)
                    {
                        ret = 1;
                    }
                    return(ret);
                });

                return(grd);
            };

            // exact solution
            // ==============
            R.uA_Ex = ((X, t) => 3.0 / Math.Sqrt(X[0].Pow2() + X[1].Pow2()));
            R.uB_Ex = ((X, t) => 1.0 / Math.Sqrt(X[0].Pow2() + X[1].Pow2()));

            // boundary condition
            // ==================

            R.AddBoundaryCondition("Inflow", "u", R.uA_Ex);
            R.AddBoundaryCondition("Outflow");

            // Initial values
            // ==============

            const double S = 1;

            R.S   = ((double[] X, double t) => S);
            R.Phi = ((double[] X, double t) => X[0].Pow2() + X[1].Pow2() - (1.0 + t).Pow2());

            R.CircleRadius          = t => (1.0 + t);
            R.CutCellQuadratureType = XQuadFactoryHelper.MomentFittingVariants.ExactCircle;

            R.InitialValues_Evaluators.Add("Phi", X => R.Phi(X, 0.0));
            R.InitialValues_Evaluators.Add("Vx", X => X[0] / Math.Sqrt(X[0].Pow2() + X[1].Pow2()));
            R.InitialValues_Evaluators.Add("Vy", X => X[1] / Math.Sqrt(X[0].Pow2() + X[1].Pow2()));
            R.InitialValues_Evaluators.Add("u#A", X => R.uA_Ex(X, 0.0));
            R.InitialValues_Evaluators.Add("u#B", X => R.uB_Ex(X, 0.0));

            // restart
            // =======

            //R.RestartInfo = new Tuple<Guid, Foundation.IO.TimestepNumber>(new Guid("aff36e92-1546-4fdf-a7bc-fbeff1e67f49"), 58);
            //R.InitialValues_Evaluators.Clear();

            // anderes zeugs
            // =============

            R.TimeSteppingScheme = TimeSteppingScheme.BDF4;
            R.InterfaceMode      = tsm;

            //R.Endtime = 0.05;
            R.Endtime       = 0.4;
            R.NoOfTimesteps = NoOfTimesteps;
            R.dtFixed       = R.Endtime / R.NoOfTimesteps;

            R.AgglomerationThreshold = 0.1;

            // return
            // ======

            return(R);
        }
        public static FSI_Control TestActiveParticle(string _DbPath = null, int k = 2, double VelXBase = 0.0, double stressM = 1, double cellAgg = 0.2, int maxCurv = 20, double muA = 1e-1)
        {
            FSI_Control C = new FSI_Control();


            // General scaling parameter
            // =============================
            const double BaseSize = 1.0;


            // basic database options
            // =============================
            //C.DbPath = @"\\hpccluster\hpccluster-scratch\deussen\cluster_db\active_particle_test";
            C.savetodb           = false;
            C.saveperiod         = 1;
            C.ProjectName        = "ActiveParticleTest";
            C.ProjectDescription = "Active";
            C.SessionName        = C.ProjectName;
            C.Tags.Add("with immersed boundary method");


            // DG degrees
            // =============================
            C.FieldOptions.Add("VelocityX", new FieldOpts()
            {
                Degree   = k,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("VelocityY", new FieldOpts()
            {
                Degree   = k,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Pressure", new FieldOpts()
            {
                Degree   = k - 1,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("PhiDG", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Curvature", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });


            // Grid
            // =============================
            //Generating grid
            C.GridFunc = delegate {
                int q = new int();
                int r = new int();

                switch (99)
                {
                case 1:
                    q = 60;
                    r = 178;
                    break;

                case 2:
                    q = 41;
                    r = 121;
                    break;

                case 3:
                    q = 31;
                    r = 91;
                    break;

                case 99:
                    q = 20;
                    r = 100;
                    break;

                default:

                    throw new ApplicationException();
                }

                double[] Xnodes = GenericBlas.Linspace(-1 * BaseSize, 1 * BaseSize, q);
                double[] Ynodes = GenericBlas.Linspace(-10 * BaseSize, 0 * BaseSize, r);

                var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: false);

                grd.EdgeTagNames.Add(1, "Pressure_Outlet_left");
                grd.EdgeTagNames.Add(2, "Pressure_Outlet_right");
                grd.EdgeTagNames.Add(3, "Wall_lower");
                grd.EdgeTagNames.Add(4, "Pressure_Outlet_upper");


                grd.DefineEdgeTags(delegate(double[] X) {
                    byte et = 0;
                    if (Math.Abs(X[0] - (-1 * BaseSize)) <= 1.0e-8)
                    {
                        et = 1;
                    }
                    if (Math.Abs(X[0] + (-1 * BaseSize)) <= 1.0e-8)
                    {
                        et = 2;
                    }
                    if (Math.Abs(X[1] - (-10 * BaseSize)) <= 1.0e-8)
                    {
                        et = 3;
                    }
                    if (Math.Abs(X[1] + (-0 * BaseSize)) <= 1.0e-8)
                    {
                        et = 4;
                    }

                    Debug.Assert(et != 0);
                    return(et);
                });

                Console.WriteLine("Cells:" + grd.NumberOfCells);

                return(grd);
            };


            //Mesh refinement
            // =============================
            C.AdaptiveMeshRefinement = true;
            C.RefinementLevel        = 2;
            C.maxCurvature           = maxCurv;


            // Boundary conditions
            // =============================
            C.AddBoundaryValue("Pressure_Outlet_left");  //, "VelocityX", X => 0.0);
            C.AddBoundaryValue("Pressure_Outlet_right"); //, "VelocityX", X => 0.0);
            C.AddBoundaryValue("Wall_lower");
            C.AddBoundaryValue("Pressure_Outlet_upper");


            // Coupling Properties
            // =============================
            //C.LevelSetMovement = "coupled";
            C.Timestepper_LevelSetHandling = LevelSetHandling.LieSplitting;
            C.splitting_fully_coupled      = true;
            C.max_iterations_fully_coupled = 1000;
            C.includeRotation    = true;
            C.includeTranslation = true;


            // Fluid Properties
            // =============================
            C.PhysicalParameters.rho_A    = 0.9982; //pg/(mum^3)
            C.PhysicalParameters.mu_A     = muA;    //pg(mum*s)
            C.PhysicalParameters.Material = true;


            // Particle Properties
            // =============================
            // Defining particles
            C.Particles = new List <Particle>();
            int numOfParticles = 1;

            for (int d = 0; d < numOfParticles; d++)
            {
                C.Particles.Add(new Particle(2, 9, new double[] { 0 + 14.0 * d, -1.0 }, startAngl: 180.0 * d, shape: Particle.ParticleShape.elliptic)
                                //Generates a series of opposing particles
                {
                    radius_P           = 1,
                    rho_P              = 1.1,//pg/(mum^3)
                    includeGravity     = true,
                    active_P           = false,
                    stress_magnitude_P = stressM,
                    thickness_P        = 0.05,
                    length_P           = 0.5,
                    velResidual_ConvergenceCriterion = 1e-18,
                    underrelaxationFT_constant       = false,
                    underrelaxationFT_exponent       = -0,
                    underrelaxation_factor           = 0.5
                });
            }
            //Define level-set
            Func <double[], double, double> phiComplete = delegate(double[] X, double t)
            {
                //Generating the correct sign
                int    exp = C.Particles.Count - 1;
                double ret = Math.Pow(-1, exp);
                //Level-set function depending on #particles
                for (int i = 0; i < C.Particles.Count; i++)
                {
                    ret *= C.Particles[i].phi_P(X, t);
                }
                return(ret);
            };


            // Quadrature rules
            // =============================
            C.CutCellQuadratureType = Foundation.XDG.XQuadFactoryHelper.MomentFittingVariants.Saye;


            //Initial Values
            // =============================
            C.InitialValues_Evaluators.Add("Phi", X => phiComplete(X, 0));
            C.InitialValues_Evaluators.Add("VelocityX", X => 0);
            C.InitialValues_Evaluators.Add("VelocityY", X => 0);


            // For restart
            // =============================
            //C.RestartInfo = new Tuple<Guid, TimestepNumber>(new Guid("42c82f3c-bdf1-4531-8472-b65feb713326"), 400);
            //C.GridGuid = new Guid("f1659eb6 -b249-47dc-9384-7ee9452d05df");


            // Physical Parameters
            // =============================
            C.PhysicalParameters.IncludeConvection = false;


            // misc. solver options
            // =============================
            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = cellAgg;
            C.LevelSetSmoothing             = false;
            C.MaxSolverIterations           = 1000;
            C.MinSolverIterations           = 1;
            C.NoOfMultigridLevels           = 1;
            C.LevelSet_ConvergenceCriterion = 5e-10;
            C.LSunderrelax = 1.0;


            // Timestepping
            // =============================
            C.Timestepper_Mode   = FSI_Control.TimesteppingMode.Splitting;
            C.Timestepper_Scheme = FSI_Solver.FSI_Control.TimesteppingScheme.BDF2;
            double dt = 1e-2;//s

            C.dtMax         = dt;
            C.dtMin         = dt;
            C.Endtime       = 10;
            C.NoOfTimesteps = 10000;



            // haben fertig...
            // ===============

            return(C);
        }
Exemple #33
0
        public static XdgTimesteppingTestControl Burgers(int degree               = 1,
                                                         int NoOfTimesteps        = 40,
                                                         InterfaceMode tsm        = InterfaceMode.MovingInterface,
                                                         int GridResolutionFactor = 2)
        {
            XdgTimesteppingTestControl R = new XdgTimesteppingTestControl();

            R.ProjectName = "XdgMassMatrixEvolution/Burgers";
            R.savetodb    = false;
            R.DbPath      = null; //@"\\fdyprime\userspace\kummer\BoSSS-db-XNSE";

            // DG config
            // =========

            R.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("u", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vx", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vy", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });

            // grid
            // ====

            R.GridFunc = delegate() {
                double[] Xnodes = GenericBlas.Linspace(-2, 2, 7 * GridResolutionFactor + 1);
                double[] Ynodes = GenericBlas.Linspace(-2, 2, 7 * GridResolutionFactor + 1);
                var      grd    = Grid2D.Cartesian2DGrid(Xnodes, Ynodes);

                grd.EdgeTagNames.Add(1, "Dirichlet");
                grd.EdgeTagNames.Add(2, "Neumann");

                grd.DefineEdgeTags(delegate(double[] X) {
                    byte ret;
                    if (Math.Abs(X[0] - (-1)) <= 1.0e-8 || Math.Abs(X[0] - (+1)) <= 1.0e-8)
                    {
                        ret = 1;
                    }
                    else
                    {
                        ret = 2;
                    }
                    return(ret);
                });

                return(grd);
            };

            // exact solution
            // ==============

            double TimeOffset = 0.1;

            double angle = 45 * Math.PI / 180.0;
            //double angle = 0.0;
            double Nx = Math.Cos(angle);
            double Ny = Math.Sin(angle);

            R.BurgersDirection = new Platform.LinAlg.Vector2D(Nx, Ny);

            const double S = 0.5 * (2 + 1);

            R.S   = ((double[] X, double t) => S);
            R.Phi = ((double[] X, double t) => (X[0] - Nx * S * (t + TimeOffset)) * Nx + (X[1] - Ny * S * (t + TimeOffset)) * Ny);

            Func <double[], double> projCoord = X => X[0] * Nx + X[1] * Ny;

            // initial value for x < 0
            Func <double, double> uA0 = x => Math.Exp(-x.Pow2()) + 1.0;

            // We will need Newtons alg. to find the origin of a characteristic;
            // for a decent initial value of Newton, we sample the initial value at certain points
            double[] xTrial = GenericBlas.Linspace(-10, 10, 1000);
            double[] u0Tril = xTrial.Select(x => uA0(x)).ToArray();


            Func <double, double, double> uAEx = delegate(double t, double xi) {
                double ret = 0;

                t += TimeOffset;

                if (t < 0)
                {
                    throw new ArgumentOutOfRangeException();
                }
                if (t == 0)
                {
                    return(uA0(xi));
                }

                // find low ang high bound for Newton
                int    I           = xTrial.Length;
                int    iMinDist_lo = -1;
                double MinDist_lo  = double.MaxValue;
                int    iMinDist_hi = -1;
                double MinDist_hi  = double.MaxValue;

                for (int i = 0; i < I; i++)
                {
                    double x0     = xTrial[i];
                    double u0Atx0 = u0Tril[i];

                    double x1   = x0 + u0Atx0 * t; // x1 is position of the characteristic, which originates from x0,  at time t
                    double dist = Math.Abs(x1 - xi);
                    if (dist < MinDist_lo && x1 < xi)
                    {
                        iMinDist_lo = i;
                        MinDist_lo  = dist;
                    }
                    if (dist < MinDist_hi && x1 > xi)
                    {
                        iMinDist_hi = i;
                        MinDist_hi  = dist;
                    }
                }
                double xi_lo = xTrial[iMinDist_lo];
                double xi_hi = xTrial[iMinDist_hi];



                Func <double, double> func  = (xi0 => (uA0(xi0) * t + xi0 - xi));
                Func <double, double> dfunc = (xi0 => (1.0 - 2.0 * t * Math.Exp(-(xi0.Pow2()))));
                double xi0i = rtsave(func, dfunc, xi_lo, xi_hi, 1e-12);

                // Probe
                //if (!converged)
                //    throw new ArithmeticException();

                // return value at origin of characteristic
                ret = uA0(xi0i);

                return(ret);
            };

            {
                // test for uAEx
                double x0      = -0.5;
                double u_at_x0 = uA0(x0);
                double dt      = -0.02;
                double x       = x0 + u_at_x0 * (dt + TimeOffset); // characteristic through x0, at time dt

                double u_at = uAEx(dt, x);
                if (Math.Abs(u_at - u_at_x0) > 1.0e-8)
                {
                    throw new ArithmeticException();
                }
            }

            /*
             * Func<double, double, double> uAEx = delegate (double t, double xi) {
             *  return 2.0;
             * };
             */

            R.uA_Ex = ((X, t) => uAEx(t, projCoord(X)));
            R.uB_Ex = ((X, t) => 1.0);

            R.Eq = Equation.Burgers;

            R.InitialValues_Evaluators.Add("Phi", X => R.Phi(X, 0.0));
            R.InitialValues_Evaluators.Add("u#A", X => R.uA_Ex(X, 0.0));
            R.InitialValues_Evaluators.Add("u#B", X => R.uB_Ex(X, 0.0));


            // anderes zeugs
            // =============

            R.TimeSteppingScheme = TimeSteppingScheme.RK4;
            R.MultiStepInit      = false;
            R.InterfaceMode      = tsm;

            R.Endtime       = 0.11;
            R.NoOfTimesteps = NoOfTimesteps;
            R.dtFixed       = R.Endtime / R.NoOfTimesteps;

            R.AgglomerationThreshold = 0.1;

            // return
            // ======

            return(R);
        }
Exemple #34
0
 public Day_11()
 {
     _input = Grid2D.FromFile(InputFilePath);
 }
Exemple #35
0
        private static IBMControl ControlCutNextToCut(bool agglomeration)
        {
            IBMControl c = new IBMControl();

            c.savetodb = false;

            int    dgDegree    = 2;
            double vortexSpeed = 1.0;

            // IBM Settings
            c.CutCellQuadratureType   = XQuadFactoryHelper.MomentFittingVariants.Classic;
            c.LevelSetQuadratureOrder = 5;
            c.AgglomerationThreshold  = agglomeration ? 0.3 : 0.0;

            c.DomainType         = DomainTypes.StaticImmersedBoundary;
            c.ActiveOperators    = Operators.Convection;
            c.ConvectiveFluxType = ConvectiveFluxTypes.Rusanov;
            c.ExplicitScheme     = ExplicitSchemes.RungeKutta;
            c.ExplicitOrder      = 1;
            c.EquationOfState    = IdealGas.Air;

            c.MachNumber = 1 / Math.Sqrt(c.EquationOfState.HeatCapacityRatio);

            c.AddVariable(CompressibleVariables.Density, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.xComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Momentum.yComponent, dgDegree);
            c.AddVariable(CompressibleVariables.Energy, dgDegree);
            c.AddVariable(IBMVariables.LevelSet, 2);

            c.GridFunc = delegate {
                GridCommons grid = Grid2D.Cartesian2DGrid(
                    GenericBlas.Linspace(-5.0, 5.0, 21),
                    GenericBlas.Linspace(-0.5, 0.5, 3));
                grid.EdgeTagNames.Add(1, "supersonicInlet");
                grid.DefineEdgeTags((Vector X) => 1);
                return(grid);
            };

            c.LevelSetBoundaryTag = "supersonicInlet";

            IsentropicVortexExactSolution solution = new IsentropicVortexExactSolution(c, vortexSpeed);

            c.InitialValues_Evaluators.Add(CompressibleVariables.Density, X => solution.rho()(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.xComponent, X => solution.u()(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Velocity.yComponent, X => solution.v()(X, 0.0));
            c.InitialValues_Evaluators.Add(CNSVariables.Pressure, X => solution.p()(X, 0.0));
            if (agglomeration)
            {
                c.LevelSetFunction = (X, t) => - ((X[1] - 0.17) * (X[1] - 0.17) - 0.1);
            }
            else
            {
                c.LevelSetFunction = (X, t) => - (X[1] * X[1] - 0.2);
            }


            c.AddBoundaryValue("supersonicInlet", CompressibleVariables.Density, solution.rho());
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity[0], solution.u());
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Velocity[1], solution.v());
            c.AddBoundaryValue("supersonicInlet", CNSVariables.Pressure, solution.p());

            c.Queries.Add("L2ErrorDensity", IBMQueries.L2Error(CompressibleVariables.Density, solution.rho()));
            c.Queries.Add("L2ErrorPressure", IBMQueries.L2Error(state => state.Pressure, solution.p()));
            c.Queries.Add("L2ErrorEntropy", IBMQueries.L2Error(state => state.Entropy, (X, t) => 1.0));

            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.CFLFraction   = 0.2;
            c.Endtime       = double.MaxValue;
            c.NoOfTimesteps = 100;

            return(c);
        }
Exemple #36
0
        void UpdateLOS()
        {
            Debug.Assert(this.World.LivingVisionMode == LivingVisionMode.LOS);

            if (this.Environment == null)
                return;

            lock (m_visionMapLock)
            {
                if (m_losLocation == this.Location && m_losMapVersion == this.Environment.Version && m_visionMap != null)
                    return;

                int visionRange = this.VisionRange;

                if (m_visionMap == null)
                {
                    m_visionMap = new Grid2D<bool>(visionRange * 2 + 1, visionRange * 2 + 1,
                        visionRange, visionRange);
                    m_losMapVersion = 0;
                }

                var env = this.Environment;
                var z = this.Location.Z;

                ShadowCastRecursive.Calculate(this.Location.ToIntPoint(), visionRange,
                    m_visionMap, env.Size.Plane,
                    p2 =>
                    {
                        var td = env.GetTileData(new IntPoint3(p2, z));
                        return !td.IsUndefined && !td.IsSeeThrough;
                    });

                m_losMapVersion = this.Environment.Version;
                m_losLocation = this.Location;
            }
        }
Exemple #37
0
        /// <summary>
        /// Test on a 2D Voronoi mesh
        /// </summary>
        /// <param name="Res">
        /// number of randomly chosen Delaunay vertices
        /// </param>
        /// <param name="deg">
        /// polynomial degree
        /// </param>
        /// <param name="solver_name">
        /// Name of solver to use.
        /// </param>
        public static SipControl TestVoronoi(int Res, SolverCodes solver_name = SolverCodes.classic_pardiso, int deg = 3)
        {
            if (System.Environment.MachineName.ToLowerInvariant().EndsWith("rennmaschin")
                //|| System.Environment.MachineName.ToLowerInvariant().Contains("jenkins")
                )
            {
                // This is Florians Laptop;
                // he is to poor to afford MATLAB, so he uses OCTAVE
                BatchmodeConnector.Flav = BatchmodeConnector.Flavor.Octave;
                BatchmodeConnector.MatlabExecuteable = "C:\\cygwin64\\bin\\bash.exe";
            }


            var R = new SipControl();

            R.ProjectName = "SipPoisson-Voronoi";
            R.SessionName = "testrun";
            R.savetodb    = false;

            R.FieldOptions.Add("T", new FieldOpts()
            {
                Degree = deg, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Tex", new FieldOpts()
            {
                Degree = deg * 2
            });
            R.InitialValues_Evaluators.Add("RHS", X => 1.0);
            R.InitialValues_Evaluators.Add("Tex", X => 0.0);
            R.ExactSolution_provided = false;
            R.NoOfMultigridLevels    = int.MaxValue;
            R.solver_name            = solver_name;
            //R.TargetBlockSize = 100;



            bool IsIn(params double[] X)
            {
                Debug.Assert(X.Length == 2);
                double xi = X[0];
                double yi = X[1];

                //for(int l = 0; l < bndys.Length; l++) {
                //    Debug.Assert(bndys[l].Normal.Length == 2);
                //    if (bndys[l].PointDistance(xi, yi) > 0.0)
                //        return false;
                //}
                if (xi > 1.0)
                {
                    return(false);
                }
                if (yi > 1.0)
                {
                    return(false);
                }
                if (xi < 0 && yi < 0)
                {
                    return(false);
                }
                if (xi < -1)
                {
                    return(false);
                }
                if (yi < -1)
                {
                    return(false);
                }

                return(true);
            }

            int Mirror(ref double[] _x, ref double[] _y, AffineManifold[] bndys)
            {
                if (_x.Length != _y.Length)
                {
                    throw new ArgumentException();
                }
                var x = _x.ToList();
                var y = _y.ToList();
                int N = _x.Length;



                // filter all points that are outside of the domain
                for (int n = 0; n < N; n++)
                {
                    if (!IsIn(x[n], y[n]))
                    {
                        x.RemoveAt(n);
                        y.RemoveAt(n);
                        N--;
                        n--;
                    }
                }
                Debug.Assert(x.Count == N);
                Debug.Assert(y.Count == N);
                for (int n = 0; n < N; n++)
                {
                    Debug.Assert(IsIn(x[n], y[n]));
                }

                // mirror each point
                for (int n = 0; n < N; n++)
                {
                    double xn = x[n];
                    double yn = y[n];
                    for (int l = 0; l < bndys.Length; l++)
                    {
                        var bndy_l = bndys[l];

                        double dist = bndy_l.PointDistance(xn, yn);

                        if (dist < 0)
                        {
                            double xMirr = xn - bndy_l.Normal[0] * dist * 2;
                            double yMirr = yn - bndy_l.Normal[1] * dist * 2;

                            Debug.Assert(bndy_l.PointDistance(xMirr, yMirr) > 0);

                            if (!IsIn(xMirr, yMirr))
                            {
                                x.Add(xMirr);
                                y.Add(yMirr);
                            }
                        }
                    }
                }

                // return
                _x = x.ToArray();
                _y = y.ToArray();
                return(N);
            }

            GridCommons GridFunc()
            {
                GridCommons grd = null;

                var Matlab = new BatchmodeConnector();

                // boundaries for L-domain
                AffineManifold[] Boundaries = new AffineManifold[6];
                Boundaries[0] = new AffineManifold(new[] { 0.0, 1.0 }, new[] { 0.0, 1.0 });
                Boundaries[1] = new AffineManifold(new[] { 1.0, 0.0 }, new[] { 1.0, 0.0 });
                Boundaries[2] = new AffineManifold(new[] { -1.0, 0.0 }, new[] { -1.0, 0.0 });
                Boundaries[3] = new AffineManifold(new[] { -1.0, 0.0 }, new[] { 0.0, 0.0 });
                Boundaries[4] = new AffineManifold(new[] { 0.0, -1.0 }, new[] { 0.0, -1.0 });
                Boundaries[5] = new AffineManifold(new[] { 0.0, -1.0 }, new[] { 0.0, 0.0 });


                // generate Delaunay vertices
                Random rnd = new Random(0);

                double[] xNodes = Res.ForLoop(idx => rnd.NextDouble() * 2 - 1);
                double[] yNodes = Res.ForLoop(idx => rnd.NextDouble() * 2 - 1);
                int      ResFix = Mirror(ref xNodes, ref yNodes, Boundaries);


                var Nodes = MultidimensionalArray.Create(xNodes.Length, 2);

                Nodes.SetColumn(0, xNodes);
                Nodes.SetColumn(1, yNodes);

                Matlab.PutMatrix(Nodes, "Nodes");

                // compute Voronoi diagramm
                Matlab.Cmd("[V, C] = voronoin(Nodes);");

                // output (export from matlab)
                int[][] OutputVertexIndex = new int[Nodes.NoOfRows][];
                Matlab.GetStaggeredIntArray(OutputVertexIndex, "C");
                Matlab.GetMatrix(null, "V");

                // run matlab
                Matlab.Execute(false);

                // import here
                MultidimensionalArray VertexCoordinates = (MultidimensionalArray)(Matlab.OutputObjects["V"]);

                // correct indices (1-based index to 0-based index)
                foreach (int[] cell in OutputVertexIndex)
                {
                    int K = cell.Length;
                    for (int k = 0; k < K; k++)
                    {
                        cell[k]--;
                    }
                }

                // tessellation
                List <Cell>  cells       = new List <Cell>();
                List <int[]> aggregation = new List <int[]>();

                for (int jV = 0; jV < ResFix; jV++)  // loop over Voronoi Cells
                {
                    Debug.Assert(IsIn(Nodes.GetRow(jV)));
                    int[] iVtxS = OutputVertexIndex[jV];
                    int   NV    = iVtxS.Length;

                    List <int> Agg2Pt = new List <int>();

                    for (int iTri = 0; iTri < NV - 2; iTri++)  // loop over triangles of voronoi cell
                    {
                        int iV0 = iVtxS[0];
                        int iV1 = iVtxS[iTri + 1];
                        int iV2 = iVtxS[iTri + 2];

                        double[] V0 = VertexCoordinates.GetRow(iV0);
                        double[] V1 = VertexCoordinates.GetRow(iV1);
                        double[] V2 = VertexCoordinates.GetRow(iV2);

                        double[] D1 = V1.Minus(V0);
                        double[] D2 = V2.Minus(V0);
                        Debug.Assert(D1.CrossProduct2D(D2).Abs() > 1.0e-8);
                        if (D1.CrossProduct2D(D2) < 0)
                        {
                            double[] T = V2;
                            int      t = iV2;
                            V2  = V1;
                            iV2 = iV1;
                            V1  = T;
                            iV1 = t;
                        }

                        double[] Center = V0.Plus(V1).Plus(V2).Mul(1.0 / 3.0);
                        //Debug.Assert(IsIn(Center[0], Center[1]));

                        Cell Cj = new Cell();
                        Cj.GlobalID             = cells.Count;
                        Cj.Type                 = CellType.Triangle_3;
                        Cj.TransformationParams = MultidimensionalArray.Create(3, 2);
                        Cj.NodeIndices          = new int[] { iV0, iV1, iV2 };
                        Cj.TransformationParams.SetRow(0, V0);
                        Cj.TransformationParams.SetRow(1, V1);
                        Cj.TransformationParams.SetRow(2, V2);

                        Agg2Pt.Add(cells.Count);

                        cells.Add(Cj);
                    }

                    aggregation.Add(Agg2Pt.ToArray());
                }

                // return grid
                grd       = new Grid2D(Triangle.Instance);
                grd.Cells = cells.ToArray();
                grd.EdgeTagNames.Add(1, BoundaryType.Dirichlet.ToString());
                grd.DefineEdgeTags(X => (byte)1);

                //grd.Plot2DGrid();

                // create aggregation grid
                //var agrd = new AggregationGrid(grd, aggregation.ToArray());
                return(grd);
            };
            R.GridFunc = GridFunc;

            R.AddBoundaryValue(BoundaryType.Dirichlet.ToString(), "T",
                               delegate(double[] X) {
                //double x = X[0], y = X[1];

                return(0.0);
                //if(Math.Abs(X[0] - (0.0)) < 1.0e-8)
                //    return 0.0;
                //
                //throw new ArgumentOutOfRangeException();
            });



            return(R);
        }
    void Awake()
    {
        tiles = new SpriteRenderer[(int)gridSize.x, (int)gridSize.y];
        grid = new Grid2D((int)gridSize.x, (int)gridSize.y);

        switch (searchEngine)
        {
            case Engine.Fringe:
                pathFinder = new Fringe(Grid2D.HeuristicManhattan2);
                break;
            case Engine.AStar:
                pathFinder = new AStar(Grid2D.HeuristicManhattan2);
                break;
        }
    }
        public static FSI_Control Test_ParticleInShearFlow(int k = 2)
        {
            FSI_Control C = new FSI_Control();

            const double BaseSize = 1.0;

            // basic database options
            // ======================

            C.savetodb           = false;
            C.ProjectName        = "ShearFlow_Test";
            C.ProjectDescription = "ShearFlow";
            C.Tags.Add("with immersed boundary method");

            // DG degrees
            // ==========

            C.SetDGdegree(k);

            // grid and boundary conditions
            // ============================

            C.GridFunc = delegate {
                double[] Xnodes = GenericBlas.Linspace(-2 * BaseSize, 2 * BaseSize, 21);
                double[] Ynodes = GenericBlas.Linspace(-3 * BaseSize, 3 * BaseSize, 31);
                var      grd    = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: true);

                grd.EdgeTagNames.Add(1, "Velocity_Inlet_left");
                grd.EdgeTagNames.Add(2, "Velocity_Inlet_right");


                grd.DefineEdgeTags(delegate(double[] X) {
                    byte et = 0;
                    if (Math.Abs(X[0] - (-2 * BaseSize)) <= 1.0e-8)
                    {
                        et = 1;
                    }
                    if (Math.Abs(X[0] + (-2 * BaseSize)) <= 1.0e-8)
                    {
                        et = 2;
                    }

                    Debug.Assert(et != 0);
                    return(et);
                });

                return(grd);
            };

            C.AddBoundaryValue("Velocity_Inlet_left", "VelocityY", X => 0.02);
            C.AddBoundaryValue("Velocity_Inlet_right", "VelocityY", X => - 0.02);

            // Boundary values for level-set
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0.1 * 2 * Math.PI * -Math.Sin(Math.PI * 2 * 1 * t), (t) =>  0};
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0, (t) => 0 };

            // Initial Values
            // ==============
            C.Timestepper_LevelSetHandling = LevelSetHandling.Coupled_Once;
            C.gravity = new double[] { 0, 0 };
            double             particleDensity = 1;
            ParticleMotionInit motion          = new ParticleMotionInit(C.gravity, particleDensity, C.pureDryCollisions, false, true);

            C.Particles.Add(new Particle_Sphere(motion, 0.4, new double[] { 0.0, 0.0 }));

            // For restart
            //C.RestartInfo = new Tuple<Guid, TimestepNumber>(new Guid("fec14187-4e12-43b6-af1e-e9d535c78668"), -1);


            // Physical Parameters
            // ===================

            C.PhysicalParameters.rho_A             = 1;
            C.PhysicalParameters.mu_A              = 0.25;
            C.PhysicalParameters.IncludeConvection = true;


            // misc. solver options
            // ====================
            C.AdvancedDiscretizationOptions.PenaltySafety = 1;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.1;
            C.LevelSetSmoothing                   = false;
            C.LinearSolver.SolverCode             = LinearSolverCode.classic_pardiso;
            C.LinearSolver.MaxSolverIterations    = 100;
            C.LinearSolver.MinSolverIterations    = 1;
            C.NonLinearSolver.MaxSolverIterations = 100;
            C.NonLinearSolver.MinSolverIterations = 1;
            C.LinearSolver.NoOfMultigridLevels    = 1;

            // Timestepping
            // ============

            C.Timestepper_Scheme = FSI_Control.TimesteppingScheme.BDF2;
            double dt = 0.1;

            C.dtFixed       = dt;
            C.dtMax         = dt;
            C.dtMin         = dt;
            C.Endtime       = 120;
            C.NoOfTimesteps = 100;



            // haben fertig...
            // ===============

            return(C);
        }
Exemple #40
0
        /// <summary>
        /// Testing of particle/wall interactions using a single particle
        /// </summary>
        public static FSI_Control HundredDryActiveParticles(string _DbPath = null)
        {
            FSI_Control C = new FSI_Control();

            // basic database options
            // ======================

            C.DbPath             = _DbPath;
            C.savetodb           = _DbPath != null;
            C.saveperiod         = 1;
            C.ProjectName        = "ParticleCollisionTest";
            C.ProjectDescription = "Gravity";
            C.SessionName        = C.ProjectName;
            C.Tags.Add("with immersed boundary method");
            C.pureDryCollisions = true;

            // DG degrees
            // ==========

            C.SetDGdegree(2);

            // grid and boundary conditions
            // ============================

            double[] Xnodes = GenericBlas.Linspace(-6, 6, 120);
            double[] Ynodes = GenericBlas.Linspace(-6, 6, 120);
            double   h      = Math.Min((Xnodes[1] - Xnodes[0]), (Ynodes[1] - Ynodes[0]));

            C.GridFunc = delegate {
                var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: false);
                grd.EdgeTagNames.Add(1, "Wall");
                grd.DefineEdgeTags(delegate(double[] X) {
                    byte et = 1;
                    return(et);
                });

                return(grd);
            };

            C.AddBoundaryValue("Wall");

            // Boundary values for level-set
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0.1 * 2 * Math.PI * -Math.Sin(Math.PI * 2 * 1 * t), (t) =>  0};
            //C.BoundaryFunc = new Func<double, double>[] { (t) => 0, (t) => 0 };

            // Initial Values
            // ==============

            // Coupling Properties
            C.Timestepper_LevelSetHandling = LevelSetHandling.LieSplitting;


            // Fluid Properties
            C.PhysicalParameters.rho_A = 1;
            C.PhysicalParameters.mu_A  = 0.1;

            // Particles
            // =========
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    double StartAngle = 10 * i - 10 * i * j + 8;
                    C.Particles.Add(new Particle_Ellipsoid(new double[] { -4 + 2 * i + Math.Pow(-1, j) * 0.5, -4 + 2 * j }, StartAngle)
                    {
                        particleDensity = 100.0,
                        length_P        = 0.5,
                        thickness_P     = 0.4,
                        GravityVertical = -0.001,
                        //ActiveVelocity = 1,
                    });
                }
            }

            C.collisionModel = FSI_Control.CollisionModel.MomentumConservation;


            // Physical Parameters
            // ===================

            C.PhysicalParameters.IncludeConvection = true;


            // misc. solver options
            // ====================

            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.2;
            C.LevelSetSmoothing = false;
            C.LinearSolver.MaxSolverIterations    = 10;
            C.NonLinearSolver.MaxSolverIterations = 10;
            C.LinearSolver.NoOfMultigridLevels    = 1;
            C.AdaptiveMeshRefinement = false;
            C.RefinementLevel        = 1;

            // Timestepping
            // ============

            //C.Timestepper_Mode = FSI_Control.TimesteppingMode.Splitting;
            C.Timestepper_Scheme = FSI_Solver.FSI_Control.TimesteppingScheme.BDF2;

            double dt = 1e-1;

            C.dtMax = dt;
            C.dtMin = dt;

            C.Endtime       = 100000000.0;
            C.NoOfTimesteps = 225000000;

            // haben fertig...
            // ===============

            return(C);
        }
        /// <summary>
        /// Testing particle bouncing
        /// </summary>
        public static FSI_Control Test_DryParticleBounce(string _DbPath = null)
        {
            FSI_Control C = new FSI_Control {
                // basic database options
                // ======================

                DbPath             = _DbPath,
                savetodb           = _DbPath != null,
                saveperiod         = 1,
                ProjectName        = "ParticleCollisionTest",
                ProjectDescription = "Gravity"
            };

            C.SessionName = C.ProjectName;
            C.Tags.Add("with immersed boundary method");


            // DG degrees
            // ==========

            C.SetDGdegree(1);

            // grid and boundary conditions
            // ============================

            double[] Xnodes = GenericBlas.Linspace(-1, 1, 20);
            double[] Ynodes = GenericBlas.Linspace(-1, 2, 30);
            double   h      = Math.Min((Xnodes[1] - Xnodes[0]), (Ynodes[1] - Ynodes[0]));

            C.GridFunc = delegate {
                var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: false);
                grd.EdgeTagNames.Add(1, "Wall");
                grd.DefineEdgeTags(delegate(double[] X) {
                    byte et = 1;
                    return(et);
                });

                return(grd);
            };

            C.AddBoundaryValue("Wall");

            // Coupling Properties
            C.Timestepper_LevelSetHandling = LevelSetHandling.Coupled_Once;


            // Fluid Properties
            C.PhysicalParameters.rho_A = 1;
            C.PhysicalParameters.mu_A  = 0.1;

            C.PhysicalParameters.IncludeConvection = true;
            C.CoefficientOfRestitution             = 1;


            // Particles
            // =========
            C.pureDryCollisions = true;
            double             particleDensity = 1.0;
            ParticleMotionInit motion          = new ParticleMotionInit(C.gravity, particleDensity, C.pureDryCollisions);

            C.Particles.Add(new Particle_Sphere(motion, 0.15, new double[] { 0.0, 0.8 }, 0.0));

            C.collisionModel = FSI_Control.CollisionModel.MomentumConservation;

            // misc. solver options
            // ====================

            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.2;
            C.LevelSetSmoothing = false;
            C.LinearSolver.MaxSolverIterations    = 10;
            C.NonLinearSolver.MaxSolverIterations = 10;
            C.LinearSolver.NoOfMultigridLevels    = 1;
            C.AdaptiveMeshRefinement = false;

            // Timestepping
            // ============

            //C.Timestepper_Mode = FSI_Control.TimesteppingMode.Splitting;
            C.Timestepper_Scheme = FSI_Solver.FSI_Control.TimesteppingScheme.BDF2;

            double dt = 1e-2;

            C.dtMax = dt;
            C.dtMin = dt;

            C.Endtime       = 2;
            C.NoOfTimesteps = 116;

            // haben fertig...
            // ===============

            return(C);
        }
Exemple #42
0
        public static IBMControl PistonControl(int dgDegree, int rkDegree, ConvectiveFluxTypes convectiveFlux, TimesteppingStrategies timeSteppingStrategy, double agglomerationThreshold)
        {
            double pistonVelocity          = 1.0;
            double initialLevelSetPosition = 0.1;
            //double initialLevelSetPosition = 0.5;

            IBMControl c = new IBMControl();

            c.DbPath   = null;
            c.savetodb = false;

            c.ProjectName        = "Piston";
            c.ProjectDescription = "Vertical moving at flow velocity through constant flow field";

            c.DomainType         = DomainTypes.MovingImmersedBoundary;
            c.ActiveOperators    = Operators.Convection;
            c.ConvectiveFluxType = convectiveFlux;
            c.EquationOfState    = IdealGas.Air;
            c.MachNumber         = 1.0 / Math.Sqrt(c.EquationOfState.HeatCapacityRatio);

            c.TimesteppingStrategy = timeSteppingStrategy;
            c.ExplicitScheme       = ExplicitSchemes.RungeKutta;
            c.ExplicitOrder        = rkDegree;

            c.AddVariable(Variables.Density, dgDegree);
            c.AddVariable(Variables.Momentum.xComponent, dgDegree);
            c.AddVariable(Variables.Momentum.yComponent, dgDegree);
            c.AddVariable(Variables.Energy, dgDegree);
            c.AddVariable(IBMVariables.LevelSet, 1);

            c.GridFunc = delegate {
                double[] xNodes = GenericBlas.Linspace(0.0, 2.0, 4);
                double[] yNodes = GenericBlas.Linspace(-1.0, 1.0, 4);
                var      grid   = Grid2D.Cartesian2DGrid(xNodes, yNodes, periodicX: false, periodicY: true);
                grid.EdgeTagNames.Add(1, "adiabaticSlipWall");
                grid.EdgeTagNames.Add(2, "supersonicInlet");
                grid.DefineEdgeTags(X => 2);
                return(grid);
            };

            c.CutCellQuadratureType   = XQuadFactoryHelper.MomentFittingVariants.Classic;
            c.LevelSetQuadratureOrder = 10;
            c.LevelSetBoundaryTag     = "adiabaticSlipWall";
            c.AgglomerationThreshold  = agglomerationThreshold;

            c.InitialValues_Evaluators.Add(Variables.Density, X => 1.0);
            c.InitialValues_Evaluators.Add(Variables.Velocity.xComponent, X => pistonVelocity);
            c.InitialValues_Evaluators.Add(Variables.Velocity.yComponent, X => 0.0);
            c.InitialValues_Evaluators.Add(Variables.Pressure, X => 1.0);

            c.LevelSetFunction = delegate(double[] X, double time) {
                double newLevelSetPosition = initialLevelSetPosition + pistonVelocity * time;
                return(X[0] - newLevelSetPosition);
            };
            c.LevelSetVelocity = (X, t) => new Vector3D(pistonVelocity, 0.0, 0.0);

            c.AddBoundaryCondition("adiabaticSlipWall", Variables.Velocity.xComponent, X => pistonVelocity);
            c.AddBoundaryCondition("adiabaticSlipWall", Variables.Velocity.yComponent, X => 0.0);
            c.AddBoundaryCondition("supersonicInlet", Variables.Density, X => 1.0);
            c.AddBoundaryCondition("supersonicInlet", Variables.Velocity[0], X => pistonVelocity);
            c.AddBoundaryCondition("supersonicInlet", Variables.Velocity[1], X => 0.0);
            c.AddBoundaryCondition("supersonicInlet", Variables.Pressure, X => 1.0);

            c.Queries.Add("L2ErrorDensity", IBMQueries.L2Error(Variables.Density, (X, t) => 1.0));
            c.Queries.Add("L2ErrorXMomentum", IBMQueries.L2Error(Variables.Momentum.xComponent, (X, t) => 1.0));
            c.Queries.Add("L2ErrorYMomentum", IBMQueries.L2Error(Variables.Momentum.yComponent, (X, t) => 0.0));
            c.Queries.Add("L2ErrorPressure", IBMQueries.L2Error(state => state.Pressure, (X, t) => 1.0));

            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.CFLFraction   = 0.1;
            c.Endtime       = 0.75;
            c.NoOfTimesteps = int.MaxValue;

            return(c);
        }
        public static FSI_Control Test_HydrodynamicForces(int k = 2)
        {
            FSI_Control C = new FSI_Control {
                // basic database options
                // =============================
                //C.DbPath = @"\\hpccluster\hpccluster-scratch\deussen\cluster_db\straightChannel";
                savetodb           = false,
                saveperiod         = 1,
                ProjectName        = "Test_singleActiveParticle",
                ProjectDescription = "Test_singleActiveParticle"
            };

            C.SessionName = C.ProjectName;
            C.Tags.Add("activeParticle");

            // DG degrees
            // =============================
            C.SetDGdegree(k);

            // Grid
            // =============================
            //Generating grid
            C.GridFunc = delegate
            {
                int q = new int(); // #Cells in x-dircetion + 1
                int r = new int(); // #Cells in y-dircetion + 1

                q = 40;
                r = 30;

                double[] Xnodes = GenericBlas.Linspace(-4, 4, q);
                double[] Ynodes = GenericBlas.Linspace(-3, 3, r);

                var grd = Grid2D.Cartesian2DGrid(Xnodes, Ynodes, periodicX: false, periodicY: false);

                grd.EdgeTagNames.Add(1, "Velocity_Inlet_left");
                grd.EdgeTagNames.Add(2, "Pressure_Outlet_right");
                grd.EdgeTagNames.Add(3, "Wall_lower");
                grd.EdgeTagNames.Add(4, "Wall_upper");


                grd.DefineEdgeTags(delegate(double[] X)
                {
                    byte et = 0;
                    if (Math.Abs(X[0] - (-4)) <= 1.0e-8)
                    {
                        et = 1;
                    }
                    if (Math.Abs(X[0] + (-4)) <= 1.0e-8)
                    {
                        et = 2;
                    }
                    if (Math.Abs(X[1] - (-3)) <= 1.0e-8)
                    {
                        et = 3;
                    }
                    if (Math.Abs(X[1] + (-3)) <= 1.0e-8)
                    {
                        et = 4;
                    }

                    Debug.Assert(et != 0);
                    return(et);
                });

                Console.WriteLine("Cells:" + grd.NumberOfCells);

                return(grd);
            };


            // Mesh refinement
            // =============================
            C.AdaptiveMeshRefinement = false;
            C.RefinementLevel        = 1;


            // Boundary conditions
            // =============================
            C.AddBoundaryValue("Velocity_Inlet_left", "VelocityX", X => 1.0);
            C.AddBoundaryValue("Pressure_Outlet_right");//, "VelocityX", X => 0.0);
            C.AddBoundaryValue("Wall_lower");
            C.AddBoundaryValue("Wall_upper");


            // Fluid Properties
            // =============================
            C.PhysicalParameters.rho_A    = 0.1;  //pg/(mum^3)
            C.PhysicalParameters.mu_A     = 1e-1; //pg(mum*s)
            C.PhysicalParameters.Material = true;
            C.gravity = new double[] { 0, 0 };
            double particleDensity = 1.0;

            C.hydrodynamicsConvergenceCriterion = 1e-2;
            ParticleUnderrelaxationParam underrelaxationParam = new ParticleUnderrelaxationParam(C.hydrodynamicsConvergenceCriterion, ParticleUnderrelaxationParam.UnderrelaxationMethod.ProcentualRelaxation, 9, true);
            ParticleMotionInit           motion = new ParticleMotionInit(C.gravity, particleDensity, C.pureDryCollisions, false, false, underrelaxationParam, 1);

            // Particle Properties
            // =============================
            C.Particles = new List <Particle>();
            int numOfParticles = 1;

            for (int d = 0; d < numOfParticles; d++)
            {
                C.Particles.Add(new Particle_Sphere(motion, 0.5, new double[] { 0.0, 0.0 }, startAngl: 0));
            }

            // Quadrature rules
            // =============================
            C.CutCellQuadratureType = Foundation.XDG.XQuadFactoryHelper.MomentFittingVariants.Saye;

            //Initial Values
            // =============================
            C.InitialValues_Evaluators.Add("VelocityX", X => 0);
            C.InitialValues_Evaluators.Add("VelocityY", X => 0);

            // Physical Parameters
            // =============================
            C.PhysicalParameters.IncludeConvection = true;

            // misc. solver options
            // =============================
            C.AdvancedDiscretizationOptions.PenaltySafety = 4;
            C.AdvancedDiscretizationOptions.CellAgglomerationThreshold = 0.2;
            C.LevelSetSmoothing = false;
            C.NonLinearSolver.MaxSolverIterations = 1000;
            C.NonLinearSolver.MinSolverIterations = 1;
            C.LinearSolver.NoOfMultigridLevels    = 1;
            C.LinearSolver.MaxSolverIterations    = 1000;
            C.LinearSolver.MinSolverIterations    = 1;
            C.LSunderrelax = 1.0;

            // Coupling Properties
            // =============================
            C.Timestepper_LevelSetHandling = LevelSetHandling.FSI_LieSplittingFullyCoupled;
            C.LSunderrelax = 1;
            C.maxIterationsFullyCoupled = 1000;



            // Timestepping
            // =============================
            C.Timestepper_Scheme = FSI_Solver.FSI_Control.TimesteppingScheme.BDF2;
            double dt = 1e-3;

            C.dtMax         = dt;
            C.dtMin         = dt;
            C.Endtime       = 1e-3;
            C.NoOfTimesteps = 2;

            // haben fertig...
            // ===============

            return(C);
        }
        static public RheologyControl ConsistencyConstitutiveGeneric(int GridRes = 2, int PolyDeg = 2, double beta = 0)
        {
            RheologyControl C = new RheologyControl();

            // Solver Options
            C.NoOfTimesteps = 1;
            C.savetodb      = false;
            //C.DbPath = "C:\AnnesBoSSSdb\ConsistencyConstitutive_withDiv";
            C.SessionName = "Degree" + PolyDeg + ", GridLevel" + GridRes;
            C.ProjectName = "ConsistencyStudyConstitutive";
            C.NonLinearSolver.MaxSolverIterations  = 20;
            C.NonLinearSolver.MinSolverIterations  = 3;
            C.NonLinearSolver.ConvergenceCriterion = 1E-20;
            C.LinearSolver.MaxSolverIterations     = 20;
            C.LinearSolver.MinSolverIterations     = 3;
            C.LinearSolver.ConvergenceCriterion    = 1E-13;


            //C.MaxIter = 20;
            //C.MinIter = 3;
            //C.ConvCrit = 1E-20;
            //C.ConvCritGMRES = 1E-13;
            C.dt    = 1E20;
            C.dtMax = C.dt;
            C.dtMin = C.dt;
            C.Timestepper_Scheme         = RheologyControl.TimesteppingScheme.ImplicitEuler;
            C.NonLinearSolver.SolverCode = NonLinearSolverConfig.Code.Newton;//C.NonlinearMethod = NonlinearSolverMethod.Newton;

            //Grid Params
            //double GridLevel = 5;
            double h      = Math.Pow(2, -GridRes + 1);
            double cells  = 1 / h;
            int    cells2 = (int)cells;

            //Debugging and Solver Analysis
            C.OperatorMatrixAnalysis       = false;
            C.SkipSolveAndEvaluateResidual = true;
            C.SetInitialConditions         = true;
            C.SetInitialPressure           = true;
            C.SetParamsAnalyticalSol       = false;
            C.ComputeL2Error = true;

            //Physical Params
            C.Stokes = false;
            C.FixedStreamwisePeriodicBC = false;
            C.GravitySource             = true;
            C.beta        = 0;
            C.Reynolds    = 1;
            C.Weissenberg = 1;

            //Penalties
            C.ViscousPenaltyScaling = 1;
            C.Penalty2        = 1;
            C.Penalty1[0]     = 0.0;
            C.Penalty1[1]     = 0.0;
            C.PresPenalty2    = 1;
            C.PresPenalty1[0] = 0.0;
            C.PresPenalty1[1] = 0.0;

            // Exact Solution manufactured Solution
            Func <double[], double, double> VelocityXfunction = (X, t) => X[0] * X[0];
            Func <double[], double, double> VelocityYfunction = (X, t) => - X[1];
            Func <double[], double, double> Pressurefunction  = (X, t) => 0;
            Func <double[], double, double> StressXXfunction  = (X, t) => X[0] * X[0];
            Func <double[], double, double> StressXYfunction  = (X, t) => X[0] * X[0] + X[1] * X[1];
            Func <double[], double, double> StressYYfunction  = (X, t) => X[1] * X[1];

            //Gravity sources
            //Weissenberg = 1 including Objective Terms!
            C.GravityX   = (X, t) => 2 * X[0] * X[0] * X[0] + X[0] * X[0] * (2 * X[0] - 1) - 2 * X[0] - 2 * X[1];
            C.GravityY   = (X, t) => - X[1] - X[1] * (2 * X[0] - 1) - 2 * X[0];
            C.GravityXX  = (X, t) => X[0] * X[0] - 2 * X[0] * X[0] * X[0] - 4 * X[0];
            C.GravityXY  = (X, t) => X[0] * X[0] - X[1] * X[1] + 2 * X[0] * X[0] * X[0] - (2 * X[0] - 1) * (X[0] * X[0] + X[1] * X[1]);
            C.GravityYY  = (X, t) => X[1] * X[1] + 2;
            C.GravityDiv = (X, t) => 2 * X[0] - 1;

            // Insert Exact Solution
            C.ExSol_Velocity = new Func <double[], double, double>[] { VelocityXfunction, VelocityYfunction };
            C.ExSol_Pressure = Pressurefunction;
            C.ExSol_Stress   = new Func <double[], double, double>[] { StressXXfunction, StressXYfunction, StressYYfunction };

            // Create Fields
            //int degree = 2;
            C.FieldOptions.Add("VelocityX", new FieldOpts()
            {
                Degree = PolyDeg, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("VelocityY", new FieldOpts()
            {
                Degree = PolyDeg, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Pressure", new FieldOpts()
            {
                Degree = PolyDeg - 1, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });

            C.FieldOptions.Add("StressXX", new FieldOpts()
            {
                Degree = PolyDeg, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("StressXY", new FieldOpts()
            {
                Degree = PolyDeg, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("StressYY", new FieldOpts()
            {
                Degree = PolyDeg, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("PhiDG", new FieldOpts()
            {
                Degree = 1, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            C.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree = 1, SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });


            // Create Grid
            C.GridFunc = delegate {
                var _xNodes = GenericBlas.Linspace(-1, 1, cells2 + 1);
                var _yNodes = GenericBlas.Linspace(-1, 1, cells2 + 1);

                var grd = Grid2D.Cartesian2DGrid(_xNodes, _yNodes, CellType.Square_Linear, C.FixedStreamwisePeriodicBC);

                if (!C.FixedStreamwisePeriodicBC)
                {
                    grd.EdgeTagNames.Add(1, "Velocity_inlet");
                }

                grd.DefineEdgeTags(delegate(double[] _X) {
                    var X    = _X;
                    double x = X[0];
                    double y = X[1];

                    if (Math.Abs(y - (-1)) < 1.0e-6)
                    {
                        // bottom
                        return(1);
                    }

                    if (Math.Abs(y - (+1)) < 1.0e-6)
                    {
                        // top
                        return(1);
                    }

                    if (!C.FixedStreamwisePeriodicBC)
                    {
                        if (Math.Abs(x - (-1)) < 1.0e-6)
                        {
                            // left
                            return(1);
                        }

                        if (Math.Abs(x - (+1)) < 1.0e-6)
                        {
                            // right
                            return(1);
                        }
                    }

                    throw new ArgumentOutOfRangeException();
                });

                return(grd);
            };

            // Analytical Sol for Params
            if (C.SetParamsAnalyticalSol == true)
            {
                C.VelFunctionU = X => VelocityXfunction(X, 0);
                C.VelFunctionV = X => VelocityYfunction(X, 0);
            }

            // Set Initial Conditions
            if (C.SetInitialConditions == true)
            {
                C.InitialValues_Evaluators.Add("VelocityX", X => VelocityXfunction(X, 0));
                C.InitialValues_Evaluators.Add("VelocityY", X => VelocityYfunction(X, 0));
                C.InitialValues_Evaluators.Add("StressXX", X => StressXXfunction(X, 0));
                C.InitialValues_Evaluators.Add("StressXY", X => StressXYfunction(X, 0));
                C.InitialValues_Evaluators.Add("StressYY", X => StressYYfunction(X, 0));
                C.InitialValues_Evaluators.Add("GravityX", X => C.GravityX(X, 0));
                C.InitialValues_Evaluators.Add("GravityY", X => C.GravityY(X, 0));
                C.InitialValues_Evaluators.Add("GravityXX", X => C.GravityXX(X, 0));
                C.InitialValues_Evaluators.Add("GravityXY", X => C.GravityXY(X, 0));
                C.InitialValues_Evaluators.Add("GravityYY", X => C.GravityYY(X, 0));

                if (C.SetInitialPressure == true || C.SkipSolveAndEvaluateResidual == true)
                {
                    C.InitialValues_Evaluators.Add("Pressure", X => Pressurefunction(X, 0));
                }
            }

            C.InitialValues_Evaluators.Add("Phi", X => - 1);

            // Set Boundary Conditions

            if (!C.FixedStreamwisePeriodicBC)
            {
                C.AddBoundaryValue("Velocity_inlet", "VelocityX", VelocityXfunction);
                C.AddBoundaryValue("Velocity_inlet", "VelocityY", VelocityYfunction);
                C.AddBoundaryValue("Velocity_inlet", "StressXX", StressXXfunction);
                C.AddBoundaryValue("Velocity_inlet", "StressXY", StressXYfunction);
                C.AddBoundaryValue("Velocity_inlet", "StressYY", StressYYfunction);
                C.AddBoundaryValue("Velocity_inlet", "Pressure", Pressurefunction);
                C.AddBoundaryValue("Velocity_inlet", "GravityX", C.GravityX);
                C.AddBoundaryValue("Velocity_inlet", "GravityY", C.GravityY);
                C.AddBoundaryValue("Velocity_inlet", "GravityXX", C.GravityXX);
                C.AddBoundaryValue("Velocity_inlet", "GravityXY", C.GravityXY);
                C.AddBoundaryValue("Velocity_inlet", "GravityYY", C.GravityYY);

                //C.AddBoundaryCondition("Pressure_Outlet", "Pressure", Pressurefunction);
            }
            return(C);
        }
        private static IBMControl ShockTubeToro1WithIBMAndAVTemplate(int dgDegree, ExplicitSchemes explicitScheme, int explicitOrder, int noOfCellsX = 50, int noOfCellsY = 10, bool AV = true)
        {
            IBMControl c = new IBMControl();

            c.DbPath = null;
            //c.DbPath = @"c:\bosss_db\";
            c.savetodb = false;

            c.saveperiod    = 1;
            c.PrintInterval = 1;

            double xMin = 0;
            double xMax = 1;
            double yMin = 0;
            double yMax = 1;

            c.DomainType       = DomainTypes.StaticImmersedBoundary;
            c.LevelSetFunction = delegate(double[] X, double t) {
                return(X[1] - 0.16);
            };
            c.LevelSetBoundaryTag     = "AdiabaticSlipWall";
            c.CutCellQuadratureType   = XQuadFactoryHelper.MomentFittingVariants.OneStepGaussAndStokes;
            c.LevelSetQuadratureOrder = 6;
            c.AgglomerationThreshold  = 0.3;
            c.AddVariable(IBMVariables.LevelSet, 1);

            //c.AddVariable(IBMVariables.FluidCells, 1);
            //c.AddVariable(IBMVariables.FluidCellsWithoutSourceCells, 1);
            //c.AddVariable(IBMVariables.CutCells, 1);
            //c.AddVariable(IBMVariables.CutCellsWithoutSourceCells, 1);
            //c.AddVariable(IBMVariables.SourceCells, 1);

            if (AV)
            {
                c.ActiveOperators = Operators.Convection | Operators.ArtificialViscosity;
            }
            else
            {
                c.ActiveOperators = Operators.Convection;
            }
            c.ConvectiveFluxType = ConvectiveFluxTypes.OptimizedHLLC;

            // Shock-capturing
            double sensorLimit = 1e-3;
            double epsilon0    = 1.0;
            double kappa       = 0.5;

            if (AV)
            {
                Variable sensorVariable = Variables.Density;
                c.ShockSensor = new PerssonSensor(sensorVariable, sensorLimit);
                c.AddVariable(Variables.ShockSensor, 0);
                c.ArtificialViscosityLaw = new SmoothedHeavisideArtificialViscosityLaw(c.ShockSensor, dgDegree, sensorLimit, epsilon0, kappa, lambdaMax: 2);
            }

            c.ExplicitScheme = explicitScheme;
            c.ExplicitOrder  = explicitOrder;

            c.EquationOfState = IdealGas.Air;

            c.MachNumber     = 1.0 / Math.Sqrt(c.EquationOfState.HeatCapacityRatio);
            c.ReynoldsNumber = 1.0;
            c.PrandtlNumber  = 0.71;

            c.AddVariable(Variables.Density, dgDegree);
            c.AddVariable(Variables.Momentum.xComponent, dgDegree);
            c.AddVariable(Variables.Momentum.yComponent, dgDegree);
            c.AddVariable(Variables.Energy, dgDegree);
            c.AddVariable(Variables.Velocity.xComponent, dgDegree);
            c.AddVariable(Variables.Velocity.yComponent, dgDegree);
            c.AddVariable(Variables.Pressure, dgDegree);
            c.AddVariable(Variables.Rank, 0);

            if (AV)
            {
                c.AddVariable(Variables.ArtificialViscosity, 2);
                c.AddVariable(Variables.CFLArtificialViscosity, 0);
            }
            c.AddVariable(Variables.CFL, 0);
            c.AddVariable(Variables.CFLConvective, 0);

            if (c.ExplicitScheme.Equals(ExplicitSchemes.LTS))
            {
                c.AddVariable(Variables.LTSClusters, 0);
            }

            c.GridFunc = delegate {
                double[] xNodes = GenericBlas.Linspace(xMin, xMax, noOfCellsX + 1);
                double[] yNodes = GenericBlas.Linspace(yMin, yMax, noOfCellsY + 1);
                var      grid   = Grid2D.Cartesian2DGrid(xNodes, yNodes, periodicX: false, periodicY: false);
                // Boundary conditions
                grid.EdgeTagNames.Add(1, "AdiabaticSlipWall");

                grid.DefineEdgeTags(delegate(double[] _X) {
                    return(1);
                });
                return(grid);
            };

            c.AddBoundaryValue("AdiabaticSlipWall");

            // Normal vector of initial shock
            Vector normalVector = new Vector(1, 0);

            // Direction vector of initial shock
            Vector r = new Vector(normalVector.y, -normalVector.x);

            r.Normalize();

            // Distance from a point X to the initial shock
            double[] p = new double[] { 0.5, 0.0 };

            double cellSize = Math.Min((xMax - xMin) / noOfCellsX, (yMax - yMin) / noOfCellsY);

            Func <double, double> SmoothJump = delegate(double distance) {
                // smoothing should be in the range of h/p
                double maxDistance = 4.0 * cellSize / Math.Max(dgDegree, 1);

                return((Math.Tanh(distance / maxDistance) + 1.0) * 0.5);
            };

            Func <double, double> Jump = (x => x <= 0.5 ? 0 : 1);

            // Initial conditions
            double densityLeft   = 1.0;
            double densityRight  = 0.125;
            double pressureLeft  = 1.0;
            double pressureRight = 0.1;

            //c.InitialValues_Evaluators.Add(Variables.Density, X => densityLeft - SmoothJump(DistanceFromPointToLine(X, p, r)) * (densityLeft - densityRight));
            //c.InitialValues_Evaluators.Add(Variables.Pressure, X => pressureLeft - SmoothJump(DistanceFromPointToLine(X, p, r)) * (pressureLeft - pressureRight));
            c.InitialValues_Evaluators.Add(Variables.Density, X => densityLeft - Jump(X[0]) * (densityLeft - densityRight));
            c.InitialValues_Evaluators.Add(Variables.Pressure, X => pressureLeft - Jump(X[0]) * (pressureLeft - pressureRight));
            c.InitialValues_Evaluators.Add(Variables.Velocity.xComponent, X => 0.0);
            c.InitialValues_Evaluators.Add(Variables.Velocity.yComponent, X => 0.0);

            // Time config
            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.CFLFraction   = 0.1;
            c.Endtime       = 0.001;
            c.NoOfTimesteps = int.MaxValue;

            c.ProjectName = "Shock tube";
            c.SessionName = String.Format("IBM shock tube, p={0}, {1}x{2} cells, agg={3}, s0={4:0.0E-00}, CFLFrac={5}, ALTS {6}/{7}/{8}({9}), Part={10}/{11}({12})", dgDegree, noOfCellsX, noOfCellsY, c.AgglomerationThreshold, sensorLimit, c.CFLFraction, c.ExplicitOrder, c.NumberOfSubGrids, c.ReclusteringInterval, c.maxNumOfSubSteps, c.GridPartType.ToString(), c.DynamicLoadBalancing_Period, c.DynamicLoadBalancing_ImbalanceThreshold);

            return(c);
        }
Exemple #46
0
        public static XdgTimesteppingTestControl Burgers(
            double angle             = 0.0,
            int degree               = 2,
            int NoOfTimesteps        = 80,
            InterfaceMode tsm        = InterfaceMode.MovingInterface,
            int GridResolutionFactor = 2)
        {
            XdgTimesteppingTestControl R = new XdgTimesteppingTestControl();

            R.ProjectName = "XdgMassMatrixEvolution/Burgers";
            R.savetodb    = false;
            R.DbPath      = null;

            // DG config
            // =========

            R.FieldOptions.Add("Phi", new FieldOpts()
            {
                Degree   = 2,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("u", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vx", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });
            R.FieldOptions.Add("Vy", new FieldOpts()
            {
                Degree   = degree,
                SaveToDB = FieldOpts.SaveToDBOpt.TRUE
            });

            // grid
            // ====

            R.GridFunc = delegate() {
                double[] Xnodes = GenericBlas.Linspace(-2, 2, 7 * GridResolutionFactor + 1);
                double[] Ynodes = GenericBlas.Linspace(-2, 2, 7 * GridResolutionFactor + 1);
                var      grd    = Grid2D.Cartesian2DGrid(Xnodes, Ynodes);

                grd.EdgeTagNames.Add(1, "Dirichlet");
                grd.EdgeTagNames.Add(2, "Neumann");

                grd.DefineEdgeTags(delegate(double[] X) {
                    byte ret;
                    if (Math.Abs(X[0] - (-1)) <= 1.0e-8 || Math.Abs(X[0] - (+1)) <= 1.0e-8)
                    {
                        ret = 1;
                    }
                    else
                    {
                        ret = 2;
                    }
                    return(ret);
                });

                return(grd);
            };

            // exact solution
            // ==============

            double TimeOffset = 0.1;


            double Nx = Math.Cos(angle);
            double Ny = Math.Sin(angle);

            R.BurgersDirection = new Platform.LinAlg.Vector2D(Nx, Ny);

            const double S = 0.5 * (2 + 1);

            R.S   = ((double[] X, double t) => S);
            R.Phi = ((double[] X, double t) => (X[0] - Nx * S * (t + TimeOffset)) * Nx + (X[1] - Ny * S * (t + TimeOffset)) * Ny);

            Func <double[], double> projCoord = X => X[0] * Nx + X[1] * Ny;

            Func <double, double, double> uAEx = delegate(double t, double xi) {
                return(2.0);
            };

            R.uA_Ex = ((X, t) => uAEx(t, projCoord(X)));
            R.uB_Ex = ((X, t) => 1.0);

            R.Eq = Equation.Burgers;

            R.InitialValues_Evaluators.Add("Phi", X => R.Phi(X, 0.0));
            R.InitialValues_Evaluators.Add("u#A", X => R.uA_Ex(X, 0.0));
            R.InitialValues_Evaluators.Add("u#B", X => R.uB_Ex(X, 0.0));


            // anderes zeugs
            // =============

            R.TimeSteppingScheme = TimeSteppingScheme.RK4;
            R.InterfaceMode      = tsm;

            R.Endtime       = 0.2;
            R.NoOfTimesteps = NoOfTimesteps;
            R.dtFixed       = R.Endtime / R.NoOfTimesteps;

            R.AgglomerationThreshold = 0.1;

            // return
            // ======

            return(R);
        }
Exemple #47
0
        static (GridCommons, int[][]) ExtractGridCommonsAndCellAggregation(
            IEnumerable <MeshCell <T> > cells,
            BoundaryConverter boundaryConverter)
        {
            List <BoSSS.Foundation.Grid.Classic.Cell> cellsGridCommons = new List <BoSSS.Foundation.Grid.Classic.Cell>();
            List <int[]> aggregation = new List <int[]>();

            foreach (MeshCell <T> cell in cells)
            {
                //Convert to BoSSSCell : Triangulate
                Vector[] voronoiCellVertices = cell.Vertices.Select(voVtx => voVtx.Position).ToArray();
                int[,] iVtxTri = PolygonTesselation.TesselatePolygon(voronoiCellVertices);
                //SortDescendingArea(iVtxTri, voronoiCellVertices);
                int[] Agg2Pt = new int[iVtxTri.GetLength(0)];

                bool isBoundaryCell = IsBoundary(cell);

                for (int iTri = 0; iTri < iVtxTri.GetLength(0); iTri++)
                { // loop over triangles of voronoi cell
                    int iV0 = iVtxTri[iTri, 0];
                    int iV1 = iVtxTri[iTri, 1];
                    int iV2 = iVtxTri[iTri, 2];

                    Vector V0 = voronoiCellVertices[iV0];
                    Vector V1 = voronoiCellVertices[iV1];
                    Vector V2 = voronoiCellVertices[iV2];

                    (iV0, iV1, iV2) = Rearrange(iV0, iV1, iV2, V0, V1, V2);

                    V0 = voronoiCellVertices[iV0];
                    V1 = voronoiCellVertices[iV1];
                    V2 = voronoiCellVertices[iV2];

                    Vector D1 = V1 - V0;
                    Vector D2 = V2 - V0;

                    bool positive = true;
                    if (D1.CrossProduct2D(D2) < 0)
                    {
                        if (isBoundaryCell)
                        {
                            Console.WriteLine($"Cell{cell.Node.AsVoronoiNode().Position} not positive. It is probably not convex.");
                            positive = false;
                            int it = iV0;
                            iV0 = iV2;
                            iV2 = it;

                            Vector vt = V0;
                            V0 = V2;
                            V2 = vt;

                            D1 = V1 - V0;
                            D2 = V2 - V0;
                        }
                        else
                        {
                            throw new Exception($"Created negatively oriented cell. Node = {cell.Node.AsVoronoiNode().Position}");
                        }
                    }

                    //if(D1.CrossProduct2D(D2) < 1.0e-7)
                    //{
                    //    Console.WriteLine($"Created very small cell. Node = {cell.Node.AsVoronoiNode().Position}, Area= {D1.CrossProduct2D(D2)}, positive = {positive}");
                    //}

                    Cell Cj = new Cell()
                    {
                        GlobalID = cellsGridCommons.Count,
                        Type     = CellType.Triangle_3,
                    };
                    Cj.TransformationParams = MultidimensionalArray.Create(3, 2);
                    Cj.TransformationParams.SetRowPt(0, V0);
                    Cj.TransformationParams.SetRowPt(1, V1);
                    Cj.TransformationParams.SetRowPt(2, V2);

                    Agg2Pt[iTri] = cellsGridCommons.Count;
                    cellsGridCommons.Add(Cj);

                    //Save BoundaryInformation
                    if (isBoundaryCell)
                    {
                        List <BoundaryFace> tags;
                        if (positive)
                        {
                            tags = GetBoundaryFacesOfTriangle(cell, iV0, iV1, iV2);
                        }
                        else
                        {
                            tags = GetBoundaryFacesOfNegativeTriangle(cell, iV0, iV1, iV2);
                        }
                        boundaryConverter.RegisterBoundaries(Cj, tags);
                    }
                    Cj.NodeIndices = new int[]
                    {
                        cell.Vertices[iV0].ID,
                        cell.Vertices[iV1].ID,
                        cell.Vertices[iV2].ID
                    };
                }
                aggregation.Add(Agg2Pt);
            }

            GridCommons grid = new Grid2D(Triangle.Instance)
            {
                Cells = cellsGridCommons.ToArray()
            };

            //PrintEdgeTags(cellsGridCommons);
            boundaryConverter.RegisterEdgesTo(grid);
            return(grid, aggregation.ToArray());
        }
Exemple #48
0
        /// <summary>
        /// Returns a two dimensional grid where each field contains the distance from the start point (the empty field).
        /// </summary>
        /// <returns>The path.</returns>
        /// <param name="gameGrid">Game grid.</param>
        /// <param name="fromLocation">the location to start from.</param>
        /// <param name="currentActiveTreasure">The current active treasre can always be stepped onto.</param>
        public static Grid2D<int> PreparePathGrid(GameFieldGrid gameGrid, GridLocation fromLocation, TreasureType currentActiveTreasure)
        {
            if(gameGrid == null)
            {
                throw new ArgumentNullException ("gameGrid");
            }

            if(fromLocation == null)
            {
                throw new ArgumentNullException ("fromLocation");
            }

            // Create a grid as big as the game field. The content of each item is the distance from the staring point (the empty spot).
            var pathGrid = new Grid2D<int> (gameGrid.Rows, gameGrid.Columns, pathFindingMaxVal);

            // Use a Disjkstra algorithm to find a path from the empty spot to the current active treasure.
            // First, set the presumed target location to a distance of 0.
            pathGrid.SetItem (fromLocation, 0);

            // Start calculating distances.
            while(true)
            {
                // Set to true if at least one field was changed. If nothing is changed during one loop, we're done.
                bool gridChanged = false;

                // Loop all fields until each field contains a distance value.
                for (int row = 0; row < gameGrid.Rows; row++)
                {
                    for (int col = 0; col < gameGrid.Columns; col++)
                    {
                        // Distance is one more than it was at the current location. Set for the surrounding fields.
                        int newDistance = pathGrid.GetItem (row, col);
                        if(newDistance != pathFindingMaxVal)
                        {
                            newDistance++;
                        }

                        var checkLocations = AIHelpers.GetAccessibleAdjacentLocations(gameGrid, new GridLocation(row, col), currentActiveTreasure);
                        foreach(var checkLocation in checkLocations)
                        {
                            // Remember the distance to the start point.
                            int currentDistance = pathGrid.GetItem (checkLocation);
                            if(newDistance < currentDistance)
                            {
                                pathGrid.SetItem (checkLocation, newDistance);
                                gridChanged = true;
                            }
                        }
                    }
                }

                // Bail out of the algorithm if we visited all nodes.
                if(!gridChanged)
                {
                    break;
                }
            }
            return pathGrid;
        }
Exemple #49
0
        void UpdateLOS()
        {
            if (this.Environment == null)
                return;

            if (World.LivingVisionMode != LivingVisionMode.LOS)
                throw new Exception();

            if (m_losLocation == this.Location &&
                m_losMapVersion == this.Environment.Version &&
                m_visionMap != null)
                return;

            if (m_visionMap == null)
            {
                m_visionMap = new Grid2D<bool>(this.VisionRange * 2 + 1, this.VisionRange * 2 + 1,
                    this.VisionRange, this.VisionRange);
                m_losMapVersion = 0;
            }

            int z = this.Z;
            var env = this.Environment;
            ShadowCastRecursive.Calculate(new IntPoint2(this.Location.X, this.Location.Y), this.VisionRange, m_visionMap, env.Size.Plane,
                p2 => !env.GetTileData(new IntPoint3(p2, z)).IsSeeThrough);

            m_losMapVersion = this.Environment.Version;
            m_losLocation = this.Location;
        }
Exemple #50
0
        public static IBMControl IBMNACA0012(int MeshPara, int dgDegree, double CFL, double agglomeration, double alpha)
        {
            IBMControl c = new IBMControl();

            c.savetodb = true;

            // Solver Settings
            c.dtMin         = 0.0;
            c.dtMax         = 1.0;
            c.Endtime       = 1000.0;
            c.CFLFraction   = CFL;
            c.NoOfTimesteps = 200000;

            c.PrintInterval      = 10;
            c.ResidualInterval   = 100;
            c.ResidualLoggerType = ResidualLoggerTypes.ChangeRate | ResidualLoggerTypes.Query;
            c.ResidualBasedTerminationCriteria.Add("changeRate_L2_abs_rhoE", 1E-8);

            //IBM Settings
            c.LevelSetBoundaryTag     = "adiabaticSlipWall";
            c.LevelSetQuadratureOrder = 2 * dgDegree + 2;
            c.AgglomerationThreshold  = agglomeration;

            // NEXT STEP: SET THIS BOOL TO FALSE AND JUST USE IN POSITIVE SUB_VOLUME;
            // THEN TRY BOUNDING BOX APPROACH?
            // WHY THE HELL DOES THIS CONFIGURATION FAIL!??!?!?!?
            c.CutCellQuadratureType             = XQuadFactoryHelper.MomentFittingVariants.Classic;
            c.SurfaceHMF_ProjectNodesToLevelSet = false;
            c.SurfaceHMF_RestrictNodes          = true;
            c.SurfaceHMF_UseGaussNodes          = false;
            c.VolumeHMF_NodeCountSafetyFactor   = 3.0;
            c.VolumeHMF_RestrictNodes           = true;
            c.VolumeHMF_UseGaussNodes           = false;

            //Guid restart = new Guid("cd061fe3-3215-483a-8790-f6fd686d6676");
            //c.RestartInfo = new Tuple<Guid, BoSSS.Foundation.IO.TimestepNumber>(restart, -1);

            // Session Settings
            c.DbPath = @"\\fdyprime\userspace\kraemer-eis\FDY-Cluster\dbe_NACA\";
            //c.DbPath = @"C:\bosss_dbv2\NACA0012";
            c.savetodb           = true;
            c.saveperiod         = 10000;
            c.ProjectName        = "MeshPara:" + MeshPara + "_CFL=" + c.CFLFraction + "_p=" + dgDegree + "_agg=" + c.AgglomerationThreshold + "_alpha=" + alpha + "_HMF=" + c.CutCellQuadratureType;
            c.ProjectDescription = "NACA0012 Steady Test with Ma=0.5";
            c.Tags.Add("NACA0012");
            c.Tags.Add("IBM Test");
            c.Tags.Add("steady");

            // Solver Type
            c.DomainType         = DomainTypes.StaticImmersedBoundary;
            c.ActiveOperators    = Operators.Convection;
            c.ConvectiveFluxType = ConvectiveFluxTypes.OptimizedHLLC;

            // Time-Stepping Settings
            c.ExplicitScheme = ExplicitSchemes.RungeKutta;
            c.ExplicitOrder  = 1;

            //Material Settings
            c.EquationOfState = IdealGas.Air;



            // Primary Variables
            c.AddVariable(Variables.Density, dgDegree);
            c.AddVariable(Variables.Momentum.xComponent, dgDegree);
            c.AddVariable(Variables.Momentum.yComponent, dgDegree);
            c.AddVariable(Variables.Energy, dgDegree);

            c.AddVariable(IBMVariables.LevelSet, 8);

            // Refined Region
            double xBegin = -0.012;
            double xEnd   = 1.01;

            c.GridFunc = delegate
            {
                int chords = 100;

                int xleft   = -chords;
                int xRight  = chords;
                int yBottom = -chords;
                int yTop    = chords;

                double spacingFactor = 3.95;

                double[] xnodes1 = Grid1D.TanhSpacing(xleft, xBegin, MeshPara + 1, spacingFactor, false);
                double[] xnodes2 = Grid1D.TanhSpacing_DoubleSided(xBegin, xEnd, MeshPara + 1, 2.0);
                double[] xnodes3 = Grid1D.TanhSpacing(xEnd, xRight, MeshPara + 1, spacingFactor, true);

                double[] xComplete = new double[xnodes1.Length + xnodes2.Length + xnodes3.Length - 2];
                for (int i = 0; i < xnodes1.Length; i++)
                {
                    xComplete[i] = xnodes1[i];
                }
                for (int i = 1; i < xnodes2.Length; i++)
                {
                    xComplete[i + xnodes1.Length - 1] = xnodes2[i];
                }
                for (int i = 1; i < xnodes3.Length; i++)
                {
                    xComplete[i + xnodes1.Length + xnodes2.Length - 2] = xnodes3[i];
                }

                double yrefinedTop    = 0.2;
                double yrefinedBottom = -0.2;

                double[] ynodes1 = Grid1D.TanhSpacing(yBottom, yrefinedBottom, MeshPara + 1, spacingFactor, false);
                double[] ynodes2 = GenericBlas.Linspace(yrefinedBottom, yrefinedTop, (int)(0.75 * MeshPara) + 1);
                double[] ynodes3 = Grid1D.TanhSpacing(yrefinedTop, yTop, MeshPara + 1, spacingFactor, true);

                double[] yComplete = new double[ynodes1.Length + ynodes2.Length + ynodes3.Length - 2];
                for (int i = 0; i < ynodes1.Length; i++)
                {
                    yComplete[i] = ynodes1[i];
                }
                for (int i = 1; i < ynodes2.Length; i++)
                {
                    yComplete[i + ynodes1.Length - 1] = ynodes2[i];
                }
                for (int i = 1; i < ynodes3.Length; i++)
                {
                    yComplete[i + ynodes1.Length + ynodes2.Length - 2] = ynodes3[i];
                }


                int numOfCellsX = (xRight - xleft) * MeshPara;
                int numOfCellsY = (yTop - yBottom) * MeshPara;

                GridCommons grid = Grid2D.Cartesian2DGrid(
                    xComplete,
                    yComplete
                    );

                grid.EdgeTagNames.Add(1, "supersonicinlet");
                grid.DefineEdgeTags(x => 1);
                grid.Name = "[" + xleft + "," + xRight + "]x[" + yBottom + "," + yTop + "]_Cells:(" + (xComplete.Length - 1) + "x" + (yComplete.Length - 1) + ")";

                return(grid);
            };



            // Functions
            Func <double[], double, double> rho      = (X, t) => 1.0;
            Func <double[], double, double> u0       = (X, t) => 1.0;
            Func <double[], double, double> u1       = (X, t) => 0.0;
            Func <double[], double, double> pressure = (X, t) => 2.8571428571428;

            Func <double[], double> test = X => 1 - 0.05 * 0.4 / 1.4 * Math.Pow(Math.Exp(1 - X[0] * X[0] - X[1] * X[1]), (1 / 0.4));

            Func <double[], double, double> levelSet = delegate(double[] X, double t) {
                double value = 0.0;

                double radian = alpha * Math.PI / 180;

                double xRotated = 1 + Math.Cos(radian) * (X[0] - 1) - Math.Sin(radian) * (X[1]);
                double yRotated = Math.Sin(radian) * (X[0] - 1) + Math.Cos(radian) * (X[1]);

                double a = 0.6;
                //double b = 0.2969;
                double c1 = 0.126;
                double d  = 0.3516;
                double e  = 0.2843;
                double f  = 0.1036;


                if (yRotated >= 0.0 || (X[0] > 0.562875 && X[1] > 0))
                {
                    //if (yRotated >= 0.0 ){
                    value = Math.Pow((yRotated + a * (c1 * xRotated + d * Math.Pow(xRotated, 2) - e * Math.Pow(xRotated, 3) + f * Math.Pow(xRotated, 4))), 2) - 0.0317338596 * xRotated;
                }
                else
                {
                    value = Math.Pow((-yRotated + a * (c1 * xRotated + d * Math.Pow(xRotated, 2) - e * Math.Pow(xRotated, 3) + f * Math.Pow(xRotated, 4))), 2) - 0.0317338596 * xRotated;
                }

                //value = yRotated - Math.Tan(radian)*xRotated;

                return(value);
            };

            c.LevelSetFunction = levelSet;

            //Initial Values
            c.InitialValues_Evaluators.Add(Variables.Density, X => rho(X, 0.0));
            c.InitialValues_Evaluators.Add(Variables.Velocity.xComponent, X => u0(X, 0.0));
            c.InitialValues_Evaluators.Add(Variables.Velocity.yComponent, X => u1(X, 0.0));
            c.InitialValues_Evaluators.Add(Variables.Pressure, X => pressure(X, 0.0));

            //BoundaryConditions
            c.AddBoundaryCondition("adiabaticSlipWall");
            c.AddBoundaryCondition("supersonicInlet", Variables.Density, rho);
            c.AddBoundaryCondition("supersonicInlet", Variables.Velocity.xComponent, u0);
            c.AddBoundaryCondition("supersonicInlet", Variables.Velocity.yComponent, u1);
            c.AddBoundaryCondition("supersonicInlet", Variables.Pressure, pressure);


            // Queries

            c.Queries.Add("L2ErrorEntropy", IBMQueries.L2Error(state => state.Entropy, (X, t) => 2.8571428571428));
            c.Queries.Add("IBMDragForce", IBMQueries.IBMDragForce());
            c.Queries.Add("IBMLiftForce", IBMQueries.IBMLiftForce());
            return(c);
        }