Example #1
0
 public Vertex(Math.Vector2 position)
 {
     Position = new Vector4(position.X, position.Y, 0f, 1f);
     TexturePosition = default(Vector2);
     BezierCoordinates = default(Vector2);
     Mode = VertexMode.Default;
 }
Example #2
0
 /// <summary>
 /// cut mesh by plane
 /// </summary>
 /// <param name="mesh">mesh to cut</param>
 /// <param name="meshTransform">transformation of the mesh</param>
 /// <param name="plane">cutting plane</param>
 /// <param name="triangulateHoles">flag for triangulation of holes</param>
 /// <param name="crossSectionVertexColor">this color will be assigned to cross section, valid only for vertex color shaders</param>
 /// <param name="crossUV">uv mapping area for cross section</param>
 /// <param name="allowOpenMesh">allow cutting of open mesh</param>
 /// <returns>processing time</returns>
 public float Cut(Mesh mesh, Transform meshTransform, Math.Plane plane, bool triangulateHoles, bool allowOpenMesh, ref List<CutterMesh> meshes,
                  Color crossSectionVertexColor, Vector4 crossUV)
 {
     this.crossSectionVertexColour = crossSectionVertexColor;
     this.crossSectionUV = crossUV;
     return Cut(mesh, meshTransform, plane, triangulateHoles, allowOpenMesh, ref meshes);
 }
Example #3
0
 // Constructors
 public MathProxy()
 {
     // Create Math instance in a different AppDomain
     AppDomain ad = System.AppDomain.CreateDomain("MathDomain", null, null);
     ObjectHandle o = ad.CreateInstance("Proxy_RealWorld", "Math", false,  System.Reflection.BindingFlags.CreateInstance, null, null, null, null, null);
     math = (Math)o.Unwrap();
 }
Example #4
0
        static void Main(string[] args) {
            var handbag = new Product {
                Name = "Saint Laurent Monogram",
                Price = 1290.99m,
            };
            ChangeName(handbag);
            var newPrice = 2459.25m;
            ChangePrice(handbag, ref newPrice);
            handbag.ApplyDiscount(percent: .10m, flat: 100m);

            Console.WriteLine("{0} Price: {1:c}", handbag.Name, handbag.Price);

            //AddNumbers() Assignment
            //Instance is called via math1.AddNumbers()
            var math1 = new Math();
            var sum1 = math1.AddNumbers(5, 5);
            Console.WriteLine("Sum = " + sum1);

            var math2 = new Math();
            var sum2 = math2.AddNumbers(5, 6, 7, 8, 9);
            Console.WriteLine("Sum = " + sum2);

            //Crazy Math Assignment

            //Static method is called via Math.DoSomething()
            Debug.Assert(Math.DoSomething(6, 2) == 3, "Method divides numbers!");
            Debug.Assert(Math.DoSomething(3, 3, 3) == 9, "Method adds numbers!");
            Debug.Assert(Math.DoSomething(2, 2, 2, 2) == 16, "Method multiplies numbers!");

            Console.ReadLine();
        }
Example #5
0
 // Definitely a personal style thing, but I always remove Main's argument if it's unused - not that I've written more than about 10 Main statements in real code.
 // I shan't repeat that comment everywhere, obviously.
 static void Main(string[] args)
 {
     var math = new Math();
     Console.WriteLine(math.Add(3, 4));
     Console.WriteLine(math.Subtract(3, 4));
     Console.WriteLine(math.Multiply(3, 4));
     Console.WriteLine(math.Divide(3, 4));
 }
Example #6
0
 static void Main(string[] args)
 {
     var p1 = new Point(0, 0);
     var p2 = new Point(10, 0);
     var math = new Math();
     Console.WriteLine("Length = {0}", math.Length(p1, p2));
     Console.WriteLine("Middle = {0}", math.Middle(p1,p2));
 }
Example #7
0
 static void Main(string[] args)
 {
     Math mathObj = new Math(3, 4);
     System.Console.WriteLine(mathObj.Add());
     mathObj.setxy(5, 6);
     System.Console.WriteLine(mathObj.Add());
     System.Console.ReadLine();
 }
Example #8
0
 public static async Task FibExample(Math.IMathClient client)
 {
     using (var call = client.Fib(new FibArgs.Builder { Limit = 5 }.Build()))
     {
         List<Num> result = await call.ResponseStream.ToList();
         Console.WriteLine("Fib Result: " + string.Join("|", result));
     }
 }
Example #9
0
        static void Main(string[] args)
        {
            Math myMath = new Math();

            Debug.Assert(myMath.AddInt(3, 2) == 5, "3+2=5");
            Debug.Assert(myMath.AddInt(0, 2) == 2, "0+2=2");
            Debug.Assert(myMath.AddInt(3, 3, 3) == 9, "3+3+3=9");
        }
Example #10
0
 public static void Main(string[] args)
 {
     var math = new Math();
     Console.WriteLine("4.2 + 8.1 = {0}", math.Add(4.2, 8.1));
     Console.WriteLine("1.1 - 0.6 = {0}", math.Subtract(1.1, 0.6));
     Console.WriteLine("8.3 * 2.7 = {0}", math.Multiply(8.3, 2.7));
     Console.WriteLine("9.3 / 3.0 = {0}", math.Divide(9.3, 3.0));
 }
 public Vector3d_applied(Math.Vector3d vct, Math.Vector3d apply_to)
 {
     this.set_x(vct.get_x());
     this.set_y(vct.get_y());
     this.set_z(vct.get_z());
     this.apply_to.set_x(apply_to.get_x());
     this.apply_to.set_y(apply_to.get_y());
     this.apply_to.set_z(0);
 }
Example #12
0
 static void Main()
 {
     Math m = new Math();
     int sum =         m.Add(3,5);
     int difference =  m.Subtract(3,5);
     int product =     m.Multiply(3,5);
     float quotient =  m.Divide(3.0f, 5.0f);
     Console.WriteLine("sum: {0}, difference: {1}, product: {2}, quotient: {3}", sum, difference, product, quotient);
 }
Example #13
0
        static void Main(string[] args)
        {
            var test = new Math();
            Console.WriteLine("Two Operators Supplied 6, 2: {0}", test.DoSomething(6, 2).ToString());
            Console.WriteLine("Three Operators Supplied 3, 3, and 3: {0}", test.DoSomething(3, 3, 3).ToString());
            Console.WriteLine("Four Operators Supplied 2, 2, 2, and 2: {0} ", test.DoSomething(2, 2, 2, 2).ToString());

            Console.ReadLine();
        }
Example #14
0
 /// <summary>
 /// Converts a Rectangle into a Ellipse.
 /// </summary>
 /// <param name="ellipse">The Ellipse.</param>
 /// <returns>Ellipse</returns>
 public static Ellipse ConvertEllipse(Math.Ellipse ellipse)
 {
     var ellipseDx = new Ellipse
     {
         Point = ConvertVector(ellipse.Position),
         RadiusX = ellipse.RadiusX,
         RadiusY = ellipse.RadiusY
     };
     return ellipseDx;
 }
Example #15
0
 static void Main(string[] args)
 {
     int n2;
     int n1;
     Console.WriteLine("Please enter a number and a power:");
     n1 = Int32.Parse(Console.ReadLine());
     n2 = Int32.Parse(Console.ReadLine());
     Math m = new Math();
     Console.WriteLine("The value is {0}", m.pow(n1, n2));
 }
Example #16
0
 //concurrency demo
 static void Con()
 {
     Math m = new Math();
     for (int i = 1; i <= 3; i++)
     {
         ThreadStart ts = new ThreadStart(m.Run);
         Thread t = new Thread(ts);
         t.Start();
     }
 }
 public Vector3d_applied(Math.Vector3d vct)
 {
     this.set_x(vct.get_x());
     this.set_y(vct.get_y());
     this.set_z(vct.get_z());
     this.apply_to = new Math.Vector3d();
     this.apply_to.set_x(0);
     this.apply_to.set_y(0);
     this.apply_to.set_z(0);
 }
Example #18
0
        static void Main(string[] args)
        {
            var inst = new Math();

            Console.WriteLine("{0} / {1} = {2}", 6,2, inst.DoSomething(6,2));
            
            Console.WriteLine("{0} + {1} + {2} = {3}", 3,3,3, inst.DoSomething(3,3,3));
            
            Console.WriteLine("{0} * {1} * {2} * {3} = {4}", 2, 2, 2, 2, inst.DoSomething(2, 2, 2, 2));
            Console.ReadLine();
        }
Example #19
0
        /// <summary>
        /// Converts the Rectangle.
        /// </summary>
        /// <param name="ellipse">The Ellipse.</param>
        /// <returns>Ellipse.</returns>
        public static Ellipse ConvertEllipse(Math.Ellipse ellipse)
        {
            var ellipseX = new Ellipse
            {
                Center = ConvertPointF(ellipse.Position),
                RadiusX = ellipse.RadiusX,
                RadiusY = ellipse.RadiusY
            };

            return ellipseX;
        }
Example #20
0
        static void Main(string[] args)
        {
            Math math = new Math();
            int a = 100;
            int b = 50;
            Console.WriteLine("Add: " + math.Add(a, b));
            Console.WriteLine("Sub: " + math.Sub(a, b));

            Roman r = new Roman(); // test
            r.Crazy();
            r.Say("test");
        }
        static void Main(string[] args)
        {
            Math m = new Math(3);
            Thread t1 = new Thread(new ThreadStart(m.Double));
            Thread t2 = new Thread(new ThreadStart(m.Square));
            Thread t3 = new Thread(new ThreadStart(m.Cube));

            t1.Start();
            t2.Start();
            t3.Start();

            Console.ReadKey();
        }
Example #22
0
 public static async Task DivManyExample(Math.IMathClient client)
 {
     var divArgsList = new List<DivArgs>
     {
         new DivArgs.Builder { Dividend = 10, Divisor = 3 }.Build(),
         new DivArgs.Builder { Dividend = 100, Divisor = 21 }.Build(),
         new DivArgs.Builder { Dividend = 7, Divisor = 2 }.Build()
     };
     using (var call = client.DivMany())
     { 
         await call.RequestStream.WriteAll(divArgsList);
         Console.WriteLine("DivMany Result: " + string.Join("|", await call.ResponseStream.ToList()));
     }
 }
        public static async Task SumExample(Math.MathClient client)
        {
            var numbers = new List<Num>
            {
                new Num { Num_ = 1 },
                new Num { Num_ = 2 },
                new Num { Num_ = 3 }
            };

            using (var call = client.Sum())
            {
                await call.RequestStream.WriteAllAsync(numbers);
                Console.WriteLine("Sum Result: " + await call.ResponseAsync);
            }
        }
Example #24
0
        public static async Task SumExample(Math.IMathClient client)
        {
            var numbers = new List<Num>
            {
                new Num.Builder { Num_ = 1 }.Build(),
                new Num.Builder { Num_ = 2 }.Build(),
                new Num.Builder { Num_ = 3 }.Build()
            };

            using (var call = client.Sum())
            {
                await call.RequestStream.WriteAll(numbers);
                Console.WriteLine("Sum Result: " + await call.Result);
            }
        }
        static void Main()
        {
            // Try calling some static functions.
            WriteLine($"Pi is {Math.GetPi()}");
            int x = Math.GetSquareOf(5);
            WriteLine($"Square of 5 is {x}");

            // Instantiate a Math object
            var math = new Math();   // instantiate a reference type

            // Call instance members
            math.Value = 30;
            WriteLine($"Value field of math variable contains {math.Value}");
            WriteLine($"Square of 30 is {math.GetSquare()}");

        }
Example #26
0
        static void Main(string[] args)
        {
            //Instantiate an instance of the Math class (makes an object)
            Math m = new Math();

            int result1 = m.DoSomething(6, 2);
            Debug.Assert(result1 == 3, "Result is 3 (division)");

            int result2 = m.DoSomething(3, 3, 3);
            Debug.Assert(result2 == 9, "Result is 9 (addition)");

            int result3 = m.DoSomething(2, 2, 2, 2);
            Debug.Assert(result3 == 16, "Result is 16 (multiplication");

            //pause
            Console.ReadLine();
        }
