Example #1
0
        static void Main(string[] args)
        {
            DataTable dtb = new DataTable();

            dtb.Columns.Add("Column1", Type.GetType("System.String"));
            dtb.Columns.Add("Column2", Type.GetType("System.String"));
            DataRow dtr1 = dtb.NewRow();

            dtr1[0] = "abc";
            dtr1[1] = "cdf";
            dtb.Rows.Add(dtr1);
            DataRow dtr2 = dtb.NewRow();

            dtr2[0] = "asdasd";
            dtr2[1] = "cdasdasf";
            dtb.Rows.Add(dtr2);

            using (var engine = REngine.GetInstance())
            {
                string[,] stringData = new string[dtb.Rows.Count, dtb.Columns.Count];
                for (int row = 0; row < dtb.Rows.Count; row++)
                {
                    for (int col = 0; col < dtb.Columns.Count; col++)
                    {
                        stringData[row, col] = dtb.Rows[row].ItemArray[col].ToString();
                    }
                }
                CharacterMatrix matrix = engine.CreateCharacterMatrix(stringData);
                engine.SetSymbol("myRDataFrame", matrix);
                engine.Evaluate("myRDataFrame <- as.data.frame(myRDataFrame, stringsAsFactors = FALSE)");
                engine.Evaluate("str(myRDataFrame)");
            }
            Console.ReadKey();
        }
Example #2
0
        static string Traverse(CharacterMatrix matrix, Point pos, Size direction)
        {
            StringBuilder sb = new StringBuilder();

            while (matrix.IsInside(pos))
            {
                sb.Append(matrix.GetChar(pos));
                pos += direction;
            }
            return(sb.ToString());
        }
Example #3
0
        static void Main(string[] args)
        {
            List <string> candidates = null;

            Performance.Benchmark("Read and search", () =>
            {
                var matrix = new CharacterMatrix(TextFile.ReadStringList("matrix.txt"));
                candidates = TextFile.ReadStringList("wordlist.txt");
                EliminateWords(matrix, candidates);
                candidates.Sort();
            }, 10, 10);
            Console.WriteLine(string.Join(',', candidates));
        }
        /// <summary>
        /// Returns 2D string array from given R.Net CharacterMatrix
        /// (this is a patch because RDotNet.CharacterMatrix.GetArrayFast is not implemented)
        /// </summary>
        /// <param name="mat"></param>
        /// <returns></returns>
        private static string[,] CharacterMatrixToStringArray(CharacterMatrix mat)
        {
            var r = mat.RowCount;
            var c = mat.ColumnCount;
            var z = new string[r, c];

            for (var ri = 0; ri < r; ri++)
            {
                for (var ci = 0; ci < c; ci++)
                {
                    z[ri, ci] = mat[ri, ci];
                }
            }
            return(z);
        }
Example #5
0
        private static List <string> FindAllStrings(CharacterMatrix matrix)
        {
            List <string> allStrings = new List <string>();

            //horisontal
            allStrings.AddRange(matrix.Lines);

            //vertical
            Size down = new Size(0, 1);

            for (int x = 0; x < matrix.Width; x++)
            {
                allStrings.Add(Traverse(matrix, new Point(x, 0), down));
            }

            //diag down
            Size diagDown = new Size(1, 1);

            for (int y = matrix.Height - 1; y > 0; y--)
            {
                allStrings.Add(Traverse(matrix, new Point(0, y), diagDown));
            }
            for (int x = 0; x < matrix.Width; x++)
            {
                allStrings.Add(Traverse(matrix, new Point(x, 0), diagDown));
            }

            //diag up
            Size diagUp = new Size(1, -1);

            for (int y = matrix.Height - 2; y >= 0; y--)
            {
                allStrings.Add(Traverse(matrix, new Point(0, y), diagUp));
            }
            for (int x = 0; x < matrix.Width; x++)
            {
                allStrings.Add(Traverse(matrix, new Point(x, matrix.Height - 1), diagUp));
            }

            return(allStrings);
        }
