[chronojump] Leave opened encoder R Processes (analyze done). Need to check the TODOs and clean



commit fff3fc4428de62e78754410b8418d738e3be5e5c
Author: Xavier de Blas <xaviblas gmail com>
Date:   Fri Apr 24 20:34:29 2015 +0200

    Leave opened encoder R Processes (analyze done). Need to check the TODOs and clean

 encoder/call_graph.R  |   24 ++++-
 encoder/graph.R       |   24 ++--
 src/encoderRProc.cs   |  277 ++++++++++++++++++++++++++++++++++++++++---------
 src/gui/chronojump.cs |    2 +-
 src/gui/encoder.cs    |   48 ++++++---
 src/utilEncoder.cs    |  130 +----------------------
 6 files changed, 300 insertions(+), 205 deletions(-)
---
diff --git a/encoder/call_graph.R b/encoder/call_graph.R
index 72b2ca8..3d17dd7 100644
--- a/encoder/call_graph.R
+++ b/encoder/call_graph.R
@@ -41,6 +41,12 @@ EncoderConfigurationName <- ""
 English = unlist(strsplit(options[30], "\\;"))
 Translated = unlist(strsplit(options[31], "\\;"))
 
+#TODO: now that there's a start and continue of each process from R,
+#instead of pass and script from R,
+#pass the directory
+#and R will source() the needed files (maybe all the first time)
+#and it will not do again when the process is continued (see encoderRProc.cs)
+
 scriptUtilR = options[28]
 source(scriptUtilR)
 
@@ -71,4 +77,20 @@ print("Creating (OutputData2)3.txt with touch method...")
 file.create(paste(OutputData2,"3.txt",sep=""))
 print("Created")
 
-doProcess(options)
+while(TRUE) {
+       doProcess(options)
+
+       #continue the process or exit
+       f <- file("stdin")
+       open(f)
+
+       input <- readLines(f, n = 1L)
+       if(input[1] == "Q")
+               quit("no")
+                       
+       write("received a continue signal", stderr())
+       options <- getOptionsFromFile(optionsFile, 32)
+       
+       #TODO 1: check if all the Output2, SpecialData, ... variables have to be reassigned
+       #TODO 2: check if neuromuscularProfile should be loaded
+}
diff --git a/encoder/graph.R b/encoder/graph.R
index baf1fdc..74eda45 100644
--- a/encoder/graph.R
+++ b/encoder/graph.R
@@ -1957,11 +1957,11 @@ doProcess <- function(options)
                                            stringsAsFactors=F,row.names=1)
                }
 
+
                n=length(curves[,1])
                quitIfNoData(n, curves, op$OutputData1)
                
-               print("curves")
-               print(curves)
+               #print(curves, stderr())
        
                #find SmoothingsEC
                SmoothingsEC = findSmoothingsEC(singleFile, displacement, curves, op$Eccon, op$SmoothingOneC)
@@ -2323,7 +2323,7 @@ doProcess <- function(options)
                                }
                        }
 
-                       print(c("i, curves[i,1], curves[i,2]", i, curves[i,1],curves[i,2]))
+                       #print(c("i, curves[i,1], curves[i,2]", i, curves[i,1],curves[i,2]))
 
                        #if ecS go kinematics first time with "e" and second with "c"
                        myEcconKn = myEccon