Example #27
0
        static void Main(string[] args)
        {
            //var milk = new Product()
            //{
            //    Name = "Milk",
            //    Price = 1.5m
            //};
            //milk.ApplyDiscount(percent: .03m, flat: .20m);

            //Console.WriteLine("{0} Price: {1:c}", milk.Name, milk.Price);
            //Console.ReadLine();

            var inst = new Math();

            Console.WriteLine("{0} + {1} - {2}" , 5, 7, inst.AddNumbers(5, 7));
            Console.ReadLine();

        }
Example #28
0
        static void Main(string[] args)
        {
            //Math
            Math math = new Math();

            int result1 = math.AddNumbers(3, 2);
            int result2 = math.AddNumbers(0, 2);
            int result3 = math.AddNumbers(1, 5, 2, 13, 7);

            Debug.Assert(result1 == 5, "You don't know math!");
            Debug.Assert(result2 == 2);

            //Customers
            Customer sally = new Customer(23);
            sally.Age = 23;
            sally.FirstName = "Sally";
            sally.LastName = "Williams";
            sally.BirthDate = new DateTime(2015, 6, 25);

            //Loop through an objects properties without knowing what they are
            var props = sally.GetType().GetProperties();

            for (int i = 0; i < props.Length; i++)
            {
                var p = props[i];
                Console.WriteLine("Property: {0}, Value {1}", p.Name, p.GetValue(sally));
            }

            //Property initializer syntax
            Customer mike = new Customer(10)
            {
                Age = 10,
                BirthDate = DateTime.Parse("2015-06-23"),
                FirstName = "Mike",
                LastName = "Williams"
            };

            Debug.Assert(sally.Age == 23, "Sally is 23");
            Debug.Assert(mike.Age == 10, "Mike is 10");

            Console.ReadLine();
        }
Example #29
0
        public int codeurRequest(ref Math.coordonnees robot1)
        {
            int retour, nbDataRecu = 0;
            byte[] dataRecu = new byte[8];

            retour = m_gestionCan.envoyer((uint)IDcommande.WGetCodeur);

            if (retour == 1)
            {
                retour = m_gestionCan.isDone(2000, dataRecu, nbDataRecu);

                if (retour == 1)
                {
                    robot1.x = ((dataRecu[1] << 8) + dataRecu[0]);
                    robot1.y = ((dataRecu[4] << 8) + dataRecu[3]);
                }
            }

            return retour;
        }
Example #30
0
        static void Main(string[] args)
        {
            Math x = new Math();

            int result1 = x.DoSomething(3, 3, 3, 3, 3);
            Debug.Assert(result1 == 15, "Result is 15");

            int result2 = x.DoSomething(5, 2, 1);
            Debug.Assert(result2 == 2, "Result is 2");

            int result3 = x.DoSomething(3, 5, 1, 2);
            Debug.Assert(result3 == 30, "Result is 30");

            int result4 = x.DoSomething(49, 7);
            Debug.Assert(result4 == 7, "Result is 7");

            int result5 = x.DoSomething(181, 9);
            Debug.Assert(result5 == 9, "Result is 9");


            Console.ReadLine();
        }
Example #31
0
        /// <summary>
        /// Name:pictureBox1_Click
        /// Description: a place for all the functionalities of the picture box
        /// </summary>
        /// <param name="sender">object sender</param>
        /// <param name="e">event arugment</param>
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            MouseEventArgs clicks        = e as MouseEventArgs;
            Point          point         = new Point(clicks.X, clicks.Y);
            Planets        createdPlanet = new Planets(point);
            Bitmap         bitmap        = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            Graphics       planet        = Graphics.FromImage(bitmap);
            Graphics       circle        = Graphics.FromImage(bitmap);

            if (createButton.Checked)
            {
                COG    gravity = new COG();
                double dist    = 100000.00;
                bool   val     = false;

                foreach (COG grav in this.cog)
                {
                    var determinedDistance = Math.Sqrt(Math.Pow(point.X - grav.Location.X, 2) + Math.Pow(point.Y - grav.Location.Y, 2));
                    var distances          = Math.Abs(determinedDistance);

                    if (grav.Radius + 1 > distances)
                    {
                        val = true;
                        if (!(dist < distances))
                        {
                            dist             = distances;
                            gravity.Location = grav.Location;
                            gravity.Radius   = grav.Radius;
                        }
                    }
                }

                if (val != true)
                {
                    MessageBox.Show("Place planet in a center of gravity zone");
                }
                else
                {
                    createdPlanet.evaluateCOG(gravity);
                    this.planets.Add(createdPlanet);

                    foreach (Planets plan in this.planets)
                    {
                        planet.FillEllipse(new SolidBrush(Color.Red), plan.PlanetLocation.X - 5, plan.PlanetLocation.Y - 5, 15, 15);

                        foreach (COG center in this.cog)
                        {
                            planet.FillEllipse(new SolidBrush(Color.LightGray), center.Location.X - center.Radius, center.Location.Y - center.Radius, center.Radius * 2, center.Radius * 2);
                            planet.FillEllipse(new SolidBrush(Color.Black), center.Location.X, center.Location.Y, 5, 5);
                        }
                    }

                    pictureBox1.Image = bitmap;
                }
            }
            else if (CenterButton.Checked)
            {
                COG newGravity = new COG(point, (int)numericUpDown1.Value);
                this.cog.Add(newGravity);

                foreach (Planets pt in this.planets)
                {
                    circle.FillEllipse(new SolidBrush(Color.Red), pt.PlanetLocation.X, pt.PlanetLocation.Y, 15, 15);

                    foreach (COG center in this.cog)
                    {
                        circle.FillEllipse(new SolidBrush(Color.Black), center.Location.X - 3, center.Location.Y - 3, 5, 5);
                        circle.FillEllipse(new SolidBrush(Color.LightGray), center.Location.X - center.Radius, center.Location.Y - center.Radius, center.Radius * 2, center.Radius * 2);
                    }
                }

                pictureBox1.Image = bitmap;
            }
            else if (CenterButton.Checked == false && createButton.Checked == false)
            {
                MessageBox.Show("Select an option: create a center of gravity or create a planet.");
            }
            else
            {
                MessageBox.Show("Error!!!");
            }
        }
Example #32
0
        public void createEllipsoidVertices(float _positionX = 0.4f,
                                            float _positionY = 0.4f,
                                            float _positionZ = 0.4f,
                                            float _radius    = 0.3f)
        {
            this._positionX = _positionX;
            this._positionY = _positionY;
            this._positionZ = _positionZ;
            this._radius    = _radius;

            Vector3 temp_vector;
            float   _pi = (float)Math.PI;


            for (float v = -_pi / 2; v <= _pi / 2; v += 0.01f)
            {
                for (float u = -_pi; u <= _pi; u += (_pi / 30))
                {
                    temp_vector.X = _positionX + _radius * (float)Math.Cos(v) * (float)Math.Cos(u);
                    temp_vector.Y = _positionY + _radius * (float)Math.Cos(v) * (float)Math.Sin(u);
                    temp_vector.Z = _positionZ + _radius * (float)Math.Sin(v);
                    vertices.Add(temp_vector);
                }
            }
        }
Example #33
0
 public override void AI()
 {
     projectile.localAI[0] += 1f;
     if (projectile.localAI[0] > 4f)
     {
         int num3;
         for (int num93 = 0; num93 < 5; num93 = num3 + 1)
         {
             float num94 = projectile.velocity.X / 3f * (float)num93;
             float num95 = projectile.velocity.Y / 3f * (float)num93;
             int   num96 = 4;
             int   num97 = Dust.NewDust(new Vector2(projectile.position.X + (float)num96, projectile.position.Y + (float)num96), projectile.width - num96 * 2, projectile.height - num96 * 2, 172, 0f, 0f, 100, new Color(250, 250, 250, 150), 1.6f);
             Main.dust[num97].noGravity = true;
             Dust dust3 = Main.dust[num97];
             dust3.velocity *= 0.1f;
             dust3           = Main.dust[num97];
             dust3.velocity += projectile.velocity * 0.05f;
             Dust dust6 = Main.dust[num97];
             dust6.position.X = dust6.position.X - num94;
             Dust dust7 = Main.dust[num97];
             dust7.position.Y = dust7.position.Y - num95;
             num3             = num93;
         }
         if (Main.rand.Next(5) == 0)
         {
             int  num98 = 4;
             int  num99 = Dust.NewDust(new Vector2(projectile.position.X + (float)num98, projectile.position.Y + (float)num98), projectile.width - num98 * 2, projectile.height - num98 * 2, 172, 0f, 0f, 100, new Color(150, 150, 150, 150), 1f);
             Dust dust3 = Main.dust[num99];
             dust3.velocity *= 0.25f;
             dust3           = Main.dust[num99];
             dust3.velocity += projectile.velocity * 0.01f;
         }
     }
     if (projectile.localAI[0] > 20f)
     {
         float num477 = projectile.Center.X;
         float num478 = projectile.Center.Y;
         float num479 = 400f;
         bool  flag17 = false;
         int   num3;
         for (int num480 = 0; num480 < 200; num480 = num3 + 1)
         {
             if (Main.npc[num480].CanBeChasedBy(projectile, false) && Collision.CanHit(projectile.Center, 1, 1, Main.npc[num480].Center, 1, 1))
             {
                 float num481 = Main.npc[num480].position.X + (float)(Main.npc[num480].width / 2);
                 float num482 = Main.npc[num480].position.Y + (float)(Main.npc[num480].height / 2);
                 float num483 = Math.Abs(projectile.position.X + (float)(projectile.width / 2) - num481) + Math.Abs(projectile.position.Y + (float)(projectile.height / 2) - num482);
                 if (num483 < num479)
                 {
                     num479 = num483;
                     num477 = num481;
                     num478 = num482;
                     flag17 = true;
                 }
             }
             num3 = num480;
         }
         if (flag17)
         {
             float num488 = 6f;
             num488 = 6f;
             Vector2 vector38 = new Vector2(projectile.position.X + (float)projectile.width * 0.5f, projectile.position.Y + (float)projectile.height * 0.5f);
             float   num489   = num477 - vector38.X;
             float   num490   = num478 - vector38.Y;
             //Pythagoram Theorum
             float num491 = (float)Math.Sqrt((double)(num489 * num489 + num490 * num490));
             num491  = num488 / num491;
             num489 *= num491;
             num490 *= num491;
             projectile.velocity.X = (projectile.velocity.X * 20f + num489) / 21f;
             projectile.velocity.Y = (projectile.velocity.Y * 20f + num490) / 21f;
             return;
         }
     }
 }
Example #34
0
 public bool checkPyth(double a, double b, double c) 
 {
     if (Math.Pow(a, 2) + Math.Pow(b, 2) == Math.Pow(c, 2))
         return true;
     return false;
 }
Example #35
0
 // Gets X angle in radians from a quaternion
 private static float PitchFromQuat(Quaternion q)
 {
     //return (float)Math.Atan((2f * (q.Y * q.Z + q.W * q.X)) / (q.W * q.W - q.X * q.X - q.Y * q.Y + q.Z * q.Z));
     //return (float)Math.Atan2(-2f * (q.Y * q.Z - q.W * q.X), q.W * q.W - q.X * q.X - q.Y * q.Y + q.Z * q.Z);
     return (float)Math.Atan2(2f * (q.W * q.X + q.Y * q.Z), 1 - (2 * (Math.Pow(q.X, 2) + Math.Pow(q.Y, 2))));
 }
Example #36
0
        // Ignore, doesn't work. Bad.
        private static Vector3 EulerAnglesFromQuat(Quaternion q)
        {
            float singularityTest = q.Z * q.X - q.W * q.Y;
            float yawY = 2f * (q.W * q.Z + q.X * q.Y);
            float yawX = (float)(1f - 2f * (Math.Pow(q.Y, 2) + Math.Pow(q.Z, 2)));
            float singularityThreshold = 0.4999995f;

            Vector3 eulerAngles = Vector3.Zero;

            if(singularityTest < singularityThreshold)
            {
                eulerAngles.X = -90f;
                eulerAngles.Y = (float)Math.Atan2(yawY, yawX);
                eulerAngles.Z = WMath.Clamp(-eulerAngles.Y - (2f * (float)Math.Atan2(q.X, q.W)), (float)-Math.PI, (float)Math.PI);
            }
            else if(singularityTest > singularityThreshold)
            {
                eulerAngles.X = 90;
                eulerAngles.Y = (float)Math.Atan2(yawY, yawX);
                eulerAngles.Z = WMath.Clamp(eulerAngles.Y - (2f * (float)Math.Atan2(q.X, q.W)), (float)-Math.PI, (float)Math.PI);
            }
            else
            {
                eulerAngles.X = (float)Math.Asin(2f * (singularityTest));
                eulerAngles.Y = (float)Math.Atan2(yawY, yawX);
                eulerAngles.Z = (float)Math.Atan2(-2f * (q.W * q.X + q.Y * q.Z), (1f - 2f * (Math.Pow(q.X, 2) + Math.Pow(q.Y, 2))));
            }

            return eulerAngles;
        }
