Beispiel #1
0
        public Surface(Proxys.SurfaceType surfacetype, Patch[,] patches, List <CatPoint> catPoints, SceneData scene, bool uLooped, bool vLooped)
        {
            SurfaceType  = surfacetype;
            this.patches = new List <Patch>();
            this.uLooped = uLooped;
            this.vLooped = vLooped;
            foreach (var patch in patches)
            {
                this.patches.Add(patch);
                patch.SetSurface(this);
            }
            this.catPoints = catPoints;
            this.scene     = scene;
            PatchesU       = patches.GetLength(1);
            PatchesV       = patches.GetLength(0);

            this.catPoints.ForEach(x =>
            {
                x.OnReplace            += OnPointReplaced;
                x.DependentUnremovable += 1;
            });

            orderedPatches = patches;
            ShowPoints     = ShowPoints;
        }
        /// <summary>
        /// Calculates the sum of the 3-digit numbers found in the top left corner of each sudoku solution grid
        /// </summary>
        static void P096()
        {
            int            ans     = 0;
            List <int[, ]> sudokus = new List <int[, ]>();

            List <int>[,] candidateBoardBase = new List <int> [9, 9];
            for (int r = 0; r < candidateBoardBase.GetLength(0); r++)
            {
                for (int c = 0; c < candidateBoardBase.GetLength(1); c++)
                {
                    candidateBoardBase[r, c] = Enumerable.Range(1, 9).ToList();
                }
            }
            using (var sudokuFile = File.OpenText(@"...\...\Resources\p096_sudoku.txt"))
            {
                int[,] sudokuBoard = new int[9, 9];
                while (sudokuFile.ReadLine() != null)
                {
                    readSudokuBoard(sudokuBoard, sudokuFile);
                    List <int>[,] candidateBoard = Functions.getDeepCopy <List <int> [, ]>(candidateBoardBase);
                    updateSudokuBoards(sudokuBoard, candidateBoard);
                    int[,] solution = getSudokuSolution(sudokuBoard, candidateBoard);
                    //printSudoku(solution);
                    ans += solution[0, 0] * 100 + solution[0, 1] * 10 + solution[0, 2];
                }
            }
            Console.WriteLine(ans);
        }
Beispiel #3
0
        public static SinglyLinkedList <Point> FindPaths(List <ICreature>[,] map, Point start, Point finish)
        {
            if (start == finish)
            {
                return(null);
            }
            var queue   = new Queue <SinglyLinkedList <Point> >();
            var visited = new HashSet <Point>();

            queue.Enqueue(new SinglyLinkedList <Point>(start));
            var width  = map.GetLength(0);
            var height = map.GetLength(1);

            while (queue.Count > 0)
            {
                var path  = queue.Dequeue();
                var point = path.Value;
                if (!visited.Contains(point) && point.X >= 0 && point.X < width && point.Y >= 0 && point.Y < height - 1 &&
                    !map[point.X, point.Y].Any(x => x is Terrain) &&
                    (map[point.X, point.Y + 1].Any(x => x is Terrain || x is Stairs) ||
                     (map[point.X, point.Y].Any(x => x is Stairs) && path.Previous.Value.Y < point.Y)))
                {
                    if (finish == point)
                    {
                        return(path.Reverse());
                    }
                    visited.Add(point);
                    AddPoint(queue, path);
                }
            }
            return(null);
        }
        public void SauvegarderCarte(List<Tuile>[,] tuileArray, String asset)
        {
            ecrireCarte = new System.IO.StreamWriter(asset);

            int width = tuileArray.GetLength(0);
            int height = tuileArray.GetLength(1);

            ecrireCarte.WriteLine(width);
            ecrireCarte.WriteLine(height);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    string str = "";

                    foreach (Tuile tuile in tuileArray[x, y])
                    {
                        str += tuile.type;
                        if (tuile.hauteur < 10)
                            str += "0";
                        str += tuile.hauteur;
                    }

                    ecrireCarte.WriteLine(str);

                }
            }

            ecrireCarte.Close();

            Console.WriteLine("CARTE SAUVEGARDEE");
        }
Beispiel #5
0
        /// <summary>
        /// Gets conditional probability table plot data.
        /// </summary>
        /// <param name="array">
        /// The array representing the conditional probability table.
        /// </param>
        /// <param name="mapping">
        /// The data mapping.
        /// </param>
        /// <param name="rowLabel">
        /// The row label.
        /// </param>
        /// <param name="columnLabel">
        /// The column label.
        /// </param>
        /// <returns>
        /// The conditional probability table plot data.
        /// </returns>
        public static Dictionary <string, Dictionary <string, List <Tweet> > > GetTweetMatrix(
            List <Tweet>[,] array,
            CrowdDataMapping mapping,
            string rowLabel,
            string columnLabel)
        {
            Debug.Assert(
                array.GetLength(0) == mapping.LabelCount && array.GetLength(1) == mapping.LabelCount,
                "Inconsistent arguments");

            var result = new Dictionary <string, Dictionary <string, List <Tweet> > >();

            for (var i = 0; i < mapping.LabelCount; i++)
            {
                var rowName = $"{mapping.LabelValueToString[mapping.LabelIndexToValue[i]]} ({rowLabel})";
                var row     = new Dictionary <string, List <Tweet> >();

                for (var j = 0; j < mapping.LabelCount; j++)
                {
                    var colName = $"{mapping.LabelValueToString[mapping.LabelIndexToValue[j]]} ({columnLabel})";
                    row[colName] = array[i, j];
                }

                result[rowName] = row;
            }

            return(result);
        }
