Пример #1
0
        public void drawRecognizedObject(VectorInt recognizedObjectVector)
        {
            for (int i = 1; i < recognizedObjectVector.Count(); i++)
            {

                recognizedTangible = (TangibleObject)arrayOfTangibleObjects[recognizedObjectVector[i]];
                label1.Text = "abc" + recognizedTangible.type.ToString();
                Console.WriteLine(recognizedObjectVector[i].ToString());

                if (recognizedTangible.type.Equals(TangibleType.Ruler))
                {
                    TRTangibleObject tobj = recognizer.getTangibleObjectForId(recognizedObjectVector[i]);
                    float rot = -tobj.getRotation();
                    TRPoint tran = tobj.getTranslation();
                    //Graphics g = DrawingTab.CreateGraphics();
                    tran.x = (int)Math.Round((float)tran.x * (float)glDrawingView.CreateGraphics().DpiX / 2540.0F);
                    tran.y = (int)Math.Round((float)tran.y * (float)glDrawingView.CreateGraphics().DpiY / 2540.0F);
                    float m11, m12, m21, m22;
                    m11 = (float)Math.Cos(rot);
                    m12 = (float)-Math.Sin(rot);
                    m21 = (float)Math.Sin(rot);
                    m22 = (float)Math.Cos(rot);
                    Matrix m = new Matrix(m11, m12, m21, m22, tran.x, tran.y);

                    ArrayList points = (ArrayList)recognizedTangible.outlinePoints.Clone();
                    pointsToDraw = (Point[])points.ToArray(typeof(Point));
                    m.TransformPoints(pointsToDraw);

                  // Console.WriteLine(tobj.getRotation());
                    //Console.WriteLine(tran.x + ":" + tran.y);
                    glDrawingView.Invalidate();

                }label2.Text = "";
            }
        }
Пример #2
0
    /// <summary>
    /// Writes a csv file containing fish species and frame numbers.
    /// </summary>
    /// <param name="count_path">Path to model file.</param>
    /// <param name="out_path">Path to output csv file.</param>
    /// <param name="roi">Region of interest, needed for image dims.</param>
    /// <param name="detections">Detections for each frame.</param>
    /// <param name="scores">Cover and species scores for each detection.</param>
    static void WriteCounts(
        string count_path,
        string out_path,
        Rect roi,
        VectorVectorDetection detections,
        VectorVectorClassification scores)
    {
        // Create and initialize keyframe finder.
        KeyframeFinder finder = new KeyframeFinder();
        ErrorCode      status = finder.Init(count_path, roi[2], roi[3]);

        if (status != ErrorCode.kSuccess)
        {
            throw new Exception("Failed to initialize keyframe finder!");
        }

        // Process keyframe finder.
        VectorInt keyframes = new VectorInt();

        status = finder.Process(scores, detections, keyframes);
        if (status != ErrorCode.kSuccess)
        {
            throw new Exception("Failed to process keyframe finder!");
        }

        // Write the keyframes out.
        using (var csv = new System.IO.StreamWriter(out_path)) {
            csv.WriteLine("id,frame,species_index");
            int id = 0;
            foreach (var i in keyframes)
            {
                Classification c             = scores[i][0];
                float          max_score     = 0.0F;
                int            species_index = 0;
                for (int j = 0; j < c.species.Count; ++j)
                {
                    if (c.species[j] > max_score)
                    {
                        max_score     = c.species[j];
                        species_index = j;
                    }
                }
                var line = string.Format("{0},{1},{2}", id, i, species_index);
                csv.WriteLine(line);
                id++;
            }
        }
    }
Пример #3
0
        private IEnumerator Intro(GameBase game)
        {
            var duration = 1.5f;
            var tick     = 0f;
            var initial  = cursor;
            var target   = new VectorInt(game.Width, game.Height) / 4;

            while (tick < duration)
            {
                cursor = DFMath.EaseOut(tick / duration, initial, target);
                yield return(null);

                tick += Time.DeltaTime;
            }
            cursor    = target;
            introDone = true;
        }
Пример #4
0
        public Map Build(string name, VectorInt origin, int width, int height, int length)
        {
            InitOffset.Execute(Seed);

            Result = new Map(name, width, height, length, origin);

            for (I = 0; I < width; I++)
            {
                for (J = 0; J < height; J++)
                {
                    for (K = 0; K < length; K++)
                    {
                        SetNodeType(Result.Nodes[I, J, K]);
                    }
                }
            }

            return(Result);
        }
Пример #5
0
        /// <summary>
        /// 取得一个随机三维整数向量, 输入的值将依次作为 x 的最大/最小值, y 的最大/最小值, z 的最大/最小值, 输入的值最多 6 个, 超出部分无效.
        /// 若输入三个值, 则随机的范围则是 x ∈ [0, args[0]), y ∈ [0, args[1]), z ∈ [0, args[2])
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static VectorInt GetVectorInt(int[] args)
        {
            VectorInt v = new VectorInt();

            switch (args.Length)
            {
            case 0:
                return(v);

            case 1:
                v.x = Range(args[0], args[0] * 2);
                return(v);

            case 2:
                v.x = Range(args[0], args[1]);
                return(v);

            case 3:
                v.x = Range(0, args[0]);
                v.y = Range(0, args[1]);
                v.z = Range(0, args[2]);
                return(v);

            case 4:
                v.x = Range(args[0], args[1]);
                v.y = Range(args[2], args[3]);
                return(v);

            case 5:
                v.x = Range(args[0], args[1]);
                v.y = Range(args[2], args[3]);
                v.z = Range(args[4], args[4] * 2);
                return(v);

            case 6:
                v.x = Range(args[0], args[1]);
                v.y = Range(args[2], args[3]);
                v.z = Range(args[4], args[5]);
                return(v);
            }
            return(v);
        }
Пример #6
0
        public void Print(object?obj)
        {
            var text = obj as string ?? obj?.ToString() ?? "null";

            var(x, y) = Cursor;
            x         = Math.Max(0, x);
            y         = Math.Max(0, y);
            if (y < consoleBuffer.Count)
            {
                // 置換
                consoleBuffer[y] = consoleBuffer[y].ReplaceAt(x, text);
            }
            else
            {
                // 挿入
                consoleBuffer.AddRange(Enumerable.Repeat("", y - consoleBuffer.Count));
                consoleBuffer.Add(new string(' ', x) + text);
            }
            Cursor = new VectorInt(0, y + 1);
        }
Пример #7
0
            /// <summary>
            /// 对房间进行初始化, 即生成房间内节点列表与边界节点列表
            /// </summary>
            /// <param name="map"></param>
            /// <param name="floorType"></param>
            /// <param name="boundryType"></param>
            /// <param name="minDistanceToMapEdge"></param>
            /// <returns></returns>
            public Room Init(Map map, Properties floorType, Properties boundryType, int minDistanceToMapEdge = 1)
            {
                nodes = nodes ?? new List <Node>();
                nodes.Clear();
                VectorInt diagonal = bounds.Diagonal;
                VectorInt pivot    = bounds.pivot;
                int       EndI     = Math.Min(diagonal.x, Math.Max(0, map.LengthX - 1 - minDistanceToMapEdge)),
                          EndJ     = Math.Min(diagonal.y, Math.Max(0, map.LengthY - 1 - minDistanceToMapEdge)),
                          EndK     = Math.Min(diagonal.z, Math.Max(0, map.LengthZ - 1 - minDistanceToMapEdge));

                for (int i = pivot.x; i <= EndI; i++)
                {
                    for (int j = pivot.y; j <= EndJ; j++)
                    {
                        for (int k = pivot.z; k <= EndK; k++)
                        {
                            Node n = map[i, j, k];
                            if (n != null)
                            {
                                n.SetProerties(floorType.Clone(true));
                                nodes.Add(n);
                            }
                        }
                    }
                }
                size         = new VectorInt(EndI - position.x, EndJ - position.y, EndK - position.z);
                bounds       = new FixedBounds2D(position, size);
                boundryNodes = new List <Node>();
                foreach (var point in bounds.boundriesOutside)
                {
                    Node n = map[point.x, point.y, point.z];
                    if (n != null)
                    {
                        n.SetProerties(boundryType);
                        boundryNodes.Add(n);
                    }
                }
                return(this);
            }