Example #37
0
 /// <exclude/>
 protected internal override int MeasureHeight()
 {
     return(Math.Max(ImageGapBottom +
                     ImageGapTop + ImageHeight,
                     Font.Height) + TabGapTop);
 }
Example #38
0
        /// <summary>
        /// Method for crossover (uniform crossover)
        /// </summary>
        private void crossover(ORF orf, double minimalNc, double maximalNc)
        {
            // temporary variables
            // first parent and second parent indexes
            int FirstParentIdx, SecondParentIdx;
            // new individuals
            List <string> FirstNewIndividual, SecondNewIndividual;

            // crossover mask
            List <int> CrossoverMask;
            int        CrossoverMaskSize = Population[0].Count();

            //clearing new population and scores
            NewPopulation.Clear();
            NewPopulationScores.Clear();
            int  end;
            bool allowed;

            if (Math.Round(PopulationSize * CrossoverProbability) % 2 != 0)
            {
                end = PopulationSize - (int)Math.Round(PopulationSize * CrossoverProbability) + 1;
            }
            else
            {
                end = PopulationSize - (int)Math.Round(PopulationSize * CrossoverProbability);
            }

            for (int i = 0; i < end; i++)
            {
                FirstParentIdx = rnd.Next(0, Population.Count());

                //Restricion enzymes sites removal
                if (RestrEnzymeSitesToRemoval == true)
                {
                    allowed = false;

                    while (allowed == false)
                    {
                        allowed = enzymeSitesRemove(Population[FirstParentIdx], allowed, i);
                    }
                }

                //Homopolymers removal
                if (AHomopolymersRemoval == true)
                {
                    HomopolymersRemove(Population[FirstParentIdx]);

                    allowed = false;

                    //Restricion enzymes sites removal
                    if (RestrEnzymeSitesToRemoval == true)
                    {
                        allowed = false;

                        while (allowed == false)
                        {
                            allowed = enzymeSitesRemove(Population[FirstParentIdx], allowed, i);
                        }
                    }
                }

                NewPopulation.Add(Population[FirstParentIdx]);
                NewPopulationScores.Add(PopulationScores[FirstParentIdx]);
                Population.RemoveAt(FirstParentIdx);
                PopulationScores.RemoveAt(FirstParentIdx);
            }


            // randomization of parents for cross over
            for (int i = 0; i < (PopulationSize - end) / 2; i++)
            {
                FirstParentIdx  = rnd.Next(0, Population.Count());
                SecondParentIdx = rnd.Next(0, Population.Count());

                // rerandomization if parent index was repeated
                while (FirstParentIdx == SecondParentIdx)
                {
                    SecondParentIdx = rnd.Next(0, Population.Count());
                }

                // new crossover mask initialization
                CrossoverMask = new List <int>();

                for (int x = 0; x < CrossoverMaskSize; x++)
                {
                    CrossoverMask.Add(rnd.Next(0, 2));
                }

                // new individuals initialization
                FirstNewIndividual  = new List <string>();
                SecondNewIndividual = new List <string>();

                // creation of new individuals using the crossover mask
                for (int x = 0; x < CrossoverMaskSize; x++)
                {
                    if (CrossoverMask[x] == 0)
                    {
                        FirstNewIndividual.Add(Population[FirstParentIdx][x]);
                        SecondNewIndividual.Add(Population[SecondParentIdx][x]);
                    }
                    if (CrossoverMask[x] == 1)
                    {
                        FirstNewIndividual.Add(Population[SecondParentIdx][x]);
                        SecondNewIndividual.Add(Population[FirstParentIdx][x]);
                    }
                }

                //Restricion enzymes sites removal
                if (RestrEnzymeSitesToRemoval == true)
                {
                    allowed = false;

                    while (allowed == false)
                    {
                        allowed = enzymeSitesRemove(FirstNewIndividual, allowed, i);
                    }

                    allowed = false;

                    while (allowed == false)
                    {
                        allowed = enzymeSitesRemove(SecondNewIndividual, allowed, i);
                    }
                }

                //Homopolymers removal
                if (AHomopolymersRemoval == true)
                {
                    HomopolymersRemove(FirstNewIndividual);
                    HomopolymersRemove(SecondNewIndividual);

                    allowed = false;

                    //Restricion enzymes sites removal
                    if (RestrEnzymeSitesToRemoval == true)
                    {
                        allowed = false;

                        while (allowed == false)
                        {
                            allowed = enzymeSitesRemove(FirstNewIndividual, allowed, i);
                        }

                        allowed = false;

                        while (allowed == false)
                        {
                            allowed = enzymeSitesRemove(SecondNewIndividual, allowed, i);
                        }
                    }
                }

                if (MaintainOriginalNc == true)
                {
                    // creating new population with new individuals and new scores
                    NewPopulation.Add(FirstNewIndividual);
                    NewPopulation.Add(SecondNewIndividual);

                    if (OptimizationMode == 1)
                    {
                        NewPopulationScores.Add(ORF.MultiScore(FirstNewIndividual, orf.aminoAcidCounts, minimalNc, maximalNc, 1));
                        NewPopulationScores.Add(ORF.MultiScore(SecondNewIndividual, orf.aminoAcidCounts, minimalNc, maximalNc, 1));
                    }

                    if (OptimizationMode == 0)
                    {
                        NewPopulationScores.Add(ORF.MultiScore(FirstNewIndividual, orf.aminoAcidCounts, minimalNc, maximalNc, 0));
                        NewPopulationScores.Add(ORF.MultiScore(SecondNewIndividual, orf.aminoAcidCounts, minimalNc, maximalNc, 0));
                    }

                    // removing "used" parents
                    if (FirstParentIdx > SecondParentIdx)
                    {
                        Population.RemoveAt(FirstParentIdx);
                        Population.RemoveAt(SecondParentIdx);
                    }
                    else
                    {
                        Population.RemoveAt(SecondParentIdx);
                        Population.RemoveAt(FirstParentIdx);
                    }
                }
                else
                {
                    // creating new population with new individuals and new scores
                    NewPopulation.Add(FirstNewIndividual);
                    NewPopulation.Add(SecondNewIndividual);
                    NewPopulationScores.Add(ORF.CPBcalculator(FirstNewIndividual));
                    NewPopulationScores.Add(ORF.CPBcalculator(SecondNewIndividual));

                    // removing "used" parents
                    if (FirstParentIdx > SecondParentIdx)
                    {
                        Population.RemoveAt(FirstParentIdx);
                        Population.RemoveAt(SecondParentIdx);
                    }
                    else
                    {
                        Population.RemoveAt(SecondParentIdx);
                        Population.RemoveAt(FirstParentIdx);
                    }
                }
            }

            PopulationScores.Clear();

            for (int j = 0; j < NewPopulation.Count(); j++)
            {
                Population.Add(NewPopulation[j]);
                PopulationScores.Add(NewPopulationScores[j]);
            }

            // updating best individual
            updateBestIndividual();
        }
Example #39
0
        /// <summary>
        /// ORF optimization
        /// </summary>
        /// <param name="ORFSeq"></param>
        /// <param name="AminoORFseq"></param>
        /// <param name="optimizationMode"></param>
        /// <returns></returns>
        public List <string> optimizeORF(ORF orf, object o, DoWorkEventArgs e)
        {
            int    stopCounter = 0;
            double lastScore   = 0;
            bool   allowed;

            // new population and new scores initialization
            NewPopulation       = new List <List <string> >();
            NewPopulationScores = new List <double>();

            minimalNc = MinimalNc;
            maximalNc = MaximalNc;

            // preparation
            // codons grouping to dictionary
            codonGroups = new Dictionary <string, List <string> >();
            codonGroups = SeqParser.codonToAmino.GroupBy(x => x.Value)
                          .ToDictionary(x => x.Key, x => x.Select(i => i.Key).ToList());

            //calculation of minimal and maximal Nc
            if (MaintainOriginalNc == true)
            {
                minimalNc = ORF.NcCalculator(orf.orfSeq, orf.aminoAcidCounts) - minimalNc;
                maximalNc = ORF.NcCalculator(orf.orfSeq, orf.aminoAcidCounts) + maximalNc;
            }

            //Homopolymers counting
            if (AHomopolymersRemoval == true)
            {
                lysineIdx = HomopolymersCheck(orf.aminoORFseq);
            }

            // initial population generation
            generateInitialPopulation(orf);

            //Restriction enzymes sites removal
            if (RestrEnzymeSitesToRemoval == true)
            {
                allowed = false;
                for (int i = 0; i < PopulationSize; i++)
                {
                    while (allowed == false)
                    {
                        allowed = enzymeSitesRemove(Population[i], allowed, i);
                    }
                }
            }

            //Homopolymers removal
            if (AHomopolymersRemoval == true)
            {
                for (int i = 0; i < PopulationSize; i++)
                {
                    HomopolymersRemove(Population[i]);
                }

                if (RestrEnzymeSitesToRemoval == true)
                {
                    for (int i = 0; i < PopulationSize; i++)
                    {
                        allowed = false;

                        while (allowed == false)
                        {
                            allowed = enzymeSitesRemove(Population[i], allowed, i);
                        }
                    }
                }
            }

            if (AHomopolymersRemoval == true || RestrEnzymeSitesToRemoval == true)
            {
                PopulationScores.Clear();
                for (int i = 0; i < PopulationSize; i++)
                {
                    if (OptimizationMode == 1)
                    {
                        PopulationScores.Add(ORF.MultiScore(orf.orfSeq, orf.aminoAcidCounts, minimalNc, maximalNc, 1));
                    }
                    if (OptimizationMode == 0)
                    {
                        PopulationScores.Add(ORF.MultiScore(orf.orfSeq, orf.aminoAcidCounts, minimalNc, maximalNc, 0));
                    }
                }
            }

            // reproductive cycles
            for (int i = 0; i < ReproductiveCyclesNumber; i++)
            {
                // mutation
                for (int j = 0; j < Math.Round(Population.Count * MutationProbability); j++)
                {
                    // individual randomization
                    int individual = rnd.Next(0, Population.Count());
                    // mutation of given codon
                    mutate(Population[individual], individual, orf);
                }

                if (CrossoverProbability != 0)
                {
                    // selection
                    selectIndividualsForCrossover(TournamentSize);

                    // crossover
                    crossover(orf, minimalNc, maximalNc);

                    if (lastScore != BestScore)
                    {
                        lastScore   = BestScore;
                        stopCounter = 0;
                    }
                    else
                    {
                        stopCounter++;
                    }

                    if (stopCounter == StopCriterion)
                    {
                        i = ReproductiveCyclesNumber - 1;
                    }
                }

                Thread.Sleep(1);
                (o as BackgroundWorker).ReportProgress(100 * i / (ReproductiveCyclesNumber - 1));
            }
            // updating best individual
            updateBestIndividual();

            return(BestIndividual);
        }
 public override sbyte GetValue()
 {
     return(Math.Abs(this.Param0.GetValue()));
 }
