Пример #1
0
		public RithmicClient(ILogReceiver receiver, string adminConnectionPoint, string certFile, string domainServerAddress, string domainName, string licenseServerAddress, string localBrokerAddress, string loggerAddress, string logFileName)
		{
			if (receiver == null)
				throw new ArgumentNullException(nameof(receiver));

			if (!File.Exists(certFile))
				throw new FileNotFoundException(LocalizedStrings.Str3457Params.Put(certFile));

			Callbacks = new RCallbacksImpl(this, receiver);

			var eParams = new REngineParams
			{
				AdmCnnctPt = adminConnectionPoint,
				AdmCallbacks = new AdmCallbacksImpl(this, receiver),
				AppName = "StockSharp",
				AppVersion = GetType().Assembly.GetName().Version.ToString(),
				CertFile = certFile,
				DmnSrvrAddr = domainServerAddress,
				DomainName = domainName,
				LicSrvrAddr = licenseServerAddress,
				LocBrokAddr = localBrokerAddress,
				LoggerAddr = loggerAddress,
				LogFilePath = logFileName,
			};

			Session = new REngine(eParams);
		}
Пример #2
0
        public bool Start(string user,string pw)
        {
            if (_connected)
                return true;
            try
            {
                // rithmic stuff
                setupparams();
                oEngine = new REngine(oParams);
                oEngine.login(this,
                    user,
                    pw,
                    MarketDataPt,
                    TsConnectPt,
                    string.Empty,
                    string.Empty);

                // tradelink stuff
                tl.newProviderName = Providers.Rithmic;
                tl.newAcctRequest += new StringDelegate(tl_newAcctRequest);
                tl.newFeatureRequest += new MessageArrayDelegate(tl_newFeatureRequest);
                tl.newOrderCancelRequest += new LongDelegate(tl_newOrderCancelRequest);
                tl.newPosList += new PositionArrayDelegate(tl_newPosList);
                tl.newRegisterSymbols += new SymbolRegisterDel(tl_newRegisterSymbols);
                tl.newSendOrderRequest += new OrderDelegateStatus(tl_newSendOrderRequest);
                tl.newUnknownRequest += new UnknownMessageDelegate(tl_newUnknownRequest);
                tl.SendDebugEvent+=new DebugDelegate(debug);

                _connected = LoggedIntoMd;

            }
            catch (Exception ex)
            {
                debug("error starting: " + ex.Message + ex.StackTrace);
            }

            return _connected;
        }
Пример #3
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

            pfrmProgress.lblStatus.Text    = "Processing:";
            pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
            pfrmProgress.Show();

            REngine pEngine = m_pForm.pEngine;
            // Creates the input and output matrices from the shapefile//
            string strLayerName = cboTargetLayer.Text;

            int    intLIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strLayerName);
            ILayer pLayer    = m_pForm.axMapControl1.get_Layer(intLIndex);

            IFeatureLayer pFLayer  = pLayer as IFeatureLayer;
            IFeatureClass pFClass  = pFLayer.FeatureClass;
            int           nFeature = pFClass.FeatureCount(null);

            IFeatureCursor pFCursor = pFLayer.Search(null, true);
            IFeature       pFeature = pFCursor.NextFeature();

            //Get index for independent and dependent variables
            //Get variable index
            string strVarNM1  = (string)cboFldnm1.SelectedItem;
            string strVarNM2  = (string)cboFldnm2.SelectedItem;
            int    intVarIdx1 = pFClass.FindField(strVarNM1);
            int    intVarIdx2 = pFClass.FindField(strVarNM2);

            //Store Variable at Array
            double[] arrVar1 = new double[nFeature];
            double[] arrVar2 = new double[nFeature];

            int i = 0;

            while (pFeature != null)
            {
                arrVar1[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx1));
                arrVar2[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx2));
                i++;
                pFeature = pFCursor.NextFeature();
            }

            pFCursor.Flush();

            //Plot command for R
            StringBuilder plotCommmand = new StringBuilder();

            string strStartPath = m_pForm.strPath;
            string pathr        = strStartPath.Replace(@"\", @"/");

            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_LARRY.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_neighbor.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_SASbi.R')");

            //Get the file path and name to create spatial weight matrix
            string strNameR = m_pSnippet.FilePathinRfromLayer(pFLayer);

            if (strNameR == null)
            {
                return;
            }

            //Create spatial weight matrix in R
            pEngine.Evaluate("library(spdep); library(maptools)");
            pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
            pEngine.Evaluate("sample.nb <- poly2nb(sample.shp)");

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

            pEngine.SetSymbol("sample.v1", vecVar1);
            NumericVector vecVar2 = pEngine.CreateNumericVector(arrVar2);

            pEngine.SetSymbol("sample.v2", vecVar2);

            string strRSigLv  = nudRsigLv.Value.ToString();
            string strLSigLv  = nudLsigLv.Value.ToString();
            string strLSig    = cboLocalL.Text;
            string strRsig    = cboLocalPearson.Text;
            string strRowStd  = cboRowStandardization.Text;
            string strNonZero = null;

            if (chkDiagZero.Checked)
            {
                strNonZero = "FALSE";
            }
            else
            {
                strNonZero = "TRUE";
            }

            pEngine.Evaluate("sample.result <- LARRY.bivariate.spatial.outlier(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, pearson.sig = " +
                             strRSigLv + ", lee.sig = " + strLSigLv + ", method.pearson = '" + strRsig + "', method.lee = '" +
                             strLSig + "', type.row.stand = '" + strRowStd + "', alternative = 'two', diag.zero = "
                             + strNonZero + ")");

            string[] strSPOutliers = pEngine.Evaluate("as.character(sample.result$sp.outlier)").AsCharacter().ToArray();

            //Save Output on SHP
            //Add Target fields to store results in the shapefile // Keep loop
            for (int j = 0; j < 1; j++)
            {
                string strfldName = lvFields.Items[j].SubItems[1].Text;
                if (pFClass.FindField(strfldName) == -1)
                {
                    IField     newField  = new FieldClass();
                    IFieldEdit fieldEdit = (IFieldEdit)newField;
                    fieldEdit.Name_2 = strfldName;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    pFClass.AddField(newField);
                }
            }

            //Update Field
            pFCursor = pFClass.Update(null, false);
            pFeature = pFCursor.NextFeature();

            string strSpOutlierFldName = lvFields.Items[0].SubItems[1].Text;
            int    intSpOutlierFldIdx  = pFClass.FindField(strSpOutlierFldName);

            int featureIdx = 0;

            while (pFeature != null)
            {
                pFeature.set_Value(intSpOutlierFldIdx, strSPOutliers[featureIdx]);

                pFCursor.UpdateFeature(pFeature);

                pFeature = pFCursor.NextFeature();
                featureIdx++;
            }
            pFCursor.Flush();

            if (chkMap.Checked)
            {
                ITable pTable = (ITable)pFClass;

                IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();
                pUniqueValueRenderer.FieldCount = 1;
                pUniqueValueRenderer.set_Field(0, strSpOutlierFldName);
                if (cboMaptype.Text == "choropleth map")
                {
                    ISimpleFillSymbol pSymbol;
                    IQueryFilter      pQFilter = new QueryFilterClass();
                    int    intTotalCount       = 0;
                    string strLabel            = null;

                    for (int j = 0; j < 4; j++)
                    {
                        pSymbol       = new SimpleFillSymbolClass();
                        pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                        pSymbol.Color = m_pSnippet.getRGB(m_pOutlierSymbols[j].R, m_pOutlierSymbols[j].G, m_pOutlierSymbols[j].B);

                        pQFilter.WhereClause = strSpOutlierFldName + " = '" + m_pOutlierSymbols[j].Value + "'";

                        intTotalCount = pTable.RowCount(pQFilter);

                        strLabel = m_pOutlierSymbols[j].Label + " (" + intTotalCount.ToString() + ")";
                        pUniqueValueRenderer.AddValue(m_pOutlierSymbols[j].Value, null, (ISymbol)pSymbol);
                        pUniqueValueRenderer.set_Label(m_pOutlierSymbols[j].Value, strLabel);
                    }
                    pUniqueValueRenderer.UseDefaultSymbol = false;
                }
                else if (cboMaptype.Text == "point map")
                {
                    ICharacterMarkerSymbol pSymbol;
                    stdole.IFontDisp       stdFontCls = ((stdole.IFontDisp)(new stdole.StdFont()));
                    stdFontCls.Name = "ESRI NIMA VMAP1&2 PT";
                    stdFontCls.Size = 10;

                    IQueryFilter pQFilter      = new QueryFilterClass();
                    int          intTotalCount = 0;
                    string       strLabel      = null;

                    for (int j = 0; j < 4; j++)
                    {
                        pSymbol = new CharacterMarkerSymbolClass();
                        pSymbol.CharacterIndex = 248;
                        //pSymbol.Color = m_pSnippet.getRGB(m_pQuadrantSymbols[j].R, m_pQuadrantSymbols[j].G, m_pQuadrantSymbols[j].B);
                        pSymbol.Size = 10;
                        pSymbol.Font = stdFontCls;

                        pSymbol.Angle = m_pOutlierSymbols[j].Angle;

                        pQFilter.WhereClause = strSpOutlierFldName + " = '" + m_pOutlierSymbols[j].Value + "'";

                        intTotalCount = pTable.RowCount(pQFilter);

                        strLabel = m_pOutlierSymbols[j].Label + " (" + intTotalCount.ToString() + ")";
                        pUniqueValueRenderer.AddValue(m_pOutlierSymbols[j].Value, null, (ISymbol)pSymbol);
                        pUniqueValueRenderer.set_Label(m_pOutlierSymbols[j].Value, strLabel);
                    }
                    pUniqueValueRenderer.UseDefaultSymbol = false;
                }
                IFeatureLayer pNewFLayer = new FeatureLayerClass();
                pNewFLayer.FeatureClass = pFClass;
                pNewFLayer.Name         = "Bivariate Spatial Quadrants";
                IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                m_pActiveView.FocusMap.AddLayer(pGFLayer);
                m_pActiveView.Refresh();
                m_pForm.axTOCControl1.Update();

                pfrmProgress.Close();
            }
            else
            {
                MessageBox.Show("Complete. The results are stored in the shape file");
            }
        }
Пример #4
0
 public static void NCol(this REngine engine, SymbolicExpression symbolicExpression)
 {
     engine.ExecFunction(symbolicExpression, "ncol");
 }
Пример #5
0
 /// <summary>
 /// 打印结果信息
 /// </summary>
 public static void Print(this REngine engine, SymbolicExpression symbolicExpression)
 {
     engine.ExecFunction(symbolicExpression, "print");
 }
Пример #6
0
 /// <summary>
 /// 获取R语言的工作目录
 /// </summary>
 public static SymbolicExpression GetWd(this REngine engine)
 {
     return(engine.Evaluate("getwd()"));
 }
Пример #7
0
 public ClrObjectWrapper(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
        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;
                }
            }
        }