Пример #8
0
        /// <summary>
        /// The returned size doesn't have much meaning, other than for a tooltip
        /// </summary>
        public VectorInt GetSize()
        {
            VectorInt retVal = new VectorInt(0, 0);

            foreach (ConvolutionBase2D child in this.Convolutions)
            {
                VectorInt currentSize = new VectorInt();

                if (child is Convolution2D)
                {
                    currentSize = ((Convolution2D)child).Size;
                }
                else if (child is ConvolutionSet2D)
                {
                    currentSize = ((ConvolutionSet2D)child).GetSize();
                }
                else
                {
                    throw new ApplicationException("Unknown type of convolution: " + child.GetType().ToString());
                }

                if (currentSize.X > retVal.X)
                {
                    retVal.X = currentSize.X;
                }

                if (currentSize.Y > retVal.Y)
                {
                    retVal.Y = currentSize.Y;
                }
            }

            return retVal;
        }
Пример #9
0
        /// <summary>
        /// This looks at a patch that is extracted from the result of an image and a convolution.  This patch should be a relatively
        /// small rectangle centered around a bright spot (convolution.GetMax()).  This returns a score from 0 to 1.  This is looking
        /// for a peak that drops off (ideally a very large difference between the max pixel and min pixel)
        /// </summary>
        /// <remarks>
        /// TODO: May want another overload that takes a sample ideal patch to compare to:
        ///     Subtract patches, compare differences
        ///         line up the brightest point before subtracting
        ///         allow larger differences farther away from center
        /// </remarks>
        public static double GetExtractScore(Convolution2D patch, VectorInt brightestPoint, double? idealBrightness = null)
        {
            const double PERCENT_POS_MIN = .25;
            const double PERCENT_POS_MAX = .75;

            const double PERCENT_NEG_MIN = -.25;
            const double PERCENT_NEG_MAX = .5;

            if (patch.Width < 3 || patch.Height < 3)
            {
                return 0;
            }

            double max = patch[brightestPoint];

            // Get the min.  If not enough difference from max, then return zero
            var min = patch.GetMin();

            double percent = min.Item2 / max;

            double retVal = 0;

            if (patch.IsNegPos)
            {
                #region Neg/Pos

                if (percent < PERCENT_NEG_MIN)
                {
                    retVal = 1;
                }
                else if (percent < PERCENT_NEG_MAX)
                {
                    retVal = UtilityCore.GetScaledValue(1, 0, PERCENT_NEG_MIN, PERCENT_NEG_MAX, percent);
                }
                else
                {
                    return 0;
                }

                #endregion
            }
            else
            {
                #region Positive

                if (percent < PERCENT_POS_MIN)
                {
                    retVal = 1;
                }
                else if (percent < PERCENT_POS_MAX)
                {
                    retVal = UtilityCore.GetScaledValue(1, 0, PERCENT_POS_MIN, PERCENT_POS_MAX, percent);
                }
                else
                {
                    return 0;
                }

                #endregion
            }

            if (idealBrightness == null || max >= idealBrightness.Value)
            {
                return retVal;
            }

            return retVal * (max / idealBrightness.Value);
        }
Пример #10
0
        public static RectInt GetExtractRectangle(VectorInt imageSize, bool isSquare, double sizePercent)
        {
            const double PERCENTDIFF = .02;

            Random rand = StaticRandom.GetRandomForThread();

            // Min Size
            int minSize = Math.Min(imageSize.X, imageSize.Y);
            if (minSize == 0)
            {
                throw new ArgumentException("Image size is zero");
            }

            // Percents
            double scaledPercent = UtilityCore.GetScaledValue_Capped(MINPERCENT + PERCENTDIFF, MAXPERCENT - PERCENTDIFF, 0, 1, sizePercent);

            double minPercent = scaledPercent - PERCENTDIFF;
            double maxPercent = scaledPercent + PERCENTDIFF;

            // Size
            double extractSizeMin = minSize * minPercent;
            double extractSizeMax = minSize * maxPercent;

            // Width
            int width = rand.NextDouble(extractSizeMin, extractSizeMax).ToInt_Round();
            if (width < 1) width = 1;
            int height;

            // Height
            if (isSquare)
            {
                height = width;
            }
            else
            {
                if (scaledPercent > .5)
                {
                    height = rand.NextDouble(width / Math1D.GOLDENRATIO, width).ToInt_Round();      // Reduce
                }
                else
                {
                    height = rand.NextDouble(width, width * Math1D.GOLDENRATIO).ToInt_Round();      // Increase
                }
            }

            if (height < 1) height = 1;

            // Random chance of swapping so height might be taller
            if (rand.NextBool())
            {
                UtilityCore.Swap(ref width, ref height);
            }

            // Rectangle
            return new RectInt()
            {
                X = rand.Next(imageSize.X - width),
                Y = rand.Next(imageSize.Y - height),
                Width = width,
                Height = height,
            };
        }
Пример #11
0
 public bool IsPlaceable(VectorInt location)
 {
     return(PlaceableLocations.Contains(location));
 }
        /// <summary>
        /// This returns the coordinates of tiles.  The tiles spiral outward: right,up,left,down,right,up...
        /// </summary>
        /// <returns>
        /// Item1=aabb min
        /// Item2=aabb max
        /// Item3=positions
        /// </returns>
        private static Tuple<VectorInt, VectorInt, VectorInt[]> GetTileImagePositions(int count)
        {
            int x = 0;
            int y = 0;

            int minX = 0;
            int minY = 0;
            int maxX = 0;
            int maxY = 0;

            int dirX = 1;
            int dirY = 0;

            VectorInt[] positions = new VectorInt[count];

            for (int cntr = 0; cntr < count; cntr++)
            {
                positions[cntr] = new VectorInt(x, y);

                if (cntr >= count - 1)
                {
                    // The logic below preps for the next step, but if this is the last one, leave mins and maxes alone
                    break;
                }

                x += dirX;
                y += dirY;

                if (x > maxX)
                {
                    maxX = x;
                    dirX = 0;
                    dirY = -1;
                }
                else if (x < minX)
                {
                    minX = x;
                    dirX = 0;
                    dirY = 1;
                }
                else if (y > maxY)
                {
                    maxY = y;
                    dirY = 0;
                    dirX = 1;
                }
                else if (y < minY)
                {
                    minY = y;
                    dirY = 0;
                    dirX = -1;
                }
            }

            return Tuple.Create(new VectorInt(minX, minY), new VectorInt(maxX, maxY), positions);
        }
Пример #13
0
 public void PushBack(VectorInt value)
 {
     au_std_vectorVectorInt_push_back(cppPtr, value.cppPtr);
 }
        private void RefreshStatsPanel()
        {
            if (_selectedKernelIndex < 0)
            {
                lblSelectedSize.Content = "";
                lblSelectedReduction.Content = "";
            }

            VectorInt totalReduce = new VectorInt();

            for (int cntr = 0; cntr < _kernels.Count; cntr++)
            {
                VectorInt childReduce = _kernels[cntr].GetReduction();

                totalReduce += childReduce;

                if (cntr == _selectedKernelIndex)
                {
                    if (_kernels[cntr] is Convolution2D)
                    {
                        Convolution2D childSingle = (Convolution2D)_kernels[cntr];
                        lblSelectedSize.Content = string.Format("{0}x{1}", childSingle.Width, childSingle.Height);
                    }
                    else
                    {
                        lblSelectedSize.Content = "";
                    }

                    lblSelectedReduction.Content = string.Format("{0}x{1}", childReduce.X, childReduce.Y);
                }
            }

            lblTotalReduction.Content = string.Format("{0}x{1}", totalReduce.X, totalReduce.Y);
        }