Example #41
0
        private static void MoveTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (Sneks)
            {
                foreach (var snek in Sneks)
                {
                    Point nextPosition;
                    if (snek.Fast)
                    {
                        nextPosition =
                            new Point(snek.Parts[0].Position.X + (int)(Math.Cos(snek.Dir * (Math.PI / 180)) * snek.SpeedTwo),
                                snek.Parts[0].Position.Y + (int)(Math.Sin(snek.Dir * (Math.PI / 180)) * snek.SpeedTwo));
                    }
                    else
                    {
                        nextPosition = new Point(snek.Parts[0].Position.X + (int)(Math.Cos(snek.Dir * (Math.PI / 180)) * snek.Speed),
                            snek.Parts[0].Position.Y + (int)(Math.Sin(snek.Dir * (Math.PI / 180)) * snek.Speed));
                    }


                    for (int i = 0; i < snek.Parts.Count - 1; i++)
                    {
                        if (i != snek.Parts.Count - 1)
                        {
                            snek.Parts[snek.Parts.Count - (i + 1)].Position =
                                snek.Parts[snek.Parts.Count - (2 + i)].Position;
                        }
                    }
                    snek.Parts[0].Position = nextPosition;
                    lock (Foods)
                    {
                        if (Foods.Count < 1000)
                        {
                            for (int i = 0; i < 1000 - Foods.Count; i++)
                            {
                                Point foodP = new Point(Rng.Next(0, 2000), Rng.Next(0, 2000));
                                Food food = new Food() { Color = RandomColor(), Position = foodP };
                                Foods.Add(food);
                                //Foods.Add(new Point(rng.Next(0,1000),rng.Next(0,1000)));
                            }
                        }

                        List<Food> toRemove = new List<Food>();
                        foreach (var food in Foods.ToList())
                        {
                            int w = snek.Width;
                            if (snek.Parts[0].Position.X - w <= food.Position.X &&
                                snek.Parts[0].Position.X + w >= food.Position.X &&
                                snek.Parts[0].Position.Y - w < food.Position.Y &&
                                snek.Parts[0].Position.Y + 2 * w > food.Position.Y)
                            {
                                snek.Parts.Add(snek.Parts[snek.Parts.Count - 1]);
                                snek.Parts.Add(snek.Parts[snek.Parts.Count - 1]);
                                snek.Parts.Add(snek.Parts[snek.Parts.Count - 1]);
                                toRemove.Add(food);
                            }
                        }
                        foreach (var food in toRemove)
                        {
                            Foods.Remove(food);
                        }
                    }
                }

            }
        }
Example #42
0
 protected override void UpdateAfterChildren()
 {
     base.UpdateAfterChildren();
     score1Text.X = -Math.Max(5 + score1Text.DrawWidth / 2, score1Bar.DrawWidth);
     score2Text.X = Math.Max(5 + score2Text.DrawWidth / 2, score2Bar.DrawWidth);
 }
Example #43
0
 private PointF Rotate(float x, float y, float angle)
 {
     return(new PointF(x * (float)Math.Cos(angle) + y * (float)Math.Sin(angle), -x * (float)Math.Sin(angle) + y * (float)Math.Cos(angle)));
 }
Example #44
0
        void ReadTimeSyncMessage(ulong remoteID, byte[] msg)
        {
            if (!m_remoteSentTimeCache.ContainsKey(remoteID))
            {
                SendTimeSyncMessage(remoteID);
                return;
            }

            int offset = 1;
            float remoteTime = UnpackFloat(msg, ref offset);
            float now = Time.realtimeSinceStartup;
            float latency = (now - m_remoteSentTimeCache[remoteID]) / 2;
            float remoteTimeOffset = now - (remoteTime + latency);

            m_remoteSyncTimeCache[remoteID].Add(remoteTimeOffset);

            if (m_remoteSyncTimeCache[remoteID].Count < TIME_SYNC_MESSAGE_COUNT)
            {
                SendTimeSyncMessage(remoteID);
            }
            else
            {
                if (PlatformManager.MyID < remoteID)
                {
                    // this client started the sync, need to send one last message to
                    // the remote so they can finish their sync calculation
                    SendTimeSyncMessage(remoteID);
                }

                // sort the times and remember the median
                m_remoteSyncTimeCache[remoteID].Sort();
                float median = m_remoteSyncTimeCache[remoteID][TIME_SYNC_MESSAGE_COUNT / 2];

                // calucate the mean and standard deviation
                double mean = 0;
                foreach (var time in m_remoteSyncTimeCache[remoteID])
                {
                    mean += time;
                }
                mean /= TIME_SYNC_MESSAGE_COUNT;

                double std_dev = 0;
                foreach (var time in m_remoteSyncTimeCache[remoteID])
                {
                    std_dev += (mean - time) * (mean - time);
                }
                std_dev = Math.Sqrt(std_dev) / TIME_SYNC_MESSAGE_COUNT;

                // time delta is the mean of the values less than 1 standard deviation from the median
                mean = 0;
                int meanCount = 0;
                foreach (var time in m_remoteSyncTimeCache[remoteID])
                {
                    if (Math.Abs(time - median) < std_dev)
                    {
                        mean += time;
                        meanCount++;
                    }
                }
                mean /= meanCount;
                Debug.LogFormat("Time offset to {0} is {1}", remoteID, mean);

                m_remoteSyncTimeCache.Remove(remoteID);
                m_remoteSentTimeCache.Remove(remoteID);
                m_remotePlayers[remoteID].remoteTimeOffset = (float)mean;

                // now that times are synchronized, lets try to coordinate the
                // start time for the match
                OfferMatchStartTime();
            }
        }
        public void UpdateFrame(double rateMultiplier, double powerFraction, double productionModidier, bool allowOverflow, double fixedDeltaTime, bool isStartup = false)
        {
            _effectiveMaxPower = PowerRequirements * productionModidier;
            _current_power     = PowerRequirements * powerFraction;

            _current_rate = CurrentPower / PluginHelper.PechineyUgineKuhlmannEnergyPerTon;

            // determine how much resource we have
            var partsThatContainAmmonia          = _part.GetConnectedResources(_ammonia_resource_name);
            var partsThatContainHydrogenPeroxide = _part.GetConnectedResources(_hydrogen_peroxide_name);
            var partsThatContainHydrazine        = _part.GetConnectedResources(_hydrazine_resource_name);
            var partsThatContainWater            = _part.GetConnectedResources(_water_resource_name);

            _maxCapacityAmmoniaMass          = partsThatContainAmmonia.Sum(p => p.maxAmount) * _ammonia_density;
            _maxCapacityHydrogenPeroxideMass = partsThatContainHydrogenPeroxide.Sum(p => p.maxAmount) * _hydrogen_peroxide_density;
            _maxCapacityHydrazineMass        = partsThatContainHydrogenPeroxide.Sum(p => p.maxAmount) * _hydrazine_density;
            _maxCapacityWaterMass            = partsThatContainWater.Sum(p => p.maxAmount) * _water_density;

            _availableAmmoniaMass          = partsThatContainAmmonia.Sum(r => r.amount) * _ammonia_density;
            _availableHydrogenPeroxideMass = partsThatContainHydrogenPeroxide.Sum(r => r.amount) * _hydrogen_peroxide_density;

            _spareRoomHydrazineMass = partsThatContainHydrazine.Sum(r => r.maxAmount - r.amount) * _hydrazine_density;
            _spareRoomWaterMass     = partsThatContainWater.Sum(r => r.maxAmount - r.amount) * _water_density;

            // determine how much we can consume
            var fixedMaxAmmoniaConsumptionRate = _current_rate * ammona_mass_consumption_ratio * fixedDeltaTime;
            var ammoniaConsumptionRatio        = fixedMaxAmmoniaConsumptionRate > 0 ? Math.Min(fixedMaxAmmoniaConsumptionRate, _availableAmmoniaMass) / fixedMaxAmmoniaConsumptionRate : 0;

            var fixedMaxHydrogenPeroxideConsumptionRate = _current_rate * hydrogen_peroxide_mass_consumption_ratio * fixedDeltaTime;
            var hydrogenPeroxideConsumptionRatio        = fixedMaxHydrogenPeroxideConsumptionRate > 0 ? Math.Min(fixedMaxHydrogenPeroxideConsumptionRate, _availableHydrogenPeroxideMass) / fixedMaxHydrogenPeroxideConsumptionRate : 0;

            _fixedConsumptionRate = _current_rate * fixedDeltaTime * Math.Min(ammoniaConsumptionRatio, hydrogenPeroxideConsumptionRatio);
            _consumptionRate      = _fixedConsumptionRate / fixedDeltaTime;

            if (_fixedConsumptionRate > 0 && (_spareRoomHydrazineMass > 0 || _spareRoomWaterMass > 0))
            {
                // calculate consumptionStorageRatio
                var fixedMaxHydrazineRate = _fixedConsumptionRate * hydrazine_mass_production_ratio;
                var fixedMaxWaterRate     = _fixedConsumptionRate * water_mass_production_ratio;

                var fixedMaxPossibleydrazineRate = allowOverflow ? fixedMaxHydrazineRate : Math.Min(_spareRoomHydrazineMass, fixedMaxHydrazineRate);
                var fixedMaxPossibleWaterRate    = allowOverflow ? fixedMaxWaterRate : Math.Min(_spareRoomWaterMass, fixedMaxWaterRate);

                _consumptionStorageRatio = Math.Min(fixedMaxPossibleydrazineRate / fixedMaxHydrazineRate, fixedMaxPossibleWaterRate / fixedMaxWaterRate);

                // now we do the real consumption
                var ammonia_request = _fixedConsumptionRate * ammona_mass_consumption_ratio * _consumptionStorageRatio / _ammonia_density;
                _ammonia_consumption_rate = _part.RequestResource(_ammonia_resource_name, ammonia_request) * _ammonia_density / fixedDeltaTime;

                var hydrogen_peroxide_request = _fixedConsumptionRate * hydrogen_peroxide_mass_consumption_ratio * _consumptionStorageRatio / _hydrogen_peroxide_density;
                _hydrogen_peroxide_consumption_rate = _part.RequestResource(_hydrogen_peroxide_name, hydrogen_peroxide_request) * _hydrogen_peroxide_density / fixedDeltaTime;

                var combined_consumption_rate = _ammonia_consumption_rate + _hydrogen_peroxide_consumption_rate;

                var fixed_hydrazine_production = combined_consumption_rate * hydrazine_mass_production_ratio * fixedDeltaTime / _hydrazine_density;
                _hydrazine_production_rate = -_part.RequestResource(_hydrazine_resource_name, -fixed_hydrazine_production) * _hydrazine_density / fixedDeltaTime;

                var fixed_water_production = combined_consumption_rate * water_mass_production_ratio * fixedDeltaTime / _water_density;
                _water_production_rate = -_part.RequestResource(_water_resource_name, -fixed_water_production) * _water_density / fixedDeltaTime;
            }
            else
            {
                _ammonia_consumption_rate           = 0;
                _hydrogen_peroxide_consumption_rate = 0;
                _hydrazine_production_rate          = 0;
                _water_production_rate = 0;
            }

            updateStatusMessage();
        }
        public void TestPfiRegressionStandardDeviationAndErrorOnDenseFeatures(bool saveModel)
        {
            var data  = GetDenseDataset();
            var model = ML.Regression.Trainers.OnlineGradientDescent().Fit(data);

            ImmutableArray <RegressionMetricsStatistics> pfi;

            if (saveModel)
            {
                var modelAndSchemaPath = GetOutputPath("TestPfiRegressionStandardDeviationAndErrorOnDenseFeatures.zip");
                ML.Model.Save(model, data.Schema, modelAndSchemaPath);

                var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema);
                var castedModel = loadedModel as RegressionPredictionTransformer <LinearRegressionModelParameters>;
                pfi = ML.Regression.PermutationFeatureImportance(castedModel, data, permutationCount: 20);
            }
            else
            {
                pfi = ML.Regression.PermutationFeatureImportance(model, data, permutationCount: 20);
            }

            // Keep the permutation count high so fluctuations are kept to a minimum
            //  but not high enough to slow down the tests
            //  (fluctuations lead to random test failures)

            // Pfi Indices:
            // X1: 0
            // X2Important: 1
            // X3: 2
            // X4Rand: 3

            // For these metrics, the magnitude of the difference will be greatest for 1, least for 3
            // Stardard Deviation will scale with the magnitude of the measure
            Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardDeviation));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardDeviation));

            Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanSquaredError.StandardDeviation));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanSquaredError.StandardDeviation));

            Assert.Equal(3, MinDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardDeviation));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardDeviation));

            Assert.Equal(3, MinDeltaIndex(pfi, m => m.RSquared.StandardDeviation));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RSquared.StandardDeviation));

            // Stardard Error will scale with the magnitude of the measure (as it's SD/sqrt(N))
            Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardError));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardError));

            Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanSquaredError.StandardError));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanSquaredError.StandardError));

            Assert.Equal(3, MinDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardError));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardError));

            Assert.Equal(3, MinDeltaIndex(pfi, m => m.RSquared.StandardError));
            Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RSquared.StandardError));

            // And test that the Standard Deviation and Standard Error are related as we expect
            Assert.Equal(pfi[0].RootMeanSquaredError.StandardError, pfi[0].RootMeanSquaredError.StandardDeviation / Math.Sqrt(pfi[0].RootMeanSquaredError.Count));

            Done();
        }