@@ -2359,10 +2359,10 @@ doProcess <- function(options)
                rownames(paf)=rownames(curves)
                
                if(debug) {
-                       print("--------CURVES (propulsive is not calculated yet) --------------")
-                       print(curves)
-                       print("----------PAF---------------")
-                       print(paf)
+                       #print("--------CURVES (propulsive is not calculated yet) --------------")
+                       #print(curves)
+                       #print("----------PAF---------------")
+                       #print(paf)
                }
 
                if(op$Analysis == "powerBars") {
@@ -2390,10 +2390,10 @@ doProcess <- function(options)
 
                        ecconVector = createEcconVector(singleFile, op$Eccon, length(curves[,1]), curves[,8])
 
-                       print("AnalysisVariables:")
-                       print(op$AnalysisVariables[1])
-                       print(op$AnalysisVariables[2])
-                       print(op$AnalysisVariables[3])
+                       #print("AnalysisVariables:")
+                       #print(op$AnalysisVariables[1])
+                       #print(op$AnalysisVariables[2])
+                       #print(op$AnalysisVariables[3])
 
                        if(op$AnalysisVariables[1] == "Speed,Power") {
                                par(mar=c(5,4,5,5))
@@ -2527,7 +2527,7 @@ doProcess <- function(options)
                                        "mass", "massBody", "massExtra", #unneded
                                        "laterality")
                        write.csv(paf, op$OutputData1, quote=FALSE)
-                       print("curves written")
+                       #print("curves written")
                }
        }
        if(op$Analysis=="exportCSV") {
diff --git a/src/encoderRProc.cs b/src/encoderRProc.cs
index 778f1dd..6c05dd3 100644
--- a/src/encoderRProc.cs
+++ b/src/encoderRProc.cs
@@ -25,28 +25,39 @@ using System.IO;            //for detect OS
 
 public abstract class EncoderRProc 
 {
-       protected static Process p;
-       protected static ProcessStartInfo pinfo;
-       protected static bool running;
+       protected Process p;
+       protected ProcessStartInfo pinfo;
+
+       public enum Status { WAITING, RUNNING, DONE } 
+       public Status status;
 
        protected string optionsFile;   
        protected EncoderStruct es;
 
-       public void StartOrContinue(EncoderStruct es)
+       public bool StartOrContinue(EncoderStruct es)
        {
+               status = Status.RUNNING;
+
                this.es = es;
 
                //options change at every capture. So do at continueProcess and startProcess
                writeOptionsFile();
+
+               bool ok = true;
                        
                if(isRunning()) {
                        LogB.Debug("calling continue");
                        continueProcess();
+
                } else {
                        LogB.Debug("calling start");
-                       bool startedOk = startProcess();
-                       LogB.Debug("StartedOk: " + startedOk.ToString());
+                       ok = startProcess();
+                       LogB.Debug("StartedOk: " + ok.ToString());
                }
+       
+               status = Status.DONE;
+
+               return ok;
        }
 
        protected bool isRunning() 
@@ -111,7 +122,32 @@ public abstract class EncoderRProc
        protected virtual bool startProcess() {
                return true;
        }
+       
        protected virtual void continueProcess() {
+               LogB.Debug("sending continue process");
+               p.StandardInput.WriteLine("C");
+       }
+       
+       /*
+       protected void readingOutput (object sendingProcess, DataReceivedEventArgs outputFromR)
+       {
+               if (! String.IsNullOrEmpty(outputFromR.Data))
+                       LogB.Information(outputFromR.Data);
+       }
+       */
+       protected void readingError (object sendingProcess, DataReceivedEventArgs errorFromR)
+       {
+               if (! String.IsNullOrEmpty(errorFromR.Data))
+                       LogB.Warning(errorFromR.Data);
+       }
+
+       public void SendEndProcess() 
+       {
+               if(isRunning()) {
+                       LogB.Debug("Closing R capture script");
+                       p.StandardInput.WriteLine("Q");
+               } else
+                       LogB.Debug("R capture script is not working. Don't need to close.");
        }
 }
 
@@ -122,8 +158,6 @@ public class EncoderRProcCapture : EncoderRProc
        
        protected override bool startProcess() 
        {
-               LogB.Debug("A");
-               //ProcessStartInfo pinfo;
                //If output file is not given, R will try to write in the running folder
                //in which we may haven't got permissions
 
@@ -136,7 +170,6 @@ public class EncoderRProcCapture : EncoderRProc
                        pBin = "\"" + System.IO.Path.Combine(Util.GetPrefixDir(), "bin" + 
Path.DirectorySeparatorChar + "Rscript.exe") + "\"";
                        LogB.Information("pBin:", pBin);
                }
-               LogB.Debug("B");
 
 
                //on Windows we need the \"str\" to call without problems in path with spaces
@@ -156,13 +189,11 @@ public class EncoderRProcCapture : EncoderRProc
                //pinfo.RedirectStandardOutput = true; 
 
 
-
-               LogB.Debug("C");
                try {
-                       p= new Process();
+                       p = new Process();
                        p.StartInfo = pinfo;
 
-                       p.ErrorDataReceived += new DataReceivedEventHandler(readingCurveFromRerror);
+                       p.ErrorDataReceived += new DataReceivedEventHandler(readingError);
 
                        p.Start();
 
@@ -182,20 +213,6 @@ public class EncoderRProcCapture : EncoderRProc
                        
                return true;
        }
-       private void readingCurveFromRerror (object sendingProcess, DataReceivedEventArgs curveFromR)
-       {
-               if (! String.IsNullOrEmpty(curveFromR.Data))
-               {
-                       //use Warning because it's used also to print flow messages
-                       LogB.Warning(curveFromR.Data);
-               }
-       }
-       
-       protected override void continueProcess() 
-       {
-               LogB.Debug("sending continue process");
-               p.StandardInput.WriteLine("C");
-       }
        
        //here curve is sent compressed (string. eg: "0*5 1 0 -1*3 2")
        public void SendCurve(double heightAtStart, string curveCompressed)
@@ -217,15 +234,6 @@ public class EncoderRProcCapture : EncoderRProc
                LogB.Debug("<-- writen line 1");
        }       
        