Пример #15
0
        public Room(VectorInt Position, string EntryDirection, bool initialRoom, bool Debug)
        {
            doorCounter  = 0;
            this.debug   = Debug;
            roomPosition = Position;
            Doors        = new Dictionary <string, RoomDoors>();

            #region Generate doors
            double willHaveDoor;

            if (initialRoom)
            {
                #region Initial Room
                #region Doors
                willHaveDoor = Program.rnd.Next(100);
                if (debug)
                {
                    System.Console.Write("North: " + willHaveDoor + " ");
                }
                if (willHaveDoor > 50)
                {
                    Doors["NORTH"] = new RoomDoors(true);
                }
                else
                {
                    Doors["NORTH"] = new RoomDoors(false);
                }

                willHaveDoor = Program.rnd.Next(100);
                if (debug)
                {
                    System.Console.Write("South: " + willHaveDoor + " ");
                }
                if (willHaveDoor > 50)
                {
                    Doors["SOUTH"] = new RoomDoors(true);
                }
                else
                {
                    Doors["SOUTH"] = new RoomDoors(false);
                }

                willHaveDoor = Program.rnd.Next(100);
                if (debug)
                {
                    System.Console.Write("East: " + willHaveDoor + " ");
                }
                if (willHaveDoor > 50)
                {
                    Doors["EAST"] = new RoomDoors(true);
                }
                else
                {
                    Doors["EAST"] = new RoomDoors(false);
                }

                willHaveDoor = Program.rnd.Next(100);
                if (debug)
                {
                    System.Console.Write("West: " + willHaveDoor + " ");
                }
                if (willHaveDoor > 50)
                {
                    Doors["WEST"] = new RoomDoors(true);
                }
                else
                {
                    Doors["WEST"] = new RoomDoors(false);
                }

                willHaveDoor = Program.rnd.Next(100);
                if (debug)
                {
                    System.Console.Write("Up: " + willHaveDoor + " ");
                }
                if (willHaveDoor > 50)
                {
                    Doors["UP"] = new RoomDoors(true);
                }
                else
                {
                    Doors["UP"] = new RoomDoors(false);
                }

                willHaveDoor = Program.rnd.Next(100);
                if (debug)
                {
                    System.Console.Write("Down: " + willHaveDoor + "\r\n");
                }
                if (willHaveDoor > 50)
                {
                    Doors["DOWN"] = new RoomDoors(true);
                }
                else
                {
                    Doors["DOWN"] = new RoomDoors(false);
                }
                #endregion
                description.Append("One wall of the room is marked with the word Origo.\r\n");
                #endregion
            }
            else
            {
                #region North
                if (Program.engine.gameWorld.Rooms.ContainsKey(new VectorInt(roomPosition.X, roomPosition.Y - 1, roomPosition.Z).ToString()))
                {
                    Doors["NORTH"] = new RoomDoors(Program.engine.gameWorld.Rooms[new VectorInt(roomPosition.X, roomPosition.Y - 1, roomPosition.Z).ToString()].Doors["SOUTH"].IsDoor);
                }
                else
                {
                    willHaveDoor = Program.rnd.Next(100);
                    if (willHaveDoor > 50)
                    {
                        Doors["NORTH"] = new RoomDoors(true);
                    }
                    else
                    {
                        Doors["NORTH"] = new RoomDoors(false);
                    }
                }
                #endregion
                #region East
                if (Program.engine.gameWorld.Rooms.ContainsKey(new VectorInt(roomPosition.X + 1, roomPosition.Y, roomPosition.Z).ToString()))
                {
                    Doors["EAST"] = new RoomDoors(Program.engine.gameWorld.Rooms[new VectorInt(roomPosition.X + 1, roomPosition.Y, roomPosition.Z).ToString()].Doors["WEST"].IsDoor);
                }
                else
                {
                    willHaveDoor = Program.rnd.Next(100);
                    if (willHaveDoor > 50)
                    {
                        Doors["EAST"] = new RoomDoors(true);
                    }
                    else
                    {
                        Doors["EAST"] = new RoomDoors(false);
                    }
                }
                #endregion
                #region South
                if (Program.engine.gameWorld.Rooms.ContainsKey(new VectorInt(roomPosition.X, roomPosition.Y + 1, roomPosition.Z).ToString()))
                {
                    Doors["SOUTH"] = new RoomDoors(Program.engine.gameWorld.Rooms[new VectorInt(roomPosition.X, roomPosition.Y + 1, roomPosition.Z).ToString()].Doors["NORTH"].IsDoor);
                }
                else
                {
                    willHaveDoor = Program.rnd.Next(100);
                    if (willHaveDoor > 50)
                    {
                        Doors["SOUTH"] = new RoomDoors(true);
                    }
                    else
                    {
                        Doors["SOUTH"] = new RoomDoors(false);
                    }
                }
                #endregion
                #region West
                if (Program.engine.gameWorld.Rooms.ContainsKey(new VectorInt(roomPosition.X - 1, roomPosition.Y, roomPosition.Z).ToString()))
                {
                    Doors["WEST"] = new RoomDoors(Program.engine.gameWorld.Rooms[new VectorInt(roomPosition.X - 1, roomPosition.Y, roomPosition.Z).ToString()].Doors["EAST"].IsDoor);
                }
                else
                {
                    willHaveDoor = Program.rnd.Next(100);
                    if (willHaveDoor > 50)
                    {
                        Doors["WEST"] = new RoomDoors(true);
                    }
                    else
                    {
                        Doors["WEST"] = new RoomDoors(false);
                    }
                }
                #endregion
                #region Up
                if (Program.engine.gameWorld.Rooms.ContainsKey(new VectorInt(roomPosition.X, roomPosition.Y, roomPosition.Z + 1).ToString()))
                {
                    Doors["UP"] = new RoomDoors(Program.engine.gameWorld.Rooms[new VectorInt(roomPosition.X, roomPosition.Y, roomPosition.Z + 1).ToString()].Doors["DOWN"].IsDoor);
                }
                else
                {
                    willHaveDoor = Program.rnd.Next(100);
                    if (willHaveDoor > 50)
                    {
                        Doors["UP"] = new RoomDoors(true);
                    }
                    else
                    {
                        Doors["UP"] = new RoomDoors(false);
                    }
                }
                #endregion
                #region Down
                if (Program.engine.gameWorld.Rooms.ContainsKey(new VectorInt(roomPosition.X, roomPosition.Y, roomPosition.Z - 1).ToString()))
                {
                    Doors["DOWN"] = new RoomDoors(Program.engine.gameWorld.Rooms[new VectorInt(roomPosition.X, roomPosition.Y, roomPosition.Z - 1).ToString()].Doors["UP"].IsDoor);
                }
                else
                {
                    willHaveDoor = Program.rnd.Next(100);
                    if (willHaveDoor > 50)
                    {
                        Doors["DOWN"] = new RoomDoors(true);
                    }
                    else
                    {
                        Doors["DOWN"] = new RoomDoors(false);
                    }
                }
                #endregion
            }
            #region Debug-Doors
            if (Debug)
            {
                foreach (KeyValuePair <string, RoomDoors> door in Doors)
                {
                    door.Value.IsDoor = true;
                }
            }
            #endregion
            #region ReturnDoor
            //Make sure returndoor exists
            Doors[EntryDirection] = new RoomDoors(true);
            #endregion
            #endregion

            #region Special Rooms
            if (roomPosition.X == 3 && roomPosition.Y == 1 && roomPosition.Z == 4)
            {
                description.Append("There is a pie drawn on one of the walls.\r\n");
            }
            if (roomPosition.X > 1 && roomPosition.Y == Math.Pow(roomPosition.X, 2) && roomPosition.Z == Math.Pow(roomPosition.X, 3))
            {
                description.Append("All the walls are covered in squares.\r\n");
            }
            if (roomPosition.X > 1 && roomPosition.Y == roomPosition.X * roomPosition.X && roomPosition.Z == roomPosition.Y * roomPosition.Y)
            {
                description.Append("There is a cube drawn on the floor.\r\n");
            }
            #endregion

            #region Describe Doors
            description.Append("The room has doors to:");
            foreach (KeyValuePair <string, RoomDoors> door in Doors)
            {
                if (door.Value.IsDoor)
                {
                    description.Append(" " + door.Key[0] + door.Key.Substring(1).ToLower());
                }
            }
            description.Append("\r\n");

            foreach (KeyValuePair <string, RoomDoors> door in Doors)
            {
                if (door.Value.IsDoor)
                {
                    doorCounter++;
                }
            }
            if (doorCounter == 1)
            {
                description.Append("This room is a dead-end.\r\n");
            }

            #endregion
        }
        private static Tuple<RectInt, VectorInt> GetResultRect(VectorInt imageSize, VectorInt center, VectorInt size)
        {
            if (Convolutions.IsTooSmall(imageSize) || Convolutions.IsTooSmall(size))
            {
                return null;
            }

            VectorInt offset = -(size / 2);
            VectorInt positionInitial = center + offset;

            RectInt? rect = RectInt.Intersect(new RectInt(positionInitial, size), new RectInt(0, 0, imageSize.X, imageSize.Y));
            if (rect == null)
            {
                throw new ArgumentException("No rectangle found");
            }

            if (rect.Value.X > positionInitial.X)
            {
                offset.X += rect.Value.X - positionInitial.X;
            }

            if (rect.Value.Y > positionInitial.Y)
            {
                offset.Y += rect.Value.Y - positionInitial.Y;
            }

            return Tuple.Create(rect.Value, offset);
        }
        private void NewExtract_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_images.Count == 0)
                {
                    MessageBox.Show("Add an image first", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // Pick a random image
                var image = GetSelectedImage();
                if (image == null)
                {
                    image = _images[StaticRandom.Next(_images.Count)];
                }

                #region Prefilter

                // Figure out which pre filters to choose from
                List<ConvolutionBase2D> prefilterCandidates = new List<ConvolutionBase2D>();

                if (chkPrefilterNone.IsChecked.Value)
                {
                    prefilterCandidates.Add(null);
                }

                if (chkPrefilterGaussian.IsChecked.Value)
                {
                    prefilterCandidates.AddRange(_preFilters.Where(o => o.Item1 == PrefilterType.Gaussian).SelectMany(o => o.Item2));
                }

                if (chkPrefilterGaussianSubtract.IsChecked.Value)
                {
                    prefilterCandidates.AddRange(_preFilters.Where(o => o.Item1 == PrefilterType.Gaussian_Subtract).SelectMany(o => o.Item2));
                }

                if (chkPrefilterMaxAbsSobel.IsChecked.Value)
                {
                    prefilterCandidates.AddRange(_preFilters.Where(o => o.Item1 == PrefilterType.MaxAbs_Sobel).SelectMany(o => o.Item2));
                }

                if (chkPrefilterGaussianEdge.IsChecked.Value)
                {
                    prefilterCandidates.AddRange(_preFilters.Where(o => o.Item1 == PrefilterType.Gaussian_Edge).SelectMany(o => o.Item2));
                }

                // Random chance of pre filters
                ConvolutionBase2D filter = null;
                if (prefilterCandidates.Count > 0)
                {
                    filter = prefilterCandidates[StaticRandom.Next(prefilterCandidates.Count)];
                }

                #endregion

                #region Extract convolution

                // Calculate largest image's size
                VectorInt finalSize = new VectorInt()
                {
                    X = image.Bitmap.PixelWidth,
                    Y = image.Bitmap.PixelHeight,
                };

                if (filter != null)
                {
                    finalSize -= filter.GetReduction();
                }

                // Extract rectangle
                RectInt rect = Convolutions.GetExtractRectangle(finalSize, chkIsSquare.IsChecked.Value);

                List<FeatureRecognizer_Extract_Sub> subs = new List<FeatureRecognizer_Extract_Sub>();

                #endregion

                foreach (ReducedExtract size in GetExtractSizes(image.Bitmap, filter, rect))
                {
                    #region Image and prefilter

                    // Initial image
                    BitmapSource bitmap;
                    if (size.Percent.IsNearValue(1))
                    {
                        bitmap = image.Bitmap;
                    }
                    else
                    {
                        bitmap = UtilityWPF.ResizeImage(image.Bitmap, size.ImageSize.X, size.ImageSize.Y);
                    }

                    // Get convolution
                    Convolution2D imageConv = ((BitmapCustomCachedBytes)UtilityWPF.ConvertToColorArray(bitmap, false, Colors.Transparent)).ToConvolution();

                    if (filter != null)
                    {
                        imageConv = Convolutions.Convolute(imageConv, filter);
                    }

                    #endregion

                    // Extract
                    Convolution2D extractConv = imageConv.Extract(size.Extract, ConvolutionExtractType.EdgeSoftBorder);

                    // Generate results
                    FeatureRecognizer_Extract_Sub sub = BuildExtractResult(imageConv, extractConv);
                    if (sub != null)
                    {
                        subs.Add(sub);
                    }
                }

                // Finish
                FinishBuildingExtract(filter, subs.ToArray(), image.UniqueID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private static ReducedExtract[] GetExtractSizes(BitmapSource bitmap, ConvolutionBase2D filter, RectInt rect, int minExtractSize = 10)
        {
            List<ReducedExtract> retVal = new List<ReducedExtract>();

            VectorInt filterReduce = filter == null ? new VectorInt(0, 0) : filter.GetReduction();

            Rect percents = new Rect()
            {
                X = rect.X.ToDouble() / bitmap.PixelWidth.ToDouble(),
                Y = rect.Y.ToDouble() / bitmap.PixelHeight.ToDouble(),
                Width = rect.Width.ToDouble() / bitmap.PixelWidth.ToDouble(),
                Height = rect.Height.ToDouble() / bitmap.PixelHeight.ToDouble(),
            };

            double percent = 1d;

            while (true)
            {
                VectorInt imageSize = new VectorInt()
                {
                    X = (bitmap.PixelWidth * percent).ToInt_Round(),
                    Y = (bitmap.PixelHeight * percent).ToInt_Round(),
                };

                VectorInt postSize = imageSize - filterReduce;

                RectInt newRect = new RectInt()
                {
                    X = (percents.X * postSize.X).ToInt_Round(),
                    Y = (percents.Y * postSize.Y).ToInt_Round(),
                    Width = (percents.Width * postSize.X).ToInt_Round(),
                    Height = (percents.Height * postSize.Y).ToInt_Round(),
                };

                if (newRect.Width < minExtractSize || newRect.Height < minExtractSize)
                {
                    break;
                }

                retVal.Add(new ReducedExtract()
                {
                    Percent = percent,
                    ImageSize = imageSize,
                    Extract = newRect,
                });

                percent *= .75;
            }

            return retVal.ToArray();
        }
        /// <summary>
        /// This applies the extract to the image, and returns some result patches of the brightest hit
        /// </summary>
        /// <param name="image">This is the image after filter is applied</param>
        /// <param name="extract">This is the extract to apply to the image</param>
        private static FeatureRecognizer_Extract_Sub BuildExtractResult(Convolution2D image, Convolution2D extract)
        {
            // Apply the extract
            Convolution2D applied = Convolutions.Convolute(image, extract);

            Tuple<VectorInt, double> brightestPoint = applied.GetMax();

            // Sometimes the extract is small compared to the image, sometimes it's nearly the same size.  As the extract rect
            // gets bigger, the result conv gets smaller
            VectorInt analyzeSize = new VectorInt()
            {
                X = Math.Min(applied.Width, extract.Width),
                Y = Math.Min(applied.Height, extract.Height),
            };

            VectorInt[] sizes = new[]
            {
                analyzeSize / 2d,
                analyzeSize / 4d,
                analyzeSize / 8d,
            };

            // Now extract the area around the brightest point.  This will be the ideal
            var results = sizes.
                Select(o => new { AnalyzeSize = o, Rectangle = GetResultRect(applied.Size, brightestPoint.Item1, o) }).
                Where(o => o.Rectangle != null).
                Select(o =>
                {
                    var convolution = applied.Extract(o.Rectangle.Item1, ConvolutionExtractType.Raw);
                    double score = Convolutions.GetExtractScore(convolution, brightestPoint.Item1 - o.Rectangle.Item1.Position, brightestPoint.Item2);

                    return new { o.AnalyzeSize, o.Rectangle, Convolution = convolution, Score = score };
                }).
                Where(o => o.Score > 0).
                ToArray();

            if (results.Length == 0)
            {
                return null;
            }

            // Exit Function
            return new FeatureRecognizer_Extract_Sub()
            {
                InputWidth = image.Width,
                InputHeight = image.Height,

                Extract = extract,
                ExtractDNA = extract.ToDNA(),

                Results = results.Select(o =>
                    new FeatureRecognizer_Extract_Result()
                    {
                        Offset = o.Rectangle.Item2,
                        Rectangle = o.Rectangle.Item1,
                        BrightestValue = brightestPoint.Item2,
                        Score = o.Score,
                        Result = o.Convolution,
                        ResultDNA = o.Convolution.ToDNA(),
                    }).
                    ToArray(),
            };
        }
        private static Border GetResultPositionsImage(IEnumerable<Tuple<VectorInt, double>> hits, VectorInt patchSize, int returnSize)
        {
            const int SIZE = 150;
            const double RADIUS_MAX = SIZE * .1;
            const double RADIUS_MIN = RADIUS_MAX * .25;
            const double MINOPACITY = .1;

            #region Bitmap

            RenderTargetBitmap bitmap = new RenderTargetBitmap(SIZE, SIZE, UtilityWPF.DPI, UtilityWPF.DPI, PixelFormats.Pbgra32);

            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext ctx = dv.RenderOpen())
            {
                foreach (var hit in hits)
                {
                    Point center = new Point()
                    {
                        X = UtilityCore.GetScaledValue(0, SIZE, 0, patchSize.X, hit.Item1.X),
                        Y = UtilityCore.GetScaledValue(0, SIZE, 0, patchSize.Y, hit.Item1.Y),
                    };

                    double radius = UtilityCore.GetScaledValue(RADIUS_MIN, RADIUS_MAX, 0, 1, hit.Item2);
                    double alphaPercent = UtilityCore.GetScaledValue(MINOPACITY, 1, 0, 1, hit.Item2);
                    Color color = UtilityWPF.AlphaBlend(Colors.Black, Colors.Transparent, alphaPercent);

                    ctx.DrawEllipse(new SolidColorBrush(color), null, center, radius, radius);
                }
            }

            bitmap.Render(dv);

            #endregion
            #region Image/Border

            Image image = new Image()
            {
                Source = bitmap,
                Width = returnSize,
                Height = returnSize,
            };

            Border border = new Border()
            {
                Child = image,
                BorderBrush = new SolidColorBrush(UtilityWPF.ColorFromHex("A0A0A0")),
                BorderThickness = new Thickness(1),
                Background = Brushes.White,
                Margin = new Thickness(2),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
            };

            #endregion

            return border;
        }
        private static void ApplyExtract_Draw_Matches(Grid grid, Tuple<VectorInt, ApplyResult_Match[]>[] matches, VectorInt imageSize, FeatureRecognizer_Extract_Sub sub, ContextMenu contextMenu)
        {
            const int HITSSIZE_SMALL = 50;
            const int HITSSIZE_BIG = 70;

            StackPanel mainPanel = new StackPanel();

            Grid headerRow = new Grid();
            mainPanel.Children.Add(headerRow);

            #region Draw all hit positions

            var hits = matches.Select(o =>
                {
                    double weight = 0;
                    if (o.Item2 != null && o.Item2.Length > 0)
                    {
                        weight = o.Item2.Max(p => p.Weight);
                    }

                    return new Tuple<VectorInt, double>(o.Item1, weight);
                });

            Border hitsMap = GetResultPositionsImage(hits, imageSize, HITSSIZE_BIG);

            hitsMap.HorizontalAlignment = HorizontalAlignment.Left;
            hitsMap.VerticalAlignment = VerticalAlignment.Bottom;

            headerRow.Children.Add(hitsMap);

            #endregion
            #region Compare extracts

            Grid comparesGrid = new Grid();
            comparesGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
            comparesGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });

            comparesGrid.HorizontalAlignment = HorizontalAlignment.Right;
            comparesGrid.VerticalAlignment = VerticalAlignment.Bottom;

            headerRow.Children.Add(comparesGrid);

            // Label
            TextBlock comparesHeading = new TextBlock() { Text = "compare to", ToolTip = "These are results from the original extract, and can be used to compare the current image's extracts against", HorizontalAlignment = HorizontalAlignment.Center };

            Grid.SetRow(comparesHeading, 0);
            comparesGrid.Children.Add(comparesHeading);

            // Extracts
            StackPanel headerExtracts = new StackPanel()
            {
                Orientation = Orientation.Horizontal,
            };

            foreach (Convolution2D compareResult in sub.Results.Select(o => o.Result))
            {
                headerExtracts.Children.Add(Convolutions.GetThumbnail(compareResult, THUMBSIZE_EXTRACT, contextMenu));
            }

            Grid.SetRow(headerExtracts, 1);
            comparesGrid.Children.Add(headerExtracts);

            #endregion

            foreach (var match in matches)
            {
                //TODO: Make a grid
                StackPanel row = new StackPanel()
                {
                    Orientation = Orientation.Horizontal,
                    Margin = new Thickness(2),
                };

                #region Position

                StackPanel positionPanel = new StackPanel()
                {
                    VerticalAlignment = VerticalAlignment.Center,
                };

                row.Children.Add(positionPanel);

                // Point map
                Border pointMap = GetResultPositionsImage(new[] { Tuple.Create(match.Item1, 1d) }, imageSize, HITSSIZE_SMALL);
                pointMap.HorizontalAlignment = HorizontalAlignment.Left;
                positionPanel.Children.Add(pointMap);

                // Coordinates
                positionPanel.Children.Add(new TextBlock() { Text = match.Item1.ToString(), HorizontalAlignment = HorizontalAlignment.Center });

                #endregion

                foreach (var patch in match.Item2)
                {
                    #region Match Patch

                    StackPanel patchPanel = new StackPanel();
                    row.Children.Add(patchPanel);

                    // Show convolution
                    patchPanel.Children.Add(Convolutions.GetThumbnail(patch.Patch, THUMBSIZE_EXTRACT, contextMenu));

                    // Weight
                    patchPanel.Children.Add(new TextBlock()
                    {
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Text = patch.IsMatch ? patch.Weight.ToStringSignificantDigits(2) : "no match",
                    });

                    #endregion
                }

                mainPanel.Children.Add(row);
            }

            #region Return border

            Border border = new Border()
            {
                BorderBrush = new SolidColorBrush(UtilityWPF.ColorFromHex("40000000")),
                BorderThickness = new Thickness(1),
                CornerRadius = new CornerRadius(4),
                Padding = new Thickness(4),
                Background = new SolidColorBrush(UtilityWPF.ColorFromHex("10000000")),
                Child = mainPanel,
            };

            Grid.SetColumn(border, 0);
            Grid.SetColumnSpan(border, 3);
            Grid.SetRow(border, 2);
            grid.Children.Add(border);

            #endregion
        }