Пример #9
0
 public void Run()
 {
     game = new ReactorGame(this);
     Reactor = new REngine(game);
     game.Run();
     Dispose();
 }
Пример #10
0
        //public List<sp_Forecast_GetDailyAvereageProductTransactions_Result> GetDailyAvereageProductTransactions()
        //{
        //    var result = db.sp_Forecast_GetDailyAvereageProductTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetDailyTimeSpecificAvereageProductTransactions_Result> GetDailyTimeSpecificAvereageProductTransactions()
        //{
        //    var result = db.sp_Forecast_GetDailyTimeSpecificAvereageProductTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetWeeklyAverageTransactions_Result> GetWeeklyAverageTransactions()
        //{
        //    var result = db.sp_Forecast_GetWeeklyAverageTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetWeeklyAvereageProductTransactions_Result> GetWeeklyAvereageProductTransactions()
        //{
        //    var result = db.sp_Forecast_GetWeeklyAvereageProductTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetProductCountYearDayByProductId_Result> GetProductCountYearDayByProductId(int productId)
        //{
        //    var result = db.sp_Forecast_GetProductCountYearDayByProductId(productId);
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetProductCountMonthDayByProductId_Result> GetProductCountMonthDayByProductId(int productId)
        //{
        //    var result = db.sp_Forecast_GetProductCountMonthDayByProductId(productId);
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetProductCountDayByProductId_Result> GetProductCountDayByProductId(int productId)
        //{
        //    var result = db.sp_Forecast_GetProductCountDayByProductId(productId);
        //    return result.ToList();
        //}
        #endregion

        #region R_Related

        public ForecastResult ForecastByMethod(int branchId, int productId, string method, string dataType, int periods)
        {
            ForecastResult forecastResult = new ForecastResult();

            //Methods method1 = (Methods)Enum.Parse(typeof(Methods), method, true);
            DataPeriod datatype1 = (DataPeriod)Enum.Parse(typeof(DataPeriod), dataType, true);

            //int productId = 1;
            //Methods method = Methods.rwf; //meanf(YYMMDD,MMDD,MMWWDD,DD), rtw, rtw(with Drift), Moving AVG,ets, Arima, HoltWinters, msts
            //DataPeriod dataType = DataPeriod.Daily;
            //int periods = 50;

            var values = GetCorrespondingDataByPeriod(datatype1, productId);

            //FFCEntities db = new FFCEntities();
            //var list = db.sp_Forecast_GetProductCountYearDayByProductId(productId).ToList();
            //List<double> values = list.Select(r => Double.Parse(r.Count.ToString())).ToList();
            //REngine.SetEnvironmentVariables(@"C:\Program Files\R\R-2.13.1\bin\i386");

            //SetupPath();
            //Log();

            REngine.SetEnvironmentVariables();

            // There are several options to initialize the engine, but by default the following suffice:
            REngine engine = REngine.GetInstance();

            //engine.Initialize();

            // .NET Framework array to R vector.
            //NumericVector testTs = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99, 1000 });
            //NumericVector testTs = engine.CreateNumericVector(new double[] { 10, 20, 30, 40, 50 });
            NumericVector data = engine.CreateNumericVector(values);

            engine.SetSymbol("data", data);
            //auto arima for monthly
            engine.Evaluate("tsValue <- ts(data, frequency=160, start=c(2013.5))");
            engine.Evaluate("library(forecast)");
            engine.Evaluate(String.Format("Fit <- {0}(tsValue)", method.ToString())); // Fit <- Arima(tsValue)
            //MethodManipulation(engine, method);
            engine.Evaluate(String.Format("fcast <- forecast(Fit, h={0})", periods));

            string image = PlotForecast(engine, method.ToString());

            //var a = engine.Evaluate("fcast <- forecast(tsValue, h=5)").AsCharacter();
            NumericVector forecasts = engine.Evaluate("fcast$mean").AsNumeric();

            //NumericVector forecasts = engine.Evaluate("fcast$lower[,2]").AsNumeric();

            forecastResult.BranchId       = branchId;
            forecastResult.ProductId      = productId;
            forecastResult.Method         = db.Forecast_Methods.Where(r => r.ForecastIdentifier == method).Select(a => a.ForecastMethod).FirstOrDefault();
            forecastResult.DatePeriod     = datatype1.ToString();
            forecastResult.ForecastPeriod = periods;
            forecastResult.Values         = forecasts.ToList();
            forecastResult.ImagePath      = "~/Content/Images/" + image;

            //foreach (var item in forecasts)
            //{
            //    Console.WriteLine(item);
            //}

            //engine.Dispose();

            return(forecastResult);
        }
Пример #11
0
 public Model(REngine engine)
 {
     this.engine = engine;
 }
Пример #12
0
 public NewConfig(GeneratorConfiguration gConf)
 {
     InitializeComponent();
     engine = REngine.GetInstance();
 }
Пример #13
0
     static void Main(string[] args)
          {
          string USAGE = "SampleMD adm_cnnct_pt " +
                         "user password md_cnnct_pt ts_cnnct_pt " +
                         "exchange symbol flags";

          if (args.Length < 8)
               {
               System.Console.Out.WriteLine(USAGE);
               return;
               }

          /*   -----------------------------------------------------------   */

          string sAdmCnnctPt = args[0];
          string sUser       = args[1];
          string sPassword   = args[2];
          string sMdCnnctPt  = args[3];
          string sTsCnnctPt  = args[4];
          string sExchange   = args[5];
          string sSymbol     = args[6];
          string sFlags      = args[7];

          /*   -----------------------------------------------------------   */

          MyAdmCallbacks oAdmCallbacks = new MyAdmCallbacks();
          MyCallbacks    oCallbacks    = new MyCallbacks();
          REngineParams  oParams       = new REngineParams();
          REngine        oEngine;

          /*   ----------------------------------------------------------   */
          /*   You may need to change some values, such as the CertFile     */
          /*   ----------------------------------------------------------   */

          oParams.AdmCnnctPt = sAdmCnnctPt;
          oParams.AppName      = "SampleMD.NET";
          oParams.AppVersion   = "1.0.0.0";
          oParams.AdmCallbacks = oAdmCallbacks;
          oParams.CertFile     = "c:\\data\\rithmiccerts\\RithmicCertificate.pk12";
          oParams.DmnSrvrAddr  = "rituz01000.01.rithmic.com:65000";
          oParams.DomainName   = "rithmic_uat_01_dmz_domain";
          oParams.LicSrvrAddr  = "rituz01000.01.rithmic.com:56000";
          oParams.LocBrokAddr  = "rituz01000.01.rithmic.com:64100";
          oParams.LoggerAddr   = "rituz01000.01.rithmic.com:45454";

          /*   -----------------------------------------------------------   */

          try
               {
               /*   ------------------------------------------------------   */
               /*   Instantiate the REngine.                                 */
               /*   ------------------------------------------------------   */

               oEngine = new REngine(oParams);

               /*   ------------------------------------------------------   */
               /*   Initiate the login.                                      */
               /*   ------------------------------------------------------   */

               oEngine.login(oCallbacks, 
                    sUser, 
                    sPassword, 
                    sMdCnnctPt, 
                    sTsCnnctPt, 
                    string.Empty,
                    string.Empty);

               /*   ------------------------------------------------------   */
               /*   After calling REngine::login, RCallbacks::Alert will be  */
               /*   called a number of times.  Wait for when the login to    */
               /*   the MdCnnctPt and TsCnnctPt is complete.  (See           */
               /*   MyCallbacks::Alert() for details).                       */
               /*   ------------------------------------------------------   */

               while (!oCallbacks.LoggedIntoMd)
                    {
                    System.Threading.Thread.Sleep(1000);
                    }

               /*   ------------------------------------------------------   */
               /*   Subscribe to the instrument of interest.  To express     */
               /*   interest in different types of updates, see              */
               /*   SubscriptionFlags.                                       */
               /*   ------------------------------------------------------   */

               oEngine.subscribe(sExchange, 
                    sSymbol, 
                    (SubscriptionFlags)Convert.ToInt32(sFlags), 
                    null);

               /*   ------------------------------------------------------   */
               /*   At this point the callback routines will start firing    */
               /*   on a different thread.  This main thread will wait       */
               /*   until a key is pressed before continuing.                */
               /*   ------------------------------------------------------   */

               Console.Read();

               /*   ------------------------------------------------------   */
               /*   We are done, so log out...                               */
               /*   ------------------------------------------------------   */

               oEngine.logout();

               /*   ------------------------------------------------------   */
               /*   and shutdown the REngine instance.                       */
               /*   ------------------------------------------------------   */

               oEngine.shutdown();
               }
          catch (OMException oEx)
               {
               System.Console.Out.WriteLine("error : {0}", oEx.Message);
               }
          catch (Exception e)
               {
               System.Console.Out.WriteLine("exception : {0}", e.Message);
               }

          /*   -----------------------------------------------------------   */

          return;
          }
Пример #14
0
 static void TestOptimR(REngine engine)
 {
     Console.WriteLine("*** The use case optimisation in R; engine in C# is not yet implemented");
     Console.WriteLine("*** For a similar use case see: https://r2clr.codeplex.com/wikipage?title=Spatial-temporal%20model&referringTitle=Documentation");
 }
