Example #1
0
        static void RMain(string[] args)
        {
            REngine.SetEnvironmentVariables();
            // There are several options to initialize the engine, but by default the following suffice:
            using (REngine engine = REngine.GetInstance())
            {
                // .NET Framework array to R vector.
                NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
                engine.SetSymbol("group1", group1);
                // Direct parsing from R script.
                NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();

                // Test difference of mean and get the P-value.
                GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
                double        p          = testResult["p.value"].AsNumeric().First();

                Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
                Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
                Console.WriteLine("P-value = {0:0.000}", p);

                // you should always dispose of the REngine properly.
                // After disposing of the engine, you cannot reinitialize nor reuse it
                // engine.Dispose();
            } // End Using engine
        }     // End Sub RMain
    static void Main(string[] args)
    {
        // Set the folder in which R.dll locates.
        var envPath  = Environment.GetEnvironmentVariable("PATH");
        var rBinPath = @"C:\Program Files (x86)\R\R-2.11.1\bin";

        //var rBinPath = @"C:\Program Files\R\R-2.11.1-x64\bin"; // Doesn't work ("DLL was not found.")
        Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
        using (REngine engine = REngine.CreateInstance("RDotNet"))
        {
            // Initializes settings.
            engine.Initialize();

            // .NET Framework array to R vector.
            NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
            engine.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();

            // Test difference of mean and get the P-value.
            GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            double        p          = testResult["p.value"].AsNumeric().First();

            Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            Console.WriteLine("P-value = {0:0.000}", p);
        }
    }
        internal Dictionary <string, object> GetReturnObject(GenericVector gv)
        {
            Dictionary <string, object> res = new Dictionary <string, object>();

            for (int i = 0; i < gv.Length; i++)
            {
                switch (gv[i].Type)
                {
                case RDotNet.Internals.SymbolicExpressionType.CharacterVector:
                    res.Add(gv.Names[i], gv[i].AsCharacter().ToArray());
                    break;

                case RDotNet.Internals.SymbolicExpressionType.List:
                    res.Add(gv.Names[i], ToMatrix(gv[0].AsDataFrame()));
                    break;

                case RDotNet.Internals.SymbolicExpressionType.NumericVector:
                    res.Add(gv.Names[i], gv[i].AsNumeric().ToArray());
                    break;

                case RDotNet.Internals.SymbolicExpressionType.IntegerVector:
                    res.Add(gv.Names[i], gv[i].AsInteger().ToArray());
                    break;
                }
            }
            return(res);
        }
Example #4
0
        static void Main(string[] args)
        {
            REngine.SetEnvironmentVariables(@"c:\Program Files\Microsoft\R Client\R_SERVER\bin\x64\", @"c:\Program Files\Microsoft\R Client\R_SERVER\"); // <-- May be omitted; the next line would call it.
            REngine engine = REngine.GetInstance();


            // A somewhat contrived but customary Hello World:
            //CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" });
            //engine.SetSymbol("greetings", charVec);
            //engine.Evaluate("str(greetings)"); // print out in the console
            //string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray();
            //Console.WriteLine("R answered: '{0}'", a[0]);
            //Console.WriteLine("Press any key to exit the program");
            //Console.ReadKey();

            // .NET Framework array to R vector.
            NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });

            engine.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();

            // Test difference of mean and get the P-value.
            GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            double        p          = testResult["p.value"].AsNumeric().First();

            Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            Console.WriteLine("P-value = {0:0.000}", p);
            Console.ReadKey();
            engine.Dispose();
        }
Example #5
0
 private int GetNearestCluster(GenericVector v)
 {
     return(_centroids
            .OrderBy(centroid => GenericVector.Distance(centroid.Value, v))
            .Select(centroid => centroid.Key)
            .First());
 }
