public static void barchart_months_revenue(this REngine engine) { //# Create the data for the chart. // H < -c(7, 12, 28, 3, 41) //M < -c("一月", "二月", "三月", "四月", "五月") //# Give the chart file a name. //png(file = "barchart_months_revenue.png") //# Plot the bar chart. //barplot(H, names.arg = M, xlab = "月份", ylab = "收入量", col = "blue", //main = "收入图表", border = "red") //# Save the file. //dev.off() var numVer = engine.CreateNumericVector(new double[] { 110, 300, 390, 200 }); var charVer = engine.CreateCharacterVector(new string[] { "一月", "二月", "三用", "四月" }); var mainChar = engine.CreateCharacter("收入图表"); engine.SetSymbol("H", numVer); engine.SetSymbol("M", charVer); engine.SetSymbol("name", mainChar); engine.Evaluate("png(file = 'barchart_months_revenue.jpg')"); engine.Evaluate("barplot(H,names.arg=M,xlab='月份',ylab='收入量',col='blue',main=name,border='red')"); engine.Evaluate("dev.off()"); }
/// <summary> /// 设置R语言的工作目录 /// </summary> public static void SetWd(this REngine engine, Func <string> wdPath = null) { var path = wdPath != null ? (wdPath() ?? string.Empty) : AppDomain.CurrentDomain.BaseDirectory; var pathchar = engine.CreateCharacter(path); engine.ExecFunction(pathchar, "setwd"); }
public static List <string> CreateCharacterVar(string svarname, string svalue) { try { REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); CharacterVector charVec = engine.CreateCharacter(svalue); engine.SetSymbol(svarname, charVec); List <string> lerrmsg = new List <string> { "\nCreated R variable named " + svarname }; return(lerrmsg); } catch (Exception e) { string errmsg = "\nException encountered while set R variable :" + svarname + "\n"; errmsg += "\nError message :\n" + e.Message + "\n" + e.StackTrace + "\n"; if (e.InnerException != null) { errmsg += "InnerException\n" + e.InnerException.Message + "\n" + e.InnerException.StackTrace + "\n"; } List <string> lerrmsg = new List <string> { errmsg }; return(lerrmsg); } }
/// <summary> /// /// </summary> /// <param name="engine"></param> public static void Age_title_colours(this REngine engine) { //# Create data for the graph. // x < -c(11, 30, 39, 20) //labels < -c("70后", "80后", "90后", "00后") //# Give the chart file a name. //png(file = "age_title_colours.jpg") //# Plot the chart with title and rainbow color pallet. //pie(x, labels, main = "出生年龄段 - 饼状图", col = rainbow(length(x))) //# Save the file. //dev.off() var numVer = engine.CreateNumericVector(new double[] { 11, 30, 39, 20 }); var charVer = engine.CreateCharacterVector(new string[] { "70后", "80后", "90后", "00后" }); var mainChar = engine.CreateCharacter("出生年龄段 - 饼状图"); engine.SetSymbol("x", numVer); engine.SetSymbol("labels", charVer); engine.SetSymbol("main", mainChar); var length = engine.Evaluate("rainbow(length(x))"); engine.SetSymbol("col", length); engine.Evaluate("png(file = 'age_title_colours.jpg')"); engine.Evaluate("pie(x,labels,main=main,col = col)"); engine.Evaluate("dev.off()"); }
public void Run() { if (_targetInstrumentName == null || _matchInstrumentName == null || _targetSampleList == null || _matchSampleList == null) { throw new ArgumentNullException("参数未设置"); } engine.SetSymbol("target", engine.CreateCharacter(_targetInstrumentName)); engine.SetSymbol("match", engine.CreateCharacter(_matchInstrumentName)); engine.SetSymbol("filename", engine.CreateCharacter(_imagePath)); engine.SetSymbol("检测系统A结果", engine.CreateNumericVector(_targetSampleList)); engine.SetSymbol("检测系统B结果", engine.CreateNumericVector(_matchSampleList)); engine.Evaluate("source('" + _scriptPath + "')"); }
private void SetupDotNetToRConverters() { SetupDotNetToRConverter(typeof(void), p => null); SetupDotNetToRConverter(typeof(string), p => engine.CreateCharacter((string)p)); SetupDotNetToRConverter(typeof(string[]), p => engine.CreateCharacterVector((string[])p)); SetupDotNetToRConverter(typeof(List <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(IList <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(ICollection <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(IEnumerable <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(string[, ]), p => engine.CreateCharacterMatrix((string[, ])p)); SetupDotNetToRConverter(typeof(int), p => engine.CreateInteger((int)p)); SetupDotNetToRConverter(typeof(int[]), p => engine.CreateIntegerVector((int[])p)); SetupDotNetToRConverter(typeof(List <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(IList <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(ICollection <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(IEnumerable <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(int[, ]), p => engine.CreateIntegerMatrix((int[, ])p)); SetupDotNetToRConverter(typeof(bool), p => engine.CreateLogical((bool)p)); SetupDotNetToRConverter(typeof(bool[]), p => engine.CreateLogicalVector((bool[])p)); SetupDotNetToRConverter(typeof(List <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(IList <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(ICollection <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(IEnumerable <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(bool[, ]), p => engine.CreateLogicalMatrix((bool[, ])p)); SetupDotNetToRConverter(typeof(double), p => engine.CreateNumeric((double)p)); SetupDotNetToRConverter(typeof(double[]), p => engine.CreateNumericVector((double[])p)); SetupDotNetToRConverter(typeof(List <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(IList <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(ICollection <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(IEnumerable <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(double[, ]), p => engine.CreateNumericMatrix((double[, ])p)); SetupDotNetToRConverter(typeof(DateTime), p => engine.CreatePosixct((DateTime)p)); SetupDotNetToRConverter(typeof(DateTime[]), p => engine.CreatePosixctVector((DateTime[])p)); SetupDotNetToRConverter(typeof(List <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(IList <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(ICollection <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(IEnumerable <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(DateTime[, ]), p => engine.CreatePosixctMatrix((DateTime[, ])p)); SetupDotNetToRConverter(typeof(TimeSpan), p => engine.CreateDiffTime((TimeSpan)p)); SetupDotNetToRConverter(typeof(TimeSpan[]), p => engine.CreateDiffTimeVector((TimeSpan[])p)); SetupDotNetToRConverter(typeof(List <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(IList <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(ICollection <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(IEnumerable <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(TimeSpan[, ]), p => engine.CreateDiffTimeMatrix((TimeSpan[, ])p)); }
public static void Barchart(this REngine engine) { // H < -c(7, 12, 28, 3, 41) //# Give the chart file a name. //png(file = "barchart.png") //# Plot the bar chart. //barplot(H) //# Save the file. //dev.off() var numVer = engine.CreateNumericVector(new double[] { 11, 30, 39, 20 }); var charVer = engine.CreateCharacterVector(new string[] { "70后", "80后", "90后", "00后" }); var mainChar = engine.CreateCharacter("出生年龄段 - 饼状图"); engine.SetSymbol("H", numVer); engine.Evaluate("png(file = 'barchart.jpg')"); engine.Evaluate("barplot(H)"); engine.Evaluate("dev.off()"); }
/// <summary> /// 打印字符串 /// </summary> /// <param name="engine"></param> /// <param name="content"></param> public static void Print(this REngine engine, string content) { engine.Print(engine.CreateCharacter(content)); }
/// <summary> /// 读取Csv文件 /// </summary> public static SymbolicExpression ReadCsv(this REngine engine, string csvFileName) { var csvName = engine.CreateCharacter(csvFileName); return(engine.ExecFunction(csvName, "read.csv")); }
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; } } }
static void Main(string[] args) { var scriptFile = @"C:\projects\Hackathon\crmcognitive\R-scripts\Data_Grouping.r"; var jsonResponse = @"C:\projects\Hackathon\crmcognitive\R-scripts\output10json.txt"; if (args.Length > 0) { scriptFile = args[0]; jsonResponse = args[1]; } Console.Write("click to start ..."); Console.ReadKey(); REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); engine.Initialize(); string text = File.ReadAllText(scriptFile); var myFunc = engine.Evaluate(text).AsFunction(); var v1 = engine.CreateCharacter(jsonResponse); var df = myFunc.Invoke(new SymbolicExpression[] { v1 }).AsDataFrame(); var dt = RDataFrameToDataSet(df); string[] cols; string[,] vals; string test = ""; var valueStrings = new string[df.RowCount]; var arrValueStrings = new string[1, df.RowCount]; var strList = new List <string>(); for (var i = 0; i < df.RowCount; i++) { for (var j = 0; j < df.ColumnCount; j++) { test = test + Convert.ToString(df[j][i]) + ","; } test = test.Remove(test.Length - 1, 1); valueStrings[i] = test; strList.Add(test); test = ""; } for (var x = 0; x < valueStrings.Length; x++) { arrValueStrings[0, x] = valueStrings[x]; } var arrString = strList.ToArray(); //Values = new string[,] { {Convert.ToString(valueStrings[0])} }; var strArr = new List <string[]> { valueStrings }; var splitStrArr = strArr.ToArray(); Console.Write("click to finish ..."); Console.ReadKey(); }
public DataTable getCorpTable(string Rname, int stocknum) { engine.Initialize(); string fullRFilePath = Path.Combine(currentPath, Rname + ".R"); if (!File.Exists(fullRFilePath)) { return(null); } var curPath = engine.CreateCharacter(currentPath); engine.SetSymbol("stocknum", engine.CreateInteger(stocknum)); engine.SetSymbol("curPath", curPath); engine.Evaluate("setwd(curPath)"); engine.Evaluate(String.Format("source(\"{0}\")", Rname + ".R")); DataFrame output = engine.GetSymbol("output").AsDataFrame(); DataTable table = new DataTable(); table.Columns.Add("Included", typeof(bool)); foreach (var name in output.ColumnNames) { Type t; switch (output[name].Type) { case SymbolicExpressionType.NumericVector: t = typeof(double); break; case SymbolicExpressionType.IntegerVector: t = typeof(Int32); break; case SymbolicExpressionType.CharacterVector: t = typeof(string); break; case SymbolicExpressionType.LogicalVector: t = typeof(bool); break; case SymbolicExpressionType.RawVector: t = typeof(byte); break; default: t = null; break; } table.Columns.Add(name); if (t != null) { table.Columns[name].DataType = t; } } foreach (DataFrameRow row in output.GetRows()) { DataRow newRow = table.Rows.Add(); newRow["Included"] = true; foreach (var name in output.ColumnNames) { if ((output[name].Type == SymbolicExpressionType.NumericVector || output[name].Type == SymbolicExpressionType.IntegerVector) && !(name.Contains("현재가") || name.Contains("배당") || name.Contains("RANK"))) { newRow[name] = (double.Parse(row[name].ToString())) / 1e8; } else { newRow[name] = row[name]; } } } return(table); }