Beispiel #6
0
        public void Draw(SpriteBatch spriteBatch)
        {
            foreach (Tile drawTile in DrawTiles)
            {
                if (drawTile != null)
                {
                    drawTile.Draw(spriteBatch);
                }
            }

            for (int x = 0; x < ObjectsInArea.GetLength(0); x++)
            {
                for (int y = 0; y < ObjectsInArea.GetLength(1); y++)
                {
                    int c = ObjectsInArea[x, y].Count;
                    if (c == 1)
                    {
                        spriteBatch.Draw(DrawTiles[0, 0].Texture, new Rectangle(x * 64, y * 64, 64, 64), Color.Red);
                    }

                    if (c == 2)
                    {
                        spriteBatch.Draw(DrawTiles[0, 0].Texture, new Rectangle(x * 64, y * 64, 64, 64), Color.Green);
                    }
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Maps the indicated point that has been rotated, back to the initial position.
        ///
        /// If that initial position is not in the first quadrant, it's reflecte back into it.
        /// </summary>
        /// <param name="mapPoint">Point that should be mapped to the rotationMatrix.</param>
        /// <param name="angle">Angle that the point has been rotated.</param>
        /// <param name="rotationMatrix">All the Point lists that make up the rotation data.  Indeces map to initial position values.</param>
        private static void MapRotatedPoint(Point mapPoint, int angle, List <Point>[,] rotationMatrix)
        {
            // Rotate point back to it's generic grid position
            Point rotated = RotatePointAroundCenter(-angle, mapPoint);

            // Get hash values for the rotated point
            int row = rotated.Y + MAX_FLAKE_RADIUS;
            int col = rotated.X + MAX_FLAKE_RADIUS;

            // If within the bounds of the matrix && the first quadrant
            if (col >= MAX_FLAKE_RADIUS && col < rotationMatrix.GetLength(1) &&
                row >= MAX_FLAKE_RADIUS && row < rotationMatrix.GetLength(0))
            {
                // If point list hasn't been set, set it
                if (rotationMatrix[row, col] == null)
                {
                    rotationMatrix[row, col] = new List <Point>();
                }

                // Add the point if it's not already there
                if (!rotationMatrix[row, col].Contains(mapPoint))
                {
                    rotationMatrix[row, col].Add(mapPoint);
                }
            }
        }
    void MarkCircle(ref List <int>[,] grid, Circle circle, float cellSize, int mark)
    {
        int cellX      = (int)(circle.center.x / cellSize);
        int cellY      = (int)(circle.center.y / cellSize);
        int offset     = (int)(circle.radius / cellSize);
        int markStartX = Mathf.Max(0, cellX - offset);
        int markEndX   = Mathf.Min(cellX + offset, grid.GetLength(0) - 1);
        int markStartY = Mathf.Max(0, cellY - offset);
        int markEndY   = Mathf.Min(cellY + offset, grid.GetLength(1) - 1);

        for (int x = markStartX; x <= markEndX; x++)
        {
            for (int y = markStartY; y <= markEndY; y++)
            {
                float dist = Vector2.Distance(new Vector2(cellX, cellY), new Vector2(x, y));
                if (dist <= circle.radius / 2 / cellSize)
                {
                    if (grid[x, y] == null)
                    {
                        grid[x, y] = new List <int>()
                        {
                            mark
                        }
                    }
                    ;
                    else
                    {
                        grid[x, y].Add(mark);
                    }
                }
            }
        }
    }
 /// <summary>
 /// Updates a Sudoku board and a candidate Sudoku board
 /// </summary>
 /// <param name="board">Int[,]</param>
 /// <param name="candidateBoard">List<int>[,]</param>
 static void updateSudokuBoards(int[,] board, List <int>[,] candidateBoard)
 {
     for (int r = 0; r < board.GetLength(0); r++)
     {
         for (int c = 0; c < board.GetLength(1); c++)
         {
             if (board[r, c] != 0)
             {
                 removeSudokuCandidateRow(board[r, c], r, candidateBoard);
                 removeSudokuCandidateColumn(board[r, c], c, candidateBoard);
                 removeSudokuCandidateBlock(board[r, c], r, c, candidateBoard);
                 candidateBoard[r, c] = new List <int>();
             }
         }
     }
     for (int r = 0; r < candidateBoard.GetLength(0); r++)
     {
         for (int c = 0; c < candidateBoard.GetLength(1); c++)
         {
             if (candidateBoard[r, c].Count == 1)
             {
                 board[r, c]          = candidateBoard[r, c][0];
                 candidateBoard[r, c] = new List <int>();
                 updateSudokuBoards(board, candidateBoard);
             }
         }
     }
 }
Beispiel #10
0
            public Map(RenderingTextureAllocator Allocator)
            {
                // Create map
                _map = new List <Entry> [Allocator.Size.Z, Allocator.Size.Y / _mapGranularity, Allocator.Size.X / _mapGranularity];
                for (int z = 0; z < _map.GetLength(0); ++z)
                {
                    for (int y = 0; y < _map.GetLength(1); ++y)
                    {
                        for (int x = 0; x < _map.GetLength(2); ++x)
                        {
                            _map[z, y, x] = new List <Entry>();
                        }
                    }
                }

                // Fill map
                foreach (KeyValuePair <RenderingTexture, VectorInt3> availableTexture in Allocator.AvailableTextures)
                {
                    Entry      @ref       = new Entry(availableTexture);
                    VectorInt2 startPixel = new VectorInt2(availableTexture.Value.X, availableTexture.Value.Y);
                    VectorInt2 endPixel   = startPixel + (availableTexture.Key.To - availableTexture.Key.From);
                    VectorInt2 startBlock = startPixel / _mapGranularity;
                    VectorInt2 endBlock   = (endPixel + new VectorInt2(_mapGranularity - 1, _mapGranularity - 1)) / _mapGranularity;
                    for (int x = startBlock.X; x < endBlock.X; ++x)
                    {
                        for (int y = startBlock.Y; y < endBlock.Y; ++y)
                        {
                            _map[availableTexture.Value.Z, y, x].Add(@ref);
                        }
                    }
                }
            }
        public void SaveToFile(string outputFileName, List <RelationshipDegreeUI>[,] dataArray)
        {
            using (StreamWriter outfile = new StreamWriter(outputFileName))
            {
                for (int line = 0; line < dataArray.GetLength(0); line++)
                {
                    string content = "";

                    for (int column = 0; column < dataArray.GetLength(1); column++)
                    {
                        foreach (var cell in dataArray[line, column])
                        {
                            if (cell != null)
                            {
                                content += cell.RelationshipDegreeNumber + ";";
                            }
                        }

                        if (content != "")
                        {
                            content = content.Remove(content.Length - 1);
                        }

                        content += ",";
                    }

                    if (content != "")
                    {
                        content = content.Remove(content.Length - 1);
                    }

                    outfile.WriteLine(content);
                }
            }
        }
Beispiel #12
0
    public void GenerateRoad(OrientedPoint seed, int length, bool major, bool rev)
    {
        // Inherit some variables from parents
        float offset   = GetComponentInParent <RoadNetwork>()._offset;
        int   interval = GetComponentInParent <RoadNetwork>()._interval;
        int   scale    = GetComponentInParent <CityGenerator>().scale;

        List <OrientedPoint>[,] roadPoints = GetComponentInParent <RoadNetwork>().roadPoints;

        field = new Field();
        path  = field.Trace(field.SampleOrthogonal, scale, offset, major, transform.position + seed.position, rev, length, roadPoints);

        if (path.Count == 0)
        {
            return;
        }

        // Update neighbor of first point in path
        path[0].neighbors.Add(seed);

        Extrude(path);

        // Pass road path to parent and round to chunk
        foreach (OrientedPoint point in path)
        {
            int indX = ((int)(point.position.x / 10) + roadPoints.GetLength(0) / 2);
            int indZ = ((int)(point.position.z / 10) + roadPoints.GetLength(1) / 2);

            GetComponentInParent <RoadNetwork>().roadPoints[indX, indZ].Add(point);
        }
    }
Beispiel #13
0
        public void show_Synthesis_of_Priority(string[] header, double[,] value)
        {
            List <string>[] manuals_on_table = new List <string> [value.GetLength(0)];
            double          sum = 0;

            for (int i = 0; i < manuals_on_table.GetLength(0); i++)
            {
                manuals_on_table[i] = new List <string>();
                manuals_on_table[i].Add(header[i]);
                double hasil_kali = 1;
                for (int j = 0; j < value.GetLength(1); j++)
                {
                    manuals_on_table[i].Add(Math.Round(value[i, j], 2, MidpointRounding.AwayFromZero).ToString());
                    hasil_kali = hasil_kali * value[i, j];
                }
                manuals_on_table[i].Add(Math.Round(hasil_kali, 2, MidpointRounding.AwayFromZero).ToString());
                double Ai = Math.Pow(hasil_kali, (1 / Convert.ToDouble(value.GetLength(1))));
                manuals_on_table[i].Add(Math.Round(Ai, 2, MidpointRounding.AwayFromZero).ToString());
                sum = sum + Math.Pow(hasil_kali, (1 / Convert.ToDouble(value.GetLength(1))));
            }
            Console.WriteLine("SUM : " + sum.ToString());
            for (int i = 0; i < manuals_on_table.GetLength(0); i++)
            {
                double Xi = (Convert.ToDouble(manuals_on_table[i].LastOrDefault()) / sum);
                manuals_on_table[i].Add(Math.Round(Xi, 2, MidpointRounding.AwayFromZero).ToString());
                dgv_manuals.Rows.Add(manuals_on_table[i].ToArray());
            }
        }
Beispiel #14
0
        // updates this grid based on the motion of obj
        public void Update(CollidableObject obj, CollisionBox oldBox, CollisionBox newBox)
        {
            int oldMinX = (int)(oldBox.Min.X / squareSize);
            int oldMaxX = (int)(oldBox.Max.X / squareSize);
            int oldMinY = (int)(oldBox.Min.Y / squareSize);
            int oldMaxY = (int)(oldBox.Max.Y / squareSize);
            int newMinX = (int)(newBox.Min.X / squareSize);
            int newMaxX = (int)(newBox.Max.X / squareSize);
            int newMinY = (int)(newBox.Min.Y / squareSize);
            int newMaxY = (int)(newBox.Max.Y / squareSize);

            for (int x = oldMinX; x <= oldMaxX; x++)
            {
                for (int y = oldMinY; y <= oldMaxY; y++)
                {
                    if (x >= 0 && y >= 0 && x < grid.GetLength(0) && y < grid.GetLength(1))
                    {
                        grid[x, y].Remove(obj);
                    }
                }
            }
            for (int x = newMinX; x <= newMaxX; x++)
            {
                for (int y = newMinY; y <= newMaxY; y++)
                {
                    if (x >= 0 && y >= 0 && x < grid.GetLength(0) && y < grid.GetLength(1))
                    {
                        grid[x, y].Add(obj);
                    }
                }
            }
        }
Beispiel #15
0
        private List <CameraVisibility> getUniqueVisibilities(List <CameraVisibility>[,,] camVisibilitiesAtPos)
        {
            List <CameraVisibility> list = new List <CameraVisibility>();
            int length  = camVisibilitiesAtPos.GetLength(0);
            int length2 = camVisibilitiesAtPos.GetLength(1);
            int length3 = camVisibilitiesAtPos.GetLength(2);
            int num     = 0;

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length2; j++)
                {
                    for (int k = 0; k < length3; k++)
                    {
                        List <CameraVisibility> list2 = camVisibilitiesAtPos[i, j, k];
                        if (list2 != null)
                        {
                            for (int l = 0; l < list2.Count; l++)
                            {
                                list.Add(list2[l]);
                                num++;
                            }
                        }
                    }
                }
            }
            return(list);
        }
Beispiel #16
0
 public void AddSolids()
 {
     SolidChunks = new List <Tile> [Width / CHUNK_FACTOR, Height / CHUNK_FACTOR];
     for (int x = 0; x < Width; x++)
     {
         for (int y = 0; y < Height; y++)
         {
             int chunkX = x / CHUNK_FACTOR;
             int chunkY = y / CHUNK_FACTOR;
             if (chunkX >= SolidChunks.GetLength(0))
             {
                 chunkX--;
             }
             if (chunkY >= SolidChunks.GetLength(1))
             {
                 chunkY--;
             }
             if (SolidChunks[chunkX, chunkY] == null)
             {
                 SolidChunks[chunkX, chunkY] = new List <Tile>();
             }
             AddSolidTile(0, x, y);
         }
     }
 }
        static List <Point <byte> >[,] StworzTabliceSzachowanPoPrzekatnej(int rozmiar)
        {
            var rozmiarTablicy   = rozmiar * rozmiar;
            var tablicaSzachowan = new List <Point <byte> > [rozmiar, rozmiar];

            for (int i = 0; i < tablicaSzachowan.GetLength(0); i++)
            {
                for (int j = 0; j < tablicaSzachowan.GetLength(1); j++)
                {
                    var lista = new List <Point <byte> >();

                    for (int k = 0; k < rozmiar; k++)
                    {
                        var y = j - (i - k);
                        if (y >= 0 && y < rozmiar)
                        {
                            lista.Add(new Point <byte> {
                                X = (byte)k, Y = (byte)y
                            });
                        }
                        y = j + (i - k);
                        if (y >= 0 && y < rozmiar)
                        {
                            lista.Add(new Point <byte> {
                                X = (byte)k, Y = (byte)y
                            });
                        }
                    }

                    tablicaSzachowan[i, j] = lista.GroupBy(a => new { a.X, a.Y }).Select(a => a.Last()).ToList();
                }
            }

            return(tablicaSzachowan);
        }
Beispiel #18
0
    private void InsertDataIntoList(string[] lines)
    {
        int numOfLines = lines.Length; //number of lines in the csv file

        for (int k = 0; k < numOfMagics; k++)
        {
            for (int i = 0; i < magics.GetLength(1); i++)
            {
                for (int j = 0; j < magics.GetLength(2); j++)
                {
                    magics[k, i, j] = new List <double>();
                }
            }
        }
        //runs on all the rows
        for (int i = 0; i < numOfLines; i++)
        {
            string[] line = lines[i].Split(',');
            //for each row, checks to which magic it belongs
            for (int j = 1; j < line.Length; j++)
            {
                if (line[j] != "")
                {
                    magics[(int)line[0][1] - 48, (int)line[0][2] - 48, (int)line[0][3] - 48].Add(double.Parse(line[j]));
                }
            }
        }
    }
Beispiel #19
0
            public Entry Lookup(VectorInt3 pos)
            {
                int mapX = pos.X / _mapGranularity;
                int mapY = pos.Y / _mapGranularity;

                if (mapX < 0 || mapY < 0 || mapX >= _map.GetLength(2) || mapY >= _map.GetLength(1))
                {
                    return(null);
                }

                List <Entry> candidates = _map[pos.Z, mapY, mapX];

                foreach (Entry candidate in candidates)
                {
                    if ((pos.X >= candidate.Pos.X) && (pos.Y >= candidate.Pos.Y))
                    {
                        VectorInt2 size = candidate.Texture.To - candidate.Texture.From;
                        if ((pos.X < (candidate.Pos.X + size.X)) && (pos.Y < (candidate.Pos.Y + size.Y)))
                        {
                            return(candidate);
                        }
                    }
                }
                return(null);
            }
Beispiel #20
0
        private static List <node> GetAdjacentNodes(node root, List <node>[,] nodeMap)
        {
            var ret = new List <node>();

            if (root.X != 0)
            {
                ret.AddRange(nodeMap[root.X - 1, root.Y].Where(n => n.Equipped == root.Equipped));
            }
            if (root.Y != 0)
            {
                ret.AddRange(nodeMap[root.X, root.Y - 1].Where(n => n.Equipped == root.Equipped));
            }
            if (root.X != nodeMap.GetLength(0) - 1)
            {
                ret.AddRange(nodeMap[root.X + 1, root.Y].Where(n => n.Equipped == root.Equipped));
            }
            if (root.Y != nodeMap.GetLength(1) - 1)
            {
                ret.AddRange(nodeMap[root.X, root.Y + 1].Where(n => n.Equipped == root.Equipped));
            }
            ret.AddRange(nodeMap[root.X, root.Y].Where(n => n.Equipped != root.Equipped));

            return(ret);

            // return nodes.Where(n =>
            //     (n.X == root.X && n.Y == root.Y - 1 && n.Equipped == root.Equipped) ||
            //     (n.X == root.X && n.Y == root.Y + 1 && n.Equipped == root.Equipped) ||
            //     (n.X == root.X + 1 && n.Y == root.Y && n.Equipped == root.Equipped) ||
            //     (n.X == root.X - 1 && n.Y == root.Y && n.Equipped == root.Equipped) ||
            //     (n.X == root.X && n.Y == root.Y && n.Equipped != root.Equipped)).ToList();
        }
Beispiel #21
0
        private void DrawFabric(List <int>[,] fabric, bool clearScreen = false)
        {
            if (clearScreen)
            {
                Console.Clear();
            }

            int rowLength = fabric.GetLength(0);
            int colLength = fabric.GetLength(1);

            for (int i = 0; i < rowLength; i++)
            {
                for (int j = 0; j < colLength; j++)
                {
                    if (fabric[i, j].Count == 1)
                    {
                        Console.Write(fabric[i, j][0]);
                    }
                    else if (fabric[i, j].Count > 1)
                    {
                        Console.Write("X");
                    }
                    else
                    {
                        Console.Write(".");
                    }
                }
                Console.WriteLine();
            }
        }
Beispiel #22
0
    public int length; // = 5000; // Global max length for each road generated

    public void GenerateRoadNetwork(OrientedPoint startingSeed, int iter, int length, int interval)
    {
        // Reference to parent
        CityGenerator parent = gameObject.GetComponentInParent <CityGenerator>();

        _interval = parent.interval;
        _offset   = parent.offset;
        _length   = parent.length;
        _iter     = parent.length;
        ctr       = _iter;

        // Create and initialize new lookup matrix (chunks)
        roadPoints = new List <OrientedPoint> [500, 500];
        for (int x = 0; x < roadPoints.GetLength(0); x++)
        {
            for (int z = 0; z < roadPoints.GetLength(1); z++)
            {
                roadPoints[x, z] = new List <OrientedPoint>();
            }
        }

        // Clear the queue before new generation starts
        seeds.Clear();

        // Function structure
        GameObject mainRoad = new GameObject("Main Road");

        mainRoad.AddComponent <Road>().transform.parent = this.transform;

        Road road = mainRoad.GetComponent <Road>();

        // Generate the first road from the starting point
        road.GenerateRoad(startingSeed, length, true, false);

        // Extract seeds from the road and add to queue
        AddCandidatesToQueue(road.path, interval);


        while (seeds.Count != 0 && iter > 0)
        {
            OrientedPoint roadSeed  = seeds.Dequeue();
            GameObject    leftRoad  = GenerateChildRoad();
            GameObject    rightRoad = GenerateChildRoad();

            // Generate the subroads with alternating major flag
            // Flip the major flag for the next road
            bool major = !roadSeed.major;

            Road left  = leftRoad.GetComponent <Road>();
            Road right = rightRoad.GetComponent <Road>();

            // Generate roads in either direction from seed

            GenerateRoads(left, right, roadSeed, interval, major);

            iter--;
            ctr--;
        }
    }
Beispiel #23
0
        static void Main(string[] args)
        {
            int[] s = { 0, 1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12, 24 };
            int[] e = { 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 24 };

            List <int>[,] result = new List <int> [13, 13];
            for (int i = 0; i < result.GetLength(0); ++i)
            {
                for (int j = 0; j < result.GetLength(1); ++j)
                {
                    result[i, j] = new List <int>();
                }
            }

            for (int j = 0; j < 13; ++j)
            {
                for (int i = 0; i < j - 1; ++i)
                {
                    //考虑s[ij] i结束之后 j开始之前,活动集合存不存在
                    //e[i] s[j] 这个时间之内的所有活动
                    List <int> sij = new List <int>();
                    for (int number = 1; number < s.Length - 1; ++number)
                    {
                        if (s[number] >= e[i] && e[number] <= s[j])
                        {
                            sij.Add(number);
                        }
                    }

                    if (sij.Count > 0)
                    {
                        //result[i,] = max(result[i, k] + result[k, j] + k}

                        int        maxCount = 0;
                        List <int> tempList = new List <int>();
                        foreach (int number in sij)
                        {
                            int count = result[i, number].Count + result[number, j].Count + 1;
                            if (maxCount < count)
                            {
                                maxCount = count;
                                tempList = result[i, number].Union(result[number, j]).ToList();
                                tempList.Add(number);
                            }
                        }

                        result[i, j] = tempList;
                    }
                }
            }

            foreach (int temp in result[0, 12])
            {
                Console.WriteLine(temp);
            }


            Console.ReadKey();
        }
Beispiel #24
0
 public List <GameObject> get(int x, int y)
 {
     if (x < 0 || x >= mapArray.GetLength(0) || y < 0 || y >= mapArray.GetLength(1))
     {
         return(null);
     }
     return(mapArray [x, y]);
 }
Beispiel #25
0
 public Level(string map, int numberPlayer)
 {
     Map              = MapCreator.CreateMap(map, numberPlayer);
     Width            = Map.GetLength(0);
     Height           = Map.GetLength(1);
     TextInitiallyMap = map;
     CountBeer        = DeemBeer();
 }
Beispiel #26
0
        public UnitMap(Tilemap tm)
        {
            umap = new List<Unit>[tm.NumX, tm.NumY];

            for (int i = 0; i < umap.GetLength(0); i++)
                for (int e = 0; e < umap.GetLength(1); e++)
                    umap[i, e] = new List<Unit>();
        }
Beispiel #27
0
        public UnitMap(int w, int h)
        {
            umap = new List<Unit>[w, h];

            for (int i = 0; i < umap.GetLength(0); i++)
                for (int e = 0; e < umap.GetLength(1); e++)
                    umap[i, e] = new List<Unit>();
        }
Beispiel #28
0
 internal void SetLinesMX(List<CLine>[,] mx)
 {
     this.mx = mx;
     if (mx != null)
     {
         maxX = mx.GetLength(0);
         maxY = mx.GetLength(1);
     }
 }
 private void FillArrayWithEmptyLists()
 {
     for (int x = 0; x < pointarray.GetLength(0); x++)
     {
         for (int y = 0; y < pointarray.GetLength(1); y++)
         {
             FillWithEmptyPointList(x, y);
         }
     }
 }
Beispiel #30
0
    private List <KBatchedAnimController> GetControllerList(Vector2I chunk_xy)
    {
        List <KBatchedAnimController> result = null;

        if (controllerGrid != null && 0 <= chunk_xy.x && chunk_xy.x < controllerGrid.GetLength(0) && 0 <= chunk_xy.y && chunk_xy.y < controllerGrid.GetLength(1))
        {
            result = controllerGrid[chunk_xy.x, chunk_xy.y];
        }
        return(result);
    }
Beispiel #31
0
    private void PaintGraphLog()
    {
        GameObject emptyParent = new GameObject();

        maxAmountData = (int)Mathf.Log10(maxAmountData);
        emptyParent.transform.position = spawnArea; //TODO remove spawnArea variable completely?
        emptyParent.AddComponent <Rigidbody>();
        emptyParent.GetComponent <Rigidbody>().isKinematic = true;
        emptyParent.GetComponent <Rigidbody>().useGravity  = false;
        emptyParent.AddComponent <BoxCollider>();
        emptyParent.GetComponent <BoxCollider>().size = new Vector3(graphSize, graphSize, 1); //TODO change 1
        //TODO change center of collider

        emptyParent.layer = 8;
        emptyParent.tag   = "Mark";

        for (int i = 0; i < splitMatrix.GetLength(0); i++)
        {
            for (int j = 0; j < splitMatrix.GetLength(1); j++)
            {
                float amountData = splitMatrix[i, j].Count;
                float height     = 0;
                if (amountData != 0)
                {
                    height = (float)Mathf.Log10(amountData) / maxAmountData;
                }

                List <LabeledData> data = splitMatrix[i, j];

                GameObject tmp = GameObject.CreatePrimitive(PrimitiveType.Cube);
                Destroy(tmp.GetComponent <BoxCollider>());
                Destroy(tmp.GetComponent <Rigidbody>());
                tmp.transform.localScale = new Vector3(columnSizeX, columnSizeY, height);
                tmp.transform.position   = new Vector3(spawnArea.x + ((i * columnSizeX) - (1 / 2)),
                                                       spawnArea.y + ((j * columnSizeY) - (1 / 2)),
                                                       spawnArea.z - height / 2);
                tmp.transform.parent = emptyParent.transform;

                tmp.GetComponent <Renderer>().material = barMaterial;
                Color barColor = GetComponent <GradientManager>().getColor(height);
                tmp.GetComponent <Renderer>().material.color = barColor;

                if (saveList)
                {
                    tmp.AddComponent <GraphBarHandler>();
                    tmp.GetComponent <GraphBarHandler>().dataSet = data;
                    tmp.GetComponent <GraphBarHandler>().SetDefaultColor(barColor);
                }
            }
        }
        emptyParent.transform.rotation = Quaternion.Euler(90f, 0f, 0f);

        emptyParent.transform.position = GetComponent <PlayerParts>().head.transform.position + GetComponent <PlayerParts>().head.transform.forward * 2
                                         - GetComponent <PlayerParts>().head.transform.up;
    }
Beispiel #32
0
 //Get the cell contents at the requested grid co-ordinate, if the co-ordinates are outside of the bounds of the grid return an empty list
 public List <T> GetCellContents(int x, int y)
 {
     if (x >= 0 && y >= 0 && x < gridObjects.GetLength(0) && y < gridObjects.GetLength(1))
     {
         return(gridObjects[x, y]);
     }
     else
     {
         return(new List <T>());
     }
 }
Beispiel #33
0
 private void InitializeFabric()
 {
     _fabric = new List <int> [1000, 1000];
     for (var i = 0; i < _fabric.GetLength(0); i++)
     {
         for (var j = 0; j < _fabric.GetLength(1); j++)
         {
             _fabric[i, j] = new List <int>();
         }
     }
 }
Beispiel #34
0
 private void deregisterOnGrid(MonoBehaviour objectController)
 {
     for (int x = 0; x < grid.GetLength(0); x++)
     {
         for (int y = 0; y < grid.GetLength(1); y++)
         {
             grid[x, y] = grid[x, y].Where(square => square.referenceToObject.objectController != objectController)
                          .ToList();
         }
     }
 }
Beispiel #35
0
        public void InitCarte(String asset)
        {
            lireCarte = new System.IO.StreamReader(asset);

            carteArray = new List<string>[Convert.ToInt32(lireCarte.ReadLine()), Convert.ToInt32(lireCarte.ReadLine())];

            for (int x = 0; x < carteArray.GetLength(0); x++)
                for (int y = 0; y < carteArray.GetLength(1); y++)
                    carteArray[y, x] = new List<string>();

            lireCarte.Close();
        }
Beispiel #36
0
        private int grid_offset = 10; //because space is centered at (0,0,0)

        #endregion Fields

        #region Constructors

        //constructor
        public GridStructure(int cubeLength, int max_size)
        {
            GRID_BLOCK_SIZE = max_size;
            grid_offset = (cubeLength / GRID_BLOCK_SIZE) / 2;
            gridLength = (cubeLength / GRID_BLOCK_SIZE) + 1;
            grid = new List<GridObjectInterface>[gridLength, gridLength, gridLength];

            //initialise grid structure
            for (int x = 0; x < grid.GetLength(0); x++)
                for (int y = 0; y < grid.GetLength(1); y++)
                    for (int z = 0; z < grid.GetLength(2); z++)
                        grid[x, y, z] = new List<GridObjectInterface>();
        }
 public KMeansClusteringModel(double[,] centers, IEnumerable<string> allowedInputVariables)
   : base() {
   this.name = ItemName;
   this.description = ItemDescription;
   // disect center matrix into list of double[]
   // centers are given as double matrix where number of rows = dimensions and number of columns = clusters
   // each column is a cluster center
   this.centers = new List<double[]>();
   for (int i = 0; i < centers.GetLength(1); i++) {
     double[] c = new double[centers.GetLength(0)];
     for (int j = 0; j < c.Length; j++) {
       c[j] = centers[j, i];
     }
     this.centers.Add(c);
   }
   this.allowedInputVariables = allowedInputVariables.ToArray();
 }
Beispiel #38
0
        static string to_string(List<Location>[, ,] data)
        {
            string data_string = "";
              for (int i = 0, m = data.GetLength(0); i < m; ++i)
              {
            for (int j = 0, n = data.GetLength(1); j < n; ++j)
            {
              for (int k = 0, o = data.GetLength(2); k < o; ++k)
              {
            //if (data[i, j, k] == null)
            //{
            //  data[i, j, k] = new List<Location>();
            //}
            for (int l = 0, p = data[i, j, k].Count; l < p; ++l)
            {
              data_string += data[i, j, k][l].x + "," + data[i, j, k][l].y + " ";
            }
              }
            }
              }
              return data_string;

              /***SCRIPT FOR PARSING INTO INDIVIDUAL FILES, PLEASE KEEP FOR NOW ***/
              /*string line;
              FileStream f_in = new FileStream("consolidated_by_pos.txt", FileMode.Open, FileAccess.Read);
              StreamReader s_in = new StreamReader(f_in);
              s_in.ReadLine();
              for (int i = 0; i < 5; ++i)
              {
            for (int j = 0; j < 5; ++j)
            {
              FileStream f_out = new FileStream("../../../test/fixtures/collected_data/Position_" + i + "_" + j + "_Orientation" + "_" + "0" + ".txt", FileMode.Create, FileAccess.Write);
              StreamWriter s_out = new StreamWriter(f_out);
              s_out.WriteLine("1,1 4 1");
              for (int k = 0; k < 4; ++k)
              {
            line = s_in.ReadLine();
            s_out.WriteLine(line);
              }
              s_out.Close();
              f_out.Close();
            }
              }
              s_in.Close();
              f_in.Close();*/
        }
Beispiel #39
0
        /*
         * Populates the collision grid by bucketizing each unit on the map into a cell
         * around which collisions will be processed
         */
        public List<GameUnit>[,] ConstructCollisionGrid(List<GameUnit> units, Level level)
        {
            List<GameUnit>[,] grid = new List<GameUnit>[
                (int)level.Width / CELL_SIZE, (int)level.Height / CELL_SIZE];

            foreach (GameUnit unit in units)
            {
                int x_index = (int)MathHelper.Clamp((unit.Position.X / CELL_SIZE), 0, grid.GetLength(1)-1);
                int y_index = (int)MathHelper.Clamp((unit.Position.Y / CELL_SIZE), 0, grid.GetLength(0)-1);

                if (grid[y_index, x_index] == null)
                {
                    grid[y_index, x_index] = new List<GameUnit>();
                }
                grid[y_index, x_index].Add(unit);
            }
            return grid;
        }
Beispiel #40
0
        public Carte(MoteurPhysique moteurPhysique, List<string>[,] charArray, Vector2 camera, int tileWidth, int tileHeight, int tileStepX, int tileStepY)
        {
            this.moteurPhysique = moteurPhysique;
            this.camera = camera;
            this.tileWidth = tileWidth;
            this.tileHeight = tileHeight;
            this.tileStepX = tileStepX;
            this.tileStepY = tileStepY;

            tuileArray = new List<Tuile>[charArray.GetLength(0), charArray.GetLength(1)];

            for (int x = 0; x < charArray.GetLength(0); x++)
                for (int y = 0; y < charArray.GetLength(1); y++)
                    tuileArray[y, x] = new List<Tuile>();

            InitTileArray(charArray);

            tuileHover = new Vector2(10, 10);
        }
        public ArrayBasedLocations(List<Location>[,,] location_data)
        {
            this.SignalStrengthCount = (uint)location_data.GetLength(0);
              this.NodeCount = (uint)location_data.GetLength(1);
              this.OrientationCount = (uint)location_data.GetLength(2);

              this.data = new List<Location>[this.SignalStrengthCount, this.NodeCount, this.OrientationCount];

              for(int i = 0; i < this.SignalStrengthCount; ++i)
              {
            for(int j = 0; j < this.NodeCount; ++j)
            {
              for(int k = 0; k < this.OrientationCount; ++k)
              {
            this.data[i, j, k] = new List<Location>();
            this.data[i,j,k].AddRange(location_data[i,j,k]);
              }
            }
              }
        }
 public string to_string(List<Location>[, ,] data)
 {
     string data_string = "";
       for (int i = 0, m = data.GetLength(0); i < m; ++i)
       {
     for (int j = 0, n = data.GetLength(1); j < n; ++j)
     {
       for (int k = 0, o = data.GetLength(2); k < o; ++k)
       {
     //if (data[i, j, k] == null)
     //{
     //  data[i, j, k] = new List<Location>();
     //}
     for (int l = 0, p = data[i, j, k].Count; l < p; ++l)
     {
       data_string += data[i, j, k][l].x + "," + data[i, j, k][l].y + " ";
     }
       }
     }
       }
       return data_string;
 }
Beispiel #43
0
 public void addToLayer(List<byte[]>[,] layerBitmaps, int xStart, int yStart)
 {
     for (int y = 0; y < yRange; y++)
     {
         for (int x = 0; x < xRange; x++)
         {
             if (xStart + x < layerBitmaps.GetLength(0) && yStart + y - yRange + 1 >= 0)
             {
                 layerBitmaps[xStart + x, yStart + y - yRange + 1].Add(tiles[x, y]);
             }
         }
     }
 }
Beispiel #44
0
 public NoteThread(CellState[,] notes, int measureLength, double timeSignature)
 {
     this.notes = new List<Note>();
     this.timeSignature = timeSignature;
     for (int i = 0; i < notes.GetLength(0); i++)
     {
         for (int j = 0; j < notes.GetLength(1); j++)
         {
             if (notes[i, j] == CellState.START)
             {
                 double duration = Automatone.getBeatResolution();
                 int k = j + 1;
                 while (k < notes.GetLength(1) && notes[i, k] == CellState.HOLD)
                 {
                     duration += Automatone.getBeatResolution();
                     k++;
                 }
                 this.notes.Add(new Note(new NoteName((byte)((i + Automatone.LOWEST_NOTE_CHROMATIC_NUMBER) % MusicTheory.OCTAVE_SIZE)), (byte)((i + Automatone.LOWEST_NOTE_CHROMATIC_NUMBER) / MusicTheory.OCTAVE_SIZE), duration, (int)(j / measureLength), (j % measureLength) * Automatone.getBeatResolution()));
             }
         }
     }
 }
Beispiel #45
0
        public Carte(List<string>[,] charArray, Vector2 camera, int tileWidth, int tileHeight, int tileStepX, int tileStepY)
        {
            this.camera = camera;
            this.tileWidth = tileWidth;
            this.tileHeight = tileHeight;
            this.tileStepX = tileStepX;
            this.tileStepY = tileStepY;

            tuileArray = new List<Tuile>[charArray.GetLength(0), charArray.GetLength(1)];

            for (int x = 0; x < charArray.GetLength(0); x++)
                for (int y = 0; y < charArray.GetLength(1); y++)
                    tuileArray[y, x] = new List<Tuile>();

            InitTileArray(charArray);

            inSelect = false;
            initialPos = Vector2.Zero;

            tuileHover = new Vector2(10, 10);

            rectSelect = new Rectangle(7, 7, 3, 3);
        }
Beispiel #46
0
        public DeckDealer(List<string>[] players, IList<string> deck, int handOut)
        {
            if (players == null || deck == null) throw new Exception("One of arguments is null");
            if (handOut<1 || handOut> deck.Count/ players.GetLength(0)) throw new Exception("Wrong number of cards to handout");
            foreach (var variable in players)
            {
                for (var i = 0; i < handOut; i++)
                {
                    var tmpCard = deck.ElementAt(0);
                    Console.WriteLine("Card taken form deck "+tmpCard);
                    deck.RemoveAt(0);
                    Console.WriteLine("Next card should be "+deck.ElementAt(0));
                    variable.Add(tmpCard);
                }

            }
            _tabLists = players;
        }
Beispiel #47
0
        public void AddDim(Vector2 dim)
        {
            List<Tuile>[,] carteAux = new List<Tuile>[(int)dim.X, (int)dim.Y];

            for (int x = 0; x < tuileArray.GetLength(0); x++)
                for (int y = 0; y < tuileArray.GetLength(1); y++)
                    carteAux[x, y] = tuileArray[x, y];

            for (int x = 0; x < carteAux.GetLength(0); x++)
            {
                carteAux[x, carteAux.GetLength(1) - 1] = new List<Tuile>();
                carteAux[x, carteAux.GetLength(1) - 1].Add(new Tuile(new Vector2(x, carteAux.GetLength(1) - 1), new Vector2(7, 0), false, 0));
            }

            for (int y = 0; y < carteAux.GetLength(1); y++)
            {
                carteAux[carteAux.GetLength(0) - 1, y] = new List<Tuile>();
                carteAux[carteAux.GetLength(0) - 1, y].Add(new Tuile(new Vector2(carteAux.GetLength(0) - 1, y), new Vector2(7, 0), false, 0));
            }

            tuileArray = carteAux;

            Console.WriteLine("new dim : " + tuileArray.GetLength(0));
        }
Beispiel #48
0
        private void AutoTest(object sender, DoWorkEventArgs e)
        {
            object[] param = (object[])e.Argument;
            int avg_cnt = (int)param[0];
            int KNN_K = (int)param[1];
            int KNNHC_K = (int)param[2];
            string db_file_name = (string)param[3];
            string data_file_name = (string)param[4];
            double start_snr = (double)param[5];
            double stop_snr = (double)param[6];
            double step_snr = (double)param[7];
            int ray_num = (int)param[8];
            Transmitter.EMIT_OPTION emit_opt = (Transmitter.EMIT_OPTION)param[9];
            Noise_Type noise_type = (Noise_Type)param[10];
            double alpha = (double)param[11];
            int sample_cnt = (int)param[12];
            Signal_Type signal_type = (Signal_Type)param[13];

            System.IO.FileStream data_fs = new FileStream(data_file_name, FileMode.Create, FileAccess.Write, FileShare.Read);

            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            FileStream fs = new FileStream(db_file_name, FileMode.Open, FileAccess.Read, FileShare.Read);
            FingerprintDataBase fdb = (FingerprintDataBase)formatter.Deserialize(fs);
            fs.Close();

            Point pt_real = new Point();
            foreach (Transmitter trans in this.viz_rps.Map.Transmitters)
                pt_real = trans.Location;

            double[] snrs = new double[(int)((stop_snr - start_snr) / step_snr) + 1];
            for(int i = 0; i < snrs.Length; i++)
                snrs[i] = start_snr + i * step_snr;

            foreach (Transmitter trans in this.viz_rps.Map.Transmitters)
            {
                trans.Reset();
                trans.EmitRays(ray_num, emit_opt);   //各发射机辐射波束
                foreach (Receiver rec in this.viz_rps.Map.Receivers)
                {
                    rec.Reset();
                    if (this.viz_rps.Map.IsLOS(trans.Location, rec.Location))    //若存在LOS情况
                    {
                        LineSegment segLOS = new LineSegment(trans.Location, rec.Location);
                        Ray rayLOS = new Ray(trans, new LineSegment[] { segLOS }, segLOS.DirectionRadian, trans.CenterFrequency, trans.EmitPower * trans.Gain, trans.EmitPower * trans.Gain, true);
                        rec.AcceptRay(rayLOS, this.viz_rps.Map);
                    }
                }
                foreach (Ray ray in trans.Rays)  //更新每条ray, 若被接收,则更新接收它的接收机
                {
                    Receiver rec = null;
                    while (!ray.Update(this.viz_rps.Map, out rec)) ;
                    if (rec != null)
                        rec.AcceptRay(ray, this.viz_rps.Map);
                }
            }
            FingerprintGenerator fg = new FingerprintGenerator();
            Dictionary<Fingerprint_Name, Fingerprint> result = new Dictionary<Fingerprint_Name, Fingerprint>();
            List<double>[] ray_angles = new List<double>[this.viz_rps.Map.ReceiverCount];
            List<double>[] ray_strengths = new List<double>[this.viz_rps.Map.ReceiverCount];
            List<double>[] ray_taus = new List<double>[this.viz_rps.Map.ReceiverCount];
            int kk = 0;
            foreach (Receiver rec in this.viz_rps.Map.Receivers)
            {
                ray_angles[kk] = new List<double>();
                ray_strengths[kk] = new List<double>();
                ray_taus[kk] = new List<double>();
                foreach (Ray ray in rec.Rays)
                {
                    ray_angles[kk].Add(ray.CurrentDirection);
                    ray_strengths[kk].Add(ray.FadedPower(this.viz_rps.Map.MeterPixelRatio));
                    ray_taus[kk].Add(ray.GetLifeSpan(this.viz_rps.Map.MeterPixelRatio));
                }
                kk++;
            }
            double[] args = null;
            switch (signal_type)
            {
                case Signal_Type.PSEUDO_DOPPLER:
                    //if (this.receivers.First().Value.Antenna.AntType != AntennaType.PSEUDO_DOPPLER)
                    //    return null;
                    Antenna_PseudoDoppler ant = this.viz_rps.Map.receivers.First().Value.Antenna as Antenna_PseudoDoppler;
                    args = fg.PackArgs_PseudoDoppler(this.viz_rps.Map.receivers.First().Value.FrequencyLow, this.viz_rps.Map.receivers.First().Value.CenterFrequency,
                                                     this.viz_rps.Map.receivers.First().Value.SampleFrequency, ant.SwitchFrequency, ant.Radius, ant.AntennaNumber);
                    break;
            }
            MWNumericArray[] signals = new MWNumericArray[ray_angles.GetLength(0)];
            for (int i = 0; i < signals.Length; i++)
            {
                signals[i] = new FingerprintGenerator().GenerateSignal_MW(signal_type, ray_angles[i].ToArray(), ray_strengths[i].ToArray(), ray_taus[i].ToArray(), sample_cnt, args);                
            }

            for (int n = 0; n < snrs.Length; n++)
            {
                double[] sum_errs = new double[6];//SA_single, SA_KNN, SA_KNNHC, S_single, S_KNN, S_KNNHC
                for(int i = 0; i < avg_cnt; i++)
                {
                    MWNumericArray[] n_signals = new MWNumericArray[signals.Length];
                    for (int l = 0; l < signals.Length; l++)
                    {
                        n_signals[l] = new FingerprintGenerator().AddNoise_MW(noise_type, signals[l], new double[] { snrs[n] });
                    }
                    Dictionary<Fingerprint_Name, Fingerprint> res = new Dictionary<Fingerprint_Name,Fingerprint>();
                    for (int j = 0; j < Enum.GetNames(new Fingerprint_Name().GetType()).Length; j++ )
                        res[(Fingerprint_Name)j] = new FingerprintGenerator().GenerateFingerprint(signal_type, (Fingerprint_Name)j, n_signals, args);
                    this.current_fingerprint = res;

                    //SA_single
                    PointF loc_SA_single = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.SA], FingerprintDataBase.Match_Strategy.Single, null);
                    sum_errs[0] += new MathUtils.MathUtility().point_dist(pt_real, loc_SA_single);

                    //SA_KNN
                    PointF loc_SA_KNN = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.SA], FingerprintDataBase.Match_Strategy.KNN, new double[] { KNN_K });
                    sum_errs[1] += new MathUtils.MathUtility().point_dist(pt_real, loc_SA_KNN);

                    //SA_KNNHC
                    PointF loc_SA_KNNHC = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.SA], FingerprintDataBase.Match_Strategy.KNN_HC, new double[] { KNNHC_K });
                    sum_errs[2] += new MathUtils.MathUtility().point_dist(pt_real, loc_SA_KNNHC);

                    //S_single
                    PointF loc_S_single = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.S], FingerprintDataBase.Match_Strategy.Single, null);
                    sum_errs[3] += new MathUtils.MathUtility().point_dist(pt_real, loc_S_single);

                    //S_KNN
                    PointF loc_S_KNN = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.S], FingerprintDataBase.Match_Strategy.KNN, new double[] { KNN_K });
                    sum_errs[4] += new MathUtils.MathUtility().point_dist(pt_real, loc_S_KNN);

                    //S_KNNHC
                    PointF loc_S_KNNHC = fdb.MatchLocation(this.current_fingerprint[Fingerprint_Name.S], FingerprintDataBase.Match_Strategy.KNN_HC, new double[] { KNNHC_K });
                    sum_errs[5] += new MathUtils.MathUtility().point_dist(pt_real, loc_S_KNNHC);

                    bgAutoTest.ReportProgress((int)((n * avg_cnt + i + 1) / (double)(avg_cnt * snrs.Length) * 100));
                    System.Threading.Thread.Sleep(200);
                }

                for (int m = 0; m < sum_errs.Length; m++ )
                {
                    double err = sum_errs[m] / avg_cnt;
                    byte[] tmp = Encoding.ASCII.GetBytes(err.ToString("0.00") + "\t");
                    data_fs.Write(tmp, 0, tmp.Length);
                }
                byte[] rn = Encoding.ASCII.GetBytes("\r\n");
                data_fs.Write(rn, 0, rn.Length);
            }

            data_fs.Close();
            e.Result = true;
        }