Example #6
0
        /// <summary>
        /// Run PCA in R engine
        /// </summary>
        static void PCAR()
        {
            const string directoryPath = @"C:\Users\Káťa\Desktop\Diplomka\mesh\meshes";
            var          matrix        = loadFacesR(directoryPath);

            REngine.SetEnvironmentVariables();
            REngine       engine = REngine.GetInstance();
            NumericMatrix group1 = engine.CreateNumericMatrix(matrix);

            engine.SetSymbol("group1", group1);
            GenericVector testResult = engine.Evaluate("pr.out=prcomp(group1, scale=TRUE)").AsList();
            var           eigenVec   = testResult["x"].AsNumericMatrix();

            engine.Evaluate("pr.out$sdev");
            engine.Evaluate("pr.var = pr.out$sdev ^ 2");
            engine.Evaluate("pr.var");
            engine.Evaluate("pve = pr.var / sum(pr.var)");
            engine.Evaluate("pve");
            engine.Evaluate("plot(cumsum(pve), xlab='Principal Component', ylab='Cumulative Proportion of Variance Explained', ylim=c(0,1),type='b')");
            saveVector(eigenVec);

            // var eigenVec = testResult["pr.out&x"].AsNumericMatrix();

            Console.ReadLine();
        }
Example #7
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);   //Set Start Date
            SetEndDate(2013, 10, 11);     //Set End Date
            SetCash(100000);              //Set Strategy Cash
            // Find more symbols here: http://quantconnect.com/data
            AddEquity("SPY", Resolution.Second);

            REngine engine = REngine.GetInstance();

            engine.Evaluate("print('This is from R command.')");
            // .NET Framework array to R vector.
            NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });

            engine.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();
            // Test difference of mean and get the P-value.
            GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            double        p          = testResult["p.value"].AsNumeric().First();

            // you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();
        }
Example #8
0
        /// <summary>
        /// Fits the series to model.
        /// </summary>
        /// <param name="JSONdataWithWeather">The jso ndata with weather.</param>
        /// <param name="modelName">Name of the model.</param>
        /// <param name="fittedDataName">Name of the fitted data.</param>
        /// <param name="weatherColumns">The weather columns.</param>
        /// <returns></returns>
        public List <Consuption> fitSeriesToModel(string JSONdataWithWeather, string modelName, string fittedDataName, WeatherColumns weatherColumns)
        {
            string       evaluate;
            const string fittingDataName = "dataName";

            evaluate = string.Format("{0} <-fromJSON(\'{1}\')", fittingDataName, JSONdataWithWeather);
            var sourceData = rEngine.Evaluate(evaluate);

            CreateWeatherMatrix(fittingDataName, weatherColumns);

            evaluate = string.Format("{0} <- forecast::Arima({1}$Amount,xreg = {2},model={3})", fittedDataName, fittingDataName, WEATHERMATRIX, modelName);
            //evaluate = string.Format("{0} <- forecast::Arima({1}$Amount,xreg = {2})", fittedDataName, fittingDataName, WEATHERMATRIX, modelName);
            var result = rEngine.Evaluate(evaluate);

            GenericVector resultList       = result.AsList();
            var           fittedValuesList = resultList["residuals"].AsNumeric().ToList();

            var sourceDates   = rEngine.Evaluate("sourceDates <- " + fittingDataName + "$IDDate").AsList();
            var sourceAmounts =
                rEngine.Evaluate("sourceDates <- " + fittingDataName + "$Amount").AsList();
            List <Consuption> retList = new List <Consuption>();

            for (int i = 0; i < fittedValuesList.Count; i++)
            {
                Consuption c = new Consuption();
                c.Amount = (float)fittedValuesList[i] + (float)sourceAmounts.AsNumeric().ElementAt(i);
                c.IDDate = sourceDates.AsInteger().ElementAt(i);
                retList.Add(c);
            }
            return(retList);
            //List<double> returnList = result.AsList();
        }
 private void HiSquare(List <int> activeVariables1, List <int> activeVariables2)
 {
     Header();
     wrange.Text = "Hi-square:";
     wrange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     worddoc.Paragraphs.Add();
     wrange           = worddoc.Paragraphs[iter++].Range;
     wrange.Font.Size = 14;
     wrange.Font.Bold = 0;
     wrange.Text      = "";
     latexText       += "\n\\section{Hi-square}" +
                        "\n\\begin{frame}\\frametitle{Хи-квадрат}" +
                        "\n\\begin{itemize}\n\\item";
     for (int k = 0; k < activeVariables1.Count(); k++)
     {
         wrange.Text += "\n" + (k + 1) + ". Рассматривается зависимость \"" + nameVars[activeVariables1[k]] + "\" от:";
         for (int l = 0; l < activeVariables2.Count(); l++)
         {
             GenericVector XSZ  = engine.Evaluate("Xsquared <- chisq.test(table(dataset$" + nameVars[activeVariables2[l]] + ",dataset$" + nameVars[activeVariables1[k]] + "))").AsList();
             double        xsSZ = XSZ["statistic"].AsNumeric()[0];
             double        pxSZ = engine.Evaluate("Xsquared$p.value").AsNumeric()[0];
             wrange.Text += "\n\t" + (l + 1) + ") \"" + nameVars[activeVariables2[l]] + "\":  X-squared = " + Math.Round(xsSZ, 2).ToString()
                            + ";  p-value = " + Math.Round(pxSZ, 3).ToString() + ";";
         }
     }
     wrange.Font.Bold = 0;
     for (int st = iter; iter++ <= st + activeVariables1.Count() * activeVariables2.Count(); worddoc.Paragraphs.Add())
     {
         ;
     }
     Conclusion();
     latexText += "\n\\end{itemize}" +
                  "\n\\end{frame}";
 }