-       public void SendEndProcess() 
-       {
-               if(isRunning()) {
-                       LogB.Debug("Closing R capture script");
-                       p.StandardInput.WriteLine("Q");
-               } else
-                       LogB.Debug("R capture script is not working. Don't need to close.");
-       }
-
        protected override void writeOptionsFile()
        {
                optionsFile = Path.GetTempPath() + "Roptions.txt";
@@ -249,39 +257,208 @@ public class EncoderRProcCapture : EncoderRProc
 
 public class EncoderRProcAnalyze : EncoderRProc 
 {
+       private string title;
+       private bool neuromuscularProfileDo;
+       private bool translate;
+
+       public bool CancelRScript;
+
        public EncoderRProcAnalyze() {
        }
 
+       public void SendData(string title, bool neuromuscularProfileDo, bool translate) {
+               this.title = title;
+               this.neuromuscularProfileDo = neuromuscularProfileDo;
+               this.translate = translate;
+               
+               CancelRScript = false;
+       }
+
        protected override bool startProcess() 
        {
+               //If output file is not given, R will try to write in the running folder
+               //in which we may haven't got permissions
+       
+               string pBin="";
+               pinfo = new ProcessStartInfo();
+
+               pBin="Rscript";
+               if (UtilAll.IsWindows()) {
+                       //on Windows we need the \"str\" to call without problems in path with spaces
+                       pBin = "\"" + System.IO.Path.Combine(Util.GetPrefixDir(), "bin" + 
Path.DirectorySeparatorChar + "Rscript.exe") + "\"";
+                       LogB.Information("pBin:", pBin);
+               }
+               
+               if (UtilAll.IsWindows()) {
+                       //On win32 R understands backlash as an escape character and 
+                       //a file path uses Unix-like path separator '/'         
+                       optionsFile = optionsFile.Replace("\\","/");
+               }
+               
+               //on Windows we need the \"str\" to call without problems in path with spaces
+               pinfo.Arguments = "\"" + getEncoderScriptCallGraph() + "\" " + optionsFile;
+       
+               LogB.Information("Arguments:", pinfo.Arguments);
+               LogB.Information("--- 1 --- " + optionsFile.ToString() + " ---");
+               //LogB.Information("--- 2 --- " + scriptOptions + " ---");
+               LogB.Information("--- 3 --- " + pinfo.Arguments.ToString() + " ---");
+               
+               string outputFileCheck = "";
+               string outputFileCheck2 = "";
+               
+               //Wait until this to update encoder gui (if don't wait then treeview will be outdated)
+               //exportCSV is the only one that doesn't have graph. all the rest Analysis have graph and data
+               if(es.Ep.Analysis == "exportCSV")
+                       outputFileCheck = es.OutputData1; 
+               else {
+                       //outputFileCheck = es.OutputGraph;
+                       //
+                       //OutputData1 because since Chronojump 1.3.6, 
+                       //encoder analyze has a treeview that can show the curves
+                       //when a graph analysis is done, curves file has to be written
+                       outputFileCheck = es.OutputData1;
+                       //check also the otuput graph
+                       outputFileCheck2 = es.OutputGraph; 
+               }
+                       
+               LogB.Information("outputFileChecks");
+               LogB.Information(outputFileCheck);
+               LogB.Information(outputFileCheck2);
+
+               pinfo.FileName=pBin;
+
+               pinfo.CreateNoWindow = true;
+               pinfo.UseShellExecute = false;
+               pinfo.RedirectStandardInput = true;
+               pinfo.RedirectStandardError = true;
+               
                /*
-                * WIP
-                *
-               try {   
+                * if redirect this there are problems because the buffers get saturated
+                * pinfo.RedirectStandardOutput = true; 
+                * if is not redirected, then prints are shown by console (but not in logB
+                * best solution is make the prints as write("message", stderr())
+                * and then will be shown in logB by readError
+                */
+
+
+               //delete output file check(s)
+               deleteFile(outputFileCheck);
+               if(outputFileCheck2 != "")
+                       deleteFile(outputFileCheck2);
+
+                       
+               //delete 1RM data if exists
+               if (File.Exists(es.SpecialData))
+                       File.Delete(es.SpecialData);
+
+               try {   
                        p = new Process();
                        p.StartInfo = pinfo;
+                       
+                       //do not redirect ouptut. Read above
+                       //p.OutputDataReceived += new DataReceivedEventHandler(readingOutput);
+                       p.ErrorDataReceived += new DataReceivedEventHandler(readingError);
+                       
                        p.Start();
 
-                       LogB.Information(p.StandardOutput.ReadToEnd());
-                       LogB.Warning(p.StandardError.ReadToEnd());
+                       //don't do this ReadToEnd because then this method never ends
+                       //LogB.Information(p.StandardOutput.ReadToEnd()); 
+                       //LogB.Warning(p.StandardError.ReadToEnd());
+                       
+                       // Start asynchronous read of the output.
+                       // Caution: This has to be called after Start
+                       //p.BeginOutputReadLine();
+                       p.BeginErrorReadLine();
 
-                       //p.WaitForExit(); //do NOT wait for exit
+
+                       if(outputFileCheck2 == "")
+                               while ( ! ( fileWritten(outputFileCheck) || CancelRScript) );
+                       else
+                               while ( ! ( (fileWritten(outputFileCheck) && fileWritten(outputFileCheck2)) 
|| CancelRScript ) );
                } catch {
+                       LogB.Warning("catched at startProcess");
                        return false;
                }
-                       
-               running = true;
-               */
+
                return true;
+
        }
        
        protected override void continueProcess() 
        {
-               /*
-                * create a file to be file to be readed by the Rscript
-                * or send there STDIN, like:
-                * p.StandardInput.WriteLine();
-                */
+               //TODO: outputFileCheck creation/deletion here and at startProcess, should be unique
+               string outputFileCheck = "";
+               string outputFileCheck2 = "";
+               
+               if(es.Ep.Analysis == "exportCSV")
+                       outputFileCheck = es.OutputData1; 
+               else {
+                       //outputFileCheck = es.OutputGraph;
+                       //
+                       //OutputData1 because since Chronojump 1.3.6, 
+                       //encoder analyze has a treeview that can show the curves
+                       //when a graph analysis is done, curves file has to be written
+                       outputFileCheck = es.OutputData1;
+                       //check also the otuput graph
+                       outputFileCheck2 = es.OutputGraph; 
+               }
+
+               //delete output file check(s)
+               deleteFile(outputFileCheck);
+               if(outputFileCheck2 != "")
+                       deleteFile(outputFileCheck2);
+
+               LogB.Debug("sending continue process");
+               p.StandardInput.WriteLine("C");
+
+               LogB.Debug("waiting files");
+               if(outputFileCheck2 == "")
+                       while ( ! ( fileWritten(outputFileCheck) || CancelRScript) );
+               else
+                       while ( ! ( (fileWritten(outputFileCheck) && fileWritten(outputFileCheck2)) || 
CancelRScript ) );
+               LogB.Debug("files written");
+       }
+       
+       
+       private string getEncoderScriptCallGraph() {
+               return System.IO.Path.Combine(
+                               Util.GetDataDir(), "encoder", Constants.EncoderScriptCallGraph);
+       }
+       
+       protected override void writeOptionsFile()
+       {
+               optionsFile = Path.GetTempPath() + "Roptions.txt";
+       
+               string scriptOptions = UtilEncoder.PrepareEncoderGraphOptions(
+                               title,
+                               es, 
+                               neuromuscularProfileDo,
+                               translate
+                               ).ToString();
+
+               TextWriter writer = File.CreateText(optionsFile);
+               writer.Write(scriptOptions);
+               writer.Flush();
+               writer.Close();
+               ((IDisposable)writer).Dispose();
+       }
+               
+       private void deleteFile(string filename)
+       {
+               LogB.Information("Deleting... " + filename);
+               if (File.Exists(filename))
+                       File.Delete(filename);
+       }
+
+       private bool fileWritten(string filename)
+       {
+               if(File.Exists(filename)) {
+                       FileInfo fi = new FileInfo(filename);
+                       if(fi.Length > 0)
+                               return true;
+               }
+
+               return false;
        }
 
 }
diff --git a/src/gui/chronojump.cs b/src/gui/chronojump.cs
index 5363f05..37cb8d4 100644
--- a/src/gui/chronojump.cs
+++ b/src/gui/chronojump.cs
@@ -2398,7 +2398,7 @@ public partial class ChronoJumpWindow
                LogB.Information("Bye2!");
                
                encoderRProcCapture.SendEndProcess();
-               //encoderRProcAnalyze.SendEndProcess();
+               encoderRProcAnalyze.SendEndProcess();
 
                LogB.Information("Bye3!");
                
diff --git a/src/gui/encoder.cs b/src/gui/encoder.cs
index 87fff22..6abeb8f 100644
--- a/src/gui/encoder.cs
+++ b/src/gui/encoder.cs
@@ -323,7 +323,7 @@ public partial class ChronoJumpWindow
                
                //initialize capture and analyze classes                
                encoderRProcCapture = new EncoderRProcCapture();
-               //encoderRProcAnalyze = new EncoderRProcAnalyze();
+               encoderRProcAnalyze = new EncoderRProcAnalyze();
                
                encoderCaptureOptionsWin = EncoderCaptureOptionsWindow.Create(repetitiveConditionsWin);
                encoderCaptureOptionsWin.FakeButtonClose.Clicked += new 
EventHandler(on_encoder_capture_options_closed);
@@ -718,15 +718,15 @@ public partial class ChronoJumpWindow
                                UtilEncoder.GetEncoderStatusTempBaseFileName(),
                                "none", //SpecialData
                                ep);