Пример #22
0
 public static Point ToPoint(this VectorInt vec) => new Point(vec.X, vec.Y);
Пример #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Segment"/> struct.
 /// </summary>
 /// <param name="min">
 /// The min.
 /// </param>
 /// <param name="max">
 /// The max.
 /// </param>
 public Segment(VectorInt min, VectorInt max)
 {
     this.Min = min;
     this.Max = max;
 }
Пример #24
0
        private static Texture2D[] LoadAndSplit(string path, int horizontalCount, int verticalCount, VectorInt size)
        {
            var t = Texture2D.LoadAndSplitFrom(path, horizontalCount, verticalCount, size);

            logger.Info($"Loaded an image '{path}' and generate {horizontalCount * verticalCount} textures");
            return(t);
        }
Пример #25
0
 public bool IsInside(VectorInt position)
 {
     return(position.x > leftEdge && position.x < rightEdge && position.y < topEdge && position.y > downEdge);
 }
Пример #26
0
 public void AddRoom(VectorInt Position, string EntryDirection, bool Debug)
 {
     Rooms.Add(Position.ToString(), new Room(Position, EntryDirection, false, Debug));
 }
Пример #27
0
 public void AddRoom(VectorInt Position, string EntryDirection, bool Debug)
 {
     gameWorld.AddRoom(Position, EntryDirection, Debug);
 }