Example #10
0
        //
        // GET: /Home/

        public ActionResult Index()
        {
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance();

            engine.Initialize();

            NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });

            engine.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();

            // Test difference of mean and get the P-value.
            GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            double        p          = testResult["p.value"].AsNumeric().First();

            Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            Console.WriteLine("P-value = {0:0.000}", p);

            // you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();



            return(View());
        }
Example #11
0
        public IEnumerable <VmResourceForecast> RunAlgorythms(IEnumerable <VmResourceTrace> traces)
        {
            var timer = new Stopwatch();

            var windowsCount  = traces.First().Series.Count() - Params.MinTraceWindow + 1;
            var splitedTraces = traces.GroupBy(t => t.Series.Count(v => v > 0) >= 2).ToDictionary(p => p.Key ? 1 : 0, p => p.ToArray());

            var zeroResult       = Enumerable.Range(0, windowsCount).Select(i => new ForecastResult(i, Enumerable.Repeat <float>(0, Params.PrognoseDepth).ToArray()));
            var zeroSeriesResult = splitedTraces[0]
                                   .Select(s => new VmResourceForecast(s.VmId, s.Resource, new Dictionary <string, IEnumerable <ForecastResult> >()
            {
                { "ARIMA", zeroResult },
                { "SES", zeroResult },
                { "CROST", zeroResult },
                { "HOLT", zeroResult },
                { "DHOLT", zeroResult }
            }));

            var inputList = new GenericVector(R, splitedTraces[1].Select(ConvertToRList));

            R.SetSymbol(InputListName, inputList);

            timer.Start();

            var result = R.Evaluate($"foreach(i = {InputListName}) %dopar% {ProccessTraceFunction}(i, {Params.MinTraceWindow}, {windowsCount})");

            timer.Stop();
            Debug.WriteLine($"{traces.Count()} with {windowsCount} windows evaluated in {timer.ElapsedMilliseconds}ms");

            return(result.AsList().Select(r => ReadRList(r.AsList())).Concat(zeroSeriesResult));
        }
Example #12
0
 private void TTest(List <int> activeVariables1, List <int> activeVariables2)
 {
     Header();
     wrange.Text = "T-TEST:";
     wrange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     worddoc.Paragraphs.Add();
     wrange           = worddoc.Paragraphs[iter++].Range;
     wrange.Font.Size = 14;
     wrange.Font.Bold = 0;
     latexText       += "\n\\section{T-test}" +
                        "\n\\begin{frame}\\frametitle{Т-тест}" +
                        "\n\\begin{itemize}\n\\item";
     for (int k = 0; k < activeVariables1.Count(); k++)
     {
         wrange.Text += "\n" + (k + 1) + ". Проведем t-test для \"" + nameVars[activeVariables1[k]] + "\" и:";
         for (int l = 0; l < activeVariables2.Count(); l++)
         {
             GenericVector testResAge = engine.Evaluate("ttest <- t.test(dataset$" + nameVars[activeVariables2[l]] + " ~ dataset$" + nameVars[activeVariables1[k]] + ")").AsList();
             double        tAge       = testResAge["statistic"].AsNumeric()[0];
             double        pAge       = engine.Evaluate("ttest$p.value").AsNumeric()[0];
             wrange.Text += "\n\t" + (l + 1) + ") \"" + nameVars[activeVariables2[l]] + "\":  t-value = " + Math.Round(tAge, 2).ToString()
                            + ";  p-value = " + Math.Round(pAge, 3).ToString() + ";";
         }
     }
     wrange.Font.Bold = 0;
     for (int st = iter; iter++ <= st + activeVariables1.Count() * activeVariables2.Count(); worddoc.Paragraphs.Add())
     {
         ;
     }
     Conclusion();
     latexText += "\n\\end{itemize}" +
                  "\n\\end{frame}";
 }