-               
-               bool result = UtilEncoder.RunEncoderGraphNoRDotNet(
+       
+               encoderRProcAnalyze.SendData(
                                Util.ChangeSpaceAndMinusForUnderscore(currentPerson.Name) + "-" + 
                                
Util.ChangeSpaceAndMinusForUnderscore(UtilGtk.ComboGetActive(combo_encoder_exercise)) + 
                                "-(" + Util.ConvertToPoint(findMass(Constants.MassType.DISPLACED)) + "Kg)",
-                               es,
                                false,  //do not use neuromuscularProfile script
                                preferences.RGraphsTranslate
                                ); 
+               bool result = encoderRProcAnalyze.StartOrContinue(es);
                                
                if(result)
                        //store this to show 1,2,3,4,... or 1e,1c,2e,2c,... in RenderN
@@ -1419,14 +1419,14 @@ public partial class ChronoJumpWindow
                                "none",                 //SpecialData
                                ep);
 
-               UtilEncoder.RunEncoderGraphNoRDotNet(
+               encoderRProcAnalyze.SendData(
                                Util.ChangeSpaceAndMinusForUnderscore(currentPerson.Name) + "-" + 
                                Util.ChangeSpaceAndMinusForUnderscore(lastEncoderSQLSignal.exerciseName) + 
                                        "-(" + displacedMass + "Kg)",
-                               encoderStruct,
                                false,                  //do not use neuromuscularProfile script
                                preferences.RGraphsTranslate
                                );
+               encoderRProcAnalyze.StartOrContinue(encoderStruct);
 
                //encoder_pulsebar_capture.Text = string.Format(Catalog.GetString(
                //                      "Exported to {0}."), UtilEncoder.GetEncoderExportTempFileName());
@@ -1942,7 +1942,7 @@ public partial class ChronoJumpWindow
                                );
 
                //wait to ensure capture thread has ended