Beispiel #49
0
 public void FillValues(bool fill_positions,bool fill_other_data)
 {
     if(fill_count <= 0){
         return;
     }
     if(fill_positions){
         if(single_position != -1){ //if this value is -1, nothing can be added anyway.
             if(positions == null){
                 positions = new List<int>();
             }
             while(positions.Count < fill_count){
                 positions.Add(single_position);
             }
         }
         if(single_layout != -1){
             if(layouts == null){
                 layouts = new List<int>();
             }
             while(layouts.Count < fill_count){
                 layouts.Add(single_layout);
             }
         }
     }
     if(fill_other_data){
         if(single_sprite != -1){
             if(sprites == null){
                 sprites = new List<int>();
             }
             while(sprites.Count < fill_count){
                 sprites.Add(single_sprite);
             }
         }
         if(single_sprite_type != -1){
             if(sprite_types == null){
                 sprite_types = new List<int>();
             }
             while(sprite_types.Count < fill_count){
                 sprite_types.Add(single_sprite_type);
             }
         }
         if(single_other_data != null){
             if(other_data == null){
                 other_data = new List<float>[single_other_data.GetLength(0)];
                 for(int i=0;i<other_data.GetLength(0);++i){
                     other_data[i] = new List<float>();
                 }
             }
             int idx = 0;
             foreach(List<float> l in other_data){
                 while(l.Count < fill_count * single_other_data[idx].Count){
                     foreach(float f in single_other_data[idx]){
                         l.Add(f);
                     }
                 }
                 ++idx;
             }
         }
     }
 }