Example #13
0
 private void MannWitny(List <int> activeVariables1, List <int> activeVariables2)
 {
     Header();
     wrange.Text = "Mann-Witny:";
     wrange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     worddoc.Paragraphs.Add();
     wrange           = worddoc.Paragraphs[iter++].Range;
     wrange.Font.Size = 14;
     latexText       += "\n\\section{MannWitny}" +
                        "\n\\begin{frame}\\frametitle{Тест Манна-Уитни}" +
                        "\n\\begin{itemize}\n\\item";
     for (int k = 0; k < activeVariables1.Count(); k++)
     {
         wrange.Text += "\n" + (k + 1) + ". Рассматривается зависимость \"" + nameVars[activeVariables1[k]] + "\" от:";
         for (int l = 0; l < activeVariables2.Count(); l++)
         {
             GenericVector MWtAge = engine.Evaluate("mannWetney <- wilcox.test(dataset$" + nameVars[activeVariables2[l]] + " ~ dataset$" + nameVars[activeVariables1[k]] + ", paired = FALSE)").AsList();
             double        wAge   = MWtAge["statistic"].AsNumeric()[0];
             double        pwAge  = engine.Evaluate("mannWetney$p.value").AsNumeric()[0];
             wrange.Text += "\n\t" + (l + 1) + ") \"" + nameVars[activeVariables2[l]] + "\":  W = " + Math.Round(wAge, 2).ToString()
                            + ";  p-value = " + Math.Round(pwAge, 3).ToString() + ";";
         }
     }
     wrange.Font.Bold = 0;
     for (int st = iter; iter++ <= st + activeVariables1.Count() * activeVariables2.Count(); worddoc.Paragraphs.Add())
     {
         ;
     }
     Conclusion();
     latexText += "\n\\end{itemize}" +
                  "\n\\end{frame}";
 }
Example #14
0
        public static void TestRenderFrames()
        {
            RenderBuffer <float>     buffer     = new RenderBuffer <float>(CRenderSettings.RenderWidth, CRenderSettings.RenderHeight, 3);
            CharRenderBuffer <float> charBuffer = new CharRenderBuffer <float>(buffer);

            float framerate             = 25f;
            float time                  = 10f;
            int   totalFrame            = (int)(framerate * time);
            int   frameInterval         = (int)(1000f / framerate);
            GenericVector <float> white = new GenericVector <float>(3)
            {
                1, 1, 1
            };
            GenericVector <float> black = new GenericVector <float>(3)
            {
                0, 0, 0
            };
            int lastU = 0;
            int step  = totalFrame / buffer.Width + 1;

            for (int i = 0; i < totalFrame; i++)
            {
                if (i / step > lastU)
                {
                    buffer.WritePixel(lastU, 0, black);
                    buffer.WritePixel(++lastU, 0, white);
                }
                Thread.Sleep(frameInterval);
                CRenderer.Render(charBuffer);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance();

            // REngine requires explicit initialization.
            // You can set some parameters.
            engine.Initialize();

            // .NET Framework array to R vector.
            NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });

            engine.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();

            // Test difference of mean and get the P-value.
            GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            double        p          = testResult["p.value"].AsNumeric().First();

            Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            Console.WriteLine("P-value = {0:0.000}", p);

            // you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();
        }
        public void test_NextItem_P(int numofItems, ModelNames.Models paramModel, ModelNames.CriterionTypes paramCriterion)
        {
            resultFlag = true;

            REngine.SetEnvironmentVariables();

            REngine engineObj = REngine.GetInstance();

            // Loading a library from R
            engineObj.Evaluate("library(catR)");

            // Polytomous Items
            CharacterVector modelName = engineObj.CreateCharacterVector(new string[] { paramModel.EnumToString() });

            engineObj.SetSymbol("modelName", modelName);
            DataFrame PolyItems = engineObj.Evaluate("PolyItems <- genPolyMatrix(" + numofItems + ", 5, model = modelName, same.nrCat = TRUE)").AsDataFrame();

            engineObj.SetSymbol("PolyItems", PolyItems);

            // Adapting with the existing "CAT-Items" type (Wrapper)
            Console.WriteLine("*******************************************");
            Console.WriteLine("Polytomous Items, Model : " + paramModel.EnumToString());
            Console.WriteLine("*******************************************");

            CATItems itemBank = new CATItems(PolyItems[0].Length, paramModel.EnumToString(), 5);

            Tuple <CATItems.ColumnNames, int>[] cols = itemBank.GetKeys();

            for (int i = 0; i < cols.Length; i++)
            {
                itemBank.SetItemParamter(cols[i], PolyItems[i].Select(y => (double)y).ToArray());
            }

            // Call "NextItem" function from R
            GenericVector r_NextItem = engineObj.Evaluate("r_NextItem <- nextItem(PolyItems, model = modelName, theta = 0, criterion = \"" + paramCriterion.ToString() + "\")").AsList();

            // Selected item
            NumericVector item = r_NextItem[0].AsNumeric();

            DataFrame par = r_NextItem[1].AsDataFrame();

            // Value of "info"
            NumericVector thStart = r_NextItem[2].AsNumeric();

            // Criterion
            CharacterVector startSelect = r_NextItem[3].AsCharacter();

            // Call "NextItem" function from CS
            NextItemModel cs_NextItem = CatRLib.NextItem(itemBank, model: paramModel.EnumToString(), theta: 0, criterion: (int)paramCriterion);

            //Test passed for "MFI"

            if (item[0] != cs_NextItem.item)
            {
                resultFlag = false;
            }

            Assert.IsTrue(resultFlag);
        }
