Beispiel #1
0
 public Kanne(Functional.Answersheet AnswerSheet)
 {
     InitializeComponent();
     StringBuilder sb = new StringBuilder();
     sb.AppendLine("Richtige Antworten:\n");
     foreach (var answer in AnswerSheet.SelectedQuestion.Answers)
         if (answer.Second)
             sb.AppendLine("- " + answer.First);
     rightAnswers.Text = sb.ToString();
 }
Beispiel #2
0
        static void Main()
        {
            Functional functional = new Functional(MethodF);

            Delegate3 delegate3 = functional.Invoke(new Delegate1(Method1), new Delegate2(Method2));

            Console.WriteLine(delegate3.Invoke());

            // Delay.
            Console.ReadKey();
        }
Beispiel #3
0
 /// <summary>
 /// Forcefully casts one to ComplexNumber with downcasting
 /// </summary>
 /// <returns></returns>
 public ComplexNumber AsComplexNumber()
 => new ComplexNumber(Functional.Downcast(this));
Beispiel #4
0
 public BookingController()
 {
     _functional = new Functional();
     _carService = new CarService();
 }
    protected override void OnSelectConfirm()
    {
        if (!finished || ending)
        {
            foreach (var c in choices)
            {
                c.indicator.StopAllCoroutines();
                c.indicator.Fade(false);
            }

            NetworkController.Instance.SelectCar(currentChoice);



            AudioController.Instance.PlayClip(onConfirm);
            finished = true;
            AppController.Instance.currentSessionSettings.selectedCar          = choices[currentChoice].car;
            AppController.Instance.currentSessionSettings.selectedCarShortname = choices[currentChoice].shortName;

            gasTex.SetTarget(0f);
            turnTex.SetTarget(0f);

            var selectedCar = choices[currentChoice].displayObject;
            selectedCar.GetComponent <Rigidbody>().constraints = RigidbodyConstraints.None;

            selectedCar.GetComponent <VehicleAudioController>().PlayIgnition();

            //OLD SOUND CODE

            /*var sound = selectedCar.GetComponent<CarSound>();
             * sound.SelectSceneInit();
             * sound.selectAudio.PlayOneShot(sound.startup, 0.7f * AudioController.Instance.VehicleVolume);
             *
             * StartCoroutine(Functional.DoAfter(sound.startup.length, () =>
             * {
             *  sound.selectAudio.clip = sound.selectIdle;
             *  sound.selectAudio.Play();
             * }));
             */

            var vehicleController = selectedCar.GetComponent <VehicleController>();

            //Camera follow
            StartCoroutine(Functional.DoAfter(4f, () => {
                var camTarget = vehicleController.cameraPosition;
                camMove.SetFollowTarget(camTarget);

                var driverCam = camMove.GetComponent <DriverCamera>();

                StartCoroutine(Functional.DoTimed(2f, f =>
                {
                    driverCam.SetFoV(Mathf.Lerp(AdminSettings.Instance.selectFov, AdminSettings.Instance.fov, f));
                }));

                StartCoroutine(Functional.DoAfter(1f, () => {
                    camMove.updateRotation = true;
                }));

                StartCoroutine(Functional.WatchFor(() => Vector3.Distance(camMove.transform.position, camTarget.position) < 1.5f, () =>
                {
                    camMove.GetComponent <DriverCamera>().SetCulingMask(~(1 << LayerMask.NameToLayer("PlayerCar")));
                }));
            }));


            //Car Pathing
            StartCoroutine(Functional.DoAfter(0.5f, () =>
            {
                carInitialPos = selectedCar.transform.position;
                carInitialRot = selectedCar.transform.rotation;

                selectedCar.GetComponent <VehicleController>().enabled = true;


                var careip     = selectedCar.GetComponent <VehiclePathController>();
                careip.enabled = true;

                careip.onStop = () =>
                {
                    StartCoroutine(Functional.DoAfter(1.5f, () => base.OnSelectConfirm()));

                    RemoteAdminController.Instance.SendMessage(RemoteAdminController.SendMessageType.SELECT_CAR, currentChoice);

                    Quaternion initalRot = selectedCar.transform.localRotation;
                    Quaternion targetRot = Quaternion.Euler(initalRot.eulerAngles.x, 90f, initalRot.eulerAngles.z);
                    StartCoroutine(Functional.DoTimed(1.5f, (f) => {
                        selectedCar.transform.localRotation = Quaternion.Lerp(initalRot, targetRot, f);
                        selectedCar.GetComponent <Rigidbody>().angularVelocity = Vector3.zero;
                    }));
                };
            }));
            //cam.MoveToFar(() =>
            // {
            //     base.OnSelectConfirm();
            // });
        }
    }
        public void UpVal()
        {
            double rr = 1;
            Curve  c  = new Curve(0, 2 * Math.PI, (double t, double r) => r * Math.Cos(t), (double t, double r) => r * Math.Sin(t), rr);

            c.S = (double tx, double ty, double r) => tx * ty * r; c.End = (double r) => 2 * Math.PI;

            //Functional mp = (Point g) => 1;
            //DoubleIntegral(mp, c, c.S, parallel: true, cy: 300, M: Method.GaussKronrod61).Show();

            Func <Point, int, double> ro = (Point p, int k) => {
                var cc = new Complex(p.x, p.y);
                return(Math.Pow(cc.Abs, k) * Math.Cos(k * cc.Arg));
            };
            Func <Point, Point, double> E = (Point x, Point y) => Math.Log(Point.Eudistance(x, y));


            int    xc = 100, yc = 100;
            double x0 = -8, X = 8, y0 = -8, Y = 8;

            double hx = (X - x0) / (xc - 1), hy = (Y - y0) / (yc - 1);

            double[] xa = new double[xc], ya = new double[yc];

            for (int i = 0; i < xc; i++)
            {
                xa[i] = x0 + hx * i;
            }
            for (int i = 0; i < yc; i++)
            {
                ya[i] = y0 + hy * i;
            }


            int[] kk = new int[] { 3, 5, 25, 50, 200, 500 };
            double[][,] val = new double[kk.Length][, ];
            for (int i = 0; i < kk.Length; i++)
            {
                val[i] = new double[xc, yc];
                Functional fl = (Point x) =>
                {
                    Functional tmp = (Point y) => ro(y, kk[i]) * E(x, y);
                    return(DoubleIntegral(tmp, c, c.S, parallel: true, cy: 200, M: Method.GaussKronrod61));
                };
                Functional fl2 = (Point x) =>
                {
                    Complex z = new Complex(x.x, x.y);

                    Functional tmp = (Point y) => {
                        Complex w = new Complex(y.x, y.y);
                        return(Math.Pow(w.Abs, kk[i]) * Math.Cos(kk[i] * (w.Arg)) * Math.Log(z.Abs.Sqr() + w.Abs.Sqr() - 2 * z.Abs * w.Abs * Math.Cos(w.Arg)));
                    };
                    return(DoubleIntegral(tmp, c, c.S, parallel: true, cy: 200, M: Method.GaussKronrod61) / 2 * Math.Cos(kk[i] * z.Arg));
                };

                Functional fr = (Point x) =>
                {
                    Complex z = new Complex(x.x, x.y);
                    return(Math.PI * Math.Cos(kk[i] * z.Arg) / (kk[i] + 2) * Math.Max(Math.Log((z.Abs - 1).Sqr()).Abs(), Math.Log((z.Abs + 1).Sqr()).Abs()));
                };

                for (int ix = 0; ix < xc; ix++)
                {
                    for (int iy = 0; iy < yc; iy++)
                    {
                        Point  t = new Point(xa[ix], ya[iy]), o = new Point(0);
                        double rad = Point.Eudistance(t, o);
                        // $"t = {t} fr = {fr(t)}  fl = {fl(t)}".Show();
                        //$"{fl(t)} {fl2(t)}".Show();
                        //Assert.IsTrue((fl(t) - fl2(t)).Abs() < 1e-7);

                        if (rad > 1.0)
                        {
                            val[i][ix, iy] = fr(t).Abs() - fl(t).Abs();
                        }
                        else
                        {
                            val[i][ix, iy] = Double.NaN;
                        }
                    }
                }
            }

            StreamWriter args = new StreamWriter("arg.txt");
            StreamWriter vals = new StreamWriter("vals.txt");

            for (int i = 0; i < xc; i++)
            {
                args.WriteLine($"{xa[i]} {ya[i]}");
            }

            for (int i = 0; i < xc; i++)
            {
                for (int j = 0; j < yc; j++)
                {
                    string st = "";
                    for (int s = 0; s < kk.Length; s++)
                    {
                        st += (val[s][i, j] + " ");
                    }
                    vals.WriteLine(st.Replace("NaN", "NA"));
                }
            }


            args.Close();
            vals.Close();
        }
        /// <summary>
        /// Ультра-гибридный метод суперского решения по последней координате
        /// </summary>
        /// <param name="t"></param>
        public void UltraHybridLast(int t) //гибридный с координатной минимизацией по последней координате
        {
            double[] c = new double[t];
            for (int i = 0; i < t - 1; i++)
            {
                c[i] = x[i];
            }
            Vectors mk1 = new Vectors(c), mk2 = new Vectors(c);
            bool    existres = true;

            double sum = 0;

            GaussSpeedy(t);

            double tmp = Error(t);

            if (VALUE_FOR_ULTRA < tmp) //если погрешность выросла - исправить это, потому что новое решение не годится
            {
                $"{VALUE_FOR_ULTRA} < {tmp} при t = {t} (до покоординатной минимизации результата СПИДГАУССА)".Show();
                //покоординатная минимизация результата СПИДГАУССА
                for (int k = 0; k <= t - 1; k++)
                {
                    for (int j = 0; j < k; j++)
                    {
                        sum += x[j] * A[k, j];
                    }
                    for (int j = k + 1; j < t - 1; j++)
                    {
                        sum += x[j] * A[k, j];
                    }
                    x[k] = (b[k] - sum) / A[k, k];
                    sum  = 0;
                }

                tmp = Error(t);
                if (VALUE_FOR_ULTRA < tmp)
                {
                    $"{VALUE_FOR_ULTRA} < {tmp} при t = {t} (до полно покоординатной минимизации вектора с1 с2 ... 0)".Show();
                    for (int i = 0; i < t; i++)//исправили, теперь пробуем новый метод
                    {
                        x[i] = c[i];
                    }

                    //покоординатная минимизация
                    for (int k = 0; k <= t - 1; k++)
                    {
                        for (int j = 0; j < k; j++)
                        {
                            sum += x[j] * A[k, j];
                        }
                        for (int j = k + 1; j < t - 1; j++)
                        {
                            sum += x[j] * A[k, j];
                        }
                        x[k] = (b[k] - sum) / A[k, k];
                        sum  = 0;
                    }


                    double tmp1 = Error(t);
                    if (VALUE_FOR_ULTRA < tmp1) //погрешность опять выросла - тогда просто оставляем 0 на конце
                    {
                        $"{VALUE_FOR_ULTRA} < {tmp1} при t = {t} (до полной покоординатной минимизации на конце)".Show();
                        for (int i = 0; i < t; i++)//исправили, теперь пробуем новый метод
                        {
                            x[i] = c[i];
                        }
                        for (int j = 0; j < t - 1; j++)
                        {
                            sum += x[j] * A[t - 1, j];
                        }
                        x[t - 1] = (b[t - 1] - sum) / A[t - 1, t - 1];
                        sum      = 0;
                        tmp      = Error(t);
                        if (VALUE_FOR_ULTRA < tmp)
                        {
                            for (int i = 0; i < t - 1; i++)
                            {
                                x[i] = c[i];
                            }
                            x[t - 1] = 0;
                            existres = false;
                        }
                        else
                        {
                            $"Погрешность уменьшена МИНИМАКОЙ НА КОНЦЕ на {(VALUE_FOR_ULTRA - tmp) / VALUE_FOR_ULTRA * 100} % (now {tmp})".Show();
                            VALUE_FOR_ULTRA = tmp;
                        }
                    }
                    else
                    {
                        $"Погрешность уменьшена ПОЛНОЙ МИНИМАКОЙ на {(VALUE_FOR_ULTRA - tmp1) / VALUE_FOR_ULTRA * 100}% (now {tmp1})".Show();
                        VALUE_FOR_ULTRA = tmp1;
                    }
                }
                else
                {
                    $"Погрешность уменьшена МИНИМАКОЙ СПИДГАУССА на {(VALUE_FOR_ULTRA - tmp) / VALUE_FOR_ULTRA * 100} % (now {tmp})".Show();
                    VALUE_FOR_ULTRA = tmp;
                }
            }
            else
            {
                $"Погрешность уменьшена СПИДГАУССОМ на {(VALUE_FOR_ULTRA - tmp) / VALUE_FOR_ULTRA * 100} % (now {tmp})".Show();
                VALUE_FOR_ULTRA = tmp;
            }

            ErrorsMas[t - 1] = VALUE_FOR_ULTRA;
            Functional f = (Point x) =>
            {
                sum = 0;

                for (int ii = 1; ii <= t; ii++)
                {
                    sum += this.x[ii - 1] * KursMethods.masPoints[ii - 1].PotentialF(x);
                }
                double s = sum - KursMethods.fig(x);
                return(s * s);
            };

            ErrorMasP[t - 1] = Math.Sqrt(DoubleIntegral(f, curve, curve.S, FuncMethods.DefInteg.Method.GaussKronrod15, 0.001, FuncMethods.DefInteg.countY));
            //UltraCount = t;
            NEVA = Nev(A, x, b, t);

            Functional fM1 = (Point x) =>
            {
                //    Functional M1ApproxD = (Point u) =>
                //{
                //    Functional ro = (Point y) =>
                //    {
                //        double sss = 0; for (int i = 0; i < t; i++) sss += this.x[i] * KursMethods.masPoints[i].PotentialF(u);
                //        return sss * KursMethods.Exy(u, y);
                //    };
                //    //return DoubleIntegral(ro, curve, curve.S, FuncMethods.DefInteg.Method.GaussKronrod15, 0.001, FuncMethods.DefInteg.countY) /*IntegralClass.Integral(ro, KursMethods.CIRCLE - 1)*/ /*- right(x)*/;
                //    return IntegralClass.Integral(ro, KursMethods.CIRCLE - 1);
                //};

                double su = KursMethods.M1Approx(x);
                double s  = su - KursMethods.U(x);
                return(s * s);
            };

            if (existres)
            {
                $"Считается погрешность метода 1".Show();
                ErrorsM1[t - 1] = Math.Sqrt(IntegralClass.Integral2(fM1, KursMethods.CIRCLE - 1));
            }
            else
            {
                ErrorsM1[t - 1] = ErrorsM1[t - 2];
            }


            $"{t} = {ErrorsM1[t - 1]}".Show();
        }