Beispiel #50
0
        public static void Detect(List<GameObject>[,] clusters, World gameObjects)
        {
            for (int k = 0; k < gameObjects.Count; k++)
            {
                for (int i = 0; i < gameObjects[k].Collisions.Count; i++)
                    CollisionPool.Instance.PutObject(gameObjects[k].Collisions[i]);
                gameObjects[k].Collisions.Clear();
            }

            int ww = clusters.GetLength(1);
            int wh = clusters.GetLength(0);

            // обход по кластерам
            for (int wj = 0; wj < wh; wj++)
                for (int wi = 0; wi < ww; wi++)
                {
                    // обход по окресности кластера 3x3
                    for (int k = 0; k < 5; k++)
                    {
                        int di = 0;
                        int dj = 0;
                        switch (k)
                        {
                            case 0: di = 0; dj = 0; break;
                            case 1: di = 1; dj = -1; break;  // . . 1
                            case 2: di = 1; dj = 0; break;   // . 0 2
                            case 3: di = 1; dj = 1; break;   // . 4 3
                            case 4: di = 0; dj = 1; break;
                        }
                        int clui = (wi + di + ww) % ww;
                        int cluj = (wj + dj + wh) % wh;
                        float fx = (wi + di - clui) * Game.ClusterSize;
                        float fy = (wj + dj - cluj) * Game.ClusterSize;
                        // обсчёт столкновений 9 кластеров
                        for (int j = 0; j < clusters[cluj, clui].Count; j++)
                            for (int i = k == 0 ? j : 0; i < clusters[wj, wi].Count; i++)
                            {
                                if (cluj == wj && clui == wi && i == j)  // skip self
                                    continue;
                                var go1 = clusters[cluj, clui][j];
                                var go2 = clusters[wj, wi][i];
                                float dx = go2.Position.X - go1.Position.X - fx;
                                float dy = go2.Position.Y - go1.Position.Y - fy;
                                float dv = go2.Speed.X - go1.Speed.X;
                                float du = go2.Speed.Y - go1.Speed.Y;
                                float rr = go2.Size / 2 + go1.Size / 2;
                                if (dv == 0f || du == 0f)
                                {
                                    float ol2 = rr * rr - dx * dx - dy * dy;
                                    if (ol2 > 0)
                                    {
                                        go1.Collisions.Add(CollisionPool.Instance.GetObject(go2, ol2, 0f, new Vector2(dx, dy)));
                                        go2.Collisions.Add(CollisionPool.Instance.GetObject(go1, ol2, 0f, new Vector2(-dx, -dy)));
                                    }
                                }
                                else
                                {
                                    float a = dv * dv + du * du;
                                    float b = 2f * (dv * dx + du * dy);
                                    float c = dx * dx + dy * dy - rr * rr;
                                    float disc = b * b - 4f * a * c;
                                    if (disc < 0)
                                        continue;
                                    float t1 = (-b + Maf.Sqrt(disc)) / (2f * a);
                                    float t2 = (-b - Maf.Sqrt(disc)) / (2f * a);

                                    float min = Math.Min(t1, t2);
                                    float max = Math.Max(t1, t2);

                                    float ol2 = rr * rr - dx * dx - dy * dy;
                                    if (min < 1f && max >= 0f)
                                    {
                                        go1.Collisions.Add(CollisionPool.Instance.GetObject(go2, ol2, min, new Vector2(dx, dy)));
                                        go2.Collisions.Add(CollisionPool.Instance.GetObject(go1, ol2, min, new Vector2(-dx, -dy)));
                                    }
                                }
                            }
                    }
                }
        }