Example #17
0
 private IEnumerable <ForecastResult> ParseForecastResult(GenericVector list) =>
 list.Select(exp => exp.AsList())
 .Select(r => {
     var offset     = r["offset"].AsInteger()[0];
     var r_reslult  = r["result"].AsNumeric();
     float[] result = double.IsNaN(r_reslult[0]) ? null : r_reslult.Select(f => (float)f).ToArray();
     return(new ForecastResult(offset, result));
 }).Where(x => x.Result != null);
Example #18
0
 public static GenericVector <float> Lerp(float value, GenericVector <float> from, GenericVector <float> to)
 {
     for (int i = 0; i < from.Length; i++)
     {
         from[i] = Lerp(value, from[i], to[i]);
     }
     return(from);
 }
Example #19
0
            //---------------------------------------------------------------------
            public void Deserialize(Stream Stream_in)
            {
                BinaryFormatter   formatter = new BinaryFormatter();
                GenericVector <T> vector    = (GenericVector <T>)formatter.Deserialize(Stream_in);

                this.CopyFromArray(vector.ToArray());
                return;
            }
Example #20
0
        public ListConverter(GenericVector sexp, IDataConverter converter)
        {
            var array = sexp.ToArray();

            _length = sexp.Length;

            _intersectedItemType = null;
            _converters          = new IConverter[_length];
            for (var i = 0; i < _length; i++)
            {
                _converters[i] = converter.GetConverter(array[i].DangerousGetHandle().ToInt64());
                if (_converters[i] == null)
                {
                    throw new InvalidDataException("Unable to get convert for data at index: " + i + " in List");
                }

                var itemTypes = _converters[i].GetClrTypes();
                _intersectedItemType = _intersectedItemType == null
                    ? itemTypes
                    : _intersectedItemType.Intersect(itemTypes);
            }

            if (_intersectedItemType == null)
            {
                _intersectedItemType = new[] { typeof(object) }
            }
            ;

            var fullTypes = new List <Type>();

            _names = sexp.Names;
            if (_names != null)
            {
                fullTypes.AddRange(keyTypes.GetDictionaryTypes(_intersectedItemType));
                if (_names.Length != _length)
                {
                    var swap = new string[_length];
                    for (var i = 0; i < _length; i++)
                    {
                        swap[i] = i < _names.Length
                            ? _names[i]
                            : "Column " + (i + 1);
                    }
                    _names = swap;
                }
            }

            fullTypes.AddRange(_intersectedItemType.GetListOrArrayTypes());

            var count = fullTypes.Count;

            _types = fullTypes[0].GetFullHierarchy();
            for (var i = 1; i < count; i++)
            {
                _types = _types.Union(fullTypes[i].GetFullHierarchy());
            }
        }