Beispiel #8
0
        [Test] public void Comparisons()
        {
            int    x = 29, y = -17;
            string s1 = "hello", s2 = "world";

            Assert.IsTrue(Functional.LessThan(y, x));
            Assert.IsFalse(Functional.LessThan(x, y));
            Assert.IsTrue(Functional.GreaterThan(x, y));
            Assert.IsFalse(Functional.GreaterThan(y, x));
            Assert.IsTrue(Functional.LessThanOrEqual(y, x));
            Assert.IsFalse(Functional.LessThanOrEqual(x, y));
            Assert.IsTrue(Functional.GreaterThanOrEqual(x, y));
            Assert.IsFalse(Functional.GreaterThanOrEqual(y, x));

            y = 29;
            Assert.IsFalse(Functional.LessThan(y, x));
            Assert.IsFalse(Functional.LessThan(x, y));
            Assert.IsFalse(Functional.GreaterThan(x, y));
            Assert.IsFalse(Functional.GreaterThan(y, x));
            Assert.IsTrue(Functional.LessThanOrEqual(y, x));
            Assert.IsTrue(Functional.LessThanOrEqual(x, y));
            Assert.IsTrue(Functional.GreaterThanOrEqual(x, y));
            Assert.IsTrue(Functional.GreaterThanOrEqual(y, x));

            Assert.IsTrue(Functional.LessThan(s1, s2));
            Assert.IsFalse(Functional.LessThan(s2, s1));
            Assert.IsTrue(Functional.GreaterThan(s2, s1));
            Assert.IsFalse(Functional.GreaterThan(s1, s2));
            Assert.IsTrue(Functional.LessThanOrEqual(s1, s2));
            Assert.IsFalse(Functional.LessThanOrEqual(s2, s1));
            Assert.IsTrue(Functional.GreaterThanOrEqual(s2, s1));
            Assert.IsFalse(Functional.GreaterThanOrEqual(s1, s2));

            s2 = "hello";
            Assert.IsFalse(Functional.LessThan(s1, s2));
            Assert.IsFalse(Functional.LessThan(s2, s1));
            Assert.IsFalse(Functional.GreaterThan(s2, s1));
            Assert.IsFalse(Functional.GreaterThan(s1, s2));
            Assert.IsTrue(Functional.LessThanOrEqual(s1, s2));
            Assert.IsTrue(Functional.LessThanOrEqual(s2, s1));
            Assert.IsTrue(Functional.GreaterThanOrEqual(s2, s1));
            Assert.IsTrue(Functional.GreaterThanOrEqual(s1, s2));

            s1 = null;
            Assert.IsTrue(Functional.LessThan(s1, s2));
            Assert.IsFalse(Functional.LessThan(s2, s1));
            Assert.IsTrue(Functional.GreaterThan(s2, s1));
            Assert.IsFalse(Functional.GreaterThan(s1, s2));
            Assert.IsTrue(Functional.LessThanOrEqual(s1, s2));
            Assert.IsFalse(Functional.LessThanOrEqual(s2, s1));
            Assert.IsTrue(Functional.GreaterThanOrEqual(s2, s1));
            Assert.IsFalse(Functional.GreaterThanOrEqual(s1, s2));


            s2 = null;
            Assert.IsFalse(Functional.LessThan(s1, s2));
            Assert.IsFalse(Functional.LessThan(s2, s1));
            Assert.IsFalse(Functional.GreaterThan(s2, s1));
            Assert.IsFalse(Functional.GreaterThan(s1, s2));
            Assert.IsTrue(Functional.LessThanOrEqual(s1, s2));
            Assert.IsTrue(Functional.LessThanOrEqual(s2, s1));
            Assert.IsTrue(Functional.GreaterThanOrEqual(s2, s1));
            Assert.IsTrue(Functional.GreaterThanOrEqual(s1, s2));
        }