Пример #28
0
        private void UpdateTiles_Quadrant(AxisFor axisX, AxisFor axisY, Point center, double size)
        {
            foreach (int x in axisX.Iterate())
            {
                foreach (int y in axisY.Iterate())
                {
                    if ((x + y) % 2 != 0)
                    {
                        continue;       // skip every other, so that it's a checkerboard
                    }

                    VectorInt vect = new VectorInt(x, y);

                    Rectangle rect;
                    if (!_rectangles.TryGetValue(vect, out rect))
                    {
                        rect = new Rectangle() { Fill = _brush, };
                        _rectangles.Add(vect, rect);
                        _canvas.Children.Add(rect);
                    }

                    rect.Width = size;
                    rect.Height = size;

                    Canvas.SetLeft(rect, center.X + _initialOffset.X + (x * size));
                    Canvas.SetTop(rect, center.Y + _initialOffset.Y + (y * size));
                }
            }
        }
Пример #29
0
        public MolStat GetMolStat()
        {
            /* 统计原子 */
            uint _numAtoms    = mol.NumAtoms();       //所有原子总数
            uint _numHvyAtoms = mol.NumHvyAtoms();    //所有除去氢原子的原子总数
            int  _totalCharge = mol.GetTotalCharge(); //总电荷数

            int n_C     = 0;                          // number of carbon atoms 碳原子总数
            int n_C1    = 0;                          // number of carbon atoms with sp1 hybridization sp1杂化的碳原子数
            int n_C2    = 0;                          // number of carbon atoms with sp1 hybridization sp2杂化的碳原子数
            int n_CHB1p = 0;                          // number of carbon atoms with at least 1 bond to a hetero atom 至少连接一个杂原子的碳原子数
            int n_CHB2p = 0;                          // number of carbon atoms with at least 2 bonds to a hetero atom 至少连接两个个杂原子的碳原子数
            int n_CHB3p = 0;                          // number of carbon atoms with at least 3 bonds to a hetero atom 至少连接三个杂原子的碳原子数
            int n_CHB4  = 0;                          // number of carbon atoms with 4 bonds to a hetero atom 连接了4个杂原子的碳原子数
            int n_O     = 0;                          // number of oxygen atoms 氧原子数
            int n_O2    = 0;                          // number of sp2-hybridized oxygen atoms sp2杂化的氧原子数
            int n_O3    = 0;                          // number of sp3-hybridized oxygen atoms sp3杂化的氧原子数
            int n_N     = 0;                          // number of nitrogen atoms 氮原子数
            int n_N1    = 0;                          // number of sp-hybridized nitrogen atoms sp杂化的氮原子数
            int n_N2    = 0;                          // number of sp2-hybridized nitrogen atoms sp2杂化的氮原子数
            int n_N3    = 0;                          // number of sp3-hybridized nitrogen atoms sp3杂化的氮原子数
            int n_S     = 0;                          // number of sulfur atoms 硫原子数
            int n_SeTe  = 0;                          // total number of selenium and tellurium atoms 硒和碲原子的数目
            int n_F     = 0;                          // number of fluorine atoms 氟原子的数目
            int n_Cl    = 0;                          // number of chlorine atoms 氯原子的数目
            int n_Br    = 0;                          // number of bromine atoms 溴原子的数目
            int n_I     = 0;                          // number of iodine atoms 碘原子的数目
            int n_P     = 0;                          // number of phosphorus atoms 磷原子的数目
            int n_B     = 0;                          // number of boron atoms 硼原子的数目
            int n_Met   = 0;                          // total number of metal atoms 金属原子的数目
            int n_X     = 0;                          // total number of "other" atoms (not listed above) and halogens 其他原子的数目,除了以上列出的之外。

            for (int i = 1; i <= _numAtoms; i++)
            {
                OBAtom _atom          = mol.GetAtom(i);
                uint   _AtomicNum     = _atom.GetAtomicNum();     //原子种类,周期表序号
                uint   _hyb           = _atom.GetHyb();           //原子的杂化形态,1 for sp1,  2 for sp2, 3 for sp3
                uint   _HeteroValence = _atom.GetHeteroValence(); //连接在这个原子上杂(非氢,碳)原子的数目
                //uint _HeteroValence = _atom.GetHeteroDegree();  //For openbabel 3.0

                if (_AtomicNum == 6) //碳原子
                {
                    n_C++;

                    switch (_hyb)
                    {
                    case 1:
                        n_C1++;
                        break;

                    case 2:
                        n_C2++;
                        break;

                    default:
                        break;
                    }

                    if (_HeteroValence >= 4)
                    {
                        n_CHB4++;
                    }

                    if (_HeteroValence >= 3)
                    {
                        n_CHB3p++;
                    }

                    if (_HeteroValence >= 2)
                    {
                        n_CHB2p++;
                    }

                    if (_HeteroValence >= 1)
                    {
                        n_CHB1p++;
                    }
                }
                else if (_AtomicNum == 8)
                {
                    n_O++;
                    switch (_hyb)
                    {
                    case 2:
                        n_O2++;
                        break;

                    case 3:
                        n_O3++;
                        break;

                    default:
                        break;
                    }
                }
                else if (_AtomicNum == 7)
                {
                    n_N++;
                    switch (_hyb)
                    {
                    case 1:
                        n_N1++;
                        break;

                    case 2:
                        n_N2++;
                        break;

                    case 3:
                        n_N3++;
                        break;

                    default:
                        break;
                    }
                }
                else if (_AtomicNum == 16)
                {
                    n_S++;
                }
                else if (_AtomicNum == 34 || _AtomicNum == 52)
                {
                    n_SeTe++;
                }
                else if (_AtomicNum == 9)
                {
                    n_F++;
                }
                else if (_AtomicNum == 17)
                {
                    n_Cl++;
                }
                else if (_AtomicNum == 35)
                {
                    n_Br++;
                }
                else if (_AtomicNum == 53)
                {
                    n_I++;
                }
                else if (_AtomicNum == 15)
                {
                    n_P++;
                }
                else if (_AtomicNum == 5)
                {
                    n_B++;
                }
                else if ((_AtomicNum >= 3 && _AtomicNum <= 4) || (_AtomicNum >= 11 && _AtomicNum <= 13) || (_AtomicNum >= 19 && _AtomicNum <= 32) || (_AtomicNum >= 37 && _AtomicNum <= 51) || (_AtomicNum >= 55 && _AtomicNum <= 84) || (_AtomicNum >= 87))
                {
                    n_Met++;
                }
            }

            n_X = (int)_numHvyAtoms - n_B - n_C - n_Met - n_N - n_O - n_P - n_S - n_SeTe;

            /* 统计化学键 */

            uint _numBonds = mol.NumBonds(); //所有化学键的总数

            int n_b1     = 0;                // number of single bonds 单键的个数
            int n_b1_NoH = 0;                // number of none C-H single bonds 不含氢的单键个数
            int n_b2     = 0;                // number of double bonds 双键的个数
            int n_b3     = 0;                // number of triple bonds 三键的个数
            int n_bar    = 0;                // number of aromatic bonds 芳香键的个数
            int n_C1O    = 0;                // number of C-O single bonds 碳-氧单键的个数
            int n_C2O    = 0;                // number of C=O double bonds 碳=氧双键的个数
            int n_CN     = 0;                // number of C/N bonds (any type) 任何类型的碳氮键的个数
            int n_XY     = 0;                // number of heteroatom/heteroatom bonds (any type) 任何类型的杂原子之间化学健的个数

            for (int i = 0; i < _numBonds; i++)
            {
                OBBond _bond = mol.GetBond(i);

                OBAtom _beginAtom = _bond.GetBeginAtom();
                OBAtom _endAtom   = _bond.GetEndAtom();

                uint _beginAtomAtomicNum = _beginAtom.GetAtomicNum();
                uint _endAtomAtomicNum   = _endAtom.GetAtomicNum();

                if (_bond.IsSingle())  //Replace IsSingle() method in Openbabel 3.0
                {
                    n_b1++;
                    if (_beginAtomAtomicNum != 1 && _endAtomAtomicNum != 1)
                    {
                        n_b1_NoH++;
                    }
                }
                else if (_bond.IsDouble())  // Replace IsDouble() method in Openbabel 3.0
                {
                    n_b2++;
                }
                else if (_bond.IsTriple())  // Replace IsTriple() method in Openbabel 3.0
                {
                    n_b3++;
                }
                else if (_bond.IsAromatic())
                {
                    n_bar++;
                }

                if ((_beginAtomAtomicNum == 6 && _endAtomAtomicNum == 8) || (_beginAtomAtomicNum == 8 && _endAtomAtomicNum == 6))
                {
                    uint _bondOrder = _bond.GetBondOrder();

                    if (_bondOrder == 1)
                    {
                        n_C1O++;
                    }
                    else if (_bondOrder == 2)
                    {
                        n_C2O++;
                    }
                }
                else if ((_beginAtomAtomicNum == 6 && _endAtomAtomicNum == 7) || (_beginAtomAtomicNum == 7 && _endAtomAtomicNum == 6))
                {
                    n_CN++;
                }
                else if (_beginAtomAtomicNum != 6 && _endAtomAtomicNum != 6)
                {
                    n_XY++;
                }
            }

            /* 统计环 */
            #region 统计环

            VectorpRing _SSSR = mol.GetSSSR();

            int n_r3   = 0; // number of 3-membered rings 3元环个数
            int n_r4   = 0; // number of 4-membered rings 4元环个数
            int n_r5   = 0; // number of 5-membered rings 5元环个数
            int n_r6   = 0; // number of 6-membered rings 6元环个数
            int n_r7   = 0; // number of 7-membered rings 7元环个数
            int n_r8   = 0; // number of 8-membered rings 8元环个数
            int n_r9   = 0; // number of 9-membered rings 9元环个数
            int n_r10  = 0; // number of 10-membered rings 10元环个数
            int n_r11  = 0; // number of 11-membered rings 11元环个数
            int n_r12  = 0; // number of 12-membered rings 12元环个数
            int n_r13p = 0; // number of 13-membered or larger rings 13元环或者更大的环的个数
            int n_rN   = 0; // number of rings containing nitrogen (any number) 含氮环的个数
            int n_rN1  = 0; // number of rings containing 1 nitrogen atom 含一个氮原子的环的个数
            int n_rN2  = 0; // number of rings containing 2 nitrogen atoms 含两个个氮原子的环的个数
            int n_rN3p = 0; // number of rings containing 3 or more nitrogen atoms 含三个或以上个氮原子的环的个数
            int n_rO   = 0; // number of rings containing oxygen (any number) 含氧环的个数
            int n_rO1  = 0; // number of rings containing 1 oxygen atom 含一个氧原子的环的个数
            int n_rO2p = 0; // number of rings containing 2 or more oxygen atoms 含三个或以上个氧原子的环的个数
            int n_rS   = 0; // number of rings containing sulfur (any number) 含硫环的个数
            int n_rX   = 0; // number of heterocycles (any type) 杂环的个数
            int n_rar  = 0; // number of aromatic rings (any type) 芳香环的个数

            if (_SSSR.Count != 0 || _SSSR != null)
            {
                foreach (OBRing _ring in _SSSR)
                {
                    uint _ringSize = _ring.Size();

                    if (_ringSize == 3)
                    {
                        n_r3++;
                    }
                    else if (_ringSize == 4)
                    {
                        n_r4++;
                    }
                    else if (_ringSize == 5)
                    {
                        n_r5++;
                    }
                    else if (_ringSize == 6)
                    {
                        n_r6++;
                    }
                    else if (_ringSize == 7)
                    {
                        n_r7++;
                    }
                    else if (_ringSize == 8)
                    {
                        n_r8++;
                    }
                    else if (_ringSize == 9)
                    {
                        n_r9++;
                    }
                    else if (_ringSize == 10)
                    {
                        n_r10++;
                    }
                    else if (_ringSize == 11)
                    {
                        n_r11++;
                    }
                    else if (_ringSize == 12)
                    {
                        n_r12++;
                    }
                    else if (_ringSize >= 13)
                    {
                        n_r13p++;
                    }

                    if (_ring.IsAromatic())
                    {
                        n_rar++;
                    }

                    VectorInt _pathes = _ring._path;

                    int _ct_N = 0;
                    int _ct_O = 0;
                    int _ct_S = 0;

                    bool _isRingX = false;
                    foreach (int _p in _pathes)
                    {
                        OBAtom _atom = mol.GetAtom(_p);

                        uint _AtomicNum = _atom.GetAtomicNum();

                        if (_AtomicNum == 7) //N原子
                        {
                            _ct_N++;
                        }
                        else if (_AtomicNum == 8) //O原子
                        {
                            _ct_O++;
                        }
                        else if (_AtomicNum == 16) //S原子
                        {
                            _ct_S++;
                        }

                        if (_AtomicNum != 6)
                        {
                            _isRingX = true;
                        }
                    }

                    if (_ct_N == 1)
                    {
                        n_rN1++;
                    }
                    else if (_ct_N == 2)
                    {
                        n_rN2++;
                    }
                    else if (_ct_N >= 3)
                    {
                        n_rN3p++;
                    }

                    n_rN = n_rN1 + n_rN2 + n_rN3p;

                    if (_ct_O == 1)
                    {
                        n_rO1++;
                    }
                    else if (_ct_O >= 2)
                    {
                        n_rO2p++;
                    }

                    n_rO = n_rO1 + n_rO2p;

                    if (_ct_S >= 1)
                    {
                        n_rS++;
                    }

                    if (_isRingX)
                    {
                        n_rX++;
                    }
                }
            }

            #endregion

            // 统计数字映射成MolStat对象
            MolStat stat = new MolStat
            {
                // General info
                AtomsCount      = (int)_numAtoms,
                HeavyAtomsCount = (int)_numHvyAtoms,
                TotalCharge     = _totalCharge,
                // Atoms info
                N_B     = n_B,
                N_Br    = n_Br,
                N_C     = n_C,
                N_C1    = n_C1,
                N_C2    = n_C2,
                N_CHB1p = n_CHB1p,
                N_CHB2p = n_CHB2p,
                N_CHB3p = n_CHB3p,
                N_CHB4  = n_CHB4,
                N_Cl    = n_Cl,
                N_F     = n_F,
                N_I     = n_I,
                N_Met   = n_Met,
                N_N     = n_N,
                N_N1    = n_N1,
                N_N2    = n_N2,
                N_N3    = n_N3,
                N_O     = n_O,
                N_O2    = n_O2,
                N_O3    = n_O3,
                N_P     = n_P,
                N_S     = n_S,
                N_SeTe  = n_SeTe,
                N_X     = n_X,
                // Bonds info
                BondsCount = (int)_numBonds,
                N_b1       = n_b1,
                N_b1_NoH   = n_b1_NoH,
                N_b2       = n_b2,
                N_b3       = n_b3,
                N_bar      = n_bar,
                N_C1O      = n_C1O,
                N_C2O      = n_C2O,
                N_CN       = n_CN,
                N_XY       = n_XY,
                // Rings info
                RingsCount = _SSSR.Count,
                N_r10      = n_r10,
                N_r11      = n_r11,
                N_r12      = n_r12,
                N_r13p     = n_r13p,
                N_r3       = n_r3,
                N_r4       = n_r4,
                N_r5       = n_r5,
                N_r6       = n_r6,
                N_r7       = n_r7,
                N_r8       = n_r8,
                N_r9       = n_r9,
                N_rar      = n_rar,
                N_rN       = n_rN,
                N_rN1      = n_rN1,
                N_rN2      = n_rN2,
                N_rN3p     = n_rN3p,
                N_rO       = n_rO,
                N_rO1      = n_rO1,
                N_rO2p     = n_rO2p,
                N_rS       = n_rS,
                N_rX       = n_rX
            };

            return(stat);
        }