-               Thread.Sleep(500);      
+               Thread.Sleep(50);       
                
                LogB.Debug("Going to stop");            
                capturingCsharp = encoderCaptureProcess.STOPPING;
@@ -1972,7 +1972,8 @@ public partial class ChronoJumpWindow
                if(capturedOk)
                        UtilEncoder.RunEncoderCalculeIM(
                                        encoder_configuration_win.Spin_im_weight,
-                                       encoder_configuration_win.Spin_im_length
+                                       encoder_configuration_win.Spin_im_length,
+                                       encoderRProcAnalyze
                                        );
        }
        
@@ -2692,9 +2693,12 @@ public partial class ChronoJumpWindow
                                titleStr += "-" + 
Util.ChangeSpaceAndMinusForUnderscore(UtilGtk.ComboGetActive(combo_encoder_exercise));
                }
 
-               UtilEncoder.RunEncoderGraphNoRDotNet(titleStr, encoderStruct, 
+               encoderRProcAnalyze.SendData(
+                               titleStr, 
                                encoderAnalysis == "neuromuscularProfile",
                                preferences.RGraphsTranslate);
+
+               encoderRProcAnalyze.StartOrContinue(encoderStruct);
        }
        
        /*
@@ -4456,6 +4460,7 @@ public partial class ChronoJumpWindow
                        image_encoder_height = UtilGtk.WidgetHeight(viewport_image_encoder_analyze)-5;
 
                        encoder_pulsebar_analyze.Text = Catalog.GetString("Please, wait.");
+                       encoderRProcAnalyze.status = EncoderRProc.Status.WAITING;
                
                        encoderThread = new Thread(new ThreadStart(encoderDoAnalyze));
                        GLib.Idle.Add (new GLib.IdleHandler (pulseGTKEncoderAnalyze));
@@ -4781,7 +4786,7 @@ public partial class ChronoJumpWindow
                        LogB.Information("End from curves"); 
                        LogB.ThreadEnding(); 
                        if(encoderProcessCancel){
-                               UtilEncoder.CancelRScript = true;
+                               encoderRProcAnalyze.CancelRScript = true;
                        }
 
                        finishPulsebar(encoderActions.CURVES);
@@ -4800,7 +4805,7 @@ public partial class ChronoJumpWindow
                if(! encoderThread.IsAlive || encoderProcessCancel) {
                        LogB.ThreadEnding(); 
                        if(encoderProcessCancel){
-                               UtilEncoder.CancelRScript = true;
+                               encoderRProcAnalyze.CancelRScript = true;
                        }
 
                        finishPulsebar(encoderActions.LOAD);
@@ -4816,10 +4821,10 @@ public partial class ChronoJumpWindow
        
        private bool pulseGTKEncoderAnalyze ()
        {
-               if(! encoderThread.IsAlive || encoderProcessCancel) {
+               if( encoderRProcAnalyze.status == EncoderRProc.Status.DONE || ! encoderThread.IsAlive || 
encoderProcessCancel) {
                        LogB.ThreadEnding(); 
                        if(encoderProcessCancel){
-                               UtilEncoder.CancelRScript = true;
+                               encoderRProcAnalyze.CancelRScript = true;
                        }
 
                        finishPulsebar(encoderActions.ANALYZE);
@@ -5145,8 +5150,21 @@ public partial class ChronoJumpWindow
                        } else {
                                //TODO pensar en si s'ha de fer 1er amb mida petita i despres amb gran (en el 
zoom),
                                //o si es una sola i fa alguna edicio
-                               Pixbuf pixbuf = new Pixbuf (UtilEncoder.GetEncoderGraphTempFileName()); 
//from a file
-                               image_encoder_analyze.Pixbuf = pixbuf;
+                               
+                               //maybe image is still not readable
+                               bool readedOk;
+                               do {
+                                       readedOk = true;
+                                       try {
+                                               Pixbuf pixbuf = new Pixbuf 
(UtilEncoder.GetEncoderGraphTempFileName()); //from a file
+                                               image_encoder_analyze.Pixbuf = pixbuf;
+                                       } catch {
+                                               LogB.Warning("File is still not ready. Wait a bit");
+                                               System.Threading.Thread.Sleep(50);
+                                               readedOk = false;
+                                       }
+                               } while( ! readedOk );
+
                                encoder_pulsebar_analyze.Text = "";
 
                                string contents = 
Util.ReadFile(UtilEncoder.GetEncoderAnalyzeTableTempFileName(), false);
diff --git a/src/utilEncoder.cs b/src/utilEncoder.cs
index d807b1b..4934873 100644
--- a/src/utilEncoder.cs
+++ b/src/utilEncoder.cs
@@ -30,8 +30,6 @@ using Mono.Unix;
 //this class tries to be a space for methods that are used in different classes
 public class UtilEncoder
 {
-       public static bool CancelRScript;
-
 
        /********** start of encoder paths ************/
        