Пример #15
0
        public MainWindow()
        {
            InitializeComponent();

            REngine engine;

            REngine.SetEnvironmentVariables();
            engine = REngine.GetInstance();
            engine.Initialize();

            //input = "library(TTR)\n library(quantmod)\n all <- stockSymbols()";
            //DataFrame obj = engine.Evaluate(input).AsDataFrame();

            //for (int i = 0; i < obj.RowCount; ++i)
            //{
            //    for (int k = 0; k < obj.ColumnCount; ++k)
            //    {
            //        if (obj.ColumnNames[k].Equals("Name"))
            //        {
            //            n = obj[i, k].ToString();
            //        }
            //        else if (obj.ColumnNames[k].Equals("Industry"))
            //        {
            //            ind = obj[i, k].ToString();
            //        }
            //        else if (obj.ColumnNames[k].Equals("Symbol"))
            //        {
            //            s = obj[i, k].ToString();
            //        }
            //    }
            //    c_list.Add(new Companies(n, s, ind));
            //}

            List <int> size = new List <int>()
            {
                29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238
            };
            List <int> population = new List <int>()
            {
                3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327
            };



            //c_list.Sort();



            /*
             *
             * string result;
             * string input;
             * REngine engine;
             *
             * //init the R engine
             * REngine.SetEnvironmentVariables();
             * engine = REngine.GetInstance();
             * engine.Initialize();
             *
             * //input
             * Console.WriteLine("Please enter the calculation");
             * input = "2+3";
             *
             * //calculate
             * CharacterVector vector = engine.Evaluate(input).AsCharacter();
             *
             * //shell(R CMD BATCH myRprogram.R)
             * //Process.Start("script.R");
             *
             * //engine.Evaluate("foo()");
             * string temp = "getYahooStockUrl <- function(symbol, start, end, type = \"d\") {\n start <- as.Date(start)\n end <- as.Date(end)\n url <-\"http://ichart.finance.yahoo.com/table.csv?s=%s&a=%d&b=%s&c=%s&d=%d&e=%s&f=%s&g=%s&ignore=.csv\"\n sprintf(url,\ntoupper(symbol),\nas.integer(format(start, \"%m\")) - 1,\nformat(start, \"%d\"),\nformat(start, \"%Y\"),\nas.integer(format(end, \"%m\")) - 1, \nformat(end, \"%d\"),\nformat(end, \"%Y\"),\ntype)} \ndata<- read.csv(getYahooStockUrl(\"sbux\", \"2008-1-2\", \"2008-12-31\"),\nstringsAsFactors = FALSE) \n data$High";
             *
             * //string temp = "dat<-as.Date(\"2008-12-31\")\n"+"class(dat)\n plot(dat)";
             * //string temp = "dat<- 8+5 \n"+"dat";
             * //string temp="";
             * Console.WriteLine("!!    " + engine.Evaluate(temp).AsCharacter()[0] + "    !!" + engine.Evaluate(temp).AsCharacter()[1]);
             * //engine.Evaluate("plot(data$High,type=\"l\",col=\"red\")");
             * //gr.Navigate(engine.Evaluate("plot(data$High,type=\"l\",col=\"red\")"));
             * // result = vector[0];
             * //clean up
             * engine.Dispose();
             * //output
             * Console.WriteLine("");
             * Console.WriteLine("Result: '{0}'", result);
             * Console.WriteLine("Press any key to exit");
             * //Console.ReadKey();
             */
        }
 /// <summary>
 /// Checks the equality in native memory of a pointer against a pointer to the R 'NULL' value
 /// </summary>
 /// <param name="engine">R.NET Rengine</param>
 /// <param name="pointer">Pointer to test</param>
 /// <returns>True if the pointer and pointer to R NULL are equal</returns>
 public static bool EqualsRNilValue(this REngine engine, IntPtr pointer)
 {
     return(engine.NilValue.DangerousGetHandle() == pointer);
 }
Пример #17
0
        public static void InitializeRDotNet()
        {
            try
            {
                //  Check for Path and R_Home
                using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\R-core\R"))
                {
                    string sEnvPath         = Environment.GetEnvironmentVariable("Path");
                    string sRInstallPath    = (string)registryKey.GetValue("InstallPath");
                    string sRInstallVersion = (string)registryKey.GetValue("Current Version");


                    //string rHome = @"C:\Program Files\R\R-3.4.3";
                    //string rPath = @"C:\Program Files\R\R-3.4.3\bin\x64";
                    ////string rPath = Path.Combine(rHome, @"bin\x64");
                    //REngine.SetEnvironmentVariables(rPath, rHome);
                    //_engine = REngine.GetInstance();

                    var logInfo  = RDotNet.NativeLibrary.NativeUtility.GetRHomeEnvironmentVariable();
                    var logInfo2 = RDotNet.NativeLibrary.NativeUtility.GetPlatform();
                    var rLib     = RDotNet.NativeLibrary.NativeUtility.GetRLibraryFileName();


                    REngine.SetEnvironmentVariables();
                    _engine = REngine.GetInstance();
                    _engine.Initialize();

                    //Console.WriteLine("R_values: " + _engine.P);

                    //foreach (string sPackages in MyFunctions._engine.Evaluate("installed.packages(.Library)").AsCharacter())
                    //{
                    //    Console.WriteLine("Installed packages on local machine are: " + sPackages);
                    //}

                    // Check to see which instance of R is installed
                    if (!string.IsNullOrEmpty(sRInstallPath))
                    {
                        string sRBinPath = System.Environment.Is64BitProcess ? sRInstallPath + @"bin\x64\" : sRInstallPath + @"bin\i386\";
                        Environment.SetEnvironmentVariable("Path", sEnvPath + sRInstallPath);
                        //Console.WriteLine("Env Path: " + sOrigPath + "\r\n" + "R Bin Path: " + sBinPath + "\r\n" + "R Version: " + sVersion);
                        string sNewPath = Environment.GetEnvironmentVariable("Path");
                        //var logInfo = RDotNet.NativeLibrary.NativeUtility.GetRHomeEnvironmentVariable();
                        //var rLib = RDotNet.NativeLibrary.NativeUtility.GetRLibraryFileName();
                        Console.WriteLine("Original Env Path: " + sEnvPath);
                        Console.WriteLine("     New Env Path: " + sNewPath);


                        REngine.SetEnvironmentVariables(sRBinPath, sRInstallPath);  // Leave these out for system default.
                        _engine = REngine.GetInstance();
                        _engine.Initialize();
                    }
                    else
                    {
                        MessageBox.Show("You do not have the R software installed.  Please install version 3.43.",
                                        "Critical Warning",
                                        MessageBoxButtons.OKCancel,
                                        MessageBoxIcon.Warning,
                                        MessageBoxDefaultButton.Button1,
                                        MessageBoxOptions.RightAlign,
                                        true);
                    }
                    //Console.WriteLine("R Home: " + logInfo + "\r\n");
                    //Console.WriteLine("R Library: " + rLib + "\r\n");
                    //foreach (string sPackages in MyFunctions._engine.Evaluate("installed.packages(.Library)").AsCharacter())
                    //    Console.WriteLine("Installed packages on local machine are: " + sPackages);
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error Initializing RDotNet: " + ex.Message);
            }
        }
Пример #18
0
 private static bool GetInterruptsSuspended(REngine engine)
 {
     var pointer = engine.DangerousGetHandle("R_interrupts_suspended");
     return Convert.ToBoolean(Marshal.ReadInt32(pointer));
 }
Пример #19
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            if (pDrawDenplot.cboSourceLayer.Text != "" && pDrawDenplot.cboUField.Text != "" && pDrawDenplot.cboValueField.Text != "")
            {
                mForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm;

                IActiveView pActiveView        = mForm.axMapControl1.ActiveView;
                string      strTargetLayerName = pDrawDenplot.cboSourceLayer.Text;
                string      strValueField      = pDrawDenplot.cboValueField.Text;
                string      strUncerField      = pDrawDenplot.cboUField.Text;


                int    x      = X;
                int    y      = Y;
                IPoint pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);


                double    Tol      = 4; //Needs to be changed
                IEnvelope pEnvelop = pPoint.Envelope;
                pEnvelop.Expand(Tol, Tol, false);
                ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                pSpatialFilter.Geometry   = pEnvelop;
                pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                clsSnippet pSnippet = new clsSnippet();

                int intTLayerIdx = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName);

                ILayer        pLayer         = mForm.axMapControl1.get_Layer(intTLayerIdx);
                IFeatureLayer pFLayer        = (IFeatureLayer)pLayer;
                string        ShapeFieldName = pFLayer.FeatureClass.ShapeFieldName;
                pSpatialFilter.GeometryField = pFLayer.FeatureClass.ShapeFieldName;
                IFeatureClass  pFeatureClass = pFLayer.FeatureClass;
                IFeatureCursor pFCursor      = pFeatureClass.Search(pSpatialFilter, false);
                IFeature       pFeature      = pFCursor.NextFeature();
                pFCursor.Flush();
                if (pFeature == null)
                {
                    return;
                }

                int intValueFldIdx = pFeatureClass.FindField(strValueField);
                int intUncerFldIdx = pFeatureClass.FindField(strUncerField);


                double[] dblValue = new double[1];
                dblValue[0] = Convert.ToDouble(pFeature.get_Value(intValueFldIdx));
                double[] dblUncern = new double[1];
                dblUncern[0] = Convert.ToDouble(pFeature.get_Value(intUncerFldIdx));
                REngine       pEngine  = mForm.pEngine;
                NumericVector vecValue = pEngine.CreateNumericVector(dblValue);
                NumericVector vecSD    = pEngine.CreateNumericVector(dblUncern);
                pEngine.SetSymbol("samp.mean", vecValue);
                pEngine.SetSymbol("samp.sd", vecSD);

                pEngine.Evaluate("samp.xlim <- c(samp.mean-(samp.sd*3), samp.mean+(samp.sd*3))");
                pEngine.Evaluate("confLevel <- " + pDrawDenplot.nudConfiLevel.Value.ToString());
                pEngine.Evaluate("bothlevel <- 1-((100-confLevel)/200)");
                pEngine.Evaluate("error <- qnorm(bothlevel)*samp.sd");
                pEngine.Evaluate("confint <- c(samp.mean-error, samp.mean+error)");

                StringBuilder sbCommand = new StringBuilder();
                sbCommand.Append("curve(dnorm(x, mean=samp.mean, sd=samp.sd), lwd=2, xlim=samp.xlim, ylab='Probability', xlab='" + strValueField + "');");
                sbCommand.Append("abline(v=samp.mean, col='red');");
                sbCommand.Append("abline(v=confint, col='blue');");
                string strTitle = "Probability Denstiy Plot";

                pSnippet.drawPlottoForm(strTitle, sbCommand.ToString());
            }

            //int intFID = Convert.ToInt32(pFeature.get_Value(0)); //Get FID Value
            //return intFID;



            //int intFID = FindFeatureFID(pPoint);
            //int intColumnLength = arrSimuResults.GetUpperBound(1) + 1;
            //double[] arrHist = new double[intColumnLength];
            //for (int i = 0; i < intColumnLength; i++)
            //{
            //    arrHist[i] = arrSimuResults[intFID, i];
            //}
            //NumericVector vecBLL = pEngine.CreateNumericVector(arrHist);
            //pEngine.SetSymbol(strValue, vecBLL);

            //string strCommand = "hist(" + strValue + ", freq=FALSE, main=paste('Histogram of FID ', " + intFID.ToString() + "));abline(v=" + Math.Round(arrOrivalue[intFID], 3).ToString() + ", col='red');";
            //string strTitle = "Histogram";

            //System.Text.StringBuilder CommandPlot = new System.Text.StringBuilder();
        }