Example #21
0
        public RenderBuffer <float> Draw(RenderEntity[] entities, ICamera camera)
        {
            _renderTarget.Clear();
            _matrixWorldToView = camera.WorldToView;

            TApp appdata = new TApp();

            TV2F[][]       vertexV2FData = new TV2F[entities.Length][];
            IPrimitive[][] primitives    = new IPrimitive[entities.Length][];
            Vector2[][]    screenCoords  = new Vector2[entities.Length][];
            for (int i = 0; i < entities.Length; i++)
            {
                RenderEntity instanceCopy = entities[i].GetInstanceToApply();

                _matrixObjectToWorld = instanceCopy.Transform.LocalToWorld;
                _matrixObjectToView  = _matrixWorldToView * _matrixObjectToWorld;

                Vector3[] vertices = instanceCopy.Model.Vertices;
                vertexV2FData[i] = new TV2F[vertices.Length];
                screenCoords[i]  = new Vector2[vertices.Length];
                primitives[i]    = instanceCopy.Model.Primitives;
                for (int j = 0; j < vertices.Length; j++)
                {
                    appdata.AssignAppdata(ref instanceCopy.Model, j);
                    TV2F v2f = Vertex(ref appdata);

                    vertexV2FData[i][j] = v2f;
                    screenCoords[i][j]  = ViewToScreen(v2f.Vertex_VOut);
                }
            }

            //Octree is so annoying
            //Clipping();

            Vector2Int[][][] rasterization = Rasterize(screenCoords, vertexV2FData, primitives);

            GenericVector <float> whiteColor = new GenericVector <float>(3)
            {
                1, 1, 1
            };

            //Model
            for (int i = 0; i < rasterization.Length; i++)
            {
                //Primitive
                for (int j = 0; j < rasterization[i].Length; j++)
                {
                    //PixelPos
                    for (int k = 0; k < rasterization[i][j].Length; k++)
                    {
                        _renderTarget.WritePixel(rasterization[i][j][k].X, rasterization[i][j][k].Y, whiteColor);
                    }
                }
            }

            return(_renderTarget);
        }
Example #22
0
        private GenericVector ConvertToRList(VmResourceTrace trace)
        {
            var list = new GenericVector(R, 3);

            list.SetNames("vmId", "resourceId", "series");
            list["vmId"]       = new IntegerVector(R, new int[] { trace.VmId });
            list["resourceId"] = new IntegerVector(R, new int[] { (int)trace.Resource });
            list["series"]     = new NumericVector(R, trace.Series.Select(f => (double)(f)));
            return(list);
        }
Example #23
0
    public static GenericVector ToGenericVector(this Dictionary <int, int> dictionary)
    {
        var newGenericVector = new GenericVector();

        foreach (var keyValue in dictionary)
        {
            newGenericVector.Add(keyValue.Value);
        }
        return(newGenericVector);
    }
Example #24
0
    //STATIC GENERICVECTOR METHODS
    public static float DotProduct(GenericVector vectorA, GenericVector vectorB)
    {
        if (vectorA.Size != vectorB.Size)
        {
            throw new Exception("GenericVector a size of dotProduct not equal to GenericVector b size");
        }
        var aTimesBpoints = vectorA.Points.Select((t, i) => t * vectorB.Points[i]).ToList();

        return(aTimesBpoints.Sum());
    }
Example #25
0
    public static float GetAngle(GenericVector a, GenericVector b)
    {
        var x = DotProduct(a, b) / (a.VectorLength() * b.VectorLength());

        if (x > 1 || x < -1)
        {
            return(0);
        }
        return((float)Math.Acos(x));
    }
Example #26
0
 //---------------------------------------------------------------------
 public void CopyFromByteArray(byte[] Bytes_in)
 {
     using (MemoryStream buffer = new MemoryStream(Bytes_in))
     {
         BinaryFormatter   formatter = new BinaryFormatter();
         GenericVector <T> vector    = (GenericVector <T>)formatter.Deserialize(buffer);
         this.CopyFromArray(vector.ToArray());
         buffer.Close();
     }
     return;
 }
        private GenericVector[] GetPolynomialPoints()
        {
            var polyPoints = new GenericVector[_data.Length];

            for (var i = 0; i < _data.Length; i++)
            {
                polyPoints[i] = new GenericVector(_data[i].X, ComputePolynomialPointY(_data[i].X));
            }

            return(polyPoints);
        }