Example #47
0
        public void RefreshChartAsync()
        {
            if (VisualStudioDesignMode)
            {
                return;
            }

            pbLoading.Visible = true;
            olvDataLoads.ClearObjects();
            ragSmiley1.Reset();
            ragSmiley1.SetVisible(false);

            Thread t = new Thread(() =>
            {
                try
                {
                    int countManualLoadsuccessful = 0;
                    int countManualLoadFailure    = 0;

                    foreach (LoadMetadata metadata in Activator.RepositoryLocator.CatalogueRepository.GetAllObjects <LoadMetadata>())
                    {
                        try
                        {
                            LogManager logManager;

                            try
                            {
                                //get the logging connection
                                logManager = new LogManager(metadata.GetDistinctLoggingDatabase());
                            }
                            catch (NotSupportedException e)
                            {
                                //sometimes a load metadata won't have any catalogues so we can't process it's log history
                                if (e.Message.Contains("does not have any Catalogues associated with it"))
                                {
                                    continue;
                                }

                                throw;
                            }

                            ArchivalDataLoadInfo archivalDataLoadInfo = logManager.GetArchivalDataLoadInfos(metadata.GetDistinctLoggingTask()).FirstOrDefault();

                            bool lastLoadWasError;

                            var loadSummary = new DataLoadsGraphResult
                            {
                                ID   = metadata.ID,
                                Name = metadata.Name,
                            };

                            if (archivalDataLoadInfo == null)
                            {
                                this.Invoke(new MethodInvoker(() =>
                                {
                                    loadSummary.Status  = DataLoadsGraphResultStatus.NeverBeenRun;
                                    loadSummary.LastRun = "Never";
                                    olvDataLoads.AddObject(loadSummary);

                                    ResizeColumns();
                                }));
                                continue; //has never been run (or has had test runs only)
                            }

                            lastLoadWasError = archivalDataLoadInfo.Errors.Any() || archivalDataLoadInfo.EndTime == null;

                            //while we were fetching data from database the form was closed
                            if (IsDisposed || !IsHandleCreated)
                            {
                                return;
                            }

                            if (lastLoadWasError)
                            {
                                countManualLoadFailure++;
                            }
                            else
                            {
                                countManualLoadsuccessful++;
                            }

                            this.Invoke(new MethodInvoker(() =>
                            {
                                loadSummary.Status  = lastLoadWasError ? DataLoadsGraphResultStatus.Failing : DataLoadsGraphResultStatus.Succeeding;
                                loadSummary.LastRun = archivalDataLoadInfo.EndTime.ToString();

                                olvDataLoads.AddObject(loadSummary);

                                ResizeColumns();
                            }));
                        }
                        catch (Exception e)
                        {
                            ragSmiley1.Fatal(e);
                            this.Invoke(new MethodInvoker(() =>
                            {
                                pbLoading.Visible = false;
                            }));
                        }
                    }


                    //if there have been no loads at all ever
                    if (countManualLoadsuccessful == 0 && countManualLoadFailure == 0)
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            lblNoDataLoadsFound.Visible = true;
                            chart1.Visible    = false;
                            pbLoading.Visible = false;
                        }));

                        return;
                    }

                    DataTable dt = new DataTable();
                    dt.Columns.Add("Category");
                    dt.Columns.Add("NumberOfDataLoadsAtStatus");

                    dt.Rows.Add(new object[] { "Manual Successful", countManualLoadsuccessful });
                    dt.Rows.Add(new object[] { "Manual Fail", countManualLoadFailure });


                    this.Invoke(new MethodInvoker(() =>
                    {
                        chart1.Series[0].XValueMember  = "Category";
                        chart1.Series[0].YValueMembers = "NumberOfDataLoadsAtStatus";

                        chart1.DataSource = dt;
                        chart1.DataBind();

                        chart1.Series[0].Points[0].Color = Color.Green;
                        chart1.Series[0].Points[1].Color = Color.Red;

                        var max = new int[]
                        {
                            countManualLoadFailure,
                            countManualLoadsuccessful
                        }.Max();

                        int gridMarkEvery = max == 0 ? 1 : Math.Max(max / 10, 1);


                        chart1.ChartAreas[0].AxisY.Interval = gridMarkEvery;

                        chart1.ChartAreas[0].AxisY.MajorGrid.Interval           = gridMarkEvery;
                        chart1.ChartAreas[0].AxisY.MajorTickMark.Interval       = gridMarkEvery;
                        chart1.ChartAreas[0].AxisY.MajorTickMark.IntervalOffset = 0;

                        chart1.ChartAreas[0].AxisY.IsMarginVisible = false;


                        chart1.ChartAreas[0].AxisY.MinorGrid.Enabled     = false;
                        chart1.ChartAreas[0].AxisY.MinorTickMark.Enabled = false;

                        pbLoading.Visible = false;
                    }));
                }
                catch (Exception e)
                {
                    ragSmiley1.Fatal(e);
                    this.Invoke(new MethodInvoker(() =>
                    {
                        pbLoading.Visible = false;
                    }));
                }
            });

            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }
Example #48
0
        /// <summary>
        /// General distance algorithm uses all the parameters in the options object and works on tokens
        /// </summary>
        /// <param name="s1"></param>
        /// <param name="s2"></param>
        /// <param name="maxOffset"></param>
        /// <returns></returns>
        public double GeneralDistance(string s1, string s2, int maxOffset)
        {
            var t1 = _options.Tokenizer(s1);
            var t2 = _options.Tokenizer(s2);

            var l1 = t1.Length;
            var l2 = t2.Length;

            if (l1 == 0) return _options.LocalLengthEvaluator(l2);
            if (l2 == 0) return _options.LocalLengthEvaluator(l1);

            var c1 = 0;  //cursor for string 1
            var c2 = 0;  //cursor for string 2
            var lcss = 0.0;  //largest common subsequence
            var local_cs = 0.0; //local common substring
            var trans = 0.0;  //cost of transpositions ('axb' vs 'xba')
            var offset_arr = new LinkedList<OffsetPair>();  //offset pair array, for computing the transpositions

            while ((c1 < l1) && (c2 < l2))
            {
                if (_options.TokenMatcher(t1[c1], t2[c2]))
                {
                    local_cs += _options.MatchingEvaluator(t1[c1], t2[c2]);
                    var isTransposition = false;
                    var op = offset_arr.First;
                    while (op != null)
                    {  //see if current match is a transposition
                        var ofs = op.Value;
                        if (c1 <= ofs.C1 || c2 <= ofs.C2)
                        {
                            // when two matches cross, the one considered a transposition is the one with the largest difference in offsets
                            isTransposition = Math.Abs(c2 - c1) >= Math.Abs(ofs.C2 - ofs.C1);
                            if (isTransposition)
                            {
                                trans += _options.TranspositionCostEvaluator(c1, c2);
                            }
                            else
                            {
                                if (!ofs.IsTransposition)
                                {
                                    ofs.IsTransposition = true;
                                    trans += _options.TranspositionCostEvaluator(ofs.C1, ofs.C2);
                                }
                            }
                            break;
                        }
                        else
                        {
                            var next_op = op.Next;
                            if (c1 > ofs.C2 && c2 > ofs.C1)
                            {
                                offset_arr.Remove(op);
                            }
                            op = next_op;
                        }
                    }
                    offset_arr.AddLast(new OffsetPair(c1, c2)
                    {
                        IsTransposition = isTransposition
                    });
                }
                else
                {
                    lcss += _options.LocalLengthEvaluator(local_cs);
                    local_cs = 0;
                    if (c1 != c2)
                    {
                        c1 = c2 = Math.Min(c1, c2);  //using min allows the computation of transpositions
                    }
                    //if matching tokens are found, remove 1 from both cursors (they get incremented at the end of the loop)
                    //so that we can have only one code block handling matches 
                    for (var i = 0; i < maxOffset && (c1 + i < l1 || c2 + i < l2); i++)
                    {
                        if ((c1 + i < l1) && _options.TokenMatcher(t1[c1 + i], t2[c2]))
                        {
                            c1 += i - 1;
                            c2--;
                            break;
                        }
                        if ((c2 + i < l2) && _options.TokenMatcher(t1[c1], t2[c2 + i]))
                        {
                            c1--;
                            c2 += i - 1;
                            break;
                        }
                    }
                }
                c1++;
                c2++;
                if (_options.MaxDistance != null)
                {
                    var temporaryDistance = _options.LocalLengthEvaluator(Math.Max(c1, c2)) - _options.TranspositionsEvaluator(lcss, trans);
                    if (temporaryDistance >= _options.MaxDistance) return Math.Round(temporaryDistance, MidpointRounding.AwayFromZero);
                }
                // this covers the case where the last match is on the last token in list, so that it can compute transpositions correctly
                if ((c1 >= l1) || (c2 >= l2))
                {
                    lcss += _options.LocalLengthEvaluator(local_cs);
                    local_cs = 0;
                    c1 = c2 = Math.Min(c1, c2);
                }
            }
            lcss += _options.LocalLengthEvaluator(local_cs);
            return Math.Round(_options.LocalLengthEvaluator(Math.Max(l1, l2)) - _options.TranspositionsEvaluator(lcss, trans), MidpointRounding.AwayFromZero); //apply transposition cost to the final result
        }
Example #49
0
 // Gets Z angle in radians from a quaternion
 private static float RollFromQuat(Quaternion q)
 {
     //return (float)Math.Atan((2f * (q.X * q.Y + q.W * q.Z)) / (q.W * q.W + q.X * q.X - q.Y * q.Y - q.Z * q.Z));
     //return (float)Math.Atan2(2 * (q.W * q.Z + q.X * q.Y), 1 - (2 * (Math.Pow(q.Y, 2) + Math.Pow(q.Z, 2))));
     return (float)Math.Atan2(2 * (q.W * q.Z + q.X * q.Y), 1 - (2 * (Math.Pow(q.Y, 2) + Math.Pow(q.Z, 2))));
 }