Beispiel #9
0
 /// <summary>
 /// Перевести функционал в функцию комплесного переменного
 /// </summary>
 /// <param name="f"></param>
 /// <returns></returns>
 public static ComplexFunc ToCompFunc(Functional f)
 {
     return((Complex z) => f(new Point(z.Re, z.Im)));
 }
Beispiel #10
0
        public void ProcessMessage(string json_message, MonoBehaviour owner, Action <string> response)
        {
            Command msgObj = JsonUtility.FromJson <Command> (json_message);

            try
            {
                switch (msgObj.objectType)
                {
                case "Optimizer":
                {
                    if (msgObj.functionCall == "create")
                    {
                        string optimizer_type = msgObj.tensorIndexParams[0];

                        // Extract parameters
                        List <int> p = new List <int>();
                        for (int i = 1; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            p.Add(int.Parse(msgObj.tensorIndexParams[i]));
                        }
                        List <float> hp = new List <float>();
                        for (int i = 0; i < msgObj.hyperParams.Length; i++)
                        {
                            hp.Add(float.Parse(msgObj.hyperParams[i]));
                        }

                        Optimizer optim = null;

                        if (optimizer_type == "sgd")
                        {
                            optim = new SGD(this, p, hp[0], hp[1], hp[2]);
                        }
                        else if (optimizer_type == "rmsprop")
                        {
                            optim = new RMSProp(this, p, hp[0], hp[1], hp[2], hp[3]);
                        }
                        else if (optimizer_type == "adam")
                        {
                            optim = new Adam(this, p, hp[0], hp[1], hp[2], hp[3], hp[4]);
                        }

                        response(optim.Id.ToString());
                        return;
                    }
                    else
                    {
                        Optimizer optim = this.GetOptimizer(msgObj.objectIndex);
                        response(optim.ProcessMessage(msgObj, this));

                        return;
                    }
                }

                case "FloatTensor":
                {
                    if (msgObj.objectIndex == 0 && msgObj.functionCall == "create")
                    {
                        FloatTensor tensor = floatTensorFactory.Create(_shape: msgObj.shape, _data: msgObj.data, _shader: this.Shader);
                        response(tensor.Id.ToString());
                        return;
                    }
                    else
                    {
                        FloatTensor tensor = floatTensorFactory.Get(msgObj.objectIndex);
                        // Process message's function
                        response(tensor.ProcessMessage(msgObj, this));
                        return;
                    }
                }

                case "IntTensor":
                {
                    if (msgObj.objectIndex == 0 && msgObj.functionCall == "create")
                    {
                        int[] data = new int[msgObj.data.Length];
                        for (int i = 0; i < msgObj.data.Length; i++)
                        {
                            data[i] = (int)msgObj.data[i];
                        }
                        IntTensor tensor = intTensorFactory.Create(_shape: msgObj.shape, _data: data);
                        response(tensor.Id.ToString());
                        return;
                    }
                    else
                    {
                        IntTensor tensor = intTensorFactory.Get(msgObj.objectIndex);
                        // Process message's function
                        response(tensor.ProcessMessage(msgObj, this));
                        return;
                    }
                }

                case "agent":
                {
                    if (msgObj.functionCall == "create")
                    {
                        Layer     model     = (Layer)GetModel(int.Parse(msgObj.tensorIndexParams[0]));
                        Optimizer optimizer = optimizers[int.Parse(msgObj.tensorIndexParams[1])];
                        response(new Syft.NN.RL.Agent(this, model, optimizer).Id.ToString());
                        return;
                    }

                    //Debug.Log("Getting Model:" + msgObj.objectIndex);
                    Syft.NN.RL.Agent agent = this.GetAgent(msgObj.objectIndex);
                    response(agent.ProcessMessageLocal(msgObj, this));
                    return;
                }

                case "model":
                {
                    if (msgObj.functionCall == "create")
                    {
                        string model_type = msgObj.tensorIndexParams[0];

                        Debug.LogFormat("<color=magenta>createModel:</color> {0}", model_type);

                        if (model_type == "linear")
                        {
                            response(this.BuildLinear(msgObj.tensorIndexParams).Id.ToString());
                            return;
                        }
                        else if (model_type == "relu")
                        {
                            response(this.BuildReLU().Id.ToString());
                            return;
                        }
                        else if (model_type == "log")
                        {
                            response(this.BuildLog().Id.ToString());
                            return;
                        }
                        else if (model_type == "dropout")
                        {
                            response(this.BuildDropout(msgObj.tensorIndexParams).Id.ToString());
                            return;
                        }
                        else if (model_type == "sigmoid")
                        {
                            response(this.BuildSigmoid().Id.ToString());
                            return;
                        }
                        else if (model_type == "sequential")
                        {
                            response(this.BuildSequential().Id.ToString());
                            return;
                        }
                        else if (model_type == "softmax")
                        {
                            response(this.BuildSoftmax(msgObj.tensorIndexParams).Id.ToString());
                            return;
                        }
                        else if (model_type == "logsoftmax")
                        {
                            response(this.BuildLogSoftmax(msgObj.tensorIndexParams).Id.ToString());
                            return;
                        }
                        else if (model_type == "tanh")
                        {
                            response(new Tanh(this).Id.ToString());
                            return;
                        }
                        else if (model_type == "crossentropyloss")
                        {
                            response(new CrossEntropyLoss(this, int.Parse(msgObj.tensorIndexParams[1])).Id.ToString());
                            return;
                        }
                        else if (model_type == "categorical_crossentropy")
                        {
                            response(new CategoricalCrossEntropyLoss(this).Id.ToString());
                            return;
                        }
                        else if (model_type == "nllloss")
                        {
                            response(new NLLLoss(this).Id.ToString());
                            return;
                        }
                        else if (model_type == "mseloss")
                        {
                            response(new MSELoss(this).Id.ToString());
                            return;
                        }
                        else if (model_type == "embedding")
                        {
                            response(new Embedding(this, int.Parse(msgObj.tensorIndexParams[1]), int.Parse(msgObj.tensorIndexParams[2])).Id.ToString());
                            return;
                        }
                        else
                        {
                            Debug.LogFormat("<color=red>Model Type Not Found:</color> {0}", model_type);
                        }
                    }
                    else
                    {
                        //Debug.Log("Getting Model:" + msgObj.objectIndex);
                        Model model = this.GetModel(msgObj.objectIndex);
                        response(model.ProcessMessage(msgObj, this));
                        return;
                    }
                    response("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
                    return;
                }

                case "controller":
                {
                    if (msgObj.functionCall == "num_tensors")
                    {
                        response(floatTensorFactory.Count() + "");
                        return;
                    }
                    else if (msgObj.functionCall == "num_models")
                    {
                        response(models.Count + "");
                        return;
                    }
                    else if (msgObj.functionCall == "new_tensors_allowed")
                    {
                        Debug.LogFormat("New Tensors Allowed:{0}", msgObj.tensorIndexParams[0]);
                        if (msgObj.tensorIndexParams[0] == "True")
                        {
                            allow_new_tensors = true;
                        }
                        else if (msgObj.tensorIndexParams[0] == "False")
                        {
                            allow_new_tensors = false;
                        }
                        else
                        {
                            throw new Exception("Invalid parameter for new_tensors_allowed. Did you mean true or false?");
                        }

                        response(allow_new_tensors + "");
                        return;
                    }
                    else if (msgObj.functionCall == "load_floattensor")
                    {
                        FloatTensor tensor = floatTensorFactory.Create(filepath: msgObj.tensorIndexParams[0], _shader: this.Shader);
                        response(tensor.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "set_seed")
                    {
                        Random.InitState(int.Parse(msgObj.tensorIndexParams[0]));
                        response("Random seed set!");
                        return;
                    }
                    else if (msgObj.functionCall == "concatenate")
                    {
                        List <int> tensor_ids = new List <int>();
                        for (int i = 1; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            tensor_ids.Add(int.Parse(msgObj.tensorIndexParams[i]));
                        }
                        FloatTensor result = Functional.Concatenate(floatTensorFactory, tensor_ids, int.Parse(msgObj.tensorIndexParams[0]));
                        response(result.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "ones")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Ones(floatTensorFactory, dims);
                        response(result.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "randn")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Randn(floatTensorFactory, dims);
                        response(result.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "random")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Random(floatTensorFactory, dims);
                        response(result.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "zeros")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Zeros(floatTensorFactory, dims);
                        response(result.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "model_from_json")
                    {
                        Debug.Log("Loading Model from JSON:");
                        var json_str = msgObj.tensorIndexParams[0];
                        var config   = JObject.Parse(json_str);

                        Sequential model;

                        if ((string)config["class_name"] == "Sequential")
                        {
                            model = this.BuildSequential();
                        }
                        else
                        {
                            response("Unity Error: SyftController.processMessage: while Loading model, Class :" + config["class_name"] + " is not implemented");
                            return;
                        }

                        for (int i = 0; i < config["config"].ToList().Count; i++)
                        {
                            var layer_desc        = config["config"][i];
                            var layer_config_desc = layer_desc["config"];

                            if ((string)layer_desc["class_name"] == "Linear")
                            {
                                int previous_output_dim;

                                if (i == 0)
                                {
                                    previous_output_dim = (int)layer_config_desc["batch_input_shape"][layer_config_desc["batch_input_shape"].ToList().Count - 1];
                                }
                                else
                                {
                                    previous_output_dim = (int)layer_config_desc["units"];
                                }

                                string[] parameters = { "linear", previous_output_dim.ToString(), layer_config_desc["units"].ToString(), "Xavier" };
                                Layer    layer      = this.BuildLinear(parameters);
                                model.AddLayer(layer);

                                string activation_name = layer_config_desc["activation"].ToString();

                                if (activation_name != "linear")
                                {
                                    Layer activation;
                                    if (activation_name == "softmax")
                                    {
                                        parameters = new string[] { activation_name, "1" };
                                        activation = this.BuildSoftmax(parameters);
                                    }
                                    else if (activation_name == "relu")
                                    {
                                        activation = this.BuildReLU();
                                    }
                                    else
                                    {
                                        response("Unity Error: SyftController.processMessage: while Loading activations, Activation :" + activation_name + " is not implemented");
                                        return;
                                    }
                                    model.AddLayer(activation);
                                }
                            }
                            else
                            {
                                response("Unity Error: SyftController.processMessage: while Loading layers, Layer :" + layer_desc["class_name"] + " is not implemented");
                                return;
                            }
                        }

                        response(model.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "from_proto")
                    {
                        Debug.Log("Loading Model from ONNX:");
                        var filename = msgObj.tensorIndexParams[0];

                        var        input      = File.OpenRead(filename);
                        ModelProto modelProto = ModelProto.Parser.ParseFrom(input);

                        Sequential model = this.BuildSequential();

                        foreach (NodeProto node in modelProto.Graph.Node)
                        {
                            Layer      layer;
                            GraphProto g = ONNXTools.GetSubGraphFromNodeAndMainGraph(node, modelProto.Graph);
                            if (node.OpType == "Gemm")
                            {
                                layer = new Linear(this, g);
                            }
                            else if (node.OpType == "Dropout")
                            {
                                layer = new Dropout(this, g);
                            }
                            else if (node.OpType == "Relu")
                            {
                                layer = new ReLU(this, g);
                            }
                            else if (node.OpType == "Softmax")
                            {
                                layer = new Softmax(this, g);
                            }
                            else
                            {
                                response("Unity Error: SyftController.processMessage: Layer not yet implemented for deserialization:");
                                return;
                            }
                            model.AddLayer(layer);
                        }

                        response(model.Id.ToString());
                        return;
                    }
                    else if (msgObj.functionCall == "to_proto")
                    {
                        ModelProto model    = this.ToProto(msgObj.tensorIndexParams);
                        string     filename = msgObj.tensorIndexParams[2];
                        string     type     = msgObj.tensorIndexParams[3];
                        if (type == "json")
                        {
                            response(model.ToString());
                        }
                        else
                        {
                            using (var output = File.Create(filename))
                            {
                                model.WriteTo(output);
                            }
                            response(new FileInfo(filename).FullName);
                        }
                        return;
                    }

                    response("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
                    return;
                }

                case "Grid":
                    if (msgObj.functionCall == "learn")
                    {
                        var inputId  = int.Parse(msgObj.tensorIndexParams[0]);
                        var targetId = int.Parse(msgObj.tensorIndexParams[1]);

                        response(this.grid.Run(inputId, targetId, msgObj.configurations, owner));
                        return;
                    }

                    if (msgObj.functionCall == "getResults")
                    {
                        this.grid.GetResults(msgObj.experimentId, response);
                        return;
                    }

                    // like getResults but doesn't pause to wait for results
                    // this function will return right away telling you if
                    // it knows whether or not it is done
                    if (msgObj.functionCall == "checkStatus")
                    {
                        this.grid.CheckStatus(msgObj.experimentId, response);
                        return;
                    }

                    break;

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                Debug.LogFormat("<color=red>{0}</color>", e.ToString());
                response("Unity Error: " + e.ToString());
                return;
            }

            // If not executing createTensor or tensor function, return default error.

            response("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
            return;
        }
Beispiel #11
0
        /// <summary>
        /// Вычисление криволинейного интеграла первого рода по этой кривой от функции f методом Гаусса
        /// </summary>
        /// <param name="f"></param>
        /// <returns></returns>
        public double Firstkind(Functional f)
        {
            Func <double, double> h = (double t) => f(this.Transfer(t));

            return(FuncMethods.DefInteg.GaussKronrod.Integral(h, this.a, this.b));
        }
 public ContractController(IOptions <StateConfigs> config)
 {
     _func     = new Functional();
     _info     = new Information(config);
     _reqModel = new RequestDataModel();
 }
Beispiel #13
0
 public static double Integral2(Functional f, int Curve) => DoubleIntegral(f, KursMethods.myCurve, KursMethods.myCurve.S, FuncMethods.DefInteg.Method.GaussKronrod15, 0.001, FuncMethods.DefInteg.countY);
 public FunctionalAuthorizeFilter(Functional functional)
 {
     _functional = functional;
 }
        public void Graf3Dtest()
        {
            Functional f = (Point a) => Math.Cos(a.Abs);

            ForScripts.MakeFilesForSurfaces(-2, 2, -4, 5, 100, "", new Functional[] { f }, (Point p) => true);
        }
 /// <summary>
 /// Calculates the exact value of arccotangent of num
 /// </summary>
 /// <param name="num"></param>
 /// <returns></returns>
 public static ComplexNumber Arccotan(Number num)
 => (num as ComplexNumber).IsDefinite()
         ? Functional.Downcast(Complex.Atan(1 / num.AsComplex())) as ComplexNumber
         : RealNumber.NaN();
Beispiel #17
0
        public void ExistingDestinationComplex()
        {
            Mapper.Register <ItemModel, ItemModelViewModel>();
            Mapper.Register <SubItem, SubItemViewModel>();
            Mapper.Register <Unit, UnitViewModel>();
            Mapper.Register <SubUnit, SubUnitViewModel>();
            Mapper.Compile();

            var sizeResult = Functional.ExistingDestinationComplex();

            var itemModelHash         = sizeResult.Value.GetHashCode();
            var itemModelSubItemsHash = sizeResult.Value.SubItems.GetHashCode();

            var subItemsHashes               = new List <int>(sizeResult.Value.SubItems.Length);
            var subItemUnitsCollHashes       = new Dictionary <int, int>();
            var subItemUnitsHashes           = new Dictionary <int, List <int> >();
            var subItemUnitSubUnitCollHashes = new Dictionary <int, List <int> >();
            var subItemUnitSubUnitsHashes    = new Dictionary <int, Dictionary <int, List <int> > >();

            foreach (var subItem in sizeResult.Value.SubItems)
            {
                var sbHash = subItem.GetHashCode();
                subItemsHashes.Add(sbHash);
                subItemUnitsCollHashes.Add(sbHash, subItem.Units.GetHashCode());
                subItemUnitsHashes.Add(sbHash, new List <int>());
                subItemUnitSubUnitCollHashes.Add(sbHash, new List <int>());
                subItemUnitSubUnitsHashes.Add(sbHash, new Dictionary <int, List <int> >());

                foreach (var unit in subItem.Units.Skip(1))
                {
                    subItemUnitsHashes[sbHash].Add(unit.GetHashCode());
                    subItemUnitSubUnitCollHashes[sbHash].Add(unit.SubUnits.GetHashCode());
                    subItemUnitSubUnitsHashes[sbHash][unit.GetHashCode()] = new List <int>();

                    foreach (var subUnit in unit.SubUnits)
                    {
                        subItemUnitSubUnitsHashes[sbHash][unit.GetHashCode()].Add(subUnit.GetHashCode());
                    }
                }
            }

            var result = Mapper.Map(sizeResult.Key, sizeResult.Value);

            Assert.AreEqual(result, sizeResult.Value);
            Assert.AreEqual(result.GetHashCode(), itemModelHash);
            Assert.AreEqual(result.SubItems.GetHashCode(), itemModelSubItemsHash);
            for (var i = 0; i < result.SubItems.Length; i++)
            {
                Assert.AreEqual(result.SubItems[i].GetHashCode(), subItemsHashes[i]);
                Assert.AreEqual(result.SubItems[i].Units.GetHashCode(), subItemUnitsCollHashes[result.SubItems[i].GetHashCode()]);

                for (var j = 0; j < 4; j++)
                {
                    Assert.AreEqual(result.SubItems[i].Units[j].GetHashCode(), subItemUnitsHashes[result.SubItems[i].GetHashCode()][j]);
                    Assert.AreEqual(result.SubItems[i].Units[j].SubUnits.GetHashCode(), subItemUnitSubUnitCollHashes[result.SubItems[i].GetHashCode()][j]);
                    for (var k = 0; k < 3; k++)
                    {
                        Assert.AreEqual(result.SubItems[i].Units[j].SubUnits[k].GetHashCode(), subItemUnitSubUnitsHashes[result.SubItems[i].GetHashCode()][result.SubItems[i].Units[j].GetHashCode()][k]);
                    }
                }
            }
        }
Beispiel #18
0
 public FileController(IOptions <StateConfigs> config)
 {
     _state = config.Value;
     _func  = new Functional();
     _file  = new FileManagement(config);
 }
Beispiel #19
0
 public LockService(Func <String, Tuple <Action, CancellationToken> > acquire, TimeSpan delay)
     : this((key, token) => Functional.Lock(() => acquire(key), delay, token))
 {
 }
Beispiel #20
0
        public string processMessage(string json_message)
        {
            //Debug.LogFormat("<color=green>SyftController.processMessage {0}</color>", json_message);

            Command msgObj = JsonUtility.FromJson <Command> (json_message);

            try
            {
                switch (msgObj.objectType)
                {
                case "Optimizer":
                {
                    if (msgObj.functionCall == "create")
                    {
                        string optimizer_type = msgObj.tensorIndexParams[0];

                        // Extract parameters
                        List <int> p = new List <int>();
                        for (int i = 1; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            p.Add(int.Parse(msgObj.tensorIndexParams[i]));
                        }
                        List <float> hp = new List <float>();
                        for (int i = 0; i < msgObj.hyperParams.Length; i++)
                        {
                            hp.Add(float.Parse(msgObj.hyperParams[i]));
                        }

                        Optimizer optim = null;

                        if (optimizer_type == "sgd")
                        {
                            optim = new SGD(this, p, hp[0], hp[1], hp[2]);
                        }
                        else if (optimizer_type == "rmsprop")
                        {
                            optim = new RMSProp(this, p, hp[0], hp[1], hp[2], hp[3]);
                        }
                        else if (optimizer_type == "adam")
                        {
                            optim = new Adam(this, p, hp[0], hp[1], hp[2], hp[3], hp[4]);
                        }

                        return(optim.Id.ToString());
                    }
                    else
                    {
                        Optimizer optim = this.getOptimizer(msgObj.objectIndex);
                        return(optim.ProcessMessage(msgObj, this));
                    }
                }

                case "FloatTensor":
                {
                    if (msgObj.objectIndex == 0 && msgObj.functionCall == "create")
                    {
                        FloatTensor tensor = floatTensorFactory.Create(_shape: msgObj.shape, _data: msgObj.data, _shader: this.Shader);
                        return(tensor.Id.ToString());
                    }
                    else
                    {
                        FloatTensor tensor = floatTensorFactory.Get(msgObj.objectIndex);
                        // Process message's function
                        return(tensor.ProcessMessage(msgObj, this));
                    }
                }

                case "IntTensor":
                {
                    if (msgObj.objectIndex == 0 && msgObj.functionCall == "create")
                    {
                        int[] data = new int[msgObj.data.Length];
                        for (int i = 0; i < msgObj.data.Length; i++)
                        {
                            data[i] = (int)msgObj.data[i];
                        }
                        IntTensor tensor = intTensorFactory.Create(_shape: msgObj.shape, _data: data, _shader: this.Shader);
                        return(tensor.Id.ToString());
                    }
                    else
                    {
                        IntTensor tensor = intTensorFactory.Get(msgObj.objectIndex);
                        // Process message's function
                        return(tensor.ProcessMessage(msgObj, this));
                    }
                }

                case "agent":
                {
                    if (msgObj.functionCall == "create")
                    {
                        Layer     model     = (Layer)getModel(int.Parse(msgObj.tensorIndexParams[0]));
                        Optimizer optimizer = optimizers[int.Parse(msgObj.tensorIndexParams[1])];
                        return(new Syft.NN.RL.Agent(this, model, optimizer).Id.ToString());
                    }

                    //Debug.Log("Getting Model:" + msgObj.objectIndex);
                    Syft.NN.RL.Agent agent = this.getAgent(msgObj.objectIndex);
                    return(agent.ProcessMessageLocal(msgObj, this));
                }

                case "model":
                {
                    if (msgObj.functionCall == "create")
                    {
                        string model_type = msgObj.tensorIndexParams[0];

                        Debug.LogFormat("<color=magenta>createModel:</color> {0}", model_type);

                        if (model_type == "linear")
                        {
                            return(new Linear(this, int.Parse(msgObj.tensorIndexParams[1]),
                                              int.Parse(msgObj.tensorIndexParams[2]),
                                              msgObj.tensorIndexParams[3]).Id.ToString());
                        }
                        else if (model_type == "relu")
                        {
                            return(new ReLU(this).Id.ToString());
                        }
                        else if (model_type == "log")
                        {
                            return(new Log(this).Id.ToString());
                        }
                        else if (model_type == "dropout")
                        {
                            return(new Dropout(this, float.Parse(msgObj.tensorIndexParams[1])).Id.ToString());
                        }
                        else if (model_type == "sigmoid")
                        {
                            return(new Sigmoid(this).Id.ToString());
                        }
                        else if (model_type == "sequential")
                        {
                            return(new Sequential(this).Id.ToString());
                        }
                        else if (model_type == "softmax")
                        {
                            return(new Softmax(this, int.Parse(msgObj.tensorIndexParams[1])).Id.ToString());
                        }
                        else if (model_type == "logsoftmax")
                        {
                            return(new LogSoftmax(this, int.Parse(msgObj.tensorIndexParams[1])).Id.ToString());
                        }
                        else if (model_type == "tanh")
                        {
                            return(new Tanh(this).Id.ToString());
                        }
                        else if (model_type == "crossentropyloss")
                        {
                            return(new CrossEntropyLoss(this, int.Parse(msgObj.tensorIndexParams[1])).Id.ToString());
                        }
                        else if (model_type == "categorical_crossentropy")
                        {
                            return(new CategoricalCrossEntropyLoss(this).Id.ToString());
                        }
                        else if (model_type == "nllloss")
                        {
                            return(new NLLLoss(this).Id.ToString());
                        }
                        else if (model_type == "mseloss")
                        {
                            return(new MSELoss(this).Id.ToString());
                        }
                        else if (model_type == "embedding")
                        {
                            return(new Embedding(this, int.Parse(msgObj.tensorIndexParams[1]), int.Parse(msgObj.tensorIndexParams[2])).Id.ToString());
                        }
                        else
                        {
                            Debug.LogFormat("<color=red>Model Type Not Found:</color> {0}", model_type);
                        }
                    }
                    else
                    {
                        //Debug.Log("Getting Model:" + msgObj.objectIndex);
                        Model model = this.getModel(msgObj.objectIndex);
                        return(model.ProcessMessage(msgObj, this));
                    }
                    return("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
                }

                case "controller":
                {
                    if (msgObj.functionCall == "num_tensors")
                    {
                        return(floatTensorFactory.Count() + "");
                    }
                    else if (msgObj.functionCall == "num_models")
                    {
                        return(models.Count + "");
                    }
                    else if (msgObj.functionCall == "new_tensors_allowed")
                    {
                        Debug.LogFormat("New Tensors Allowed:{0}", msgObj.tensorIndexParams[0]);
                        if (msgObj.tensorIndexParams[0] == "True")
                        {
                            allow_new_tensors = true;
                        }
                        else if (msgObj.tensorIndexParams[0] == "False")
                        {
                            allow_new_tensors = false;
                        }
                        else
                        {
                            throw new Exception("Invalid parameter for new_tensors_allowed. Did you mean true or false?");
                        }

                        return(allow_new_tensors + "");
                    }
                    else if (msgObj.functionCall == "load_floattensor")
                    {
                        FloatTensor tensor = floatTensorFactory.Create(filepath: msgObj.tensorIndexParams[0], _shader: this.Shader);
                        return(tensor.Id.ToString());
                    }
                    else if (msgObj.functionCall == "set_seed")
                    {
                        Random.InitState(int.Parse(msgObj.tensorIndexParams[0]));
                        return("Random seed set!");
                    }
                    else if (msgObj.functionCall == "concatenate")
                    {
                        List <int> tensor_ids = new List <int>();
                        for (int i = 1; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            tensor_ids.Add(int.Parse(msgObj.tensorIndexParams[i]));
                        }
                        FloatTensor result = Functional.Concatenate(floatTensorFactory, tensor_ids, int.Parse(msgObj.tensorIndexParams[0]));
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "ones")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Ones(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "randn")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Randn(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "random")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Random(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "zeros")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Zeros(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    return("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
                }

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                Debug.LogFormat("<color=red>{0}</color>", e.ToString());
                return("Unity Error: " + e.ToString());
            }

            // If not executing createTensor or tensor function, return default error.
            return("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
        }
Beispiel #21
0
 public static T Execute <T>(this IReliable reliable, Func <T> func, TimeSpan wait, CancellationToken?token = null)
 {
     return(Functional.Wait(cancel => reliable.Execute(func, cancel), wait, token ?? new CancellationToken()));
 }
        private void OnGUI()
        {
            GUILayout.Label("Members");

            if (GUILayout.Button("Get TestClass field name"))
            {
                string memberName;
                if (StaticReflectionHelper.GetMemberName <TestClass>(c => c.testField).TryGet(out memberName))
                {
                    Debug.Log(memberName);
                }
            }

            if (GUILayout.Button("Get TestClass property name"))
            {
                string memberName;
                if (StaticReflectionHelper.GetMemberName <TestClass>(c => c.testProperty).TryGet(out memberName))
                {
                    Debug.Log(memberName);
                }
            }

            if (GUILayout.Button("Get TestClass static field name"))
            {
                string memberName;
                if (StaticReflectionHelper.GetMemberName(() => TestClass.staticTestField).TryGet(out memberName))
                {
                    Debug.Log(memberName);
                }
            }

            if (GUILayout.Button("Get TestClass static property name"))
            {
                string memberName;
                if (StaticReflectionHelper.GetMemberName(() => TestClass.staticTestProperty).TryGet(out memberName))
                {
                    Debug.Log(memberName);
                }
            }

            GUILayout.Label("Methods");

            if (GUILayout.Button("Get TestClass method name"))
            {
                Functional.Ignore =
                    from memberName in StaticReflectionHelper.GetMemberName <TestClass>(c => c.TestMethod())
                    from methodInfo in StaticReflectionHelper.GetMethod <TestClass>(c => c.TestMethod())
                    select Functional.Do(() => Debug.Log(memberName + ", MethodInfo.Name: " + methodInfo.Name));
            }

            if (GUILayout.Button("Get TestClass no return method name"))
            {
                Functional.Ignore =
                    from memberName in StaticReflectionHelper.GetMemberName <TestClass>(c => c.TestMethodNoReturn())
                    from methodInfo in StaticReflectionHelper.GetMethod <TestClass>(c => c.TestMethodNoReturn())
                    select Functional.Do(() => Debug.Log(memberName + ", MethodInfo.Name: " + methodInfo.Name));
            }

            if (GUILayout.Button("Get TestClass static methods name"))
            {
                Functional.Ignore =
                    from memberName in StaticReflectionHelper.GetMemberName(() => TestClass.StaticTestMethod())
                    from methodInfo in StaticReflectionHelper.GetMethod(() => TestClass.StaticTestMethod())
                    select Functional.Do(() => Debug.Log(memberName + ", MethodInfo.Name: " + methodInfo.Name));
            }

            if (GUILayout.Button("Get TestClass no return static methods name"))
            {
                Functional.Ignore =
                    from memberName in StaticReflectionHelper.GetMemberName(() => TestClass.StaticTestMethodNoReturn())
                    from methodInfo in StaticReflectionHelper.GetMethod(() => TestClass.StaticTestMethodNoReturn())
                    select Functional.Do(() => Debug.Log(memberName + ", MethodInfo.Name: " + methodInfo.Name));
            }
        }
Beispiel #23
0
 public static void Execute(this IReliable reliable, Action action, TimeSpan wait, CancellationToken?token = null)
 {
     reliable.Execute(Functional.ToFunc <Boolean>(action), wait, token);
 }
        public string processMessage(string json_message, MonoBehaviour owner)
        {
            //Debug.LogFormat("<color=green>SyftController.processMessage {0}</color>", json_message);

            Command msgObj = JsonUtility.FromJson <Command> (json_message);

            try
            {
                switch (msgObj.objectType)
                {
                case "Optimizer":
                {
                    if (msgObj.functionCall == "create")
                    {
                        string optimizer_type = msgObj.tensorIndexParams[0];

                        // Extract parameters
                        List <int> p = new List <int>();
                        for (int i = 1; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            p.Add(int.Parse(msgObj.tensorIndexParams[i]));
                        }
                        List <float> hp = new List <float>();
                        for (int i = 0; i < msgObj.hyperParams.Length; i++)
                        {
                            hp.Add(float.Parse(msgObj.hyperParams[i]));
                        }

                        Optimizer optim = null;

                        if (optimizer_type == "sgd")
                        {
                            optim = new SGD(this, p, hp[0], hp[1], hp[2]);
                        }
                        else if (optimizer_type == "rmsprop")
                        {
                            optim = new RMSProp(this, p, hp[0], hp[1], hp[2], hp[3]);
                        }
                        else if (optimizer_type == "adam")
                        {
                            optim = new Adam(this, p, hp[0], hp[1], hp[2], hp[3], hp[4]);
                        }

                        return(optim.Id.ToString());
                    }
                    else
                    {
                        Optimizer optim = this.getOptimizer(msgObj.objectIndex);
                        return(optim.ProcessMessage(msgObj, this));
                    }
                }

                case "FloatTensor":
                {
                    if (msgObj.objectIndex == 0 && msgObj.functionCall == "create")
                    {
                        FloatTensor tensor = floatTensorFactory.Create(_shape: msgObj.shape, _data: msgObj.data, _shader: this.Shader);
                        return(tensor.Id.ToString());
                    }
                    else
                    {
                        FloatTensor tensor = floatTensorFactory.Get(msgObj.objectIndex);
                        // Process message's function
                        return(tensor.ProcessMessage(msgObj, this));
                    }
                }

                case "IntTensor":
                {
                    if (msgObj.objectIndex == 0 && msgObj.functionCall == "create")
                    {
                        int[] data = new int[msgObj.data.Length];
                        for (int i = 0; i < msgObj.data.Length; i++)
                        {
                            data[i] = (int)msgObj.data[i];
                        }
                        IntTensor tensor = intTensorFactory.Create(_shape: msgObj.shape, _data: data, _shader: this.Shader);
                        return(tensor.Id.ToString());
                    }
                    else
                    {
                        IntTensor tensor = intTensorFactory.Get(msgObj.objectIndex);
                        // Process message's function
                        return(tensor.ProcessMessage(msgObj, this));
                    }
                }

                case "agent":
                {
                    if (msgObj.functionCall == "create")
                    {
                        Layer     model     = (Layer)getModel(int.Parse(msgObj.tensorIndexParams[0]));
                        Optimizer optimizer = optimizers[int.Parse(msgObj.tensorIndexParams[1])];
                        return(new Syft.NN.RL.Agent(this, model, optimizer).Id.ToString());
                    }

                    //Debug.Log("Getting Model:" + msgObj.objectIndex);
                    Syft.NN.RL.Agent agent = this.getAgent(msgObj.objectIndex);
                    return(agent.ProcessMessageLocal(msgObj, this));
                }

                case "model":
                {
                    if (msgObj.functionCall == "create")
                    {
                        string model_type = msgObj.tensorIndexParams[0];

                        Debug.LogFormat("<color=magenta>createModel:</color> {0}", model_type);

                        if (model_type == "linear")
                        {
                            return(this.BuildLinear(msgObj.tensorIndexParams).Id.ToString());
                        }
                        else if (model_type == "relu")
                        {
                            return(this.BuildReLU().Id.ToString());
                        }
                        else if (model_type == "log")
                        {
                            return(this.BuildLog().Id.ToString());
                        }
                        else if (model_type == "dropout")
                        {
                            return(this.BuildDropout(msgObj.tensorIndexParams).Id.ToString());
                        }
                        else if (model_type == "sigmoid")
                        {
                            return(this.BuildSigmoid().Id.ToString());
                        }
                        else if (model_type == "sequential")
                        {
                            return(this.BuildSequential().Id.ToString());
                        }
                        else if (model_type == "softmax")
                        {
                            return(this.BuildSoftmax(msgObj.tensorIndexParams).Id.ToString());
                        }
                        else if (model_type == "logsoftmax")
                        {
                            return(this.BuildLogSoftmax(msgObj.tensorIndexParams).Id.ToString());
                        }
                        else if (model_type == "tanh")
                        {
                            return(new Tanh(this).Id.ToString());
                        }
                        else if (model_type == "crossentropyloss")
                        {
                            return(new CrossEntropyLoss(this, int.Parse(msgObj.tensorIndexParams[1])).Id.ToString());
                        }
                        else if (model_type == "categorical_crossentropy")
                        {
                            return(new CategoricalCrossEntropyLoss(this).Id.ToString());
                        }
                        else if (model_type == "nllloss")
                        {
                            return(new NLLLoss(this).Id.ToString());
                        }
                        else if (model_type == "mseloss")
                        {
                            return(new MSELoss(this).Id.ToString());
                        }
                        else if (model_type == "embedding")
                        {
                            return(new Embedding(this, int.Parse(msgObj.tensorIndexParams[1]), int.Parse(msgObj.tensorIndexParams[2])).Id.ToString());
                        }
                        else
                        {
                            Debug.LogFormat("<color=red>Model Type Not Found:</color> {0}", model_type);
                        }
                    }
                    else
                    {
                        //Debug.Log("Getting Model:" + msgObj.objectIndex);
                        Model model = this.getModel(msgObj.objectIndex);
                        return(model.ProcessMessage(msgObj, this));
                    }
                    return("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
                }

                case "controller":
                {
                    if (msgObj.functionCall == "num_tensors")
                    {
                        return(floatTensorFactory.Count() + "");
                    }
                    else if (msgObj.functionCall == "num_models")
                    {
                        return(models.Count + "");
                    }
                    else if (msgObj.functionCall == "new_tensors_allowed")
                    {
                        Debug.LogFormat("New Tensors Allowed:{0}", msgObj.tensorIndexParams[0]);
                        if (msgObj.tensorIndexParams[0] == "True")
                        {
                            allow_new_tensors = true;
                        }
                        else if (msgObj.tensorIndexParams[0] == "False")
                        {
                            allow_new_tensors = false;
                        }
                        else
                        {
                            throw new Exception("Invalid parameter for new_tensors_allowed. Did you mean true or false?");
                        }

                        return(allow_new_tensors + "");
                    }
                    else if (msgObj.functionCall == "load_floattensor")
                    {
                        FloatTensor tensor = floatTensorFactory.Create(filepath: msgObj.tensorIndexParams[0], _shader: this.Shader);
                        return(tensor.Id.ToString());
                    }
                    else if (msgObj.functionCall == "set_seed")
                    {
                        Random.InitState(int.Parse(msgObj.tensorIndexParams[0]));
                        return("Random seed set!");
                    }
                    else if (msgObj.functionCall == "concatenate")
                    {
                        List <int> tensor_ids = new List <int>();
                        for (int i = 1; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            tensor_ids.Add(int.Parse(msgObj.tensorIndexParams[i]));
                        }
                        FloatTensor result = Functional.Concatenate(floatTensorFactory, tensor_ids, int.Parse(msgObj.tensorIndexParams[0]));
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "ones")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Ones(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "randn")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Randn(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "random")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Random(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "zeros")
                    {
                        int[] dims = new int[msgObj.tensorIndexParams.Length];
                        for (int i = 0; i < msgObj.tensorIndexParams.Length; i++)
                        {
                            dims[i] = int.Parse(msgObj.tensorIndexParams[i]);
                        }
                        FloatTensor result = Functional.Zeros(floatTensorFactory, dims);
                        return(result.Id.ToString());
                    }
                    else if (msgObj.functionCall == "model_from_json")
                    {
                        Debug.Log("Loading Model from JSON:");
                        var json_str = msgObj.tensorIndexParams[0];
                        var config   = JObject.Parse(json_str);

                        Sequential model;

                        if ((string)config["class_name"] == "Sequential")
                        {
                            model = this.BuildSequential();
                        }
                        else
                        {
                            return("Unity Error: SyftController.processMessage: while Loading model, Class :" + config["class_name"] + " is not implemented");
                        }

                        for (int i = 0; i < config["config"].ToList().Count; i++)
                        {
                            var layer_desc        = config["config"][i];
                            var layer_config_desc = layer_desc["config"];

                            if ((string)layer_desc["class_name"] == "Linear")
                            {
                                int previous_output_dim;

                                if (i == 0)
                                {
                                    previous_output_dim = (int)layer_config_desc["batch_input_shape"][layer_config_desc["batch_input_shape"].ToList().Count - 1];
                                }
                                else
                                {
                                    previous_output_dim = (int)layer_config_desc["units"];
                                }

                                string[] parameters = new string[] { "linear", previous_output_dim.ToString(), layer_config_desc["units"].ToString(), "Xavier" };
                                Layer    layer      = this.BuildLinear(parameters);
                                model.AddLayer(layer);

                                string activation_name = layer_config_desc["activation"].ToString();

                                if (activation_name != "linear")
                                {
                                    Layer activation;
                                    if (activation_name == "softmax")
                                    {
                                        parameters = new string[] { activation_name, "1" };
                                        activation = this.BuildSoftmax(parameters);
                                    }
                                    else if (activation_name == "relu")
                                    {
                                        activation = this.BuildReLU();
                                    }
                                    else
                                    {
                                        return("Unity Error: SyftController.processMessage: while Loading activations, Activation :" + activation_name + " is not implemented");
                                    }
                                    model.AddLayer(activation);
                                }
                            }
                            else
                            {
                                return("Unity Error: SyftController.processMessage: while Loading layers, Layer :" + layer_desc["class_name"] + " is not implemented");
                            }
                        }

                        return(model.Id.ToString());
                    }
                    return("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
                }

                case "Grid":
                    if (msgObj.functionCall == "learn")
                    {
                        var inputId  = int.Parse(msgObj.tensorIndexParams[0]);
                        var targetId = int.Parse(msgObj.tensorIndexParams[1]);

                        var g = new Grid(this);
                        g.Run(inputId, targetId, msgObj.configurations, owner);

                        return("");
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                Debug.LogFormat("<color=red>{0}</color>", e.ToString());
                return("Unity Error: " + e.ToString());
            }

            // If not executing createTensor or tensor function, return default error.
            return("Unity Error: SyftController.processMessage: Command not found:" + msgObj.objectType + ":" + msgObj.functionCall);
        }
Beispiel #25
0
 public FullApiController()
 {
     Functional = new Functional(pathToConfigs);
     Utills     = new Utills(pathToConfigs);
 }
Beispiel #26
0
 /// <summary>
 /// Forcefully casts one to RealNumber with downcasting
 /// </summary>
 /// <returns></returns>
 public RealNumber AsRealNumber()
 => new RealNumber(Functional.Downcast(this));
Beispiel #27
0
 public AuthorizeController(IOptions <StateConfigs> configs)
 {
     func = new Functional();
     auth = new AuthorizeModel(configs);
     acc  = new AccountModel(configs);
 }
Beispiel #28
0
 /// <summary>
 /// Forcefully casts one to IntegerNumber with downcasting
 /// </summary>
 /// <returns></returns>
 public IntegerNumber AsIntegerNumber()
 => new IntegerNumber(Functional.Downcast(this));
Beispiel #29
0
        private IEnumerable <Args> GetFinalCommandLines(string baseCommandLine)
        {
            var exitCodeTest =
                _testCasesToRun.SingleOrDefault(tc => tc.IsExitCodeTestCase);

            if (exitCodeTest != null)
            {
                _testCasesToRun.Remove(exitCodeTest);
                if (!_testCasesToRun.Any())
                {
                    return(CreateDummyCommandLineArgs(baseCommandLine, exitCodeTest).Yield());
                }
            }

            var    commandLines = new List <Args>();
            string userParam    = GetAdditionalUserParameter();

            if (AllTestCasesOfExecutableAreRun())
            {
                commandLines.Add(new Args(_testCasesToRun, baseCommandLine + userParam));
                return(commandLines);
            }

            List <string> suitesRunningAllTests = GetSuitesRunningAllTests();
            int           maxSuiteLength        = MaxCommandLength - _lengthOfExecutableString - userParam.Length - 1;

            List <List <string> > suiteLists = GetSuiteListsForCommandLines(suitesRunningAllTests, maxSuiteLength);

            // lambda to return the base commandline string (including suite filters) and the list of testcases to execute
            var getFilterAndTestCasesForSuites = Functional.ToFunc((List <string> suites) =>
            {
                string suiteNamesFilter = GetFilterForSuitesRunningAllTests(suites);
                System.Diagnostics.Debug.Assert(suiteNamesFilter.Length < maxSuiteLength);

                string baseCommandLineWithFilter = baseCommandLine + GoogleTestConstants.FilterOption + suiteNamesFilter;
                List <TestCase> testCases        = suites.Select(GetTestCasesRunBySuite).SelectMany(testCase => testCase).ToList();
                return(new { baseCommandLineWithFilter, testCases });
            });

            // process all but the last suites-list
            suiteLists.Take(suiteLists.Count - 1)
            .Select(getFilterAndTestCasesForSuites).ToList()
            .ForEach(suitesFilterAndTests
                     => commandLines.Add(new Args(suitesFilterAndTests.testCases, suitesFilterAndTests.baseCommandLineWithFilter + userParam)));

            // process the last suite-list and all test-cases which belong to test-suites that are not fully executed
            var    filterAndTestsForLastSuites  = getFilterAndTestCasesForSuites(suiteLists.Last());
            string baseCommandLineForLastSuites = filterAndTestsForLastSuites.baseCommandLineWithFilter;

            List <TestCase> testCasesNotRunBySuite = GetTestCasesNotRunBySuite(suitesRunningAllTests);

            int    remainingLength = MaxCommandLength - baseCommandLineForLastSuites.Length - _lengthOfExecutableString - userParam.Length - 1;
            string commandLine     = baseCommandLineForLastSuites + JoinTestsUpToMaxLength(testCasesNotRunBySuite, remainingLength, out var includedTestCases);

            includedTestCases.AddRange(filterAndTestsForLastSuites.testCases);

            // a single command line holding both suite- and single-tests-filters
            commandLines.Add(new Args(includedTestCases, commandLine + userParam));

            // command lines holding only single-test- but no suite-filters
            string baseCommandLineWithoutSuites = baseCommandLine + GoogleTestConstants.FilterOption;

            while (testCasesNotRunBySuite.Count > 0)
            {
                remainingLength = MaxCommandLength - baseCommandLineWithoutSuites.Length - _lengthOfExecutableString - userParam.Length - 1;
                commandLine     = baseCommandLineWithoutSuites + JoinTestsUpToMaxLength(testCasesNotRunBySuite, remainingLength, out includedTestCases);
                commandLines.Add(new Args(includedTestCases, commandLine + userParam));
            }

            return(commandLines);
        }
 /// <summary>
 /// Calculates the exact value of cosine of num
 /// </summary>
 /// <param name="num"></param>
 /// <returns></returns>
 public static ComplexNumber Cos(Number num)
 => (num as ComplexNumber).IsDefinite()
         ? Functional.Downcast(Complex.Cos(num.AsComplex())) as ComplexNumber
         : RealNumber.NaN();
Beispiel #31
0
 public HomeController()
 {
     Functional = new Functional(pathToConfigs);
     Utills     = new Utills(pathToConfigs);
 }