Beispiel #51
0
 private MWNumericArray[][] wrap_func(int num, int ray_num, Transmitter.EMIT_OPTION emit_opt, Signal_Type signal_type, int sample_cnt)
 {
     MWNumericArray[][] signals = new MWNumericArray[num][];
     while (num-- > 0)
     {
         foreach (Transmitter trans in this.viz_rps.Map.Transmitters)
         {
             trans.Reset();
             trans.EmitRays(ray_num, emit_opt);   //各发射机辐射波束
             foreach (Receiver rec in this.viz_rps.Map.Receivers)
             {
                 rec.Reset();
                 if (this.viz_rps.Map.IsLOS(trans.Location, rec.Location))    //若存在LOS情况
                 {
                     LineSegment segLOS = new LineSegment(trans.Location, rec.Location);
                     Ray rayLOS = new Ray(trans, new LineSegment[] { segLOS }, segLOS.DirectionRadian, trans.CenterFrequency, trans.EmitPower * trans.Gain, trans.EmitPower * trans.Gain, true);
                     rec.AcceptRay(rayLOS, this.viz_rps.Map);
                 }
             }
             foreach (Ray ray in trans.Rays)  //更新每条ray, 若被接收,则更新接收它的接收机
             {
                 Receiver rec = null;
                 while (!ray.Update(this.viz_rps.Map, out rec)) ;
                 if (rec != null)
                     rec.AcceptRay(ray, this.viz_rps.Map);
             }
         }
         FingerprintGenerator fg = new FingerprintGenerator();
         Dictionary<Fingerprint_Name, Fingerprint> result = new Dictionary<Fingerprint_Name, Fingerprint>();
         List<double>[] ray_angles = new List<double>[this.viz_rps.Map.ReceiverCount];
         List<double>[] ray_strengths = new List<double>[this.viz_rps.Map.ReceiverCount];
         List<double>[] ray_taus = new List<double>[this.viz_rps.Map.ReceiverCount];
         int kk = 0;
         foreach (Receiver rec in this.viz_rps.Map.Receivers)
         {
             ray_angles[kk] = new List<double>();
             ray_strengths[kk] = new List<double>();
             ray_taus[kk] = new List<double>();
             foreach (Ray ray in rec.Rays)
             {
                 ray_angles[kk].Add(ray.CurrentDirection);
                 ray_strengths[kk].Add(ray.FadedPower(this.viz_rps.Map.MeterPixelRatio));
                 ray_taus[kk].Add(ray.GetLifeSpan(this.viz_rps.Map.MeterPixelRatio));
             }
             kk++;
         }
         double[] args = null;
         switch (signal_type)
         {
             case Signal_Type.PSEUDO_DOPPLER:
                 //if (this.receivers.First().Value.Antenna.AntType != AntennaType.PSEUDO_DOPPLER)
                 //    return null;
                 Antenna_PseudoDoppler ant = this.viz_rps.Map.receivers.First().Value.Antenna as Antenna_PseudoDoppler;
                 args = fg.PackArgs_PseudoDoppler(this.viz_rps.Map.receivers.First().Value.FrequencyLow, this.viz_rps.Map.receivers.First().Value.CenterFrequency,
                                                  this.viz_rps.Map.receivers.First().Value.SampleFrequency, ant.SwitchFrequency, ant.Radius, ant.AntennaNumber);
                 break;
         }
         signals[num - 1] = new MWNumericArray[ray_angles.GetLength(0)];
         for (int i = 0; i < signals.Length; i++)
         {
             signals[num - 1][i] = new FingerprintGenerator().GenerateSignal_MW(signal_type, ray_angles[i].ToArray(), ray_strengths[i].ToArray(), ray_taus[i].ToArray(), sample_cnt, args);
         }
     }
     return signals;
 }