Пример #20
0
        public override void Render()
        {
            if (IsDrawable)
            {
                ApplyState();
                base.Render();

                /*
                 * GL.Enable(EnableCap.CullFace);
                 * REngine.CheckGLError();
                 * GL.FrontFace(FrontFaceDirection.Ccw);
                 * REngine.CheckGLError();
                 * GL.CullFace(CullFaceMode.FrontAndBack);
                 * REngine.CheckGLError();
                 */
                _material.Shader.Bind();
                _material.Apply();
                VertexBuffer.BindVertexArray();
                VertexBuffer.Bind();

                VertexBuffer.VertexDeclaration.Apply(_material.Shader, IntPtr.Zero);

                _material.Shader.BindSemantics(matrix, REngine.camera.viewMatrix, REngine.camera.projMatrix);
                if (PrimitiveType == RPrimitiveType.Points)
                {
                    GL.PointParameter(PointParameterName.PointSizeMin, 0.0f);
                    GL.PointParameter(PointParameterName.PointSizeMax, 1024.0f);
                    GL.Enable(EnableCap.PointSprite);
                    GL.Enable(EnableCap.PointSmooth);
                    GL.Enable(EnableCap.ProgramPointSize);
                }
                if (_index != null)
                {
                    var shortIndices       = _index.IndexElementSize == RIndexElementSize.SixteenBits;
                    var indexElementType   = shortIndices ? DrawElementsType.UnsignedShort : DrawElementsType.UnsignedInt;
                    var indexElementSize   = shortIndices ? 2 : 4;
                    var indexOffsetInBytes = (IntPtr)(indexElementSize);
                    var indexElementCount  = _index.GetElementCountArray((PrimitiveType)PrimitiveType, vertCount);
                    _index.Bind();
                    REngine.CheckGLError();
                    GL.DrawRangeElements((PrimitiveType)PrimitiveType, 0, 1, _index.IndexCount, indexElementType, indexOffsetInBytes);
                    REngine.CheckGLError();
                    _index.Unbind();
                    REngine.CheckGLError();
                }
                else
                {
                    GL.DrawArrays((PrimitiveType)PrimitiveType, 0, VertexBuffer.VertexCount);
                    REngine.CheckGLError();
                }
                if (PrimitiveType == RPrimitiveType.Points)
                {
                    GL.Disable(EnableCap.PointSprite);
                    GL.Disable(EnableCap.PointSmooth);
                    GL.Disable(EnableCap.ProgramPointSize);
                }
                _material.Shader.Unbind();

                VertexBuffer.Unbind();
                VertexBuffer.UnbindVertexArray();
            }
        }
Пример #21
0
        private static object ZEvalOnData(string[] expressionSet, bool reverse, bool noLabels, string[] names,
                                          Stopwatch sw1, Dictionary <string, string> tickersToVariables,
                                          Dictionary <string, SortedDictionary <DateTime, double> > data, SortedSet <DateTime> dates)
        {
            // Set up vectors in R.
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance();

            // Load basic script.
            engine.Evaluate("source('" + XL.ZEvalScript.Replace('\\', '/') + "')");

            foreach (string ticker in tickersToVariables.Keys)
            {
                List <double> data1 = new List <double>();

                foreach (DateTime dt in dates)
                {
                    if (data[ticker].ContainsKey(dt))
                    {
                        data1.Add(data[ticker][dt]);
                    }
                    else
                    {
                        data1.Add(data[ticker].Where(x => x.Key < dt).OrderBy(x => x.Key).LastOrDefault().Value);
                    }
                }

                NumericVector group = engine.CreateNumericVector(data1);
                engine.SetSymbol(tickersToVariables[ticker], group);
            }

            Debug.Write("prepped R in " + sw1.ElapsedMilliseconds + "ms; ");
            sw1.Restart();

            // Now evaluate each expression.
            Dictionary <string, SortedDictionary <DateTime, double> > data2 = new Dictionary <string, SortedDictionary <DateTime, double> >();

            foreach (string expression in expressionSet)
            {
                string expr_mod = expression;

                if (expr_mod[0] == '*')
                {
                    expr_mod = "cumprod(1 + " + expr_mod.Substring(1) + ")";
                }

                foreach (string ticker in tickersToVariables.Keys)
                {
                    expr_mod = expr_mod.Replace("{" + ticker + "}", tickersToVariables[ticker]);

                    expr_mod = expr_mod.Replace("{r@" + ticker + "}", "percentage_returns(" + tickersToVariables[ticker] + ")");
                    expr_mod = expr_mod.Replace("{d@" + ticker + "}", "normal_returns(" + tickersToVariables[ticker] + ")");
                    expr_mod = expr_mod.Replace("{l@" + ticker + "}", "log_returns(" + tickersToVariables[ticker] + ")");
                }

                try
                {
                    var result = engine.Evaluate(expr_mod.ToLower());
                    var values = result.AsNumeric();

                    data2[expression] = new SortedDictionary <DateTime, double>();

                    int k = 0;
                    foreach (DateTime dt in dates.Reverse())
                    {
                        data2[expression][dt] = values[values.Length - k - 1];

                        k++;
                    }
                }
                catch (Exception e)
                {
                    string error = expression + " ------- " + e.ToString();
                    Debug.WriteLine(error);
                    return(error);
                }
            }

            Debug.Write("ran R in " + sw1.ElapsedMilliseconds + "ms; ");
            sw1.Restart();

            object[,] ret = new object[dates.Count + (noLabels ? 0 : 1), expressionSet.Length + (noLabels ? 0 : 1)];
            ret[0, 0]     = "Date";

            int i = 1;

            foreach (DateTime date in (reverse ? dates.Reverse() : dates))
            {
                ret[i, 0] = date;

                int j = 0;
                foreach (string expression in expressionSet)
                {
                    if (i == 1 && !noLabels)
                    {
                        ret[0, j + 1] = (names.Length < j + 1 ? expression : names[j]);
                    }

                    ret[i, j + 1] = data2[expression][date];
                    j++;
                }

                i++;
            }

            Debug.WriteLine("finished in " + sw1.ElapsedMilliseconds + "ms; ");

            return(ret);
        }