Пример #30
0
 public static Number SimpleDistance(VectorInt a, VectorInt b)
 {
     return(Math.Abs(a.x - b.x) + Math.Abs(a.y - b.y));
 }
Пример #31
0
        public static RectInt GetExtractRectangle(VectorInt imageSize, bool isSquare)
        {
            Random rand = StaticRandom.GetRandomForThread();

            // Min Size
            int minSize = Math.Min(imageSize.X, imageSize.Y);
            double extractSizeMin, extractSizeMax;

            extractSizeMin = minSize * MINPERCENT;
            extractSizeMax = minSize * MAXPERCENT;

            // Width
            int width = rand.NextDouble(extractSizeMin, extractSizeMax).ToInt_Round();
            int height;

            // Height
            if (isSquare)
            {
                height = width;
            }
            else
            {
                height = rand.NextDouble(extractSizeMin, extractSizeMax).ToInt_Round();

                double ratio = width.ToDouble() / height.ToDouble();

                if (ratio > Math1D.GOLDENRATIO)
                {
                    width = (height * Math1D.GOLDENRATIO).ToInt_Round();
                }
                else
                {
                    ratio = height.ToDouble() / width.ToDouble();

                    if (ratio > Math1D.GOLDENRATIO)
                    {
                        height = (width * Math1D.GOLDENRATIO).ToInt_Round();
                    }
                }
            }

            // Rectangle
            return new RectInt()
            {
                X = rand.Next(imageSize.X - width),
                Y = rand.Next(imageSize.Y - height),
                Width = width,
                Height = height,
            };
        }