Beispiel #52
0
        private void createMapGrid()
        {
            // Add walls to the grid
            BoundingRectangle test = new BoundingRectangle(Vector2.Zero, gridLength / 2);

            grid = new List<Wall>[(int)Math.Ceiling((Map.HEIGHT + 100) / gridLength), (int)Math.Ceiling((Map.WIDTH + 100) / gridLength)];

            int y = grid.GetLength(0);
            int x = grid.GetLength(1);

            for (int i = 0; i != y; ++i)
            {
                for (int j = 0; j != x; ++j)
                {
                    test.Update(new Vector2(j * test.Bounds.Height, i * test.Bounds.Width));

                    grid[i, j] = new List<Wall>();

                    // Check collision
                    for (int k = 0; k != map.walls.Count; ++k)
                    {
                        if (test.Collides(map.walls[k].BoundingRectangle))
                        {
                            grid[i, j].Add(map.walls[k]);
                        }
                    }
                }
            }
        }
        static void Main()
        {
            Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));

            var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            // N
            var numberOfPoints = input[0];
            // M
            var numberOfStreets = input[1];
            // H
            var numberOfHospitals = input[2];

            // H numbers
            var pointsHospitalInput = Console.ReadLine();

            // M numbers
            var streets = new int[numberOfStreets, 3];
            for (int i = 0; i < numberOfStreets; i++)
            {
                var currentStreet = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                for (int j = 0, len = streets.GetLength(1); j < len; j++)
                {
                    streets[i, j] = currentStreet[j];
                }
            }

            Graph = new List<KeyValuePair<int, int>>[numberOfPoints + 1];
            for (int i = 0; i < numberOfStreets; i++)
            {
                if (Graph[streets[i, 0]] == null)
                {
                    Graph[streets[i, 0]] = new List<KeyValuePair<int, int>>();
                }

                if (Graph[streets[i, 1]] == null)
                {
                    Graph[streets[i, 1]] = new List<KeyValuePair<int, int>>();
                }

                Graph[streets[i, 0]].Add(new KeyValuePair<int, int>(streets[i, 1], streets[i, 2]));
                Graph[streets[i, 1]].Add(new KeyValuePair<int, int>(streets[i, 0], streets[i, 2]));
            }

            var minMoves = int.MaxValue;

            for (int i = 0; i < numberOfHospitals; i++)
            {
                Distance = new int[Graph.GetLength(0)];

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

                if (numberOfHospitals == 1)
                {
                    hospitals.Add(int.Parse(pointsHospitalInput));
                    Dijkstra(Graph, hospitals[0]);
                }
                else
                {
                    //Console.WriteLine(pointsHospitalInput.Length);
                    hospitals = pointsHospitalInput.Split(' ').Select(int.Parse).ToList();
                    Dijkstra(Graph, hospitals[i]);
                }

                foreach (var hospital in hospitals)
                {
                    Distance[hospital] = 0;
                }

                int currentMinMoves = Distance.Sum();

                if (currentMinMoves < minMoves)
                {
                    minMoves = currentMinMoves;
                }
            }

            Console.WriteLine(minMoves);
        }
        public void SetCarte(List<Tuile>[,] carte)
        {
            collisionCarte = new int[carte.GetLength(0), carte.GetLength(1)];

            for (int x = 0; x < collisionCarte.GetLength(0); x++)
                for (int y = 0; y < collisionCarte.GetLength(1); y++)
                    collisionCarte[y, x] = carte[y, x].Count;
        }
Beispiel #55
0
        private void InitTileArray(List<string>[,] charArray)
        {
            for (int x = 0; x < charArray.GetLength(0); x++)
            {
                for (int y = 0; y < charArray.GetLength(1); y++)
                {
                    Vector2 positionSource = Vector2.Zero;

                    bool isCollision = false;

                    foreach(string tuileStr in charArray[y, x])
                    {

                        switch (tuileStr[0])
                        {
                            case 'a':
                                positionSource = new Vector2(0, 0);
                                break;

                            case 'b':
                                positionSource = new Vector2(1, 0);
                                isCollision = true;
                                break;

                            case 'c':
                                positionSource = new Vector2(2, 0);
                                break;

                            case 'd':
                                positionSource = new Vector2(3, 0);
                                break;

                            case 'e':
                                positionSource = new Vector2(4, 0);
                                break;

                            case 'f':
                                positionSource = new Vector2(5, 0);
                                break;

                            case 'g':
                                positionSource = new Vector2(6, 0);
                                break;

                            case 'h':
                                positionSource = new Vector2(7, 0);
                                break;

                            case 'i':
                                positionSource = new Vector2(8, 0);
                                break;

                            case 'j':
                                positionSource = new Vector2(9, 0);
                                break;

                            case 'k':
                                positionSource = new Vector2(10, 0);
                                break;

                            case 'l':
                                positionSource = new Vector2(11, 0);
                                break;

                            case 'm':
                                positionSource = new Vector2(12, 0);
                                break;

                            case 'n':
                                positionSource = new Vector2(13, 0);
                                break;

                            case 'o':
                                positionSource = new Vector2(14, 0);
                                break;

                            case 'p':
                                positionSource = new Vector2(15, 0);
                                break;

                            default: //('a')
                                positionSource = new Vector2(7, 0);
                                break;
                        }

                        tuileArray[x, y].Add(new Tuile(new Vector2(x, y), positionSource, isCollision, int.Parse(tuileStr.Substring(1, 2))));
                    }
                }
            }
        }
Beispiel #56
0
        /// <summary>
        /// implements the recomputing utility function. figures out what the utility for n would be if n flipped its state
        /// from its present state in S.
        /// </summary>
        /// <param name="BucketTable"></param>
        /// <param name="Best"></param>
        /// <param name="ChosenParent"></param>
        /// <param name="SecP"></param>
        /// <param name="S"></param>
        /// <param name="n"></param>
        /// <param name="L"></param>
        /// <param name="BestRelation"></param>
        /// <param name="W"></param>
        /// <returns></returns>
        public int ComputeUtility(List<UInt32>[][] BucketTable, List<UInt32>[] Best, UInt32[] param_ChosenParent, bool[] param_SecP, bool[] S, UInt32 n, int L, byte BestRelation, UInt16[] W)
        {
            if (L == 0)
                 return 0;//no utility for routing to itself

             int UNTilda = 0;//utility for S with n's state flipped

             Int32 CustomerTreeSize = 0;
             Int32 CustomerWeightedTreeSize = 0;
             Int32 PeerWeightedTreeSize = 0;
             Int32 ProviderWeightedTreeSize = 0;

             //DON'T LET US OVERWRITE THINGS; we can overwrite S and flip it back at the end.
             ChosenParent = (UInt32[])param_ChosenParent.Clone();
             SecP = (bool[])param_SecP.Clone();

             S[n] = !S[n];//reverse n's state (we revert this before we return).

             //update n's path. if it has options
             if (Best[n].Count > 1)
             {
                 if (S[n]) //n became secure it cares about security in picking its path
                     updateParentWorker(n, ref Best, ref S, ref SecP, ref ChosenParent);//, ref tieBreakSet);
                 else
                 {
                     //n became insecure; re-evaluate its path options from the set of all paths.
                     UInt32 newParent = Best[n][0];
                     ChosenParent[n] = newParent;
                 }
             }
              //   if (S[n])//can only have secP if n is secure. (using an and so we revoke SecP for n flipping back.
                 SecP[n] = S[n]&SecP[ChosenParent[n]];

             byte[] throughN = new byte[Constants._numASNs];

             for (int i = 0; i < Constants._numASNs; i++)
                 throughN[i] = 0;//empty value.

             for (int row = L + 1; row < BucketTable.GetLength(0); row++)
             {
                 foreach (int col in columns)
                 {
                     if (BucketTable[row][col] == null)
                         continue;
                     foreach (UInt32 i in BucketTable[row][col])
                     {
                         /*only secure nodes will change their parents based on security. We still need to update
                          * whether or not they gothrough n though because someone before them may have changed to go
                          * through n*/
                         if (Best[i].Count > 1)//update path *only* if you have options.
                             updateParentWorker(i, ref Best, ref S, ref SecP, ref ChosenParent);//, ref tieBreakSet);

                         if (S[i])//only say your path is secure if you are secure
                             SecP[i] = SecP[ChosenParent[i]];

                         /* done updating our parents need to update whether we go through n or not */

                         if (row == L + 1 && ChosenParent[i] == n && col == Destination._PROVIDERCOLUMN)
                             throughN[i] = CustomerOf;//i is a customer of N
                         else if (row == L + 1 && ChosenParent[i] == n && col == Destination._PEERCOLUMN)
                             throughN[i] = PeerOf;
                         else if (row == L + 1 && ChosenParent[i] == n && col == Destination._CUSTOMERCOLUMN)
                             throughN[i] = ProviderTo;//i is a provider to N
                         else if (row > (L + 1))
                             throughN[i] = throughN[ChosenParent[i]];

                         //update utility values on how we pass through n
                         switch (throughN[i])
                         {
                             case CustomerOf:
                                 CustomerTreeSize++;
                                 CustomerWeightedTreeSize += W[i];
                                 break;
                             case PeerOf:
                                 PeerWeightedTreeSize += W[i];
                                 break;
                             case ProviderTo:
                                 ProviderWeightedTreeSize += W[i];
                                 break;
                         }

                     }
                 }
             }

             S[n] = !S[n];//flip n back
             UInt16 dWeight = W[BucketTable[0][ 0][0]];
             UNTilda = SimulatorLibrary.utilityComputation(CustomerTreeSize,
                 CustomerWeightedTreeSize,
                 PeerWeightedTreeSize,
                 ProviderWeightedTreeSize,
                 BestRelation,dWeight);

             return UNTilda;
        }