Example #50
0
        /// <summary>
        /// Static distance algorithm working on strings, computing transpositions as well as stopping when maxDistance was reached.
        /// </summary>
        /// <param name="s1"></param>
        /// <param name="s2"></param>
        /// <param name="maxOffset"></param>
        /// <param name="maxDistance"></param>
        /// <returns></returns>
        public static double CommonDistance(string s1, string s2, int maxOffset, int maxDistance = 0)
        {
            var l1 = s1 == null ? 0 : s1.Length;
            var l2 = s2 == null ? 0 : s2.Length;

            if (l1 == 0) return l2;
            if (l2 == 0) return l1;

            var c1 = 0;  //cursor for string 1
            var c2 = 0;  //cursor for string 2
            var lcss = 0;  //largest common subsequence
            var local_cs = 0; //local common substring
            var trans = 0;  //number of transpositions ('axb' vs 'xba')
            var offset_arr = new LinkedList<OffsetPair>();  //offset pair array, for computing the transpositions

            while ((c1 < l1) && (c2 < l2))
            {
                if (s1[c1] == s2[c2])
                {
                    local_cs++;
                    var isTransposition = false;
                    var op = offset_arr.First;
                    while (op != null)
                    {  //see if current match is a transposition
                        var ofs = op.Value;
                        if (c1 <= ofs.C1 || c2 <= ofs.C2)
                        {
                            // when two matches cross, the one considered a transposition is the one with the largest difference in offsets
                            isTransposition = Math.Abs(c2 - c1) >= Math.Abs(ofs.C2 - ofs.C1);
                            if (isTransposition)
                            {
                                trans++;
                            }
                            else
                            {
                                if (!ofs.IsTransposition)
                                {
                                    ofs.IsTransposition = true;
                                    trans++;
                                }
                            }
                            break;
                        }
                        else
                        {
                            var next_op = op.Next;
                            if (c1 > ofs.C2 && c2 > ofs.C1)
                            {
                                offset_arr.Remove(op);
                            }
                            op = next_op;
                        }
                    }
                    offset_arr.AddLast(new OffsetPair(c1, c2)
                    {
                        IsTransposition = isTransposition
                    });
                }
                else
                {
                    lcss += local_cs;
                    local_cs = 0;
                    if (c1 != c2)
                    {
                        c1 = c2 = Math.Min(c1, c2);  //using min allows the computation of transpositions
                    }
                    //if matching tokens are found, remove 1 from both cursors (they get incremented at the end of the loop)
                    //so that we can have only one code block handling matches 
                    for (var i = 0; i < maxOffset && (c1 + i < l1 || c2 + i < l2); i++)
                    {
                        if ((c1 + i < l1) && s1[c1 + i] == s2[c2])
                        {
                            c1 += i - 1;
                            c2--;
                            break;
                        }
                        if ((c2 + i < l2) && s1[c1] == s2[c2 + i])
                        {
                            c1--;
                            c2 += i - 1;
                            break;
                        }
                    }
                }
                c1++;
                c2++;
                if (maxDistance > 0)
                {
                    var temporaryDistance = Math.Max(c1, c2) - (lcss - trans);
                    if (temporaryDistance >= maxDistance) return temporaryDistance;
                }
                // this covers the case where the last match is on the last token in list, so that it can compute transpositions correctly
                if ((c1 >= l1) || (c2 >= l2))
                {
                    lcss += local_cs;
                    local_cs = 0;
                    c1 = c2 = Math.Min(c1, c2);
                }
            }
            lcss += local_cs;
            return Math.Max(l1, l2) - (lcss - trans); //apply transposition cost to the final result
        }
Example #51
0
        public static double fixedRequestResource(Part part, string resourcename, double resource_amount)
        {
            List <PartResource> prl   = part.GetConnectedResources(resourcename).ToList();
            List <Part>         parts = new List <Part>();
            ResourceFlowMode    flow  = PartResourceLibrary.Instance.GetDefinition(resourcename).resourceFlowMode;

            prl = prl.Where(p => p.flowState == true).ToList();
            double max_available  = 0;
            double spare_capacity = 0;

            foreach (PartResource partresource in prl)
            {
                parts.Add(partresource.part);
                max_available  += partresource.amount;
                spare_capacity += partresource.maxAmount - partresource.amount;
            }

            if (flow == ResourceFlowMode.ALL_VESSEL)
            { // use our code
                double resource_left_to_draw = 0;
                double total_resource_change = 0;
                double res_ratio             = 0;

                if (resource_amount > 0)
                {
                    resource_left_to_draw = Math.Min(resource_amount, max_available);
                    res_ratio             = Math.Min(resource_amount / max_available, 1);
                }
                else
                {
                    resource_left_to_draw = Math.Max(-spare_capacity, resource_amount);
                    res_ratio             = Math.Min(-resource_amount / spare_capacity, 1);
                }

                if (double.IsNaN(res_ratio) || double.IsInfinity(res_ratio) || res_ratio == 0)
                {
                    return(0);
                }
                else
                {
                    foreach (PartResource local_part_resource in prl)
                    {
                        if (resource_amount > 0)
                        {
                            local_part_resource.amount = local_part_resource.amount - local_part_resource.amount * res_ratio;
                            total_resource_change     += local_part_resource.amount * res_ratio;
                        }
                        else
                        {
                            local_part_resource.amount = local_part_resource.amount + (local_part_resource.maxAmount - local_part_resource.amount) * res_ratio;
                            total_resource_change     -= (local_part_resource.maxAmount - local_part_resource.amount) * res_ratio;
                        }
                    }
                }
                return(total_resource_change);
            }
            else
            {
                if (resource_amount > 0)
                {
                    return(part.RequestResource(resourcename, Math.Min(resource_amount, max_available)));
                }
                else
                {
                    return(part.RequestResource(resourcename, Math.Max(-spare_capacity, resource_amount)));
                }
            }
        }
        /// <summary>
        /// THis method does the work.
        /// </summary>
        /// <param name="audioRecording">the recording.</param>
        /// <param name="configuration">the config file.</param>
        /// <param name="profileName">name of call/event type to be found.</param>
        /// <param name="segmentStartOffset">where one segment is located in the total recording.</param>
        /// <returns>a list of events.</returns>
        private static RecognizerResults WingBeats(AudioRecording audioRecording, Config configuration, string profileName, TimeSpan segmentStartOffset)
        {
            ConfigFile.TryGetProfile(configuration, profileName, out var profile);
            // get the common properties
            string speciesName            = configuration[AnalysisKeys.SpeciesName] ?? "Pteropus species";
            string abbreviatedSpeciesName = configuration[AnalysisKeys.AbbreviatedSpeciesName] ?? "Pteropus";

            // The following parameters worked well on a ten minute recording containing 14-16 calls.
            // Note: if you lower the dB threshold, you need to increase maxDurationSeconds
            int    minHz = profile.GetIntOrNull(AnalysisKeys.MinHz) ?? 100;
            int    maxHz = profile.GetIntOrNull(AnalysisKeys.MaxHz) ?? 3000;
            double minDurationSeconds = profile.GetDoubleOrNull(AnalysisKeys.MinDuration) ?? 1.0;
            double maxDurationSeconds = profile.GetDoubleOrNull(AnalysisKeys.MaxDuration) ?? 10.0;
            double decibelThreshold   = profile.GetDoubleOrNull("DecibelThreshold") ?? 6.0;
            double dctDuration        = profile.GetDoubleOrNull("DctDuration") ?? 1.0;
            double dctThreshold       = profile.GetDoubleOrNull("DctThreshold") ?? 0.5;
            double minOscFreq         = profile.GetDoubleOrNull("MinOscilFreq") ?? 4.0;
            double maxOscFreq         = profile.GetDoubleOrNull("MaxOscilFreq") ?? 6.0;
            double eventThreshold     = profile.GetDoubleOrNull("EventThreshold") ?? 0.3;

            //######################

            //2. Don't use samples in this recognizer.
            //var samples = audioRecording.WavReader.Samples;
            //Instead, convert each segment to a spectrogram.
            var sonogram     = GetSonogram(configuration, audioRecording);
            var decibelArray = SNR.CalculateFreqBandAvIntensity(sonogram.Data, minHz, maxHz, sonogram.NyquistFrequency);

            // Look for wing beats using oscillation detector

            /*
             * int scoreSmoothingWindow = 11; // sets a default that was good for Cane toad
             * Oscillations2019.Execute(
             * (SpectrogramStandard)sonogram,
             *  minHz,
             *  maxHz,
             *  decibelThreshold,
             *  dctDuration,
             *  (int)Math.Floor(minOscFreq),
             *  (int)Math.Floor(maxOscFreq),
             *  dctThreshold,
             *  eventThreshold,
             *  minDurationSeconds,
             *  maxDurationSeconds,
             *  scoreSmoothingWindow,
             *  out var scores,
             *  out var acousticEvents,
             *  //out var hits,
             *  segmentStartOffset);
             */
            Oscillations2012.Execute(
                (SpectrogramStandard)sonogram,
                minHz,
                maxHz,
                //decibelThreshold,
                dctDuration,
                (int)Math.Floor(minOscFreq),
                (int)Math.Floor(maxOscFreq),
                dctThreshold,
                eventThreshold,
                minDurationSeconds,
                maxDurationSeconds,
                out var scores,
                out var acousticEvents,
                out var hits,
                segmentStartOffset);

            // prepare plots
            double intensityNormalisationMax = 3 * decibelThreshold;
            var    normThreshold             = decibelThreshold / intensityNormalisationMax;
            var    normalisedIntensityArray  = DataTools.NormaliseInZeroOne(decibelArray, 0, intensityNormalisationMax);
            var    plot1 = new Plot(speciesName + " Wing-beat band", normalisedIntensityArray, normThreshold);
            var    plot2 = new Plot(speciesName + " Wing-beat Osc Score", scores, eventThreshold);
            var    plots = new List <Plot> {
                plot1, plot2
            };

            // ######################################################################

            // add additional information about the recording and sonogram properties from which the event is derived.
            acousticEvents.ForEach(ae =>
            {
                ae.FileName               = audioRecording.BaseName;
                ae.SpeciesName            = speciesName;
                ae.Name                   = abbreviatedSpeciesName + profileName;
                ae.Profile                = profileName;
                ae.SegmentDurationSeconds = audioRecording.Duration.TotalSeconds;
                ae.SegmentStartSeconds    = segmentStartOffset.TotalSeconds;
                var frameOffset           = sonogram.FrameStep;
                var frameDuration         = sonogram.FrameDuration;
                ae.SetTimeAndFreqScales(frameOffset, frameDuration, sonogram.FBinWidth);

                //UNCOMMENT following lines to get spectral profiles of the Wingbeat events.

                /*    double[,] spectrogramData = sonogram.Data;
                 *  int maxBin = (int)Math.Round(8000 / sonogram.FBinWidth);
                 *  double startSecond = ae.EventStartSeconds - ae.SegmentStartSeconds;
                 *  int startFrame = (int)Math.Round(startSecond / sonogram.FrameStep);
                 *  int frameLength = (int)Math.Round(ae.EventDurationSeconds / sonogram.FrameStep);
                 *  int endFrame = startFrame + frameLength;
                 *
                 *  // get only the frames from centre of the acoustic event
                 *  var subMatrix = DataTools.Submatrix(spectrogramData, startFrame + 10, 0, endFrame - 10, maxBin);
                 *  var spectrum = MatrixTools.GetColumnAverages(subMatrix);
                 *  var normalisedSpectrum = DataTools.normalise(spectrum);
                 *  normalisedSpectrum = DataTools.filterMovingAverageOdd(normalisedSpectrum, 11);
                 *  var maxId = DataTools.GetMaxIndex(normalisedSpectrum);
                 *  var hzMax = (int)Math.Ceiling(maxId * sonogram.FBinWidth);
                 *  string name = "BeatSpectrum " + (ae.SegmentStartSeconds / 60) + "m" + (int)Math.Floor(startSecond) + "s hzMax" + hzMax;
                 *  var bmp2 = GraphsAndCharts.DrawGraph(name, normalisedSpectrum, 100);
                 *
                 *  //Set required path
                 *  bmp2.Save(Path.Combine(@"C:\PATH", name + ".png"));
                 */
            });

            return(new RecognizerResults()
            {
                Events = acousticEvents,
                Hits = null,
                ScoreTrack = null,
                Plots = plots,
                Sonogram = sonogram,
            });
        }