Пример #32
0
        public override VectorInt GetReduction()
        {
            VectorInt retVal = new VectorInt();

            if (!this.ExpandBorder)
            {
                retVal.X = (this.Width - 1) * this.Iterations;
                retVal.Y = (this.Height - 1) * this.Iterations;
            }

            return retVal;
        }
Пример #33
0
 public static bool IsTooSmall(VectorInt size, bool allow1x1 = false)
 {
     return IsTooSmall(size.X, size.Y, allow1x1);
 }
Пример #34
0
 public abstract void OnBreak(VectorInt location, byte blockState, IBlockEntity?blockEntity, World world);
Пример #35
0
        public override VectorInt GetReduction()
        {
            VectorInt retVal = new VectorInt(0, 0);

            if (this.OperationType == SetOperationType.MaxOf)
            {
                foreach (ConvolutionBase2D child in this.Convolutions)
                {
                    var childReduce = child.GetReduction();

                    if (childReduce.X > retVal.X)
                        retVal.X = childReduce.X;

                    if (childReduce.Y > retVal.Y)
                        retVal.Y = childReduce.Y;
                }
            }
            else
            {
                foreach (ConvolutionBase2D child in this.Convolutions)
                {
                    var childReduce = child.GetReduction();

                    retVal.X += childReduce.X;
                    retVal.Y += childReduce.Y;
                }
            }

            return retVal;
        }