Beispiel #57
0
        /*
         * Calculates and processes all collisions that occur,
         * using the collision cell optimization structure
         */
        public void Update(List<GameUnit> units, Level level)
        {
            cellGrid = ConstructCollisionGrid(units, level);

            for (int ii = 0; ii < cellGrid.GetLength(0); ii++)
            {
                for (int jj = 0; jj < cellGrid.GetLength(1); jj++)
                {
                    if (cellGrid[ii, jj] != null)
                    {
                        ProcessCollisions(jj, ii, level.Map);
                    }
                }
            }
        }
Beispiel #58
0
        private void BuildTiles()
        {
            tiles = new List<int>[roomHeight / 32 + 1, roomWidth / 32 + 1];
            for (int i = 0; i < tiles.GetLength(0); i++)
                for (int j = 0; j < tiles.GetLength(1); j++)
                {
                    tiles[i, j] = new List<int>();
                    tiles[i, j].Add(-1);
                }

            // Fill each wall object with middle tiles
            var realWalls = from Wall w in walls
                            where !(w is PlatformWall) && !(w is FloatingPlatform) && !(w is DeathWall) && !(w is Mirror)
                            select w;
            foreach (Wall w in realWalls)
            {
                for (int x = w.Bounds.X; x < w.Bounds.Right; x += 32)
                    for (int y = w.Bounds.Y; y < w.Bounds.Bottom; y += 32)
                        if (x >= 0 && x <= roomWidth && y >= 0 && y <= roomHeight)
                            tiles[y / 32, x / 32].Insert(0, 4);
            }

            // Fill each death wall with death tile
            var deathWalls = from Wall w in walls
                             where w is DeathWall
                             select w;
            foreach (Wall w in deathWalls)
            {
                for (int x = w.Bounds.X; x < w.Bounds.Right; x += 32)
                    for (int y = w.Bounds.Y; y < w.Bounds.Bottom; y += 32)
                        if (x >= 0 && x <= roomWidth && y >= 0 && y <= roomHeight)
                            tiles[y / 32, x / 32].Insert(0, 9);
            }

            // Fill each mirror with mirror tile
            var mirrors = from Wall w in walls
                             where w is Mirror
                             select w;
            foreach (Wall w in mirrors)
            {
                for (int x = w.Bounds.X; x < w.Bounds.Right; x += 32)
                    for (int y = w.Bounds.Y; y < w.Bounds.Bottom; y += 32)
                        if (x >= 0 && x <= roomWidth && y >= 0 && y <= roomHeight)
                            tiles[y / 32, x / 32].Insert(0, 10);
            }

            int newHeight = roomHeight / 32;
            int newWidth = roomWidth / 32;

            // Find all corners and sides and attach corresponding tile
            for (int x = 0; x <= newWidth; x++)
                for (int y = 0; y <= newHeight; y++)
                    if (tiles[y, x].Count > 0 && tiles[y, x][0] == 4)
                    {
                        // Corners
                        if (x - 1 >= 0 && x - 1 <= newWidth && y - 1 >= 0 && y - 1 <= newHeight && tiles[y, x - 1][0] != 4 && tiles[y - 1, x - 1][0] != 4 && tiles[y - 1, x][0] != 4)
                            tiles[y - 1, x - 1].Add(0);
                        if (x - 1 >= 0 && x - 1 <= newWidth && y + 1 >= 0 && y + 1 <= newHeight && tiles[y, x - 1][0] != 4 && tiles[y + 1, x - 1][0] != 4 && tiles[y + 1, x][0] != 4)
                            tiles[y + 1, x - 1].Add(2);
                        if (x + 1 >= 0 && x + 1 <= newWidth && y - 1 >= 0 && y - 1 <= newHeight && tiles[y, x + 1][0] != 4 && tiles[y - 1, x + 1][0] != 4 && tiles[y - 1, x][0] != 4)
                            tiles[y - 1, x + 1].Add(6);
                        if (x + 1 >= 0 && x + 1 <= newWidth && y + 1 >= 0 && y + 1 <= newHeight && tiles[y, x + 1][0] != 4 && tiles[y + 1, x + 1][0] != 4 && tiles[y + 1, x][0] != 4)
                            tiles[y + 1, x + 1].Add(8);

                        // Sides
                        if (x - 1 >= 0 && x - 1 <= newWidth && tiles[y, x - 1][0] != 4)
                            tiles[y, x - 1].Add(1);
                        if (y - 1 >= 0 && y - 1 <= newHeight && tiles[y - 1, x][0] != 4)
                            tiles[y - 1, x].Add(3);
                        if (y + 1 >= 0 && y + 1 <= newHeight && tiles[y + 1, x][0] != 4)
                            tiles[y + 1, x].Add(5);
                        if (x + 1 >= 0 && x + 1 <= newWidth && tiles[y, x + 1][0] != 4)
                            tiles[y, x + 1].Add(7);
                    }
        }