Example #6
0
        private static void EliminateWords(CharacterMatrix matrix, List <string> candidates)
        {
            List <string> strings = null;

            strings = FindAllStrings(matrix);

            Dictionary <string, string> reverseMap = new Dictionary <string, string>();

            foreach (var str in candidates)
            {
                reverseMap.Add(str, Reverse(str));
            }

            foreach (var kvp in reverseMap)
            {
                if (FindString(strings, kvp.Key, kvp.Value))
                {
                    candidates.Remove(kvp.Key);
                }
            }
        }
        private void runTask()
        {
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string mapPath = basedir + "/tmp/";
//            string mapPath = HttpContext.Current.Server.MapPath("~/tmp/");
            REngine engine          = Utils.getREngineInstance();
            string  primer3path     = System.Web.Configuration.WebConfigurationManager.AppSettings["primer3Home"];
            string  processNum      = System.Web.Configuration.WebConfigurationManager.AppSettings["processNum"];
            string  isDeleteTempDir = System.Web.Configuration.WebConfigurationManager.AppSettings["deleteTempDir"];

            while (true)
            {
                if (task_queue.Count != 0)
                {
                    Application.Lock();
                    CustomTask customTask = (CustomTask)task_queue.Dequeue();
                    Application.UnLock();
                    customTask.waitQueue = 0;
                    Object[] task_queue_array = task_queue.ToArray();
                    for (int i = 0; i < task_queue_array.Length; i++)
                    {
                        CustomTask tmpTask = (CustomTask)task_queue_array[i];
                        tmpTask.waitQueue = i + 1;
                    }
                    Application["running_task"] = customTask;
                    string fileName = customTask.url;
                    fileName = basedir + "/" + customTask.url;
                    DataTable dt = read_primer_sequence(fileName);
                    string[,] primerMat = getPrimerMat(dt);
                    customTask.status   = "preparing ...";
                    WriteLog(customTask.key, customTask);
                    CharacterMatrix primer    = engine.CreateCharacterMatrix(primerMat);
                    string          rand_file = System.IO.Path.GetRandomFileName();
                    string          tmp_path  = mapPath + rand_file;
                    //string primer3path = "D:/Install/primer3-win-bin-2.3.6";

                    if (Directory.Exists(tmp_path))
                    {
                        DirectoryInfo di = new DirectoryInfo(tmp_path);
                        di.Delete(true);
                    }
                    else if (File.Exists(tmp_path))
                    {
                        FileInfo fi = new FileInfo(tmp_path);
                        fi.Delete();
                    }
                    Directory.CreateDirectory(tmp_path);
                    engine.Evaluate("library(xlsx)");
                    customTask.percent = 8;
                    string script_path = basedir + "/primer_dimer_check.R";
                    script_path = script_path.Replace(@"\", @"/");
                    engine.Evaluate("source(\"" + script_path + "\")");
                    customTask.percent = 10;
                    engine.SetSymbol("primer", primer);
                    engine.SetSymbol("tmp_dir", engine.CreateCharacter(tmp_path));
                    engine.SetSymbol("primer", primer);
                    engine.SetSymbol("primer3dir", engine.CreateCharacter(primer3path));
                    int?nProcess = Convert.ToInt32(processNum);
                    if (nProcess != null)
                    {
                        engine.SetSymbol("nprocess", engine.CreateInteger(Convert.ToInt32(nProcess)));
                    }
                    else
                    {
                        engine.SetSymbol("nprocess", engine.CreateInteger(4));
                    }
                    engine.SetSymbol("outputfile", engine.CreateCharacter(fileName));
                    string[] bat_cmds = engine.Evaluate("prepare_bat(tmp_dir,primer,primer3dir,nprocess)").AsCharacter().ToArray();
                    customTask.status  = "dimer calculating ...";
                    customTask.percent = 20;
                    WriteLog(customTask.key, customTask);
                    AutoResetEvent[] resets = new AutoResetEvent[bat_cmds.Length];

                    for (int i = 0; i < bat_cmds.Length; i++)
                    {
                        resets[i] = new AutoResetEvent(false);
                        Global.ThreadTransfer transfer = new Global.ThreadTransfer(bat_cmds[i], resets[i]);
                        Thread thread = new Thread(new ParameterizedThreadStart(run_cmd));
                        thread.Start(transfer);
                    }
                    foreach (var v in resets)
                    {
                        v.WaitOne();
                        customTask.percent += 60 / resets.Length;
                    }
                    customTask.status  = "result generating ...";
                    customTask.percent = 80;
                    WriteLog(customTask.key, customTask);
                    engine.Evaluate("output_result(tmp_dir,primer,outputfile)");
                    if (isDeleteTempDir == "true")
                    {
                        DirectoryInfo di = new DirectoryInfo(tmp_path);
                        di.Delete(true);
                    }
                    customTask.status  = "complete";
                    customTask.percent = 100;
                    WriteLog(customTask.key, customTask);


                    Application["running_task"] = null;
                }
            }
        }
        /// <summary>
        /// Converts the specified expression to a CharacterMatrix.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>The CharacterMatrix. Returns <c>null</c> if the specified expression is not vector.</returns>
        public static CharacterMatrix AsCharacterMatrix(this SymbolicExpression expression)
        {
            if (!expression.IsVector())
            {
                return null;
            }

            int rowCount = 0;
            int columnCount = 0;

            if (expression.IsMatrix())
            {
                if (expression.Type == SymbolicExpressionType.CharacterVector)
                {
                    return new CharacterMatrix(expression.Engine, expression.DangerousGetHandle());
                }
                else
                {
                    rowCount = expression.GetFunction<Rf_nrows>()(expression.DangerousGetHandle());
                    columnCount = expression.GetFunction<Rf_ncols>()(expression.DangerousGetHandle());
                }
            }

            if (columnCount == 0)
            {
                rowCount = expression.GetFunction<Rf_length>()(expression.DangerousGetHandle());
                columnCount = 1;
            }

            IntPtr coerced = expression.GetFunction<Rf_coerceVector>()(expression.DangerousGetHandle(), SymbolicExpressionType.CharacterVector);
            var dim = new IntegerVector(expression.Engine, new[] { rowCount, columnCount });
            SymbolicExpression dimSymbol = expression.Engine.GetPredefinedSymbol("R_DimSymbol");
            var matrix = new CharacterMatrix(expression.Engine, coerced);
            matrix.SetAttribute(dimSymbol, dim);
            return matrix;
        }
Example #9
0
        public static Dictionary <string, List <msMetabolite.stats.corrMetabs> > correlateMetabsToMetabs(string tissue)
        {
            //block (intercept) REngine from printing to the Console
            //we are just redirecting the output of it to some StringWriter
            var stdOut = Console.Out;

            Console.SetOut(new StringWriter());

            NumericMatrix ms = rEngineInstance.engine.CreateNumericMatrix(correlationMetabsMetabsMatrix(tissue));

            rEngineInstance.engine.SetSymbol("ms", ms);
            rEngineInstance.engine.Evaluate("df <- as.data.frame(ms)");

            rEngineInstance.engine.Evaluate("corr_res <- rcorr.adjust(ms, type = \"spearman\")");
            rEngineInstance.engine.Evaluate("print(corr_res$P)");
            CharacterMatrix padjust   = rEngineInstance.engine.Evaluate("corr_res$P").AsCharacterMatrix();
            CharacterMatrix punadjust = rEngineInstance.engine.Evaluate("corr_res$P.unadj").AsCharacterMatrix();
            NumericMatrix   c         = rEngineInstance.engine.Evaluate("corr_res$R$r").AsNumericMatrix();

            double[,] pNumAdjust   = new double[padjust.RowCount, padjust.ColumnCount];
            double[,] pNumUnadjust = new double[padjust.RowCount, padjust.ColumnCount];
            double ptmp;

            for (int i = 0; i < padjust.RowCount; i++)
            {
                for (int j = 0; j < padjust.ColumnCount; j++)
                {
                    //Adjusted
                    if (padjust[i, j] == "<.0001")
                    {
                        pNumAdjust[i, j] = 0.0001;
                    }
                    else if (Double.TryParse(padjust[i, j], out ptmp)) // if done, then is a number
                    {
                        pNumAdjust[i, j] = ptmp;
                    }
                    else
                    {
                        pNumAdjust[i, j] = 1;
                    }

                    //Undjusted
                    if (punadjust[i, j] == "<.0001")
                    {
                        pNumUnadjust[i, j] = 0.0001;
                    }
                    else if (Double.TryParse(punadjust[i, j], out ptmp)) // if done, then is a number
                    {
                        pNumUnadjust[i, j] = ptmp;
                    }
                    else
                    {
                        pNumUnadjust[i, j] = 1;
                    }
                }
            }

            List <string> metabNameList = new List <string>();

            foreach (string chrg in metaboliteLevels.List_SampleForTissueAndCharge.Where(x => x.Tissue == tissue).Select(x => x.Charge).Distinct())
            {
                metabNameList.AddRange(metaboliteLevels.List_SampleForTissueAndCharge.First(x => x.Tissue == tissue && x.Charge == chrg)
                                       .ListOfMetabolites.Select(x => x.mtbltDetails.In_customId + "_" + chrg).ToList());
            }

            Dictionary <string, List <msMetabolite.stats.corrMetabs> > dictOfResults = new Dictionary <string, List <msMetabolite.stats.corrMetabs> >();

            for (int i = 0; i < metabNameList.Count; i++)
            {
                dictOfResults.Add(metabNameList[i], new List <msMetabolite.stats.corrMetabs>());
                for (int j = 0; j < metabNameList.Count; j++)
                {
                    dictOfResults[metabNameList[i]].Add(new msMetabolite.stats.corrMetabs()
                    {
                        metab_id       = metabNameList[j],
                        corr_value     = c[i, j],
                        pValueAdjust   = pNumAdjust[i, j],
                        pValueUnadjust = pNumUnadjust[i, j]
                    });
                }
            }
            rEngineInstance.engine.Evaluate("rm(ms, df, corr_res)");
            //Re-enable Console printings
            Console.SetOut(stdOut);

            return(dictOfResults);
        }
Example #10
0
 /// <summary>
 /// Returns 2D string array from given R.Net CharacterMatrix
 /// (this is a patch beause  RDotNet.CharacterMatrix.GetArrayFast is not implemented)
 /// </summary>
 /// <param name="mat"></param>
 /// <returns></returns>
 private static string[,] CharacterMatrixToStringArray(CharacterMatrix mat)
 {
     var r = mat.RowCount;
     var c = mat.ColumnCount;
     var z = new string[r, c];
     for (var ri = 0; ri < r; ri++)
     {
         for (var ci = 0; ci < c; ci++)
         {
             z[ri, ci] = mat[ri, ci];
         }
     }
     return z;
 }
Example #11
0
        private void processOutput()
        {
            DataTable dt = GetFromMainForm();

            REngine.SetEnvironmentVariables();      //Mencari lokasi .dll R secara otomatis
            REngine engine = REngine.GetInstance(); //inisialisasi R

            List <double> t    = new List <double>();
            int           nkol = selectedListBox.Items.Count;
            int           kol1 = dt.Columns[selectedListBox.Items[0].ToString()].Ordinal;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                String row = dt.Rows[i].ItemArray[kol1].ToString();
                if (String.IsNullOrEmpty(row))
                {
                    break;
                }
                else
                {
                    double r = Convert.ToDouble(row);
                    t.Add(r);
                }
            }
            NumericVector u = engine.CreateNumericVector(t);

            engine.SetSymbol("matdt", u); //assign u in c# as matdt in R
            NumericMatrix matdata = engine.Evaluate("matdt").AsNumericMatrix();

            if (nkol > 1)
            {
                for (int j = 1; j < nkol; j++)
                {
                    //j = j + 1;
                    int           kol = dt.Columns[selectedListBox.Items[j].ToString()].Ordinal;
                    List <double> s   = new List <double>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        String row = dt.Rows[i].ItemArray[kol].ToString();
                        if (String.IsNullOrEmpty(row))
                        {
                            break;
                        }
                        else
                        {
                            double r = Convert.ToDouble(row);
                            s.Add(r);
                        }
                    }
                    String        nokol = Convert.ToString(j + 1);
                    NumericVector v     = engine.CreateNumericVector(s);
                    engine.SetSymbol("dum", v);
                    matdata = engine.Evaluate("matdt=matrix(cbind(matdt,dum),ncol=" + nokol + ")").AsNumericMatrix();
                }
            }
            int namekol = nameListBox.Items.Count;

            if (namekol != 0)
            {
                List <String> n        = new List <String>();
                int           namekol1 = dt.Columns[nameListBox.Items[0].ToString()].Ordinal;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    String row = dt.Rows[i].ItemArray[namekol1].ToString();
                    if (String.IsNullOrEmpty(row))
                    {
                        break;
                    }
                    else
                    {
                        n.Add(row);
                    }
                }
                CharacterVector a = engine.CreateCharacterVector(n);
                engine.SetSymbol("namedt", a);
                CharacterMatrix namedata = engine.Evaluate("namedt").AsCharacterMatrix();
                if (namekol > 1)
                {
                    for (int j = 1; j < nkol; j++)
                    {
                        //j = j + 1;
                        int           kol = dt.Columns[nameListBox.Items[j].ToString()].Ordinal;
                        List <String> s   = new List <String>();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            String row = dt.Rows[i].ItemArray[kol].ToString();
                            if (String.IsNullOrEmpty(row))
                            {
                                break;
                            }
                            else
                            {
                                s.Add(row);
                            }
                        }
                        String          nokol = Convert.ToString(j + 1);
                        CharacterVector v     = engine.CreateCharacterVector(s);
                        engine.SetSymbol("dum", v);
                        namedata = engine.Evaluate("namedt=matrix(cbind(namedt,dum),ncol=" + nokol + ")").AsCharacterMatrix();
                    }
                }
            }

            engine.Evaluate("m <- " + textBox_m.Text);
            CharacterVector m_ = engine.GetSymbol("m").AsCharacter();

            parname.Add("Fuzzifier (m)");
            parval.Add(m_[0]);

            engine.Evaluate("a <- " + textBox_konsa.Text);
            CharacterVector a_ = engine.GetSymbol("a").AsCharacter();

            parname.Add("a");
            parval.Add(a_[0]);

            engine.Evaluate("eta <- " + textBox_eta.Text);
            CharacterVector eta_ = engine.GetSymbol("eta").AsCharacter();

            parname.Add("Fuzzifier (η)");
            parval.Add(eta_[0]);

            engine.Evaluate("b <- " + textBox_konsb.Text);
            CharacterVector b_ = engine.GetSymbol("b").AsCharacter();

            parname.Add("b");
            parval.Add(b_[0]);

            engine.Evaluate("k <- " + textBox_konsk.Text);
            CharacterVector k_ = engine.GetSymbol("k").AsCharacter();

            parname.Add("K");
            parval.Add(k_[0]);

            String distance_text = listBox_distance.SelectedItem.ToString();

            //engine.Evaluate(@"distance <- """ + distance_text + "\"");
            engine.Evaluate(@"distance <- """ + distance_text + @"""");
            CharacterVector distance_ = engine.GetSymbol("distance").AsCharacter();

            parname.Add("Distance");
            parval.Add(distance_[0]);

            engine.Evaluate("c <- " + textBox_clus.Text);
            CharacterVector c_ = engine.GetSymbol("c").AsCharacter();

            parname.Add("Cluster");
            parval.Add(c_[0]);

            engine.Evaluate("loop <- " + textBox_maxiter.Text);
            CharacterVector loop_ = engine.GetSymbol("loop").AsCharacter();

            parname.Add("max PFCM loop");
            parval.Add(loop_[0]);

            engine.Evaluate("e <- " + textBox_error.Text);
            CharacterVector e_ = engine.GetSymbol("e").AsCharacter();

            parname.Add("Error criteria");
            parval.Add(e_[0]);

            engine.Evaluate("actualdata <- matdt");
            string bound_value = @"
             madt <- matrix(apply(matdt, 2, max),nrow = 1)
             midt <- matrix(apply(matdt, 2, min),nrow = 1)
            ";

            engine.Evaluate(bound_value);

            string path_source = Path.GetDirectoryName(Application.ExecutablePath);

            path_source = Path.Combine(path_source, "Main/PFCM.R");
            String pd_source      = path_source.Replace("\\", Regex.Escape("/"));
            String cdplot_source  = "";
            String apppath_source = pd_source + cdplot_source;

            engine.Evaluate("source('" + apppath_source + "')");

            String p_compute = @"
                       result <- pfcm(data = as.matrix(matdt), ncluster = c, m = m, eta = eta, K = k, a = a, b = b, distance = distance, max.iter = loop, error = e)
                        V <- result$centroid
                        U <- result$membership
                        loop <-result$max.iter
                        jf <- result$jf
                        actualcen = result$centroid
                        kel = result$finaldata[,1]
                        "

            ;

            var watch = Stopwatch.StartNew();

            engine.Evaluate(p_compute);

            NumericMatrix cen  = engine.GetSymbol("V").AsNumericMatrix();
            NumericMatrix loop = engine.GetSymbol("loop").AsNumericMatrix();

            parname.Add("Number of iteration");
            parval.Add((loop[0, 0] - 1).ToString());
            NumericMatrix lastof = engine.Evaluate("jf").AsNumericMatrix();

            parname.Add("Last objective function");
            parval.Add(lastof[0, 0].ToString());

            parname.Add("Computation time");
            parval.Add(watch.Elapsed.ToString());

            NumericMatrix actualdat = engine.GetSymbol("actualdata").AsNumericMatrix();
            NumericMatrix actualcen = engine.GetSymbol("actualcen").AsNumericMatrix();

            for (int i = 0; i < actualcen.ColumnCount; ++i)
            {
                center.Columns.Add();
            }
            for (int k = 0; k < actualcen.RowCount; ++k)
            {
                center.Rows.Add();
            }
            for (int i = 0; i < actualcen.RowCount; ++i)
            {
                for (int k = 0; k < actualcen.ColumnCount; ++k)
                {
                    center.Rows[i].SetField(k, actualcen[i, k]);
                }
            }

            NumericMatrix partmat = engine.Evaluate("U").AsNumericMatrix();

            if (namekol != 0)
            {
                DataFrame allpartmat = engine.Evaluate("data.frame(cbind(namedt,U))").AsDataFrame();
                for (int i = 0; i < allpartmat.ColumnCount; ++i)
                {
                    partition.Columns.Add();
                }
                for (int k = 0; k < allpartmat.RowCount; ++k)
                {
                    partition.Rows.Add();
                }
                for (int i = 0; i < allpartmat.RowCount; ++i)
                {
                    for (int k = 0; k < allpartmat.ColumnCount; ++k)
                    {
                        partition.Rows[i].SetField(k, allpartmat[i, k]);
                    }
                }
            }
            else
            {
                for (int i = 0; i < partmat.ColumnCount; ++i)
                {
                    partition.Columns.Add();
                }
                for (int k = 0; k < partmat.RowCount; ++k)
                {
                    partition.Rows.Add();
                }
                for (int i = 0; i < partmat.RowCount; ++i)
                {
                    for (int k = 0; k < partmat.ColumnCount; ++k)
                    {
                        partition.Rows[i].SetField(k, partmat[i, k]);
                    }
                }
            }

            String partcm = @"
    kelompok=matrix(ncol=1,nrow=nrow(U))
    for(i in 1:nrow(U)){
        kelompok[i,]=which.max(U[i,])
    }
    ";

            engine.Evaluate(partcm);
            NumericMatrix kelompok = engine.Evaluate("kelompok").AsNumericMatrix();

            //validity index

            this.vival  = new List <double>();
            this.viname = new List <String>();
            if (picheckBox.Checked)
            {
                engine.Evaluate(@"nPE <- result$validasi$EPE");
                NumericVector a = engine.GetSymbol("nPE").AsNumeric();
                vival.Add(a[0]);
                viname.Add("Partition Entropy");
            }

            if (xbcheckBox.Checked)
            {
                engine.Evaluate(@"nXB <- result$validasi$EXB");
                NumericVector a = engine.GetSymbol("nXB").AsNumeric();
                vival.Add(a[0]);
                viname.Add("Modified Partition Coefficient");
            }

            if (kwonbox.Checked)
            {
                engine.Evaluate(@"nKwon <- result$validasi$EKwon");
                NumericVector a = engine.GetSymbol("nKwon").AsNumeric();
                vival.Add(a[0]);
                viname.Add("Kwon");
            }

            String cm;

            if (namekol != 0)
            {
                cm = @"actualdata=data.frame(cbind(namedt,actualdata))
                    actualdata=cbind(actualdata,kelompok)";
                DataFrame allclust = engine.Evaluate(cm).AsDataFrame();
                for (int i = 0; i < allclust.ColumnCount; ++i)
                {
                    allclusters.Columns.Add();
                }
                for (int k = 0; k < allclust.RowCount; ++k)
                {
                    allclusters.Rows.Add();
                }

                for (int i = 0; i < allclust.RowCount; ++i)
                {
                    for (int k = 0; k < allclust.ColumnCount; ++k)
                    {
                        allclusters.Rows[i].SetField(k, allclust[i, k]);
                    }
                }
            }
            else
            {
                NumericMatrix allclust = engine.Evaluate("actualdata=cbind(actualdata,kelompok)").AsNumericMatrix();
                for (int i = 0; i < allclust.ColumnCount; ++i)
                {
                    allclusters.Columns.Add();
                }
                for (int k = 0; k < allclust.RowCount; ++k)
                {
                    allclusters.Rows.Add();
                }
                for (int i = 0; i < allclust.RowCount; ++i)
                {
                    for (int k = 0; k < allclust.ColumnCount; ++k)
                    {
                        allclusters.Rows[i].SetField(k, allclust[i, k]);
                    }
                }
            }

            if (namekol != 0)
            {
                isnamed = true;
            }
            else
            {
                isnamed = false;
            }

            if (plotcheckBox.Checked == true)
            {
                engine = REngine.GetInstance();
                engine.SetSymbol("data", actualdat);
                engine.SetSymbol("cluster", kelompok);
                string path_sourceR = Path.GetDirectoryName(Application.ExecutablePath);
                path_sourceR = Path.Combine(path_sourceR, "Main/fcm_distance.R");
                String pd_sourceR      = path_sourceR.Replace("\\", Regex.Escape("/"));
                String cdplot_sourceR  = "";
                String apppath_sourceR = pd_sourceR + cdplot_sourceR;
                engine.Evaluate("source('" + apppath_sourceR + "')");
                String script_cluster_plot = @"
    library(cluster)
    clusplot(data, cluster, color=TRUE, shade=TRUE,labels=0, lines=0,span=TRUE)
                ";

                String        script_facto = @"
dev.new()
library(factoextra)
library(FactoMineR)
bi <- bi.plot(data=data,cluster=kel)
    print(bi)
";
                NumericVector klaster      = engine.GetSymbol("c").AsNumeric();

                try
                {
                    //engine.Evaluate(script_cluster_plot);
                    //engine.Evaluate(script_ggplot);
                    if (klaster[0] <= 6)
                    {
                        engine.Evaluate(script_facto);
                    }
                    else
                    {
                        engine.Evaluate(script_cluster_plot);
                    }
                }
                catch
                {
                    MessageBox.Show("Failed to display plot");
                }
            }
            if (RadarPlotCheckBox.Checked == true)
            {
                engine = REngine.GetInstance();
                engine.SetSymbol("data", actualdat);
                engine.SetSymbol("cluster", kelompok);
                engine.Evaluate("c <- " + textBox_clus.Text);

                string path_sourceR = Path.GetDirectoryName(Application.ExecutablePath);
                path_sourceR = Path.Combine(path_sourceR, "Main/fcm_distance.R");
                String pd_sourceR      = path_sourceR.Replace("\\", Regex.Escape("/"));
                String cdplot_sourceR  = "";
                String apppath_sourceR = pd_sourceR + cdplot_sourceR;
                engine.Evaluate("source('" + apppath_sourceR + "')");

                String script_radar = @"
                dev.new()
                rad <- radarplot (data=data, cluster=kel)
                print(rad)
                ";
                try
                {
                    engine.Evaluate(script_radar);
                }
                catch
                {
                    MessageBox.Show("Failed to display plot");
                }
            }
            if (mapcheckBox.Checked == true && maptextBox.Text != null && datakeyListBox.ValueMember != null)
            {
                engine = REngine.GetInstance();
                engine.SetSymbol("data", actualdat);
                string sha = maptextBox.Text.ToString();
                string shp = Regex.Replace(sha, @"\\", @"/");
                engine.Evaluate("shp <- '" + shp + "'");
                List <string> dk = new List <string>();
                int           nk = datakeyListBox.Items.Count;
                int           k1 = dt.Columns[datakeyListBox.Items[0].ToString()].Ordinal;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    String row = dt.Rows[i].ItemArray[k1].ToString();
                    if (String.IsNullOrEmpty(row))
                    {
                        break;
                    }
                    else
                    {
                        string ll = Convert.ToString(row);
                        dk.Add(ll);
                    }
                }
                CharacterVector dtk = engine.CreateCharacterVector(dk);
                engine.SetSymbol("dk", dtk);
                string path_sourceR = Path.GetDirectoryName(Application.ExecutablePath);
                path_sourceR = Path.Combine(path_sourceR, "Main/fcm_distance.R");
                String pd_sourceR      = path_sourceR.Replace("\\", Regex.Escape("/"));
                String cdplot_sourceR  = "";
                String apppath_sourceR = pd_sourceR + cdplot_sourceR;
                engine.Evaluate("source('" + apppath_sourceR + "')");
                String script_map = @"                
                dev.new()
                ma <- mapping(data, kel, shp, dk)
                print(ma)
                ";
                engine.Evaluate(script_map);
            }
        }