Пример #22
0
 public ExternalPointer(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
Пример #23
0
        private void button3_Click(object sender, EventArgs e)
        {
            int FeatureNum = app.FeaName.GetLength(0);
            int SampleNum  = app.SamName.GetLength(0);

            REngine.SetEnvironmentVariables();

            REngine PCA = REngine.GetInstance();

            PCA.Initialize();

            NumericMatrix Freq = PCA.CreateNumericMatrix(app.CountMatrix);

            PCA.SetSymbol("Freq", Freq);
            CharacterVector SampleName  = PCA.CreateCharacterVector(app.SamName);
            CharacterVector FeatureName = PCA.CreateCharacterVector(app.FeaName);

            PCA.SetSymbol("FeatureName", FeatureName);
            PCA.SetSymbol("SampleName", SampleName);

            PCA.Evaluate("library(stats)");
            PCA.Evaluate("pr <- prcomp(t(Freq),cor = TRUE)");
            PCA.Evaluate("score <- predict(pr)");
            double[,] Count = PCA.GetSymbol("score").AsNumericMatrix().ToArray();
            app.Score       = new double[SampleNum, 2];
            for (int i = 0; i < SampleNum; i++)
            {
                app.Score[i, 0] = Count[i, 0];
                app.Score[i, 1] = Count[i, 1];
            }
            if (this.radioButton1.Checked)
            {
                PCA.Evaluate("windows()");
                PCA.Evaluate("plot(score[,1:2],main=\"PCA\", type=\"p\")");
            }

            else
            {
                if ((app.cluster == null) || (app.cluster.Length != SampleNum))
                {
                    MessageBox.Show("Sample number in input data is not equal to that in cluster information!!", "Warning!!!", MessageBoxButtons.OK);
                }
                else
                {
                    IntegerVector cluster = PCA.CreateIntegerVector(app.cluster);
                    PCA.SetSymbol("cluster", cluster);
                    PCA.Evaluate("clusterNum <- max(cluster)");
                    PCA.Evaluate("clustermin <- min(cluster)");
                    app.clusterNum = (int)PCA.GetSymbol("clusterNum").AsNumeric().First();
                    int clustermin = (int)PCA.GetSymbol("clustermin").AsNumeric().First();
                    if (app.clusterNum > 10)
                    {
                        MessageBox.Show("Too many clusters!!", "WARNING!");
                    }
                    else if (clustermin < 0)
                    {
                        MessageBox.Show("Illegal cluster number!!!", "WARNING!");
                    }
                    else
                    {
                        PCA_whole_Output plot = new PCA_whole_Output();
                        plot.MdiParent = this.MdiParent;
                        plot.Show();
                    }
                }
            }
            this.Close();
        }
Пример #24
0
        /// <summary>
        /// 读取Csv文件
        /// </summary>
        public static SymbolicExpression ReadCsv(this REngine engine, string csvFileName)
        {
            var csvName = engine.CreateCharacter(csvFileName);

            return(engine.ExecFunction(csvName, "read.csv"));
        }
Пример #25
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            //Get Start up path to set a sample data path and path of temporary folder
            strPath = System.Windows.Forms.Application.StartupPath;
            axMapControl1.ActiveView.FocusMap.Name = "Layers";
            //get the MapControl
            m_mapControl = (IMapControl3)axMapControl1.Object;

            //disable the Save menu (since there is no document yet)
            menuSaveDoc.Enabled = false;

            lstRenderedLayers = new List <clsRenderedLayers>();
            m_pSnippet        = new clsSnippet();
            try
            {
                //Load sample mxd
                //string filePath = strPath + @"\Sample.mxd";
                //string filePath = strPath + @"\SampleData\Sample_plano.mxd";//For Plano
                //string filePath = strPath + @"\SampleData\Classification\Iowa_cnties.mxd";//For Iowa

                //if (axMapControl1.CheckMxFile(filePath))
                //    axMapControl1.LoadMxFile(filePath, Type.Missing, Type.Missing);
                //else
                //    MessageBox.Show("Wrong direction");

                ////Get Envelope of mxd
                //IActiveView pActiveView1 = axMapControl1.ActiveView.FocusMap as IActiveView;
                ////ILayer pLayer1 = pActiveView1.FocusMap.get_Layer(2);
                //ILayer pLayer1 = pActiveView1.FocusMap.get_Layer(0);

                ////adjust extent to fit a screen resolution
                //IFeatureLayer pFLayer1 = pLayer1 as IFeatureLayer;
                //IEnvelope envelope1 = new EnvelopeClass();
                //envelope1.PutCoords(pFLayer1.AreaOfInterest.Envelope.XMin - (pFLayer1.AreaOfInterest.Envelope.XMin * 0.0005), pFLayer1.AreaOfInterest.Envelope.YMin - (pFLayer1.AreaOfInterest.Envelope.YMin * 0.0005), pFLayer1.AreaOfInterest.Envelope.XMax * 1.0005, pFLayer1.AreaOfInterest.Envelope.YMax * 1.0005);
                //axMapControl1.ActiveView.Extent = envelope1;
                //axMapControl1.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 101: " + ex.Message);
            }

            try
            {
                //R environment setting

                #region Previous Methods
                //var envPath = Environment.GetEnvironmentVariable("PATH");
                //var rBinPath = strPath + @"\R-3.1.2\bin\i386"; // R is copited into startup path
                //Environment.SetEnvironmentVariable("PATH", envPath + System.IO.Path.PathSeparator + rBinPath);
                ////Environment.SetEnvironmentVariable("PATH", rBinPath); //Not working
                //Environment.SetEnvironmentVariable("R_HOME", strPath + @"\R-3.1.2");

                ////Loading REngine
                //pEngine = REngine.CreateInstance(strREngineName);
                //pEngine.Initialize();

                ////string[] strRHOME = pEngine.Evaluate("R.home(component = 'home')").AsCharacter().ToArray(); //For Deburgging
                //LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();

                //string strLibPath = strPath.Replace(@"\", @"/") + "/R-3.1.2/library";
                ////pEngine.Evaluate(".libPaths(" + strLibPath + ")");
                ////pEngine.Evaluate(".libPaths(c(" + strLibPath + ", .Library.site, .Library))");//Same results with the above
                ////pEngine.Evaluate(".libPaths(c(" + strLibPath + "))");//Same results with the above
                //pEngine.Evaluate(".Library.site <- file.path('"+strLibPath+"')"); //Same results with the above
                //pEngine.Evaluate("Sys.setenv(R_LIBS_USER='******')");
                ////string[] tempstring1 = pEngine.Evaluate("Sys.getenv('R_LIBS_USER')").AsCharacter().ToArray();
                ////string[] tempstring = pEngine.Evaluate(".Library.site").AsCharacter().ToArray();
                //pEngine.Evaluate(".libPaths(c('" + strLibPath + "', .Library.site, .Library))");

                //LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                //pEngine.Evaluate("ip <- installed.packages()").AsCharacter();
                //string[] installedPackages = pEngine.Evaluate("ip[,1]").AsCharacter().ToArray(); //To Check Installed Packages in R
                //clsRPackageNames pPckNames = new clsRPackageNames();
                //blnsInstalledPcks = pPckNames.CheckedRequiredPackages(installedPackages);

                #endregion

                //Current version of R is 3.4.4 (03/19/18 HK)
                var envPath  = Environment.GetEnvironmentVariable("PATH");
                var rBinPath = strPath + @"\R-3.4.4\bin\i386"; // R is copited into startup path
                Environment.SetEnvironmentVariable("PATH", envPath + System.IO.Path.PathSeparator + rBinPath);
                Environment.SetEnvironmentVariable("R_HOME", strPath + @"\R-3.4.4");

                //Loading REngine
                pEngine = REngine.CreateInstance(strREngineName);
                pEngine.Initialize();

                //Set Library home and remove local home!
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                string strLibPath = strPath.Replace(@"\", @"/") + "/R-3.4.4/library"; //path for R packages
                pEngine.Evaluate(".Library.site <- file.path('" + strLibPath + "')");
                pEngine.Evaluate("Sys.setenv(R_LIBS_USER='******')");
                pEngine.Evaluate(".libPaths(c('" + strLibPath + "', .Library.site, .Library))");

                //Checked installed packages and R
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                pEngine.Evaluate("ip <- installed.packages()").AsCharacter();
                string[]         installedPackages = pEngine.Evaluate("ip[,1]").AsCharacter().ToArray(); //To Check Installed Packages in R
                clsRPackageNames pPckNames         = new clsRPackageNames();
                blnsInstalledPcks = pPckNames.CheckedRequiredPackages(installedPackages);



                ////Installing Additional Package
                //Currently required pacakges:: MASS, geoR, car, spdep, maptools, deldir, rgeos, e1071
                //package required for Testing: fpc
                //pEngine.Evaluate("install.packages('fpc')");
                //pEngine.Evaluate("install.packages('e1071')");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 102:" + ex.Message);
            }

            try
            {
                //Toolbar Control, insert new tools here!!
                m_ToolbarControl = (IToolbarControl2)axToolbarControl1.Object;

                int intItemCounts = m_ToolbarControl.Count;
                m_ToolbarControl.AddItem(new toolDenPlot(), -1, intItemCounts, true, 0, esriCommandStyles.esriCommandStyleIconOnly);        //Probability density plot tool
                //m_ToolbarControl.AddItem(new toolUncernFeature(), -1, intItemCounts+1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); // Remove now 07/31/15
                m_ToolbarControl.AddItem(new ToolCumsum(), -1, intItemCounts + 1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);    // Empirical cumulative density function
                m_ToolbarControl.AddItem(new toolHistogram(), -1, intItemCounts + 2, false, 0, esriCommandStyles.esriCommandStyleIconOnly); // Histogram tool
                m_ToolbarControl.AddItem(new LinkingTool(), -1, intItemCounts + 3, true, 0, esriCommandStyles.esriCommandStyleIconOnly);    // Histogram tool
                m_ToolbarControl.AddItem(new AddFeatureClass(), -1, 1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);               // Histogram tool
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 103: " + ex.Message);
            }

            try
            {
                //Loading Context menu at TOC
                m_tocControl = axTOCControl1.Object as ITOCControl2;
                m_tocControl.SetBuddyControl(m_mapControl);
                m_menuLayer = new ToolbarMenuClass();
                m_menuLayer.AddItem(new RemoveLayer(), -1, 0, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new OpenAttriTable(), -1, 1, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new ZoomToLayer(), -1, 2, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new ZoomToSelectedFeatures(), -1, 3, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new SaveLayerFile(), -1, 4, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new LayerSymbology(), -1, 5, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new LayerProperty(), -1, 6, false, esriCommandStyles.esriCommandStyleTextOnly);
                //m_menuLayer.AddItem(new Symbology(), -1, 3, false, esriCommandStyles.esriCommandStyleTextOnly);
                //m_menuLayer.AddItem(new SimpleSymbology(), -1, 3, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.SetHook(m_mapControl);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 104:" + ex.Message);
            }
        }
Пример #26
0
 /// <summary>
 /// 打印字符串
 /// </summary>
 /// <param name="engine"></param>
 /// <param name="content"></param>
 public static void Print(this REngine engine, string content)
 {
     engine.Print(engine.CreateCharacter(content));
 }
Пример #27
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            try
            {
                if (pfrmAttributeField.cboSourceLayer.Text != "" && pfrmAttributeField.cboValueField.Text != "")
                {
                    mForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm;

                    IActiveView pActiveView        = mForm.axMapControl1.ActiveView;
                    string      strTargetLayerName = pfrmAttributeField.cboSourceLayer.Text;
                    string      strValueField      = pfrmAttributeField.cboValueField.Text;

                    int    x      = X;
                    int    y      = Y;
                    IPoint pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);


                    double    Tol      = 4; //Needs to be changed
                    IEnvelope pEnvelop = pPoint.Envelope;
                    pEnvelop.Expand(Tol, Tol, false);
                    ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                    pSpatialFilter.Geometry   = pEnvelop;
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    clsSnippet pSnippet = new clsSnippet();

                    int intTLayerIdx = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName);

                    ILayer        pLayer         = mForm.axMapControl1.get_Layer(intTLayerIdx);
                    IFeatureLayer pFLayer        = (IFeatureLayer)pLayer;
                    string        ShapeFieldName = pFLayer.FeatureClass.ShapeFieldName;
                    pSpatialFilter.GeometryField = pFLayer.FeatureClass.ShapeFieldName;
                    IFeatureClass  pFeatureClass = pFLayer.FeatureClass;
                    IFeatureCursor pFCursor      = pFeatureClass.Search(pSpatialFilter, false);
                    IFeature       pFeature      = pFCursor.NextFeature();
                    pFCursor.Flush();
                    if (pFeature == null)
                    {
                        return;
                    }

                    int intValueFldIdx = pFeatureClass.FindField(strValueField);

                    double[] dblAllValue = pfrmAttributeField.arrValue;
                    double[] dblValue    = new double[1];
                    dblValue[0] = Convert.ToDouble(pFeature.get_Value(intValueFldIdx));
                    int           intCount    = pFeatureClass.FeatureCount(null);
                    REngine       pEngine     = mForm.pEngine;
                    NumericVector vecValue    = pEngine.CreateNumericVector(dblValue);
                    NumericVector vecAllValue = pEngine.CreateNumericVector(dblAllValue);
                    pEngine.SetSymbol("value", vecValue);
                    pEngine.SetSymbol("all.value", vecAllValue);

                    StringBuilder sbCommand = new StringBuilder();
                    sbCommand.Append("hist(all.value);");
                    sbCommand.Append("abline(v=value, col='red');");
                    string strTitle = "Histogram";

                    pSnippet.drawPlottoForm(strTitle, sbCommand.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("HistTool Error:" + ex.Message);
                return;
            }
        }
Пример #28
0
 public static void NRow(this REngine engine, SymbolicExpression symbolicExpression)
 {
     engine.ExecFunction(symbolicExpression, "nrow");
 }
Пример #29
0
 private void Application_Startup(object sender, StartupEventArgs e)
 {
     REngine.SetEnvironmentVariables();
     REngine engine = REngine.GetInstance();
 }
Пример #30
0
        static void Main(string[] args)
        {
            string USAGE = "SampleMD adm_cnnct_pt " +
                           "user password md_cnnct_pt ts_cnnct_pt " +
                           "exchange symbol flags";

            if (args.Length < 8)
            {
                System.Console.Out.WriteLine(USAGE);
                return;
            }

            /*   -----------------------------------------------------------   */

            string sAdmCnnctPt = args[0];
            string sUser       = args[1];
            string sPassword   = args[2];
            string sMdCnnctPt  = args[3];
            string sTsCnnctPt  = args[4];
            string sExchange   = args[5];
            string sSymbol     = args[6];
            string sFlags      = args[7];

            /*   -----------------------------------------------------------   */

            MyAdmCallbacks oAdmCallbacks = new MyAdmCallbacks();
            MyCallbacks    oCallbacks    = new MyCallbacks();
            REngineParams  oParams       = new REngineParams();
            REngine        oEngine;

            /*   ----------------------------------------------------------   */
            /*   You may need to change some values, such as the CertFile     */
            /*   ----------------------------------------------------------   */

            oParams.AdmCnnctPt   = sAdmCnnctPt;
            oParams.AppName      = "SampleMD.NET";
            oParams.AppVersion   = "1.0.0.0";
            oParams.AdmCallbacks = oAdmCallbacks;
            oParams.CertFile     = "c:\\data\\rithmiccerts\\RithmicCertificate.pk12";
            oParams.DmnSrvrAddr  = "rituz01000.01.rithmic.com:65000";
            oParams.DomainName   = "rithmic_uat_01_dmz_domain";
            oParams.LicSrvrAddr  = "rituz01000.01.rithmic.com:56000";
            oParams.LocBrokAddr  = "rituz01000.01.rithmic.com:64100";
            oParams.LoggerAddr   = "rituz01000.01.rithmic.com:45454";

            /*   -----------------------------------------------------------   */

            try
            {
                /*   ------------------------------------------------------   */
                /*   Instantiate the REngine.                                 */
                /*   ------------------------------------------------------   */

                oEngine = new REngine(oParams);

                /*   ------------------------------------------------------   */
                /*   Initiate the login.                                      */
                /*   ------------------------------------------------------   */

                oEngine.login(oCallbacks,
                              sUser,
                              sPassword,
                              sMdCnnctPt,
                              sTsCnnctPt,
                              string.Empty,
                              string.Empty);

                /*   ------------------------------------------------------   */
                /*   After calling REngine::login, RCallbacks::Alert will be  */
                /*   called a number of times.  Wait for when the login to    */
                /*   the MdCnnctPt and TsCnnctPt is complete.  (See           */
                /*   MyCallbacks::Alert() for details).                       */
                /*   ------------------------------------------------------   */

                while (!oCallbacks.LoggedIntoMd)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                /*   ------------------------------------------------------   */
                /*   Subscribe to the instrument of interest.  To express     */
                /*   interest in different types of updates, see              */
                /*   SubscriptionFlags.                                       */
                /*   ------------------------------------------------------   */

                oEngine.subscribe(sExchange,
                                  sSymbol,
                                  (SubscriptionFlags)Convert.ToInt32(sFlags),
                                  null);

                /*   ------------------------------------------------------   */
                /*   At this point the callback routines will start firing    */
                /*   on a different thread.  This main thread will wait       */
                /*   until a key is pressed before continuing.                */
                /*   ------------------------------------------------------   */

                Console.Read();

                /*   ------------------------------------------------------   */
                /*   We are done, so log out...                               */
                /*   ------------------------------------------------------   */

                oEngine.logout();

                /*   ------------------------------------------------------   */
                /*   and shutdown the REngine instance.                       */
                /*   ------------------------------------------------------   */

                oEngine.shutdown();
            }
            catch (OMException oEx)
            {
                System.Console.Out.WriteLine("error : {0}", oEx.Message);
            }
            catch (Exception e)
            {
                System.Console.Out.WriteLine("exception : {0}", e.Message);
            }

            /*   -----------------------------------------------------------   */

            return;
        }
