/// <summary>
        /// Executes the program
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            using (var s = RConnection.Connect(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 })))
            {
                // Generate some example data
                var x = Enumerable.Range(1, 20).ToArray();
                var y = (from a in x select(0.5 * a * a) + 2).ToArray();

                // Build an R data frame
                var d = Sexp.MakeDataFrame();
                d["x"] = Sexp.Make(x);
                d["y"] = Sexp.Make(y);
                s["d"] = d;

                // Run a linear regression, obtain the summary, and print the result
                s.VoidEval("linearModelSummary = summary(lm(y ~ x, d))");
                var coefs    = s["linearModelSummary$coefficients"];
                var rSquared = s["linearModelSummary$r.squared"].AsDouble;
                Console.WriteLine("y = {0} x + {1}. R^2 = {2,4:F}%", coefs[1, 0], coefs[0, 0], rSquared * 100);

                // Now let's do some linear algebra
                var matA = new double[, ] {
                    { 14, 9, 3 }, { 2, 11, 15 }, { 0, 12, 17 }, { 5, 2, 3 }
                };
                var matB = new double[, ] {
                    { 12, 25 }, { 9, 10 }, { 8, 5 }
                };
                s["a"] = Sexp.Make(matA);
                s["b"] = Sexp.Make(matB);
                Console.WriteLine(s["a %*% b"].ToString());
            }
            Console.WriteLine("Done");
        }
        private void ReConnectToRserve()
        {
            while (RserveToken != null && !RserveToken.IsCancellationRequested)
            {
                try
                {
                    if (Connection == null)
                    {
                        string userLogString = "empty user";
                        if (Parameter.Credentials != null)
                        {
                            userLogString = Parameter.User;
                        }

                        RConnection con = null;
                        if (Parameter.UseIpAddress)
                        {
                            con = RConnection.Connect(Parameter.IpAddress, Parameter.Port, Parameter.Credentials);
                            logger.Info($"Connected to RServe {Parameter.IpAddress}:{Parameter.Port} with user ({userLogString})");
                        }
                        else
                        {
                            con = RConnection.Connect(Parameter.Hostname, Parameter.Port, Parameter.Credentials);
                            logger.Info($"Connected to RServe {Parameter.Hostname}:{Parameter.Port} with user ({userLogString})");
                        }
                        Thread.Sleep(150);

                        //Load Workspace
                        if (!String.IsNullOrWhiteSpace(Parameter.InitScript))
                        {
                            logger.Debug("Sending InitScript to Rserve...");
                            con.Eval(Parameter.InitScript);
                            logger.Debug("...InitScript done");
                        }
                        Connection = con;
                    }

                    if (!Connection.IsConnected())
                    {
                        Connection = null;
                    }
                }
                catch (SocketException ex)
                {
                    logger.Error($"Reconnect to Rserve failed (Socket error): {ex.Message}");
                    Connection = null;
                }
                catch (Exception ex)
                {
                    logger.Error($"Reconnect to Rserve failed: {ex.Message}");
                    Connection = null;
                }
                finally
                {
                    Thread.Sleep(5000);
                }
            }
        }
Example #3
0
        /// <summary>
        /// Creates a self-hosted Rserve.
        /// </summary>
        /// <param name="showWindow">If true then the Rserve window will be visible.  Useful for debugging.  Default is false.</param>
        /// <param name="maxInputBufferSizeInKb">The maximal allowable size of the input buffer in kilobytes.  That is, the maximal size of data transported from the client to the server.</param>
        public Rservice(bool showWindow = false, int maxInputBufferSizeInKb = 0)
        {
            // ReSharper disable AssignNullToNotNullAttribute
#if RTERM_PROCESS
            var    codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            var    is64BitOperatingSystem = Environment.Is64BitOperatingSystem;
            string assemblyDir            = new Uri(Path.GetDirectoryName(codeBase)).AbsolutePath;
            // ReSharper restore AssignNullToNotNullAttribute
            string rExeFilePath = Path.Combine(assemblyDir, "R-2.15.3", "bin", is64BitOperatingSystem ? "x64" : "i386", "Rterm.exe");

            // the only way to set maxinbuf is via configuration file
            // generate a config file and reference it as part of the args parameter to Rserve() below
            string args = "";
            if (maxInputBufferSizeInKb > 0)
            {
                string configFile = Path.GetTempFileName();
                // plaintext warning only shows when using a config file.  setting plaintext enable to eliminate the warning
                File.WriteAllText(configFile, "maxinbuf " + maxInputBufferSizeInKb + "\r\n" + "plaintext enable");
                args = string.Format(", args = '--RS-conf {0}' ", configFile.Replace(@"\", "/"));
            }

            // launch RTerm and tell it load Rserve.
            // Keep RTerm open, otherwise the child process will be killed.
            // We will use CmdShutdown to stop the server
            // ReSharper disable UseObjectOrCollectionInitializer
            _rtermProcess = new Process();
            _rtermProcess.StartInfo.FileName        = rExeFilePath;
            _rtermProcess.StartInfo.Arguments       = string.Format("--no-site-file --no-init-file --no-save -e \"library( Rserve ); Rserve( port = {0} , wait = TRUE {1});\"", Port, args);
            _rtermProcess.StartInfo.UseShellExecute = false;
            _rtermProcess.StartInfo.CreateNoWindow  = !showWindow;
            _rtermProcess.Start();
            Thread.Sleep(3000);
            // ReSharper restore UseObjectOrCollectionInitializer
#endif
            string hostname = "localhost";

            // create a connection to the server
            // ReSharper disable RedundantArgumentDefaultValue
            RConnection = RConnection.Connect(port: Port, hostname: hostname);
            // ReSharper restore RedundantArgumentDefaultValue
        }
Example #4
0
        private static Boolean SendMessage(Server server, String message)
        {
            var con = new RConnection();

            con.HostName          = server.Host;
            con.Port              = (ushort)server.Port;
            con.PlaintextPassword = server.Password;

            con.Connect();

            while (!con.Client.Connected)
            {
                System.Threading.Thread.Sleep(200);
            }
            con.Login();
            con.Command("admin.say", message, "all");
            System.Threading.Thread.Sleep(200);
            con.Shutdown();

            return(true);
        }
Example #5
0
        private void RunClient()
        {
            Connection.Connect();

            while (Connection.Client.Connected == true)
            {
                // Reconnect logic should be here later on

                #region Shutdown app
                String messageInput = Console.ReadLine();
                if (String.Compare(messageInput, "exit", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    Connection.Shutdown();
                }
                else
                {
                    Connection.Command(messageInput.Wordify());
                }
                #endregion
            }

            //Console.WriteLine("{0} {1}", DateTime.Now, "[INFO] - Lost connection to game server");
        }
 public RServeClient(string servername)
 {
     _rconnection = RConnection.Connect(servername);
 }