Example #53
0
        public static bool UploadFile(this BosClient bosClient, BOSMultipartUploadRequest bosUploadRequest, IProgress <int> onProgressPercentChanged)
        {
            Debug.Assert(bosUploadRequest.RequestInfo.PartSize > 0);
            var filePath = bosUploadRequest.RequestInfo.FilePath;

            if (!File.Exists(filePath))
            {
                return(false);
            }

            var fileInfo = new FileInfo(filePath);

            long partSize = bosUploadRequest.RequestInfo.PartSize;

            int parts = (int)(fileInfo.Length / partSize);

            if (fileInfo.Length % partSize != 0)
            {
                parts += 1;
            }

            if (bosUploadRequest.RequestInfo.PartETags == null)
            {
                bosUploadRequest.RequestInfo.PartETags = new List <PartETag>();
            }

            if (string.IsNullOrEmpty(bosUploadRequest.RequestInfo.UploadId))
            {
                var initiateMultipartUploadRequest = new InitiateMultipartUploadRequest()
                {
                    BucketName = bosUploadRequest.RequestInfo.Bucket,
                    Key        = bosUploadRequest.RequestInfo.ObjectKey
                };
                var initiateMultipartUploadResponse = bosClient.InitiateMultipartUpload(initiateMultipartUploadRequest);

                bosUploadRequest.RequestInfo.UploadId = initiateMultipartUploadResponse.UploadId;
            }

            var uploadId = bosUploadRequest.RequestInfo.UploadId;

            for (int i = bosUploadRequest.RequestInfo.LastPartNumber; i < parts; ++i)
            {
                if (bosUploadRequest.PauseCancellationToken.IsCancellationRequested)
                {
                    return(false);
                }

                if (bosUploadRequest.AbortCancellationToken.IsCancellationRequested)
                {
                    var abortMultipartUploadRequest = new AbortMultipartUploadRequest()
                    {
                        BucketName = bosUploadRequest.RequestInfo.Bucket,
                        Key        = bosUploadRequest.RequestInfo.ObjectKey,
                        UploadId   = uploadId,
                    };
                    bosClient.AbortMultipartUpload(abortMultipartUploadRequest);

                    return(false);
                }

                using (var stream = fileInfo.OpenRead()) // TODO:
                {
                    var skipBytes = partSize * i;
                    stream.Seek(skipBytes, SeekOrigin.Begin);

                    onProgressPercentChanged?.Report((int)(((double)skipBytes / fileInfo.Length) * 100));

                    var actualPartSize = Math.Min(partSize, fileInfo.Length - skipBytes);

                    var uploadPartRequest = new UploadPartRequest();
                    uploadPartRequest.BucketName  = bosUploadRequest.RequestInfo.Bucket;
                    uploadPartRequest.Key         = bosUploadRequest.RequestInfo.ObjectKey;
                    uploadPartRequest.UploadId    = uploadId;
                    uploadPartRequest.InputStream = stream;
                    uploadPartRequest.PartSize    = actualPartSize;
                    uploadPartRequest.PartNumber  = i + 1;

                    var uploadPartResponse = bosClient.UploadPart(uploadPartRequest);

                    bosUploadRequest.RequestInfo.PartETags.Add(
                        new PartETag()
                    {
                        ETag       = uploadPartResponse.ETag,
                        PartNumber = uploadPartResponse.PartNumber
                    });

                    bosUploadRequest.RequestInfo.LastPartNumber = uploadPartResponse.PartNumber;
                }
            }

            var completeMultipartUploadRequest =
                new CompleteMultipartUploadRequest()
            {
                BucketName = bosUploadRequest.RequestInfo.Bucket,
                Key        = bosUploadRequest.RequestInfo.ObjectKey,
                UploadId   = uploadId,
                PartETags  = bosUploadRequest.RequestInfo.PartETags
            };

            var completeMultipartUploadResponse = bosClient.CompleteMultipartUpload(completeMultipartUploadRequest);

            onProgressPercentChanged?.Report(100);

            return(completeMultipartUploadResponse != null);
        }
        /// <summary>
        /// Remove events whose acoustic profile does not match that of a flying fox.
        /// </summary>
        /// <param name="events">unfiltered acoustic events.</param>
        /// <param name="sonogram">includes matrix of spectrogram values.</param>
        /// <returns>filtered acoustic events.</returns>
        private static List <AcousticEvent> FilterEventsForSpectralProfile(List <AcousticEvent> events, BaseSonogram sonogram)
        {
            double[,] spectrogramData = sonogram.Data;
            //int colCount = spectrogramData.GetLength(1);

            // The following freq bins are used to demarcate freq bands for spectral tests below.
            // The hertz values are hard coded but could be included in the config.yml file.
            int maxBin        = (int)Math.Round(8000 / sonogram.FBinWidth);
            int fourKiloHzBin = (int)Math.Round(4000 / sonogram.FBinWidth);
            int oneKiloHzBin  = (int)Math.Round(1000 / sonogram.FBinWidth);

            var filteredEvents = new List <AcousticEvent>();

            foreach (AcousticEvent ae in events)
            {
                int startFrame = ae.Oblong.RowTop;
                //int endFrame = ae.Oblong.RowBottom;

                // get all the frames of the acoustic event
                //var subMatrix = DataTools.Submatrix(spectrogramData, startFrame, 0, endFrame, colCount - 1);

                // get only the frames from centre of the acoustic event
                var subMatrix          = DataTools.Submatrix(spectrogramData, startFrame + 1, 0, startFrame + 4, maxBin);
                var spectrum           = MatrixTools.GetColumnAverages(subMatrix);
                var normalisedSpectrum = DataTools.normalise(spectrum);
                normalisedSpectrum = DataTools.filterMovingAverageOdd(normalisedSpectrum, 11);
                var maxId = DataTools.GetMaxIndex(normalisedSpectrum);
                //var hzMax = (int)Math.Ceiling(maxId * sonogram.FBinWidth);

                // Do TESTS to determine if event has spectrum matching a Flying fox.
                // Test 1: Spectral maximum should be below 4 kHz.
                bool passTest1 = maxId < fourKiloHzBin;

                // Test 2: There should be little energy in 0-1 kHz band.
                var    subband1Khz  = DataTools.Subarray(normalisedSpectrum, 0, oneKiloHzBin);
                double bandArea1    = subband1Khz.Sum();
                double energyRatio1 = bandArea1 / normalisedSpectrum.Sum();

                // 0.125  = 1/8.  i.e. test requires that energy in 0-1kHz band is less than average in all 8 kHz bands
                // 0.0938 = 3/32. i.e. test requires that energy in 0-1kHz band is less than 3/4 average in all 8 kHz bands
                // 0.0625 = 1/16. i.e. test requires that energy in 0-1kHz band is less than half average in all 8 kHz bands
                bool passTest2 = !(energyRatio1 > 0.1);

                // Test 3: There should be little energy in 4-5 kHz band.
                var    subband4Khz  = DataTools.Subarray(normalisedSpectrum, fourKiloHzBin, oneKiloHzBin);
                double bandArea2    = subband4Khz.Sum();
                double energyRatio2 = bandArea2 / normalisedSpectrum.Sum();
                bool   passTest3    = !(energyRatio2 > 0.125);

                // TODO write method to determine similarity of spectrum to a true flying fox spectrum.
                // Problem: it is not certain how variable the FF spectra are.
                // In ten minutes of recording used so far, which include 14-15 obvious calls, there appear to be two spectral types.
                // One type has three peaks at around 1.5 kHz, 3 kHz and 6 kHz.
                // The other type have two peaks around 2.5 and 5.5 kHz.

                //if (passTest1)
                //if (true)
                if (passTest1 && passTest2 && passTest3)
                {
                    filteredEvents.Add(ae);

                    //DEBUG SPECTRAL PROFILES: UNCOMMENT following lines to get spectral profiles of the events.

                    /*
                     * double startSecond = ae.EventStartSeconds - ae.SegmentStartSeconds;
                     * string name = "CallSpectrum " + (ae.SegmentStartSeconds / 60) + "m" + (int)Math.Floor(startSecond) + "s hzMax" + hzMax;
                     * var bmp2 = GraphsAndCharts.DrawGraph(name, normalisedSpectrum, 100);
                     * bmp2.Save(Path.Combine(@"PATH\Towsey.PteropusSpecies", name + ".png"));
                     */
                }
            }

            return(filteredEvents);
        }
Example #55
0
		// Token: 0x0600013C RID: 316 RVA: 0x00013188 File Offset: 0x00011388
		public VTex(BinaryReader reader) : base(reader)
		{
			reader.BaseStream.Position = 608L;
			bool yCoCg = false;
			for (int i = 0; i < 15; i++)
			{
				Encoding utf = Encoding.UTF8;
				int byteCount = utf.GetByteCount("e");
				string @string;
				using (MemoryStream memoryStream = new MemoryStream())
				{
					for (;;)
					{
						byte[] array = new byte[byteCount];
						reader.Read(array, 0, byteCount);
						if (utf.GetString(array, 0, byteCount) == "\0")
						{
							break;
						}
						memoryStream.Write(array, 0, array.Length);
					}
					@string = utf.GetString(memoryStream.ToArray());
				}
				if (string.IsNullOrEmpty(@string))
				{
					reader.BaseStream.Position += 32L;
				}
				else if (!(@string == "CompileTexture") && @string == "Texture Compiler Version Image YCoCg Conversion")
				{
					yCoCg = true;
					break;
				}
			}
			reader.BaseStream.Position = base.StreamStartPosition + (long)((ulong)base.Offset);
			this.Version = reader.ReadUInt16();
			if (this.Version != 1)
			{
				throw new InvalidDataException(string.Format("invalid version {0}", this.Version));
			}
			this.Flags = reader.ReadUInt16();
			this.Reflectivity = new float[]
			{
				reader.ReadSingle(),
				reader.ReadSingle(),
				reader.ReadSingle(),
				reader.ReadSingle()
			};
			this.Width = reader.ReadUInt16();
			this.Height = reader.ReadUInt16();
			this.Depth = reader.ReadUInt16();
			this.Format = reader.ReadByte();
			this.NumMipLevels = reader.ReadByte();
			reader.BaseStream.Position = (long)((ulong)base.Data);
			VTexFormat format = this.Format;
			switch (format)
			{
			case VTexFormat.IMAGE_FORMAT_DXT1:
				for (ushort num = 0; num < this.Depth; num += 1)
				{
					if (num >= 255)
					{
						break;
					}
					byte b = this.NumMipLevels;
					while (b > 0 && b != 1)
					{
						int num2 = 0;
						while ((double)num2 < (double)this.Height / Math.Pow(2.0, (double)(b + 1)))
						{
							int num3 = 0;
							while ((double)num3 < (double)this.Width / Math.Pow(2.0, (double)(b + 1)))
							{
								reader.BaseStream.Position += 8L;
								num3++;
							}
							num2++;
						}
						b -= 1;
					}
					this.Bitmap = DDSImage.UncompressDXT1(reader, (int)this.Width, (int)this.Height);
				}
				goto IL_480;
			case VTexFormat.IMAGE_FORMAT_DXT5:
			{
				ushort num4 = 0;
				while (num4 < this.Depth && num4 < 255)
				{
					byte b2 = this.NumMipLevels;
					while (b2 > 0 && b2 != 1)
					{
						int num5 = 0;
						while ((double)num5 < (double)this.Height / Math.Pow(2.0, (double)(b2 + 1)))
						{
							int num6 = 0;
							while ((double)num6 < (double)this.Width / Math.Pow(2.0, (double)(b2 + 1)))
							{
								reader.BaseStream.Position += 16L;
								num6++;
							}
							num5++;
						}
						b2 -= 1;
					}
					this.Bitmap = DDSImage.UncompressDXT5(reader, (int)this.Width, (int)this.Height, yCoCg);
					num4 += 1;
				}
				goto IL_480;
			}
			case (VTexFormat)3:
				goto IL_480;
			case VTexFormat.IMAGE_FORMAT_RGBA8888:
				break;
			default:
				if (format == VTexFormat.IMAGE_FORMAT_RGBA16161616F)
				{
					this.Bitmap = DDSImage.ReadRGBA16161616F(reader, (int)this.Width, (int)this.Height);
					goto IL_480;
				}
				if (format != VTexFormat.IMAGE_FORMAT_PNG)
				{
					goto IL_480;
				}
				using (MemoryStream memoryStream2 = new MemoryStream(reader.ReadBytes((int)reader.BaseStream.Length)))
				{
					this.Bitmap = new Bitmap(memoryStream2);
					goto IL_480;
				}
				break;
			}
			for (ushort num7 = 0; num7 < this.Depth; num7 += 1)
			{
				if (num7 >= 255)
				{
					break;
				}
				byte b3 = this.NumMipLevels;
				while (b3 > 0 && b3 != 1)
				{
					int num8 = 0;
					while ((double)num8 < (double)this.Height / Math.Pow(2.0, (double)(b3 - 1)))
					{
						reader.BaseStream.Position += (long)((int)((double)(4 * this.Width) / Math.Pow(2.0, (double)(b3 - 1))));
						num8++;
					}
					b3 -= 1;
				}
				this.Bitmap = DDSImage.ReadRGBA8888(reader, (int)this.Width, (int)this.Height);
			}
			IL_480:
			reader.BaseStream.Position = base.StreamEndPosition;
		}