Пример #31
0
        public static void Main(string[] args)
        {
            /*
             * REngine engine = REngine.GetInstance();
             * string fileName;
             *
             * //init the R engine
             * REngine.SetEnvironmentVariables();
             * engine = REngine.GetInstance();
             * engine.Initialize();
             *
             * //prepare data
             * List<int> size = new List<int>() { 29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238 };
             * List<int> population = new List<int>() { 3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327 };
             *
             * fileName = "C:\\Users\\ofunke\\Desktop\\myplot.png";
             *
             * //calculate
             * IntegerVector sizeVector = engine.CreateIntegerVector(size);
             * engine.SetSymbol("size", sizeVector);
             *
             * IntegerVector populationVector = engine.CreateIntegerVector(population);
             * engine.SetSymbol("population", populationVector);
             *
             * CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName });
             * engine.SetSymbol("fileName", fileNameVector);
             *
             * engine.Evaluate("reg <- lm(population~size)");
             * engine.Evaluate("png(filename=fileName, width=6, height=6, units='in', res=100)");
             * engine.Evaluate("plot(population~size)");
             * engine.Evaluate("abline(reg)");
             * engine.Evaluate("dev.off()");
             *
             * //clean up
             * engine.Dispose();
             *
             * //output
             * Console.WriteLine("");
             * Console.WriteLine("Press any key to exit");
             * Console.ReadKey();
             */
            StartupParameter rinit = new StartupParameter();

            rinit.Quiet       = true;
            rinit.RHome       = "C:/Program Files/R/R-3.4.3";
            rinit.Interactive = true;

            REngine.SetEnvironmentVariables();
            // There are several options to initialize the engine, but by default the following suffice:
            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();
        }