Beispiel #59
0
        /// <summary>
        /// calibrate stereo camera from the given images
        /// </summary>
        /// <param name="directory">directory containing the calibration images</param>
        /// <param name="baseline_mm">baseline of the stereo camera</param>
        /// <param name="dotdist_mm">horizontal distance to the centre of the calibration pattern in millimetres</param>
        /// <param name="height_mm">vertical height of the cameras above the calibration pattern</param>
        /// <param name="fov_degrees">field of view of the cameras in degrees</param>
        /// <param name="dot_spacing_mm">spacing between dots on the calibration pattern in millimetres</param>
        /// <param name="focal_length_pixels">focal length of the cameras in pixels</param>
        /// <param name="file_extension">file extension of the calibration images (typically "jpg" or "bmp")</param>
        public static void Calibrate(string directory,
                                     int baseline_mm,
                                     int dotdist_mm,
                                     int height_mm,
                                     float fov_degrees,
                                     float dot_spacing_mm,
                                     float focal_length_pixels,
                                     string file_extension)
        {
            string calibration_xml_filename = "calibration.xml";
            if (File.Exists(calibration_xml_filename))
                File.Delete(calibration_xml_filename);

            if (directory.Contains("\\"))
            {
                if (!directory.EndsWith("\\")) directory += "\\";
            }
            else
            {
                if (directory.Contains("/"))
                    if (!directory.EndsWith("/")) directory += "/";
            }
            string[] filename = Directory.GetFiles(directory, "*." + file_extension);
            if (filename != null)
            {
                // two lists to store filenames for camera 0 and camera 1
                List<string>[] image_filename = new List<string>[2];
                image_filename[0] = new List<string>();
                image_filename[1] = new List<string>();

                // populate the lists
                for (int i = 0; i < filename.Length; i++)
                {
                    if (filename[i].Contains("raw0"))
                        image_filename[0].Add(filename[i]);
                    if (filename[i].Contains("raw1"))
                        image_filename[1].Add(filename[i]);
                }

                if (image_filename[0].Count == 0)
                {
                    Console.WriteLine("Did not find any calibration files.  Do they begin with raw0 or raw1 ?");
                }
                else
                {
                    if (image_filename[0].Count != image_filename[1].Count)
                    {
                        Console.WriteLine("There must be the same number of images from camera 0 and camera 1");
                    }
                    else
                    {
                        string lens_distortion_image_filename = "temp_lens_distortion.jpg";
                        string curve_fit_image_filename = "temp_curve_fit.jpg";
                        string rectified_image_filename = "temp_rectified.jpg";
                        string[] lens_distortion_filename = { "lens_distortion0.jpg", "lens_distortion1.jpg" };
                        string[] curve_fit_filename = { "curve_fit0.jpg", "curve_fit1.jpg" };
                        string[] rectified_filename = { "rectified0.jpg", "rectified1.jpg" };
                        int img_width = 0, img_height = 0;

                        // distance to the centre dot
                        float dist_to_centre_dot_mm = (float)Math.Sqrt(dotdist_mm * dotdist_mm + height_mm * height_mm);

                        // find dots within the images
                        polynomial[] distortion_curve = new polynomial[2];
                        double[] centre_x = new double[2];
                        double[] centre_y = new double[2];
                        double[] scale_factor = new double[2];
                        double[] rotation = new double[2];

                        // unrectified position of the calibration dot (in image coordinates) for each image
                        List<List<double>> centre_dot_position = new List<List<double>>();

                        // pan/tilt mechanism servo positions
                        List<List<double>> pan_servo_position = new List<List<double>>();
                        List<List<double>> tilt_servo_position = new List<List<double>>();

                        List<int[]> calibration_map = new List<int[]>();

                        int[] winner_index = new int[2];

                        for (int cam = 0; cam < image_filename.GetLength(0); cam++)
                        {
                            // unrectified centre dot positions in image coordinates
                            centre_dot_position.Add(new List<double>());
                            centre_dot_position.Add(new List<double>());

                            // pan/tilt mechanism servo positions
                            pan_servo_position.Add(new List<double>());
                            tilt_servo_position.Add(new List<double>());

                            double minimum_error = double.MaxValue;

                            for (int i = 0; i < image_filename[cam].Count; i++)
                            {
                                // extract the pan and tilt servo positions of from the filename
                                double pan = 9999, tilt = 9999;
                                GetPanTilt(image_filename[cam][i], ref pan, ref tilt);
                                pan_servo_position[cam].Add(pan);
                                tilt_servo_position[cam].Add(tilt);
                                
                                int random_seed = 0;

                                // detect the dots and calculate a best fit curve
                                double centre_of_distortion_x = 0;
                                double centre_of_distortion_y = 0;
                                polynomial lens_distortion_curve = null;
                                double camera_rotation = 0;
                                double scale = 0;
                                float dot_x = -1, dot_y = -1;
                                double min_err = double.MaxValue;
                                int[] calib_map = null;
                                hypergraph dots =
                                    Detect(image_filename[cam][i],
                                    ref img_width, ref img_height,
                                    fov_degrees, dist_to_centre_dot_mm, dot_spacing_mm,
                                    ref centre_of_distortion_x, ref centre_of_distortion_y,
                                    ref lens_distortion_curve,
                                    ref camera_rotation, ref scale,
                                    lens_distortion_image_filename,
                                    curve_fit_image_filename,
                                    rectified_image_filename,
                                    ref dot_x, ref dot_y,
                                    ref min_err, ref calib_map,
                                    random_seed);

                                centre_dot_position[cam].Add(dot_x);
                                centre_dot_position[cam].Add(dot_y);

                                if (lens_distortion_curve != null)
                                {
                                    bool update = false;
                                    if (distortion_curve[cam] == null)
                                    {
                                        update = true;
                                    }
                                    else
                                    {
                                        if (min_err < minimum_error)
                                            update = true;
                                    }

                                    if (update)
                                    {
                                        minimum_error = min_err;

                                        // record the result with the smallest RMS error
                                        distortion_curve[cam] = lens_distortion_curve;
                                        centre_x[cam] = centre_of_distortion_x;
                                        centre_y[cam] = centre_of_distortion_y;
                                        rotation[cam] = camera_rotation;
                                        scale_factor[cam] = scale;
                                        if (calibration_map.Count <= cam)
                                            calibration_map.Add(calib_map);
                                        else
                                            calibration_map[cam] = calib_map;

                                        winner_index[cam] = i;

                                        if (File.Exists(lens_distortion_filename[cam])) File.Delete(lens_distortion_filename[cam]);
                                        File.Copy(lens_distortion_image_filename, lens_distortion_filename[cam]);

                                        if (File.Exists(curve_fit_filename[cam])) File.Delete(curve_fit_filename[cam]);
                                        File.Copy(curve_fit_image_filename, curve_fit_filename[cam]);

                                        if (File.Exists(rectified_filename[cam])) File.Delete(rectified_filename[cam]);
                                        File.Copy(rectified_image_filename, rectified_filename[cam]);
                                    }
                                }
                            }
                        }


                        // positions of the centre dots
                        List<List<double>> rectified_dots = new List<List<double>>();
                        for (int cam = 0; cam < image_filename.GetLength(0); cam++)
                        {
                            if (distortion_curve[cam] != null)
                            {
                                // position in the centre dots in the raw image
                                List<double> pts = new List<double>();

                                for (int i = 0; i < centre_dot_position[cam].Count; i += 2)
                                {
                                    pts.Add(centre_dot_position[cam][i]);
                                    pts.Add(centre_dot_position[cam][i + 1]);
                                }

                                // rectified positions for the centre dots
                                List<double> rectified_pts =
                                    RectifyDots(pts, img_width, img_height,
                                                distortion_curve[cam],
                                                centre_x[cam], centre_y[cam],
                                                rotation[cam], scale_factor[cam]);

                                rectified_dots.Add(rectified_pts);
                            }
                        }

                        ShowCentreDots(filename[winner_index[0]], rectified_dots, "centre_dots.jpg");
                        ShowCentreDots(filename[winner_index[0]], centre_dot_position, "centre_dots2.jpg");

                        if (calibration_map.Count == 2)
                        {
                            if ((calibration_map[0] != null) &&
                                (calibration_map[1] != null))
                            {
                                Rectify(image_filename[0][winner_index[0]], image_filename[1][winner_index[0]],
                                        calibration_map[0], calibration_map[1], "Rectification2.jpg");
                            }
                        }

                        if (rectified_dots.Count > 1)
                        {

                            // calibrate the pan and tilt mechanism
                            polynomial pan_curve = null, tilt_curve = null;
                            float pan_offset_x = 0, pan_offset_y = 0;
                            float tilt_offset_x = 0, tilt_offset_y = 0;
                            CalibratePanTilt(pan_servo_position, tilt_servo_position,
                                             rectified_dots, fov_degrees,
                                             img_width, img_height,
                                             dotdist_mm, height_mm,
                                             ref pan_curve, ref pan_offset_x, ref pan_offset_y,
                                             ref tilt_curve, ref tilt_offset_x, ref tilt_offset_y);

                            if (distortion_curve[0] != null)
                            {
                                // find the relative offset in the left and right images
                                double offset_x = 0;
                                double offset_y = 0;
                                bool is_valid = false;

                                if (distortion_curve[1] != null)
                                {
                                    int index0 = winner_index[0] * 2;
                                    int index1 = winner_index[1] * 2;

                                    if ((rectified_dots[0].Count < index0 + 1) &&
                                        (rectified_dots[1].Count < index1 + 1))
                                    {
                                        double x0 = rectified_dots[0][index0];
                                        double y0 = rectified_dots[0][index0 + 1];
                                        double x1 = rectified_dots[1][index1];
                                        double y1 = rectified_dots[1][index1 + 1];
                                        offset_x = x1 - x0;
                                        offset_y = y1 - y0;

                                        // calculate the focal length
                                        if (focal_length_pixels < 1)
                                        {
                                            focal_length_pixels = GetFocalLengthFromDisparity((float)dist_to_centre_dot_mm, (float)baseline_mm, (float)offset_x);
                                            Console.WriteLine("Calculated focal length (pixels): " + focal_length_pixels.ToString());
                                        }

                                        // subtract the expected disparity for the centre dot
                                        float expected_centre_dot_disparity = GetDisparityFromDistance(focal_length_pixels, baseline_mm, dist_to_centre_dot_mm);
                                        float check_dist_mm = GetDistanceFromDisparity(focal_length_pixels, baseline_mm, expected_centre_dot_disparity);

                                        //Console.WriteLine("expected_centre_dot_disparity: " + expected_centre_dot_disparity.ToString());
                                        //Console.WriteLine("observed disparity: " + offset_x.ToString());

                                        offset_x -= expected_centre_dot_disparity;

                                        is_valid = true;
                                    }
                                }

                                if (is_valid)
                                {
                                    // save the results as an XML file
                                    Save(calibration_xml_filename, "Test", focal_length_pixels, baseline_mm, fov_degrees,
                                         img_width, img_height, distortion_curve,
                                         centre_x, centre_y, rotation, scale_factor,
                                         lens_distortion_filename, curve_fit_filename,
                                         (float)offset_x, (float)offset_y,
                                         pan_curve, pan_offset_x, pan_offset_y,
                                         tilt_curve, tilt_offset_x, tilt_offset_y);
                                }
                            }

                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("No calibration " + file_extension + " images were found");
            }
        }
        public InputCatchData(float[] modelLats, float[] modelLons, float cellSize)
        {
            StreamReader r_ht = new StreamReader("input\\data\\Fisheries\\catchratesyr2000HT.csv");
            StreamReader r = new StreamReader("input\\data\\Fisheries\\catchrateyr2000.csv");

            //Read trait data
            Traits = new FishTraits();
            //Retrieve the Max Mass range from the trait data
            var temp = Traits.MassRange();
            double[] MaxMassRange = temp.Item1;
            string[] MaxMassRangeSp = temp.Item2;

            //Calculate a set of mass bins to be used for removing fisheries catches from binned Madingley biomasses 
            //TO DO: make these bins flexible and user defined
            int MinMassbinMax = Convert.ToInt32(Math.Ceiling(Math.Log10(MaxMassRange[0])));
            int MaxMassbinMax = Convert.ToInt32(Math.Ceiling(Math.Log10(MaxMassRange[1])));

            int NumBins = (MaxMassbinMax - MinMassbinMax) + 1;

            _MassBins = new double[NumBins];
            for (int i = 0; i < NumBins - 1; i++)
            {
                _MassBins[i] = Math.Pow(10, MinMassbinMax + i);
            }
            _UnknownMassBinIndex = NumBins - 1;

            string l;
            char[] comma = ",".ToCharArray();

            string[] f;

            List<int> year_ht = new List<int>();
            List<int> cell_ht = new List<int>();
            List<double> catchRate_ht = new List<Double>();
            List<string> taxa_ht = new List<string>();

            List<int> year = new List<int>();
            List<int> cell = new List<int>();
            List<double> catchRate = new List<Double>();
            List<string> taxa = new List<string>();

            //Read the Higher Taxonomy file
            while (!r_ht.EndOfStream)
            {
                l = r_ht.ReadLine();
                // Split fields by commas
                f = l.Split(comma);

                // Lists of the different fields
                year_ht.Add(Convert.ToInt32(f[0]));
                cell_ht.Add(Convert.ToInt32(f[1]));
                catchRate_ht.Add(Convert.ToDouble(f[2]));
                taxa_ht.Add(f[3]);
            }

            //Read the species catch file
            while (!r.EndOfStream)
            {
                l = r.ReadLine();
                // Split fields by commas
                f = l.Split(comma);

                // Lists of the different fields
                year.Add(Convert.ToInt32(f[0]));
                cell.Add(Convert.ToInt32(f[1]));
                catchRate.Add(Convert.ToDouble(f[2]));
                taxa.Add(f[3]);
            }

            float MinLon = -179.75f;
            float MaxLon = 179.75f;
            float MaxLat = 89.75f;
            float MinLat = -89.75f;

            _CatchNumLats = (int)((MaxLat - MinLat) / 0.5) + 1;
            _CatchNumLons = (int)((MaxLon - MinLon) / 0.5) + 1;

            _CatchTotal = new double[_CatchNumLats, _CatchNumLons];
            _CatchBinned = new double[_CatchNumLats, _CatchNumLons, NumBins];

            UnknownTaxa = new List<string>[_CatchNumLats, _CatchNumLons];
            for (int i = 0; i < UnknownTaxa.GetLength(0); i++)
            {
                for (int j = 0; j < UnknownTaxa.GetLength(1); j++)
                {
                    UnknownTaxa[i, j] = new List<string>();
                }
            }

            _CatchLats = new float[_CatchNumLats];
            _CatchLons = new float[_CatchNumLons];

            int[] Index;

            // Match lon index to lon
            for (int i = 0; i < _CatchNumLons; i++)
            {
                _CatchLons[i] = MinLon + (i * 0.5f);
            }

            // Match lat index to lat
            for (int i = 0; i < _CatchNumLats; i++)
            {
                _CatchLats[i] = MaxLat - (i * 0.5f);
            }

            //Will hold the mass bin index for the catch data
            int mb = 0;
            //Allocate the species level catch to cells and mass bins
            for (int i = 0; i < catchRate.Count; i++)
            {
                Index = IndexLookup(cell[i]);

                //Need to convert to size bins
                mb = AssignCatchToMassBin(taxa[i]);

                _CatchTotal[Index[0], Index[1]] += catchRate[i] * 1E6;
                _CatchBinned[Index[0], Index[1], mb] += catchRate[i] * 1E6;

                //If the taxa does not have trait data then list this taxa
                if (mb == UnknownMassBinIndex) UnknownTaxa[Index[0], Index[1]].Add(taxa[i]);
            }
            //Allocate the higher taxa level catch to cells and mass bins
            for (int i = 0; i < catchRate_ht.Count; i++)
            {
                Index = IndexLookup(cell_ht[i]);

                //Need to convert to size bins
                mb = AssignCatchToMassBin(taxa_ht[i]);

                _CatchTotal[Index[0], Index[1]] += catchRate_ht[i] * 1E6;
                _CatchBinned[Index[0], Index[1], mb] += catchRate_ht[i] * 1E6;

                //If the taxa does not have trait data then list this taxa
                if (mb == UnknownMassBinIndex) UnknownTaxa[Index[0], Index[1]].Add(taxa_ht[i]);
            }

            //foreach (var u in UnknownTaxa)
            //{
            //    if (u.Count > 0.0) Console.WriteLine(u.Count);
            //}

            double CumulativeCatch = 0.0;
            for (int i = 0; i < _CatchTotal.GetLength(0); i++)
            {
                for (int j = 0; j < _CatchTotal.GetLength(1); j++)
                {
                    CumulativeCatch += _CatchTotal[i, j];
                }
            }

            Console.WriteLine(CumulativeCatch);

            AggregateCatchData(modelLats, modelLons, cellSize);
        }