Example #56
0
        private void PrioritySchedulingAlgorithm()
        {
            updateReadyProcessList();
            if (readyProcessList.Count != 0)
            {
                readyProcessList = readyProcessList.OrderBy(o => o.Priority).ToList();
                dgvProgress.Rows.Clear();
                setProgressDGViews(dgvProgress);
                foreach (cProcess pr in readyProcessList)
                {
                    createRow(dgvProgress, pr);
                }
                if (i == 0)
                {
                    executing = readyProcessList[0];
                    quant++;
                    firstTime("PS");
                }
                else if (quant % Convert.ToInt32(cbTQ.SelectedItem) != 0 && quant != 0 || quant == 0)
                {
                    if (executing == null) executing = readyProcessList[0];
                    quant++;
                }
                else if (quant % Convert.ToInt32(cbTQ.SelectedItem) == 0 && quant != 0)
                {
                    quant = 0;
                    if (readyProcessList.Count > 1 )
                    {
                        readyProcessList.Add(executing);
                        readyProcessList.RemoveAt(0);
                        dgvProgress.Rows.Clear();
                        setProgressDGViews(dgvProgress);
                        readyProcessList = readyProcessList.OrderBy(o => o.Priority).ToList();
                        foreach (cProcess pr in readyProcessList)
                        {
                            createRow(dgvProgress, pr);
                        }
                        executing = readyProcessList[0];
                    }
                    quant++;
                }
            }
            else if (i == 0)
            {
                setProgressDGViews(dgvProgress);
                firstTime("PS");
            }
            if (executing == null && i > 0)
            {
                addNewCell("(" + i.ToString() + "-" + (i + 1).ToString() + ")" + "s", Color.Black);
            }
            else if (executing != null && i > 0)
            {
                addNewCell(executing.ID + "\n\n\n\n\n" + "(" + i.ToString() + "-" + (i + 1).ToString() + ")" + "s", executing.ProcessColor);

                executing.Progress++; executing.ProgressLeft--;
                dgvProgress.Rows[0].Cells[1].Value = Math.Round(1.0 * executing.Progress / executing.TBurst * 100, 4).ToString() + "%";

                processDone("PS");
            }
            i++;
            if (dgvDone.Rows.Count == dgvProcesses.Rows.Count) timer1.Stop();
            dgvTimeline.ClearSelection();
        }
Example #57
0
        /// <summary>
        /// Calculates "cost" of conversion.
        /// </summary>
        static int ConvCost(CommonConversion conv, TypeSymbol from, TypeSymbol to)
        {
            if (conv.Exists)
            {
                if (conv.IsIdentity)
                {
                    return(0);
                }

                // calculate magically the conversion cost
                // TODO: unify with ConversionCost

                int cost;

                if (conv.IsReference)
                {
                    cost = 1;
                }
                else if (conv.IsNumeric)
                {
                    cost = 1;

                    var clfrom = ClassifyNumericType(from);
                    var clto   = ClassifyNumericType(to);

                    if (clfrom.size == 1) // bool
                    {
                        cost += 128;      // bool -> {0|1} // only if there is nothing better!!!
                    }

                    //
                    cost += Math.Abs(clto.size / 16 - clfrom.size / 16) + (clfrom.floating != clto.floating ? 1 : 0);
                }
                else if (conv.IsUserDefined) // preferring user defined conversions
                {
                    // do not treat all the implicit conversios the same

                    // PhpString <-> string
                    if ((to.IsStringType() || from.IsStringType()) && (to.Is_PhpString() || from.Is_PhpString()))
                    {
                        cost = 2;
                    }
                    else
                    {
                        cost = 4;
                    }
                }
                else
                {
                    cost = 8;
                }

                //
                if (conv.IsImplicit == false)
                {
                    cost *= 2;
                }

                //
                return(cost);
            }
            else
            {
                throw new ArgumentException();
            }
        }
        public List <ExpressionInfo> GenerateQuantfiers(List <ExpressionInfo> predicates, int numExpressions, int maxVariable, int maxExpansion, int maxQuantifiers)
        {
            var result      = new List <ExpressionInfo>();
            var allBindings = MergeBindings(predicates);
            var allTypes    = VariablesByType(allBindings);

            for (var exp = 0; exp < numExpressions; ++exp)
            {
                var expression = RandomChoice(predicates);
                var info       = new ExpressionInfo(expression.Expression);
                var numQuants  = 1 + Rand.Next(maxQuantifiers - 1);
                var chosen     = new HashSet <string>();
                var maxBase    = Math.Min(expression.Bindings.Count, numQuants);
                for (var quant = 0; quant < maxBase; ++quant)
                {
                    KeyValuePair <string, Comparison> baseBinding;

                    // Can only map each expression variable once in a quantifier
                    do
                    {
                        baseBinding = expression.Bindings.ElementAt(Rand.Next(expression.Bindings.Count));
                    }while (chosen.Contains(baseBinding.Key));
                    chosen.Add(baseBinding.Key);
                    SplitMemory(baseBinding.Key, out var baseName);
                    var mappings  = new List <string>();
                    var expansion = 1 + Rand.Next(maxExpansion - 1);
                    for (var i = 0; i < expansion; ++i)
                    {
                        if (i == 0)
                        {
                            mappings.Add($"{baseBinding.Key}");
                        }
                        else
                        {
                            var mapping = RandomChoice <string>(allTypes[baseBinding.Value.Value.GetType()]);
                            if (!mappings.Contains(mapping))
                            {
                                mappings.Add(mapping);
                            }
                        }
                    }

                    var any = Rand.NextDouble() < 0.5;
                    if (any)
                    {
                        var mem = RandomChoice(mappings);
                        if (!info.Bindings.ContainsKey(mem))
                        {
                            info.Bindings.Add(mem, baseBinding.Value);
                        }

                        info.Quantifiers.Add(new Quantifier(baseBinding.Key, QuantifierType.Any, mappings));
                    }
                    else
                    {
                        foreach (var mapping in mappings)
                        {
                            if (!info.Bindings.ContainsKey(mapping))
                            {
                                info.Bindings.Add(mapping, baseBinding.Value);
                            }
                        }

                        info.Quantifiers.Add(new Quantifier(baseBinding.Key, QuantifierType.All, mappings));
                    }
                }

                result.Add(info);
            }

            return(result);
        }
Example #59
0
        public void pidControl()
        {
            Console.WriteLine("iter\tnormVal\terror\tpid_val\tpower");

//			while (!Button.ESCAPE.isDown())
//			while (true)
            while (iter++ < max_iter)
            {
//				int normVal = ls.readNormalizedValue();
                int normVal = ev3.getAngularVelocity();

                // Proportional Error:
                int error = normVal - offset;
                // Adjust far and near light readings:
//				if (error < 0) error = (int)(error * 1.8F);

                // Integral Error:
                int_error = ((int_error + error) * 2) / 3;

                // Derivative Error:
                int deriv_error = error - prev_error;
                prev_error = error;

                int pid_val = (int)(KP * error + KI * int_error + KD * deriv_error) / SCALE_PID;

                if (pid_val > 100)
                {
                    pid_val = 100;
                }
                if (pid_val < -100)
                {
                    pid_val = -100;
                }

                // Power derived from PID value:
                int power = Math.Abs(pid_val);
                power = SPEED + (power * NORM_POWER) / SCALE_POWER;                 // NORMALIZE POWER

                Console.Write(iter + "\t" + normVal + "\t" + error + "\t"
                              + pid_val + "\t" + power + "\t");

                if (pid_val >= 0)
                {
                    Console.WriteLine("Forward");
                    ev3.onMotorA(power);
                    ev3.onMotorD(power);
//					MotorPort.B.controlMotor(power, BasicMotorPort.FORWARD);
//					MotorPort.C.controlMotor(power, BasicMotorPort.FORWARD);
                }
                else
                {
                    Console.WriteLine("Backward");
                    ev3.onMotorA(-1 * power);
                    ev3.onMotorD(-1 * power);
//					MotorPort.B.controlMotor(power, BasicMotorPort.BACKWARD);
//					MotorPort.C.controlMotor(power, BasicMotorPort.BACKWARD);
                }

//				Thread.Sleep (SLEEP);
            }
        }
Example #60
0
        private void BelowGraphInputsGUI(GraphInputs input)
        {
            GUILayout.BeginHorizontal();

            GUILayout.Label(Localizer.Format("FAREditorStaticGraphLowLim"),
                            GUILayout.Width(50.0F),
                            GUILayout.Height(25.0F));
            input.lowerBound = GUILayout.TextField(input.lowerBound, GUILayout.ExpandWidth(true));
            GUILayout.Label(Localizer.Format("FAREditorStaticGraphUpLim"),
                            GUILayout.Width(50.0F),
                            GUILayout.Height(25.0F));
            input.upperBound = GUILayout.TextField(input.upperBound, GUILayout.ExpandWidth(true));
            GUILayout.Label(Localizer.Format("FAREditorStaticGraphPtCount"),
                            GUILayout.Width(70.0F),
                            GUILayout.Height(25.0F));
            input.numPts = GUILayout.TextField(input.numPts, GUILayout.ExpandWidth(true));
            GUILayout.Label(isMachMode ? Localizer.Format("FARAbbrevAoA") : Localizer.Format("FARAbbrevMach"),
                            GUILayout.Width(50.0F),
                            GUILayout.Height(25.0F));
            input.otherInput = GUILayout.TextField(input.otherInput, GUILayout.ExpandWidth(true));

            if (GUILayout.Button(isMachMode
                                     ? Localizer.Format("FAREditorStaticSweepMach")
                                     : Localizer.Format("FAREditorStaticSweepAoA"),
                                 GUILayout.Width(100.0F),
                                 GUILayout.Height(25.0F)))
            {
                input.lowerBound   = Regex.Replace(input.lowerBound, @"[^-?[0-9]*(\.[0-9]*)?]", "");
                input.upperBound   = Regex.Replace(input.upperBound, @"[^-?[0-9]*(\.[0-9]*)?]", "");
                input.numPts       = Regex.Replace(input.numPts, @"[^-?[0-9]*(\.[0-9]*)?]", "");
                input.pitchSetting = Regex.Replace(input.pitchSetting, @"[^-?[0-9]*(\.[0-9]*)?]", "");
                input.otherInput   = Regex.Replace(input.otherInput, @"[^-?[0-9]*(\.[0-9]*)?]", "");

                double lowerBound = double.Parse(input.lowerBound);
                lowerBound       = lowerBound.Clamp(-90, 90);
                input.lowerBound = lowerBound.ToString(CultureInfo.InvariantCulture);

                double upperBound = double.Parse(input.upperBound);
                upperBound       = upperBound.Clamp(lowerBound, 90);
                input.upperBound = upperBound.ToString(CultureInfo.InvariantCulture);

                double numPts = double.Parse(input.numPts);
                numPts       = Math.Ceiling(numPts);
                input.numPts = numPts.ToString(CultureInfo.InvariantCulture);

                double pitchSetting = double.Parse(input.pitchSetting);
                pitchSetting       = pitchSetting.Clamp(-1, 1);
                input.pitchSetting = pitchSetting.ToString(CultureInfo.InvariantCulture);

                double otherInput = double.Parse(input.otherInput);

                SweepSim sim = simManager.SweepSim;
                if (sim.IsReady())
                {
                    GraphData data;
                    if (isMachMode)
                    {
                        data = sim.MachNumberSweep(otherInput,
                                                   pitchSetting,
                                                   lowerBound,
                                                   upperBound,
                                                   (int)numPts,
                                                   input.flapSetting,
                                                   input.spoilers,
                                                   bodySettingDropdown.ActiveSelection);
                        SetAngleVectors(pitchSetting, pitchSetting);
                    }
                    else
                    {
                        data = sim.AngleOfAttackSweep(otherInput,
                                                      pitchSetting,
                                                      lowerBound,
                                                      upperBound,
                                                      (int)numPts,
                                                      input.flapSetting,
                                                      input.spoilers,
                                                      bodySettingDropdown.ActiveSelection);
                        SetAngleVectors(lowerBound, upperBound);
                    }

                    UpdateGraph(data,
                                isMachMode
                                    ? Localizer.Format("FAREditorStaticGraphMach")
                                    : Localizer.Format("FAREditorStaticGraphAoA"),
                                Localizer.Format("FAREditorStaticGraphCoeff"),
                                lowerBound,
                                upperBound);
                }
            }

            GUILayout.EndHorizontal();
        }