Пример #32
0
        private void button1_Click(object sender, EventArgs e)
        {
            REngine.SetEnvironmentVariables();

            textBox6.Text = "";
            textBox6.Hide();
            REngine engine = REngine.GetInstance();

            engine.Evaluate(".libPaths('C:\\\\Program Files\\\\R\\\\R-3.4.3\\\\library')");
            pictureBox1.Hide();
            string rExp, input, bl = "\r\n", its = "";
            float  a, b, valorReal = 0, Stop, aux;

            if ((comboBox2.SelectedItem.Equals("ER") && float.Parse(textBox4.Text) != 0) || !comboBox2.SelectedItem.Equals("ER"))
            {
                if (comboBox2.SelectedItem.Equals("EA") || comboBox2.SelectedItem.Equals("ER"))
                {
                    try
                    {
                        valorReal = float.Parse(textBox4.Text);
                    }
                    catch (Exception l)
                    {
                        MessageBox.Show("Insira o Valor Real.");
                    }
                }

                #region METODO DA BISSEÇÃO
                if (comboBox1.SelectedItem.Equals("Método da Bisseção"))
                {
                    int   count = 1;
                    float midT = 0, mid = 0;

                    try
                    {
                        input = textBox1.Text;
                        string aT = textBox2.Text;
                        string bT = textBox3.Text;
                        Stop = float.Parse(textBox5.Text);

                        if (comboBox2.SelectedItem.Equals("EA"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + aT + "," + bT + "]" + bl;

                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp = "x=" + aT + ";" + input;
                                a    = float.Parse(rExe(engine, rExp));
                                its += "f(" + aT + ") = " + Convert.ToString(a);
                                if (a < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                rExp = "x=" + bT + ";" + input;
                                b    = float.Parse(rExe(engine, rExp));
                                its += "f(" + bT + ") = " + Convert.ToString(b);
                                if (b < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                midT = (float.Parse(aT) + float.Parse(bT)) / 2;
                                rExp = "x=" + Convert.ToString(midT) + ";" + input;
                                mid  = float.Parse(rExe(engine, rExp));
                                its += "(a+b)/2 = " + Convert.ToString(midT) + bl;
                                its += "f(" + midT + ") = " + Convert.ToString(mid);
                                if (mid < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }
                                its += "Erro absoluto: " + Convert.ToString(Math.Abs(valorReal - midT)) + bl;

                                if ((mid > 0 && b > 0 && a < 0) || (mid < 0 && b < 0 && a > 0))
                                {
                                    bT = Convert.ToString(midT);
                                }
                                else
                                {
                                    aT = Convert.ToString(midT);
                                }
                            }while (Math.Abs(valorReal - midT) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("ER"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + aT + "," + bT + "]" + bl;

                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp = "x=" + aT + ";" + input;
                                a    = float.Parse(rExe(engine, rExp));
                                its += "f(" + aT + ") = " + Convert.ToString(a);
                                if (a < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                rExp = "x=" + bT + ";" + input;
                                b    = float.Parse(rExe(engine, rExp));
                                its += "f(" + bT + ") = " + Convert.ToString(b);
                                if (b < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                midT = (float.Parse(aT) + float.Parse(bT)) / 2;
                                rExp = "x=" + Convert.ToString(midT) + ";" + input;
                                mid  = float.Parse(rExe(engine, rExp));
                                its += "(a+b)/2 = " + Convert.ToString(midT) + bl;
                                its += "f(" + midT + ") = " + Convert.ToString(mid);
                                if (mid < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }
                                its += "Erro relativo: " + Convert.ToString((Math.Abs(valorReal - midT)) / valorReal) + bl;

                                if ((mid > 0 && b > 0 && a < 0) || (mid < 0 && b < 0 && a > 0))
                                {
                                    bT = Convert.ToString(midT);
                                }
                                else
                                {
                                    aT = Convert.ToString(midT);
                                }
                            }while ((Math.Abs(valorReal - midT) / valorReal) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("Nº de iterações"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + aT + "," + bT + "]" + bl;

                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp = "x=" + aT + ";" + input;
                                a    = float.Parse(rExe(engine, rExp));
                                its += "f(" + aT + ") = " + Convert.ToString(a);
                                if (a < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                rExp = "x=" + bT + ";" + input;
                                b    = float.Parse(rExe(engine, rExp));
                                its += "f(" + bT + ") = " + Convert.ToString(b);
                                if (b < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                midT = (float.Parse(aT) + float.Parse(bT)) / 2;
                                rExp = "x=" + Convert.ToString(midT) + ";" + input;
                                mid  = float.Parse(rExe(engine, rExp));
                                its += "(a+b)/2 = " + Convert.ToString(midT) + bl;
                                its += "f(" + midT + ") = " + Convert.ToString(mid);
                                if (mid < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                its += "Erro absoluto: " + Convert.ToString(Math.Abs(valorReal - midT)) + bl;
                                its += "Erro relativo: " + Convert.ToString((Math.Abs(valorReal - midT)) / valorReal) + bl;

                                if ((mid > 0 && b > 0 && a < 0) || (mid < 0 && b < 0 && a > 0))
                                {
                                    bT = Convert.ToString(midT);
                                }
                                else
                                {
                                    aT = Convert.ToString(midT);
                                }
                            }while (count <= Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("Valor no ponto"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + aT + "," + bT + "]" + bl;

                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp = "x=" + aT + ";" + input;
                                a    = float.Parse(rExe(engine, rExp));
                                its += "f(" + aT + ") = " + Convert.ToString(a);
                                if (a < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                rExp = "x=" + bT + ";" + input;
                                b    = float.Parse(rExe(engine, rExp));
                                its += "f(" + bT + ") = " + Convert.ToString(b);
                                if (b < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                midT = (float.Parse(aT) + float.Parse(bT)) / 2;
                                rExp = "x=" + Convert.ToString(midT) + ";" + input;
                                mid  = float.Parse(rExe(engine, rExp));
                                its += "(a+b)/2 = " + Convert.ToString(midT) + bl;
                                its += "f(" + Convert.ToString(midT) + ") = " + Convert.ToString(mid);
                                if (mid < 0)
                                {
                                    its += " < 0" + bl;
                                }
                                else
                                {
                                    its += " > 0" + bl;
                                }

                                its += "Valor no ponto: " + Convert.ToString(mid);

                                if ((mid > 0 && b > 0 && a < 0) || (mid < 0 && b < 0 && a > 0))
                                {
                                    bT = Convert.ToString(midT);
                                }
                                else
                                {
                                    aT = Convert.ToString(midT);
                                }
                            }while (Math.Abs(mid) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }

                        textBox6.Show();
                        textBox6.Text = its;
                        #region PLOT
                        pictureBox1.Show();
                        rPlot(engine, "curve(" + textBox1.Text + "," + Convert.ToString(midT - (0.5 * midT)) + "," + Convert.ToString(midT + (0.5 * midT)) + ");abline(h=0,col=\"black\");abline(v=0,col=\"black\");grid()", pictureBox1);
                        FileStream stream = new FileStream("rplot.jpg", FileMode.Open, FileAccess.Read);
                        pictureBox1.Image = Image.FromStream(stream);
                        stream.Dispose();
                        File.Delete(@"rplot.jpg");
                        #endregion
                    }
                    catch (Exception d)
                    {
                        MessageBox.Show("Insira todos os valores corretamente");
                    }
                }
                #endregion

                #region POSIÇÃO FALSA
                else if (comboBox1.SelectedItem.Equals("Método da Posição Falsa"))
                {
                    float  x = 0;
                    string rExpA, rExpB, rExpX;
                    int    count = 0;

                    try
                    {
                        input = textBox1.Text;
                        a     = float.Parse(s: textBox2.Text);
                        b     = float.Parse(s: textBox3.Text);
                        if (a > b)
                        {
                            aux = a;
                            a   = b;
                            b   = aux;
                        }
                        Stop = float.Parse(textBox5.Text);

                        if (comboBox2.SelectedItem.Equals("EA"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + Convert.ToString(a) + "," + Convert.ToString(b) + "]" + bl;

                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;
                                rExpA = "x=" + Convert.ToString(a) + ";" + input;
                                rExpB = "x=" + Convert.ToString(b) + ";" + input;
                                its  += "((" + Convert.ToString(a) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + ") - (" + Convert.ToString(b) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + "))/(" + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + " - " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + ") =";
                                x     = (a * float.Parse(rExe(engine, rExpB)) - b * float.Parse(rExe(engine, rExpA))) / (float.Parse(rExe(engine, rExpB)) - float.Parse(rExe(engine, rExpA)));
                                its  += Convert.ToString(x) + bl;
                                rExpX = "x=" + Convert.ToString(x) + ";" + input;
                                its  += "[a,b] = [" + Convert.ToString(Math.Round(a, 3)) + " , " + Convert.ToString(Math.Round(b, 3)) + "]" + bl;
                                if (x < b)
                                {
                                    a = x;
                                }
                                else
                                {
                                    a = b;
                                    b = x;
                                }

                                its += "Erro absoluto: " + (Math.Abs(x - valorReal)) + bl;
                            }while ((Math.Abs(x - valorReal)) >= Stop);
                        }

                        else if (comboBox2.SelectedItem.Equals("ER"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + Convert.ToString(a) + "," + Convert.ToString(b) + "]" + bl;
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;
                                rExpA = "x=" + Convert.ToString(a) + ";" + input;
                                rExpB = "x=" + Convert.ToString(b) + ";" + input;
                                its  += "((" + Convert.ToString(a) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + ") - (" + Convert.ToString(b) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + "))/(" + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + " - " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + ") =";
                                x     = (a * float.Parse(rExe(engine, rExpB)) - b * float.Parse(rExe(engine, rExpA))) / (float.Parse(rExe(engine, rExpB)) - float.Parse(rExe(engine, rExpA)));
                                its  += Convert.ToString(x) + bl;
                                rExpX = "x=" + Convert.ToString(x) + ";" + input;
                                its  += "[a,b] = [" + Convert.ToString(Math.Round(a, 3)) + " , " + Convert.ToString(Math.Round(b, 3)) + "]" + bl;
                                if (x < b)
                                {
                                    a = x;
                                }
                                else
                                {
                                    a = b;
                                    b = x;
                                }

                                its += "Erro relativo: " + Convert.ToString((Math.Abs(x - valorReal) / valorReal)) + bl;
                            }while ((Math.Abs(x - valorReal) / valorReal) > Stop);
                        }

                        else if (comboBox2.SelectedItem.Equals("Nº de iterações"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + Convert.ToString(a) + "," + Convert.ToString(b) + "]" + bl;
                            int i;
                            for (i = 0; i < Stop; i++)
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;
                                rExpA = "x=" + Convert.ToString(a) + ";" + input;
                                rExpB = "x=" + Convert.ToString(b) + ";" + input;
                                its  += "((" + Convert.ToString(a) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + ") - (" + Convert.ToString(b) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + "))/(" + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + " - " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + ") = ";
                                x     = (a * float.Parse(rExe(engine, rExpB)) - b * float.Parse(rExe(engine, rExpA))) / (float.Parse(rExe(engine, rExpB)) - float.Parse(rExe(engine, rExpA)));
                                its  += Convert.ToString(x) + bl;
                                its  += "[a,b] = [" + Convert.ToString(Math.Round(a, 3)) + " , " + Convert.ToString(Math.Round(b, 3)) + "]" + bl;
                                if (x < b)
                                {
                                    a = x;
                                }
                                else
                                {
                                    a = b;
                                    b = x;
                                }
                            }
                        }

                        else if (comboBox2.SelectedItem.Equals("Valor no ponto"))
                        {
                            its += input + bl;
                            its += "[a,b] = [" + Convert.ToString(a) + "," + Convert.ToString(b) + "]" + bl;
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;
                                rExpA = "x=" + Convert.ToString(a) + ";" + input;
                                rExpB = "x=" + Convert.ToString(b) + ";" + input;
                                its  += "((" + Convert.ToString(a) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + ") - (" + Convert.ToString(b) + " x " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + "))/(" + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpB)), 4)) + " - " + Convert.ToString(Math.Round(float.Parse(rExe(engine, rExpA)), 4)) + ") =";
                                x     = (a * float.Parse(rExe(engine, rExpB)) - b * float.Parse(rExe(engine, rExpA))) / (float.Parse(rExe(engine, rExpB)) - float.Parse(rExe(engine, rExpA)));
                                its  += Convert.ToString(x) + bl;
                                rExpX = "x=" + Convert.ToString(value: x) + ";" + input;
                                its  += "[a,b] = [" + Convert.ToString(Math.Round(a, 3)) + " , " + Convert.ToString(Math.Round(b, 3)) + "]" + bl;
                                if (x < b)
                                {
                                    a = x;
                                }
                                else
                                {
                                    a = b;
                                    b = x;
                                }

                                its += "f(" + Convert.ToString(x) + ") = " + rExe(engine, rExpX) + bl;
                            }while (Math.Abs(float.Parse(rExe(engine, rExpX))) > Stop);
                        }

                        #region PLOT
                        pictureBox1.Show();
                        rPlot(engine, "curve(" + textBox1.Text + "," + Convert.ToString(x - (0.5 * x)) + "," + Convert.ToString(x + (0.5 * x)) + ");abline(h=0,col=\"black\");abline(v=0,col=\"black\");grid()", pictureBox1);
                        FileStream stream = new FileStream("rplot.jpg", FileMode.Open, FileAccess.Read);
                        pictureBox1.Image = Image.FromStream(stream);
                        stream.Dispose();
                        File.Delete(@"rplot.jpg");
                        #endregion
                        //MessageBox.Show(Convert.ToString(value: x));
                        its += bl + "Resultado: " + Convert.ToString(x);
                        textBox6.Show();
                        textBox6.Text = its;
                    }
                    catch (Exception g)
                    {
                        MessageBox.Show("Insira todos os valores corretamente eu");
                    }
                }
                #endregion

                #region Metodo de Newton
                if (comboBox1.SelectedItem.Equals("Método de Newton-Raphson"))
                {
                    int    count = 1;
                    float  midT = 0, mid = 0;
                    float  f_linha;
                    float  f;
                    string valT;
                    input = textBox1.Text;
                    string aT = textBox2.Text;

                    try
                    {
                        Stop = float.Parse(textBox5.Text);
                        midT = float.Parse(aT);
                        its += input + bl;
                        if (comboBox2.SelectedItem.Equals("EA"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));

                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( " + Convert.ToString(f) + " / " + Convert.ToString(f_linha) + " )" + bl;
                                midT = midT - (f / f_linha);
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;

                                its += "Erro absoluto: " + Convert.ToString(Math.Abs(valorReal - midT)) + bl;
                            }while (Math.Abs(valorReal - midT) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("ER"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));



                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( " + Convert.ToString(f) + " / " + Convert.ToString(f_linha) + " )" + bl;
                                midT = midT - (f / f_linha);
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;

                                its += "Erro relativo: " + Convert.ToString((Math.Abs(valorReal - midT)) / valorReal) + bl;
                            }while ((Math.Abs(valorReal - midT) / valorReal) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("Nº de iterações"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));

                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( " + Convert.ToString(f) + " / " + Convert.ToString(f_linha) + " )" + bl;
                                midT = midT - (f / f_linha);
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;
                            }while (count <= Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("Valor no ponto"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));
                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;

                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( " + Convert.ToString(f) + " / " + Convert.ToString(f_linha) + " )" + bl;
                                midT = midT - (f / f_linha);

                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;

                                rExp = "x=" + Convert.ToString(midT) + ";" + input;
                                mid  = float.Parse(rExe(engine, rExp));

                                its += "Valor no ponto: " + Convert.ToString(mid) + bl;
                            }while (Math.Abs(mid) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }

                        textBox6.Show();
                        textBox6.Text = its;
                        #region PLOT
                        pictureBox1.Show();
                        rPlot(engine, "curve(" + textBox1.Text + "," + Convert.ToString(midT - (0.5 * midT)) + "," + Convert.ToString(midT + (0.5 * midT)) + ");abline(h=0,col=\"black\");abline(v=0,col=\"black\");grid()", pictureBox1);
                        FileStream stream = new FileStream("rplot.jpg", FileMode.Open, FileAccess.Read);
                        pictureBox1.Image = Image.FromStream(stream);
                        stream.Dispose();
                        File.Delete(@"rplot.jpg");
                        #endregion */
                    }
                    catch (Exception d)
                    {
                        MessageBox.Show("Insira todos os valores corretamente");
                    }
                }
                #endregion

                #region Metodo de Halley
                if (comboBox1.SelectedItem.Equals("Método de Halley"))
                {
                    int    count = 1;
                    float  midT = 0, mid = 0;
                    float  f_2linha;
                    float  f_linha;
                    float  f;
                    string valT;
                    input = textBox1.Text;
                    string aT = textBox2.Text;

                    try
                    {
                        Stop = float.Parse(textBox5.Text);
                        midT = float.Parse(aT);
                        its += input + bl;
                        if (comboBox2.SelectedItem.Equals("EA"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp     = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-2*f(" + Convert.ToString(midT) + ")+f(" + Convert.ToString(midT) + "-0.0000001))/(0.0000001^2);";
                                f_2linha = float.Parse(rExe(engine, rExp));

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));

                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;

                                its += "f''(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_2linha) + bl;

                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( (2* " + Convert.ToString(f) + "* " + Convert.ToString(f_linha) + ") / ( 2*(" + Convert.ToString(f_linha) + ")^2 - (" + Convert.ToString(f) + "* " + Convert.ToString(f_2linha) + ") ) )" + bl;

                                midT = midT - ((2 * f * f_linha) / (2 * (f_linha * f_linha) - f * f_2linha));
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;

                                its += "Erro absoluto: " + Convert.ToString(Math.Abs(valorReal - midT)) + bl;
                            }while (Math.Abs(valorReal - midT) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("ER"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;
                                rExp     = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-2*f(" + Convert.ToString(midT) + ")+f(" + Convert.ToString(midT) + "-0.0000001))/(0.0000001^2);";
                                f_2linha = float.Parse(rExe(engine, rExp));

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));

                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;

                                its += "f''(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_2linha) + bl;

                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( (2* " + Convert.ToString(f) + "* " + Convert.ToString(f_linha) + ") / ( 2*(" + Convert.ToString(f_linha) + ")^2 - (" + Convert.ToString(f) + "* " + Convert.ToString(f_2linha) + ") ) )" + bl;

                                midT = midT - ((2 * f * f_linha) / (2 * (f_linha * f_linha) - f * f_2linha));
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;

                                its += "Erro relativo: " + Convert.ToString((Math.Abs(valorReal - midT)) / valorReal) + bl;
                            }while ((Math.Abs(valorReal - midT) / valorReal) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("Nº de iterações"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;
                                rExp     = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-2*f(" + Convert.ToString(midT) + ")+f(" + Convert.ToString(midT) + "-0.0000001))/(0.0000001^2);";
                                f_2linha = float.Parse(rExe(engine, rExp));

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));

                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;

                                its += "f''(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_2linha) + bl;

                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( (2* " + Convert.ToString(f) + "* " + Convert.ToString(f_linha) + ") / ( 2*(" + Convert.ToString(f_linha) + ")^2 - (" + Convert.ToString(f) + "* " + Convert.ToString(f_2linha) + ") ) )" + bl;

                                midT = midT - ((2 * f * f_linha) / (2 * (f_linha * f_linha) - f * f_2linha));
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;
                            }while (count <= Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }
                        else if (comboBox2.SelectedItem.Equals("Valor no ponto"))
                        {
                            do
                            {
                                its += bl + "-> Iteração " + Convert.ToString(count) + bl + bl;
                                count++;

                                rExp     = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-2*f(" + Convert.ToString(midT) + ")+f(" + Convert.ToString(midT) + "-0.0000001))/(0.0000001^2);";
                                f_2linha = float.Parse(rExe(engine, rExp));

                                rExp    = "f = function(x) " + input + ";(f(" + Convert.ToString(midT) + "+0.0000001)-f(" + Convert.ToString(midT) + "))/(0.0000001);";
                                f_linha = float.Parse(rExe(engine, rExp));

                                rExp = "f(" + midT + ");";
                                f    = float.Parse(rExe(engine, rExp));

                                its += "x" + Convert.ToString(count - 2) + " = " + midT + bl;
                                its += "f(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f) + bl;
                                its += "f'(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_linha) + bl;

                                its += "f''(x" + Convert.ToString(count - 2) + ") = " + Convert.ToString(f_2linha) + bl;

                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + " - ( (2* " + Convert.ToString(f) + "* " + Convert.ToString(f_linha) + ") / ( 2*(" + Convert.ToString(f_linha) + ")^2 - (" + Convert.ToString(f) + "* " + Convert.ToString(f_2linha) + ") ) )" + bl;

                                midT = midT - ((2 * f * f_linha) / (2 * (f_linha * f_linha) - f * f_2linha));
                                its += "x" + Convert.ToString(count - 1) + " = " + Convert.ToString(midT) + bl;

                                rExp = "x=" + Convert.ToString(midT) + ";" + input;
                                mid  = float.Parse(rExe(engine, rExp));

                                its += "Valor no ponto: " + Convert.ToString(mid) + bl;
                            }while (Math.Abs(mid) > Stop);
                            its += bl + "Resultado: " + midT + bl;
                            its += bl;
                        }

                        textBox6.Show();
                        textBox6.Text = its;
                        #region PLOT
                        pictureBox1.Show();
                        rPlot(engine, "curve(" + textBox1.Text + "," + Convert.ToString(midT - (0.5 * midT)) + "," + Convert.ToString(midT + (0.5 * midT)) + ");abline(h=0,col=\"black\");abline(v=0,col=\"black\");grid()", pictureBox1);
                        FileStream stream = new FileStream("rplot.jpg", FileMode.Open, FileAccess.Read);
                        pictureBox1.Image = Image.FromStream(stream);
                        stream.Dispose();
                        File.Delete(@"rplot.jpg");
                        #endregion */
                    }
                    catch (Exception d)
                    {
                        MessageBox.Show("Insira todos os valores corretamente");
                    }
                }

                #endregion


                /*
                 * if (textBox1.Text.Contains("curve") || textBox1.Text.Contains("plot"))
                 * {
                 *  //PLOT SECTION
                 #region PLOT
                 *  pictureBox1.Show();
                 *  rPlot(engine, textBox1.Text, pictureBox1);
                 *  FileStream stream = new FileStream("rplot.jpg", FileMode.Open, FileAccess.Read);
                 *  pictureBox1.Image = Image.FromStream(stream);
                 *  stream.Dispose();
                 *  File.Delete(@"rplot.jpg");
                 #endregion
                 * }
                 * else
                 * {
                 *
                 * }*/
                /*
                 * else if(!textBox1.Text.Equals(""))
                 * {
                 *  if(!rExe(engine, textBox1.Text).Equals(""))
                 *  {
                 *      MessageBox.Show(rExe(engine, textBox1.Text));
                 *  }
                 * }*/
            }
            else if (comboBox2.SelectedItem.Equals("ER") && float.Parse(textBox4.Text) == 0)
            {
                MessageBox.Show("Para erros relativos, insira um \"Valor Real\" diferente de 0");
            }

            engine.ClearGlobalEnvironment();
        }