Пример #36
0
 /// <summary>
 /// 判断点是否在房间内
 /// </summary>
 /// <param name="point"></param>
 /// <returns></returns>
 public bool IsPointIn(VectorInt point)
 {
     return(bounds.IsPointInBounds(point));
 }
Пример #37
0
 public double this[VectorInt pos]
 {
     get
     {
         return this.Values[(pos.Y * this.Width) + pos.X];
     }
     set
     {
         this.Values[(pos.Y * this.Width) + pos.X] = value;
     }
 }
Пример #38
0
 public short Generate(VectorInt position) => Generate(position.X, position.Y);
Пример #39
0
        public static Convolution2D ExtendBorders(Convolution2D conv, int width, int height)
        {
            if (width < conv.Width || height < conv.Height)
            {
                throw new ArgumentException(string.Format("The new size can't be smaller than old.  Old={0},{1}  --  New={2},{3}", conv.Width, conv.Height, width, height));
            }

            VectorInt offset = new VectorInt()
            {
                X = (width - conv.Width) / 2,
                Y = (height - conv.Height) / 2,
            };

            double[] values = new double[width * height];

            #region Copy the image

            for (int y = 0; y < conv.Height; y++)
            {
                int offsetOrigY = y * conv.Width;
                int offsetNewY = (y + offset.Y) * width;

                for (int x = 0; x < conv.Width; x++)
                {
                    values[offsetNewY + offset.X + x] = conv.Values[offsetOrigY + x];
                }
            }

            #endregion

            #region Edges

            bool hasNegX = offset.X > 0;
            AxisFor forNegX = new AxisFor(Axis.X, offset.X - 1, 0);
            if (hasNegX)
            {
                ExtendEdge(values, width, conv.Width, forNegX, new AxisFor(Axis.Y, offset.Y, offset.Y + conv.Height - 1));
            }

            bool hasNegY = offset.Y > 0;
            AxisFor forNegY = new AxisFor(Axis.Y, offset.Y - 1, 0);
            if (hasNegY)
            {
                ExtendEdge(values, width, conv.Height, forNegY, new AxisFor(Axis.X, offset.X, offset.X + conv.Width - 1));
            }

            bool hasPosX = width > offset.X + conv.Width;
            AxisFor forPosX = new AxisFor(Axis.X, offset.X + conv.Width, width - 1);
            if (hasPosX)
            {
                ExtendEdge(values, width, conv.Width, forPosX, new AxisFor(Axis.Y, offset.Y, offset.Y + conv.Height - 1));
            }

            bool hasPosY = height > offset.Y + conv.Height;
            AxisFor forPosY = new AxisFor(Axis.Y, offset.Y + conv.Height, height - 1);
            if (hasPosY)
            {
                ExtendEdge(values, width, conv.Height, forPosY, new AxisFor(Axis.X, offset.X, offset.X + conv.Width - 1));
            }

            #endregion
            #region Corners

            if (hasNegX && hasNegY)
            {
                ExtendCorner(values, width, forNegX, forNegY);
            }

            if (hasPosX && hasNegY)
            {
                ExtendCorner(values, width, forPosX, forNegY);
            }

            if (hasPosX && hasPosY)
            {
                ExtendCorner(values, width, forPosX, forPosY);
            }

            if (hasNegX && hasPosY)
            {
                ExtendCorner(values, width, forNegX, forPosY);
            }

            #endregion

            return new Convolution2D(values, width, height, conv.IsNegPos);
        }
Пример #40
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(VectorInt obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Пример #41
0
 public override void OnBreak(VectorInt location, byte blockState, IBlockEntity?blockEntity, World world)
 {
 }
Пример #42
0
 /// <summary>
 /// 根据位置与尺寸, 构造一个房间, 同时将生成房间的边界信息
 /// </summary>
 /// <param name="position"></param>
 /// <param name="size"></param>
 public Room(VectorInt position, VectorInt size)
 {
     this.position = position;
     this.size     = size;
     bounds        = new FixedBounds2D(position, size);
 }