@@ -189,16 +187,6 @@ public class UtilEncoder
        }
        
 
-       /*
-        * in RDotNet, graph.R is in memory, and call_graph.R is not called
-        * if RDotNet is not working, then call_graph.R is called and this calls graph.R
-        */
-
-       private static string getEncoderScriptCallGraph() {
-               return System.IO.Path.Combine(
-                               Util.GetDataDir(), "encoder", Constants.EncoderScriptCallGraph);
-       }
-
        public static string GetEncoderScriptGraph() {
                return System.IO.Path.Combine(
                                Util.GetDataDir(), "encoder", Constants.EncoderScriptGraph);
@@ -343,121 +331,11 @@ public class UtilEncoder
        }
 
 
-       /*
-        * this method don't use RDotNet, then has to call call_graph.R, who will call graph.R
-        * and has to write a Roptions.txt file
-        */
-       public static bool RunEncoderGraphNoRDotNet(string title, EncoderStruct es, bool 
neuromuscularProfileDo, bool translate) 
-       {
-               CancelRScript = false;
-
-               ProcessStartInfo pinfo;
-               Process p;
-               //If output file is not given, R will try to write in the running folder
-               //in which we may haven't got permissions
-       
-               string pBin="";
-               pinfo = new ProcessStartInfo();
-
-               pBin="Rscript";
-               if (UtilAll.IsWindows()) {
-                       //on Windows we need the \"str\" to call without problems in path with spaces
-                       pBin = "\"" + System.IO.Path.Combine(Util.GetPrefixDir(), "bin" + 
Path.DirectorySeparatorChar + "Rscript.exe") + "\"";
-                       LogB.Information("pBin:", pBin);
-               }
-               
-
-               string scriptOptions = PrepareEncoderGraphOptions(title, es, neuromuscularProfileDo, 
translate).ToString();
-
-               string optionsFile = Path.GetTempPath() + "Roptions.txt";
-               TextWriter writer = File.CreateText(optionsFile);
-               writer.Write(scriptOptions);
-               writer.Flush();
-               writer.Close();
-               ((IDisposable)writer).Dispose();
-               
-               if (UtilAll.IsWindows()) {
-                       //On win32 R understands backlash as an escape character and 
-                       //a file path uses Unix-like path separator '/'         
-                       optionsFile = optionsFile.Replace("\\","/");
-               }
-               
-               //on Windows we need the \"str\" to call without problems in path with spaces
-               pinfo.Arguments = "\"" + getEncoderScriptCallGraph() + "\" " + optionsFile;
-       
-               LogB.Information("Arguments:", pinfo.Arguments);
-               LogB.Information("--- 1 --- " + optionsFile.ToString() + " ---");
-               LogB.Information("--- 2 --- " + scriptOptions + " ---");
-               LogB.Information("--- 3 --- " + pinfo.Arguments.ToString() + " ---");
-               
-               string outputFileCheck = "";
-               string outputFileCheck2 = "";
-               
-               //Wait until this to update encoder gui (if don't wait then treeview will be outdated)
-               //exportCSV is the only one that doesn't have graph. all the rest Analysis have graph and data
-               if(es.Ep.Analysis == "exportCSV")
-                       outputFileCheck = es.OutputData1; 
-               else {
-                       //outputFileCheck = es.OutputGraph;
-                       //
-                       //OutputData1 because since Chronojump 1.3.6, 
-                       //encoder analyze has a treeview that can show the curves
-                       //when a graph analysis is done, curves file has to be written
-                       outputFileCheck = es.OutputData1;
-                       //check also the otuput graph
-                       outputFileCheck2 = es.OutputGraph; 
-               }
-
-               pinfo.FileName=pBin;
-
-               pinfo.CreateNoWindow = true;
-               pinfo.UseShellExecute = false;
-               pinfo.RedirectStandardError = true;
-               pinfo.RedirectStandardOutput = true; 
-
-
-               //delete output file check(s)
-               LogB.Information("Deleting... " + outputFileCheck);
-               if (File.Exists(outputFileCheck))
-                       File.Delete(outputFileCheck);
-
-               if(outputFileCheck2 != "") {
-                       LogB.Information("Deleting... " + outputFileCheck2);
-                       if (File.Exists(outputFileCheck2))
-                               File.Delete(outputFileCheck2);
-               }
-                       
-               //delete 1RM data if exists
-               if (File.Exists(es.SpecialData))
-                       File.Delete(es.SpecialData);
-
-               //try catch crash sometimes when used in conjunction with RDotNet
-               //now RDotNet is not used
-               try {   
-                       p = new Process();
-                       p.StartInfo = pinfo;
-                       p.Start();
-
-                       LogB.Information(p.StandardOutput.ReadToEnd());
-                       LogB.Warning(p.StandardError.ReadToEnd());
-
-                       p.WaitForExit();
-
-                       if(outputFileCheck2 == "")
-                               while ( ! ( File.Exists(outputFileCheck) || CancelRScript) );
-                       else
-                               while ( ! ( (File.Exists(outputFileCheck) && File.Exists(outputFileCheck2)) 
|| CancelRScript ) );
-               } catch {
-                       return false;
-               }
-
-               return true;
-       }
-       
        //Inertia Momentum
-       public static void RunEncoderCalculeIM(double weight, double length) 
+       //TODO: make this work with encoderRProc
+       public static void RunEncoderCalculeIM(double weight, double length, EncoderRProcAnalyze 
encoderRProcAnalyze) 
        {
-               CancelRScript = false;
+               encoderRProcAnalyze.CancelRScript = false;
 
                ProcessStartInfo pinfo;
                Process p;
@@ -537,7 +415,7 @@ public class UtilEncoder
 
                        p.WaitForExit();
 
-                       while ( ! ( File.Exists(outputFileCheck) || CancelRScript) );
+                       while ( ! ( File.Exists(outputFileCheck) || encoderRProcAnalyze.CancelRScript) );
                } catch {
                }
        }


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]