Пример #33
0
 private static void SetInterruptsSuspended(REngine engine, bool value)
 {
     var pointer = engine.DangerousGetHandle("R_interrupts_suspended");
     Marshal.WriteInt32(pointer, Convert.ToInt32(value));
 }
 /// <summary>
 /// Checks the equality in native memory of a pointer against a pointer to the R 'R_UnboundValue',
 /// i.e. whether a symbol exists (i.e. functional equivalent to "exists('varName')" in R)
 /// </summary>
 /// <param name="engine">R.NET Rengine</param>
 /// <param name="pointer">Pointer to test</param>
 /// <returns>True if the pointer is not bound to a value</returns>
 public static bool CheckUnbound(this REngine engine, IntPtr pointer)
 {
     return(engine.UnboundValue.DangerousGetHandle() == pointer);
 }
Пример #35
0
     static void Main(string[] args)
          {
          string USAGE = "SampleOrder adm_cnnct_pt " +
                         "user password md_cnnct_pt ts_cnnct_pt " +
                         "exchange symbol [B|S]";

          if (args.Length < 8)
               {
               System.Console.Out.WriteLine(USAGE);
               return;
               }

          /*   -----------------------------------------------------------   */

          string sAdmCnnctPt  = args[0];
          string sUser        = args[1];
          string sPassword    = args[2];
          string sMdCnnctPt   = args[3];
          string sTsCnnctPt   = args[4];
          string sExchange    = args[5];
          string sSymbol      = args[6];
          string sBuySellType = args[7];

          /*   -----------------------------------------------------------   */

          MyAdmCallbacks oAdmCallbacks = new MyAdmCallbacks();
          MyCallbacks    oCallbacks    = new MyCallbacks();
          REngineParams  oParams       = new REngineParams();
          REngine        oEngine;

          /*   ----------------------------------------------------------   */
          /*   You may need to change some values, such as the CertFile     */
          /*   ----------------------------------------------------------   */

          oParams.AdmCnnctPt   = sAdmCnnctPt;
          oParams.AppName      = "SampleOrder.NET";
          oParams.AppVersion   = "1.0.0.0";
          oParams.AdmCallbacks = oAdmCallbacks;
          oParams.CertFile     = "c:\\data\\rithmiccerts\\RithmicCertificate.pk12";
          oParams.DmnSrvrAddr  = "rituz01000.01.rithmic.com:65000";
          oParams.DomainName   = "rithmic_uat_01_dmz_domain";
          oParams.LicSrvrAddr  = "rituz01000.01.rithmic.com:56000";
          oParams.LocBrokAddr  = "rituz01000.01.rithmic.com:64100";
          oParams.LoggerAddr   = "rituz01000.01.rithmic.com:45454";

          /*   ----------------------------------------------------------   */

          try
               {
               /*   ------------------------------------------------------   */
               /*   Instantiate the REngine.                                 */
               /*   ------------------------------------------------------   */

               oEngine = new REngine(oParams);

               /*   ------------------------------------------------------   */
               /*   Initiate the login.                                      */
               /*   ------------------------------------------------------   */

               oEngine.login(oCallbacks, 
                    sUser, 
                    sPassword, 
                    sMdCnnctPt, 
                    sTsCnnctPt, 
                    string.Empty,
                    string.Empty);

               /*   ------------------------------------------------------   */
               /*   After calling REngine::login, RCallbacks::Alert will be  */
               /*   called a number of times.  Wait for when the login to    */
               /*   the MdCnnctPt and TsCnnctPt is complete.  (See           */
               /*   MyCallbacks::Alert() for details).                       */
               /*   ------------------------------------------------------   */

               while (!oCallbacks.LoggedIntoMd || !oCallbacks.LoggedIntoTs)
                    {
                    System.Threading.Thread.Sleep(1000);
                    }

               /*   ------------------------------------------------------   */
               /*   Wait for the AccountList callback to fire, so we know    */
               /*   which accounts we are permissioned on.  The account on   */
               /*   which we place the order will be the first account in    */
               /*   the list.  See MyCallbacks::AccountList() for details.   */
               /*   ------------------------------------------------------   */

               while (!oCallbacks.GotAccounts)
                    {
                    System.Threading.Thread.Sleep(1000);
                    }

               /*   ------------------------------------------------------   */

               if (oCallbacks.Account == null)
                    {
                    System.Console.WriteLine("Error : didn't get an account");
                    return;
                    }

               /*   ------------------------------------------------------   */
               /*   Subscribe to account activity.  By doing so, we will     */
               /*   receive updates for orders placed on the account and     */
               /*   pnl updates for that account.                            */
               /*   ------------------------------------------------------   */

               oEngine.subscribeAccount(oCallbacks.Account);
               
               /*   ------------------------------------------------------   */
               /*   Prepare the order params and then send it.               */
               /*   ------------------------------------------------------   */

               MarketOrderParams oOrderParams = new MarketOrderParams();
               oOrderParams.Account = oCallbacks.Account;
               oOrderParams.BuySellType = sBuySellType;
               oOrderParams.Context = null;
               oOrderParams.Duration = Constants.ORDER_DURATION_DAY;
               oOrderParams.EntryType = Constants.ORDER_ENTRY_TYPE_MANUAL;
               oOrderParams.Exchange = sExchange;
               oOrderParams.Qty = 1;
               oOrderParams.Symbol = sSymbol;
               oOrderParams.Tag = null;
               oOrderParams.UserMsg = null;

               oEngine.sendOrder(oOrderParams);

               /*   ------------------------------------------------------   */
               /*   Wait for the order to complete.  A number of related     */
               /*   callbacks will fire, but the one controlling the status  */
               /*   of complete is done in MyCallbacks::LineUpdate().        */
               /*   ------------------------------------------------------   */

               while (!oCallbacks.OrderComplete)
                    {
                    System.Threading.Thread.Sleep(1000);
                    }

               /*   ------------------------------------------------------   */
               /*   We are done, so log out...                               */
               /*   ------------------------------------------------------   */

               oEngine.logout();

               /*   ------------------------------------------------------   */
               /*   and shutdown the REngine instance.                       */
               /*   ------------------------------------------------------   */

               oEngine.shutdown();
               }
          catch (OMException oEx)
               {
               System.Console.Out.WriteLine("error : {0}", oEx.Message);
               }
          catch (Exception e)
               {
               System.Console.Out.WriteLine("exception : {0}", e.Message);
               }

          /*   ----------------------------------------------------------   */

          return;
          }