Example #28
0
        public void TestGenericVector()
        {
            var a = new GenericVector(4, 4);
            var b = new GenericVector(6, 6);

            Assert.Equal(GenericVector.Distance(a, b), Math.Sqrt(8.0));

            var c = GenericVector.Sum(a, new GenericVector(6, 6));
            var d = GenericVector.Sum(b, new GenericVector(4, 4));

            Assert.Equal(GenericVector.Distance(c, d), 0);
        }
Example #29
0
        private VmResourceForecast ReadRList(GenericVector row)
        {
            var forecasts = new[] { "arima", "ses", "crost", "holt", "dholt" }
            .ToDictionary(x => x, method => ParseForecastResult(row[method].AsList()))
            .Where(p => p.Value.Any())
            .ToDictionary(p => p.Key.ToUpper(), p => p.Value);

            return(new VmResourceForecast(
                       row["vmId"].AsInteger()[0],
                       (Resource)row["resourceId"].AsInteger()[0],
                       forecasts));
        }
Example #30
0
    public void Sum(GenericVector vectorToSum)
    {
        if (Size != vectorToSum.Size)
        {
            throw new Exception("GenericVector size of vectorToSum not equal to instance vector size");
        }

        for (var i = 0; i < Points.Count; i++)
        {
            Points[i] = Points[i] + vectorToSum.Points[i];
        }
    }
Example #31
0
        /// <summary>
        /// Executes the function. Match the function arguments by name.
        /// </summary>
        /// <param name="argNames">The names of the arguments. These can be empty strings for unnamed function arguments</param>
        /// <param name="args">The arguments passed to the function</param>
        /// <returns></returns>
        protected SymbolicExpression InvokeViaPairlist(string[] argNames, SymbolicExpression[] args)
        {
            var names = new CharacterVector(Engine, argNames);
            var arguments = new GenericVector(Engine, args);
            arguments.SetNames(names);
            var argPairList = arguments.ToPairlist();

            //IntPtr newEnvironment = Engine.GetFunction<Rf_allocSExp>()(SymbolicExpressionType.Environment);
            //IntPtr result = Engine.GetFunction<Rf_applyClosure>()(Body.DangerousGetHandle(), handle,
            //                                                      argPairList.DangerousGetHandle(),
            //                                                      Environment.DangerousGetHandle(), newEnvironment);
            return createCallAndEvaluate(argPairList.DangerousGetHandle());
        }
Example #32
0
 /// <summary>
 /// Creates a new object dealing with the dynamic and binding logic for R lists
 /// </summary>
 /// <param name="parameter">The expression representing this new ListDynamicMeta in the binding process</param>
 /// <param name="list">The runtime value of the GenericVector, that this new ListDynamicMeta represents</param>
 public ListDynamicMeta(System.Linq.Expressions.Expression parameter, GenericVector list)
     : base(parameter, list)
 { }
Example #33
0
 private static void ReproWorkitem43(REngine engine)
 {
     Random r = new Random(0);
      int N = 500;
      int n1 = 207;
      int n2 = 623;
      var arGroup1Intensities = new double[N][];
      var arGroup2Intensities = new double[N][];
      for (int i = 0; i < N; i++)
      {
     arGroup1Intensities[i] = new double[n1];
     arGroup2Intensities[i] = new double[n2];
     for (int j = 0; j < n1; j++)
        arGroup1Intensities[i][j] = r.NextDouble();
     for (int j = 0; j < n2; j++)
        arGroup2Intensities[i][j] = r.NextDouble();
      }
      var res = new GenericVector[N];
      NumericVector vGroup1, vGroup2;
      for (int i = 0; i < N; i++)
      {
     vGroup1 = engine.CreateNumericVector(arGroup1Intensities[i]);
     Console.WriteLine(vGroup1.Length);
     if (i % 10 == 4)
     {
        engine.ForceGarbageCollection();
        engine.ForceGarbageCollection();
     }
     vGroup2 = engine.CreateNumericVector(arGroup2Intensities[i]);
     Console.WriteLine(vGroup2.Length);
     engine.SetSymbol("group1", vGroup1);
     engine.SetSymbol("group2", vGroup2);
     GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
     res[i] = testResult;
      }
 }