[chronojump] Added processMultiDatabase program



commit f86c6812a55fc5e32aa99ac6ebaa1075e2642707
Author: Xavier de Blas <xaviblas gmail com>
Date:   Thu Dec 19 23:42:30 2019 +0100

    Added processMultiDatabase program

 processMultiDatabases/callR.cs                 | 227 +++++++++++++++++++++++
 processMultiDatabases/constants.cs             |  43 +++++
 processMultiDatabases/encoderGraphOptions.cs   |  98 ++++++++++
 processMultiDatabases/encoderParams.cs         | 120 +++++++++++++
 processMultiDatabases/encoderSQL.cs            |  88 +++++++++
 processMultiDatabases/encoderStruct.cs         |  51 ++++++
 processMultiDatabases/howto_compile.txt        |   1 +
 processMultiDatabases/processMultiDatabases.cs | 239 +++++++++++++++++++++++++
 processMultiDatabases/util.cs                  | 130 ++++++++++++++
 processMultiDatabases/utilEncoder.cs           | 154 ++++++++++++++++
 10 files changed, 1151 insertions(+)
---
diff --git a/processMultiDatabases/callR.cs b/processMultiDatabases/callR.cs
new file mode 100644
index 00000000..06571327
--- /dev/null
+++ b/processMultiDatabases/callR.cs
@@ -0,0 +1,227 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+using System.IO; //"File" things. TextWriter. Path
+using System.Diagnostics;      //for detect OS and for Process
+
+public class CallR
+{
+       private string optionsFile;
+       private EncoderStruct es;
+
+       public EncoderGraphROptions.AnalysisModes analysisMode;
+
+       public CallR(EncoderStruct es)
+       {
+               this.es = es;
+               this.analysisMode = EncoderGraphROptions.AnalysisModes.INDIVIDUAL_CURRENT_SET;
+
+               writeOptionsFile();
+
+               callRStart();
+       }
+
+       private bool callRStart()
+       {
+               ProcessStartInfo pinfo = new ProcessStartInfo();
+               string pBin="Rscript";
+       
+               /*      
+               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;
+       
+               Console.WriteLine("Arguments:", pinfo.Arguments);
+               Console.WriteLine("--- 1 --- " + optionsFile.ToString() + " ---");
+               //Console.WriteLine("--- 2 --- " + scriptOptions + " ---");
+               Console.WriteLine("--- 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; 
+               }
+                       
+               Console.WriteLine("outputFileChecks");
+               Console.WriteLine(outputFileCheck);
+               Console.WriteLine(outputFileCheck2);
+
+               pinfo.FileName=pBin;
+
+               pinfo.CreateNoWindow = true;
+               pinfo.UseShellExecute = false;
+               pinfo.RedirectStandardInput = true;
+               pinfo.RedirectStandardError = true;
+               
+               /*
+                * 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)
+               Util.DeleteFile(outputFileCheck);
+               if(outputFileCheck2 != "")
+                       Util.DeleteFile(outputFileCheck2);
+               
+               //delete status-6 mark used on export csv
+               if(es.Ep.Analysis == "exportCSV")
+                       Util.DeleteFile(getEncoderStatusTempBaseFileName() + "6.txt");
+
+               //delete SpecialData if exists
+               string specialData = getEncoderSpecialDataTempFileName();
+               if (File.Exists(specialData))
+                       Util.DeleteFile(specialData);
+
+
+               Console.WriteLine("process a");
+//             try {   
+                       Process p = new Process();
+                       p.StartInfo = pinfo;
+                       
+                       //do not redirect ouptut. Read above
+                       //p.OutputDataReceived += new DataReceivedEventHandler(readingOutput);
+                       p.ErrorDataReceived += new DataReceivedEventHandler(readingError);
+                       
+                       p.Start();
+
+                       //don't do this ReadToEnd because then this method never ends
+                       //Console.WriteLine(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();
+
+                       Console.WriteLine("process b");
+
+
+                       if(outputFileCheck2 == "")
+                               while ( ! ( Util.FileReadable(outputFileCheck) )); //|| CancelRScript) );
+                       else
+                               while ( ! ( (Util.FileReadable(outputFileCheck) && 
Util.FileReadable(outputFileCheck2)) ));//|| CancelRScript ) );
+
+                       /*
+                       //copy export from temp file to the file that user has selected
+                       if(es.Ep.Analysis == "exportCSV")// && ! CancelRScript)
+                               copyExportedFile();
+                               */
+
+                       Console.WriteLine("process c");
+                       p.StandardInput.WriteLine("Q");
+                       //p.WaitForExit();
+
+                       Console.WriteLine("process d");
+       
+//             } catch {
+//                     Console.WriteLine("catched at startProcess");
+//                     return false;
+//             }
+
+               return true;
+       }
+
+        private void readingError (object sendingProcess, DataReceivedEventArgs errorFromR)
+        {
+                if (String.IsNullOrEmpty(errorFromR.Data))
+                        return;
+
+                string str = errorFromR.Data;
+                if(str.Length > 6 && str.StartsWith("***") && str.EndsWith("***")) {
+                        /*
+                         * 0123456
+                         * ***1***
+                         * str.Substring(3,1) 1 is the length
+                         */
+                        str = str.Substring(3, str.Length -6);
+//                        if(Util.IsNumber(str,false))
+//                              CurvesReaded = Convert.ToInt32(str);
+ 
+                        return;
+                }
+        
+                Console.WriteLine(str);
+        }
+
+       private string getEncoderScriptCallGraph()
+       {
+               /*
+               return System.IO.Path.Combine(
+                               Util.GetDataDir(), "encoder", Constants.EncoderScriptCallGraph);
+                               */
+               return "/home/xavier/informatica/progs_meus/chronojump/chronojump/encoder/call_graph.R"; 
//hardcoded
+       }
+       
+       private string getEncoderStatusTempBaseFileName() {
+               return Path.Combine(Path.GetTempPath(), Constants.EncoderStatusTempBase);
+       }
+
+       private string getEncoderSpecialDataTempFileName() {
+               return Path.Combine(Path.GetTempPath(), Constants.EncoderSpecialDataTemp);
+       }
+
+       private void writeOptionsFile()
+       {
+               optionsFile = Path.GetTempPath() + "Roptions.txt";
+       
+               string scriptOptions = UtilEncoder.PrepareEncoderGraphOptions(
+                               "hola", //title,
+                               es, 
+                               false, //neuromuscularProfileDo,
+                               false, //translate,
+                               false, //Debug,
+                               false, //CrossValidate,
+                               false, //cutByTriggers,
+                               "-1", //printTriggers(),
+                               false, //SeparateSessionInDays,
+                               analysisMode
+                               ).ToString();
+
+               TextWriter writer = File.CreateText(optionsFile);
+               writer.Write(scriptOptions);
+               writer.Flush();
+               writer.Close();
+               ((IDisposable)writer).Dispose();
+       }
+}
+
diff --git a/processMultiDatabases/constants.cs b/processMultiDatabases/constants.cs
new file mode 100644
index 00000000..ee55568d
--- /dev/null
+++ b/processMultiDatabases/constants.cs
@@ -0,0 +1,43 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+
+public class Constants
+{
+       public static string EncoderDataTemp = "chronojump-last-encoder-data.txt";
+       public static string EncoderScriptCallGraph = "call_graph.R";
+       public static string EncoderStatusTempBase = "chronojump-encoder-status-";
+       public static string EncoderSpecialDataTemp = "chronojump-special-data.txt"; //variable;result (eg. 
"1RM;82.78")
+       public static string EncoderCurvesTemp = "chronojump-last-encoder-curves.txt";
+       //public static string EncoderAnalyzeTableTemp = "chronojump-last-encoder-analyze-table.txt";
+       public static string EncoderGraphTemp = "chronojump-last-encoder-graph.png";
+
+       public static string FileNotFoundStr()
+        {
+                return "Error. File not found.";
+        }
+
+       public static string FileCopyProblemStr()
+       {
+               return "Error. Cannot copy file.";
+       }
+}
+
diff --git a/processMultiDatabases/encoderGraphOptions.cs b/processMultiDatabases/encoderGraphOptions.cs
new file mode 100644
index 00000000..758cdc4d
--- /dev/null
+++ b/processMultiDatabases/encoderGraphOptions.cs
@@ -0,0 +1,98 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+
+public class EncoderGraphROptions
+{
+       public string inputData;
+       public string outputGraph;
+       public string outputData1;
+       public string encoderRPath;
+       public string encoderTempPath;
+       public EncoderParams ep;
+       public string title;
+       public string operatingSystem;
+       public string englishWords;
+       public string translatedWords;
+       public bool debug;
+       public bool crossValidate;
+       private bool cutByTriggers;
+       private string triggerList;
+       public bool separateSessionInDays;
+       public AnalysisModes analysisMode; //the four analysisModes
+
+       public enum AnalysisModes { CAPTURE, INDIVIDUAL_CURRENT_SET, INDIVIDUAL_CURRENT_SESSION, 
INDIVIDUAL_ALL_SESSIONS, GROUPAL_CURRENT_SESSION }
+
+       public EncoderGraphROptions(
+                       string inputData, string outputGraph, string outputData1, 
+                       string encoderRPath, string encoderTempPath,
+                       EncoderParams ep,
+                       string title, string operatingSystem,
+                       string englishWords, string translatedWords,
+                       bool debug, bool crossValidate, bool cutByTriggers, string triggerList,
+                       bool separateSessionInDays, AnalysisModes analysisMode)
+       {
+               this.inputData = inputData;
+               this.outputGraph = outputGraph;
+               this.outputData1 = outputData1;
+               this.encoderRPath = encoderRPath;
+               this.encoderTempPath = encoderTempPath;
+               this.ep = ep;
+               this.title = title;
+               this.operatingSystem = operatingSystem;
+               this.englishWords = englishWords;
+               this.translatedWords = translatedWords;
+               this.debug = debug;
+               this.crossValidate = crossValidate;
+               this.cutByTriggers = cutByTriggers;
+               this.triggerList = triggerList;
+               this.separateSessionInDays = separateSessionInDays;
+               this.analysisMode = analysisMode;
+
+               //ensure triggerList is not null or blank
+               if(triggerList == null || triggerList == "")
+                       triggerList = "-1";
+       }
+
+       public override string ToString() {
+               return 
+                       "#inputdata\n" +        inputData + "\n" + 
+                       "#outputgraph\n" +      outputGraph + "\n" + 
+                       "#outputdata1\n" +      outputData1 + "\n" + 
+                       "#encoderRPath\n" +     encoderRPath + "\n" + 
+                       "#encoderTempPath\n" +  encoderTempPath + "\n" + 
+                       ep.ToStringROptions() + "\n" + 
+                       "#title\n" +            title + "\n" + 
+                       "#operatingsystem\n" +  operatingSystem + "\n" +
+                       "#englishWords\n" +     englishWords + "\n" +
+                       "#translatedWords\n" +  translatedWords + "\n" +
+                       "#debug\n" +            Util.BoolToRBool(debug) + "\n" +
+                       "#crossValidate\n" +    Util.BoolToRBool(crossValidate) + "\n" +
+                       "#cutByTriggers\n" +    Util.BoolToRBool(cutByTriggers) + "\n" +
+                       "#triggerList\n" +      triggerList + "\n" +
+                       "#separateSessionInDays\n" +    Util.BoolToRBool(separateSessionInDays) + "\n" +
+                       "#analysisMode\n" +     analysisMode.ToString() + "\n";
+       }
+       
+
+       ~EncoderGraphROptions() {}
+}
+
diff --git a/processMultiDatabases/encoderParams.cs b/processMultiDatabases/encoderParams.cs
new file mode 100644
index 00000000..d92790f3
--- /dev/null
+++ b/processMultiDatabases/encoderParams.cs
@@ -0,0 +1,120 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+
+public class EncoderParams
+{
+       //graph.R need both to know displacedMass depending on encoderConfiguration
+       //and plot both as entry data in the table of result data
+       private string massBody; //to pass always as "." to R.
+       private string massExtra; //to pass always as "." to R
+       
+       private int minHeight;
+       private int exercisePercentBodyWeight; //was private bool isJump; (if it's 0 is like "jump")
+       private string eccon;
+       private string analysis;
+       private string analysisVariables;
+       private string analysisOptions;         //p: propulsive
+       private bool captureCheckFullyExtended;
+       private int captureCheckFullyExtendedValue;
+                                       
+       //encoderConfiguration conversions
+       //in signals and curves, need to do conversions (invert, inertiaMomentum, diameter)
+       //private EncoderConfiguration encoderConfiguration;    
+       private string encoderConfiguration;    
+       
+       private string smoothCon; //to pass always as "." to R
+       private int curve;
+       private int width;
+       private int height;
+       private string decimalSeparator;        //used in export data from R to csv
+       //private bool inverted; //used only in runEncoderCapturePython. In graph.R will be used 
encoderConfigurationName
+
+       public EncoderParams()
+       {
+       }
+
+       
+       //to graph.R    
+       public EncoderParams(int minHeight, int exercisePercentBodyWeight, string massBody, string massExtra, 
+                       string eccon, string analysis, string analysisVariables, string analysisOptions, 
+                       bool captureCheckFullyExtended, int captureCheckFullyExtendedValue,
+                       string encoderConfiguration, //EncoderConfiguration encoderConfiguration,
+                       string smoothCon, int curve, int width, int height, string decimalSeparator)
+       {
+               this.minHeight = minHeight;
+               this.exercisePercentBodyWeight = exercisePercentBodyWeight;
+               this.massBody = massBody;
+               this.massExtra = massExtra;
+               this.eccon = eccon;
+               this.analysis = analysis;
+               this.analysisVariables = analysisVariables;
+               this.analysisOptions = analysisOptions;
+               this.captureCheckFullyExtended = captureCheckFullyExtended;
+               this.captureCheckFullyExtendedValue = captureCheckFullyExtendedValue;
+               this.encoderConfiguration = encoderConfiguration;
+               this.smoothCon = smoothCon;
+               this.curve = curve;
+               this.width = width;
+               this.height = height;
+               this.decimalSeparator = decimalSeparator;
+       }
+       
+       public string ToStringROptions () 
+       {
+               string capFullyExtendedStr = "-1";
+               if(captureCheckFullyExtended)
+                       capFullyExtendedStr = captureCheckFullyExtendedValue.ToString(); 
+               
+               return 
+                       "#minHeight\n" +        minHeight + "\n" + 
+                       "#exercisePercentBodyWeight\n" + exercisePercentBodyWeight + "\n" + 
+                       "#massBody\n" +         massBody + "\n" + 
+                       "#massExtra\n" +        massExtra + "\n" + 
+                       "#eccon\n" +            eccon + "\n" + 
+                       "#analysis\n" +         analysis + "\n" + 
+                       "#analysisVariables\n" + analysisVariables + "\n" + 
+                       "#analysisOptions\n" + analysisOptions + "\n" + 
+                       "#captureCheckFullyExtended\n" + capFullyExtendedStr + "\n" + 
+                       //encoderConfiguration.ToStringOutput(EncoderConfiguration.Outputs.ROPTIONS) + "\n" +
+                       "#name\nLINEAR\n" +
+                       "#str_d\n-1\n" +
+                       "#str_D\n-1\n" +
+                       "#anglePush\n-1\n" +
+                       "#angleWeight\n-1\n" +
+                       "#inertiaTotal\n-1\n" +
+                       "#gearedDown\n1\n" +
+                       "#smoothCon\n" +        smoothCon + "\n" + 
+                       "#curve\n" +            curve + "\n" + 
+                       "#width\n" +            width + "\n" + 
+                       "#height\n" +           height + "\n" + 
+                       "#decimalSeparator\n" + decimalSeparator
+                       ;
+       }
+       
+       public string Analysis {
+               get { return analysis; }
+       }
+
+
+       ~EncoderParams() {}
+}
+
diff --git a/processMultiDatabases/encoderSQL.cs b/processMultiDatabases/encoderSQL.cs
new file mode 100644
index 00000000..cefa4d9d
--- /dev/null
+++ b/processMultiDatabases/encoderSQL.cs
@@ -0,0 +1,88 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+
+//different form chronojump/encoder EncoderSQL
+public class EncoderSQL
+{
+        public string uniqueID;
+        public int personID;
+        public int sessionID;
+        public int exerciseID;
+        public string eccon;
+        public string laterality;
+        public string extraWeight;
+        public string signalOrCurve;
+        public string filename;
+        public string url;      //URL of data of signals and curves. Stored in DB as relative. Used in 
software as absolute. See SqliteEncoder
+        public int time;
+        public int minHeight;
+        public string description;
+        public string status;   //active or inactive curves
+        public string videoURL; //URL of video of signals. Stored in DB as relative. Used in software as 
absolute. See SqliteEncoder
+
+       public string encoderConfiguration;
+        public string future1;
+        public string future2;
+        public string future3;
+
+       public EncoderSQL ()
+        {
+        }
+
+       public EncoderSQL (string uniqueID, int personID, int sessionID, int exerciseID,
+                       string eccon, string laterality, string extraWeight, string signalOrCurve,
+                       string filename, string url, int time, int minHeight,
+                       string description, string status, string videoURL,
+                       //EncoderConfiguration encoderConfiguration,
+                       string encoderConfiguration,
+                       string future1, string future2, string future3//,
+                       //string exerciseName
+                       )
+       {
+               this.uniqueID = uniqueID;
+               this.personID = personID;
+               this.sessionID = sessionID;
+               this.exerciseID = exerciseID;
+               this.eccon = eccon;
+               this.laterality = laterality;
+               this.extraWeight = extraWeight;
+               this.signalOrCurve = signalOrCurve;
+               this.filename = filename;
+               this.url = url;
+               this.time = time;
+               this.minHeight = minHeight;
+               this.description = description;
+               this.status = status;
+               this.videoURL = videoURL;
+               this.encoderConfiguration = encoderConfiguration;
+               this.future1 = future1; //on curves: meanPower. Better use alter table
+               this.future2 = future2; //on curves: meanSpeed
+               this.future3 = future3; //on curves: meanForce
+               //this.exerciseName = exerciseName;
+       }
+
+       public override string ToString()
+       {
+               return string.Format("{0} - {1}", url, filename);
+       }
+}
+
diff --git a/processMultiDatabases/encoderStruct.cs b/processMultiDatabases/encoderStruct.cs
new file mode 100644
index 00000000..4c48580a
--- /dev/null
+++ b/processMultiDatabases/encoderStruct.cs
@@ -0,0 +1,51 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+
+public class EncoderStruct
+{
+       public EncoderStruct() {
+       }
+
+       public string InputData;
+       public string OutputGraph;
+       public string OutputData1;
+       public string EncoderRPath; //to load other R scripts
+       public string EncoderTempPath; //use for Status, Special, GraphParams....
+       public EncoderParams Ep;
+
+       //pass this to R
+       public EncoderStruct(string InputData, string OutputGraph, 
+                       string OutputData1, 
+                       string EncoderRPath, string EncoderTempPath,
+                       EncoderParams Ep)
+       {
+               this.InputData = InputData;
+               this.OutputGraph = OutputGraph;
+               this.OutputData1 = OutputData1;
+               this.EncoderRPath = EncoderRPath;
+               this.EncoderTempPath = EncoderTempPath;
+               this.Ep = Ep;
+       }
+
+       ~EncoderStruct() {}
+}
+
diff --git a/processMultiDatabases/howto_compile.txt b/processMultiDatabases/howto_compile.txt
new file mode 100644
index 00000000..da55668d
--- /dev/null
+++ b/processMultiDatabases/howto_compile.txt
@@ -0,0 +1 @@
+mcs processMultiDatabases.cs callR.cs constants.cs encoderGraphOptions.cs encoderParams.cs encoderSQL.cs 
encoderStruct.cs util.cs utilEncoder.cs -r:Mono.Data.Sqlite -r:System.Data
diff --git a/processMultiDatabases/processMultiDatabases.cs b/processMultiDatabases/processMultiDatabases.cs
new file mode 100644
index 00000000..8d5068e7
--- /dev/null
+++ b/processMultiDatabases/processMultiDatabases.cs
@@ -0,0 +1,239 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+using System.IO; //"File" things. TextWriter. Path
+using System.Collections.Generic; //List<T>
+using Mono.Data.Sqlite;
+
+//TODO: ara falta el CallR
+
+class ProcessMultiDatabases
+{
+       // start of configuration variables ---->
+       //
+       //barcelona
+       private string barcelona1Path = 
"/home/xavier/Documents/academic/investigacio/Encoder_SITLESS/carpetes-chronojump-senceres/barcelona/wetransfer-8ba4dd/Encoder_Copies_17_07_2019/database";
+       private int barcelona1ExSitToStand = 7;
+       private int barcelona1BicepsCurl = 8;
+       private int barcelona1ShoppingBag = 9;
+       private int barcelona1ObjectInShelf = 10;
+
+       //hardcoded stuff (search 'hardcoded' on):
+       //callR.cs
+       //utilEncoder.cs
+
+       // <---- end of configuration variables
+
+       private string database = "chronojump.db";
+        private SqliteConnection dbcon;
+       private SqliteCommand dbcmd;
+       private string dbPath = "";
+
+       public static void Main(string[] args)
+       {
+               new ProcessMultiDatabases();
+       }
+
+       public ProcessMultiDatabases()
+       {
+               dbPath = barcelona1Path;
+
+               sqliteCreateConnection();
+               sqliteOpen();
+
+               processDatabase();
+
+               sqliteClose();
+               Console.WriteLine("processMultiDatabases done!");
+       }
+
+       private void processDatabase()
+       {
+               List<EncoderSQL> list = SelectEncoder (barcelona1ExSitToStand);
+
+               TextWriter writer = File.CreateText("/tmp/barcelona1ExSitToStand.csv");
+               writer.WriteLine("city,exercise,person(cjump: 
bad),moment,rep,series,exercise,massBody,massExtra,start,width,height,meanSpeed,maxSpeed,maxSpeedT,meanPower,peakPower,peakPowerT,pp_ppt,meanForce,maxForce,maxForceT,maxForce_maxForceT,workJ,impulse,laterality,inertiaM");
+
+               int count = 0;
+               foreach(EncoderSQL eSQL in list)
+               {
+                       Console.WriteLine(string.Format("progress: {0}/{1} - ", count, list.Count) + 
eSQL.ToString());
+                       double personWeight = SelectPersonWeight(eSQL.personID);
+
+                       EncoderParams ep = new EncoderParams(
+                                       20, 
//preferences.EncoderCaptureMinHeight(encoderConfigurationCurrent.has_inertia), 
+                                       100, //TODO: change this value depending on exercise 
//getExercisePercentBodyWeightFromComboCapture (),
+                                       Util.ConvertToPoint(personWeight), // 
Util.ConvertToPoint(findMass(Constants.MassType.BODY)),
+                                       Util.ConvertToPoint(eSQL.extraWeight), 
//Util.ConvertToPoint(findMass(Constants.MassType.EXTRA)),
+                                       "c", //findEccon(true),                                        
//force ecS (ecc-conc separated)
+                                       "curves", //is the same than "curvesAC". was: analysis,
+                                       "none",                         //analysisVariables (not needed in 
create curves). Cannot be blank
+                                       "p", //analysisOptions,
+                                       true, //preferences.encoderCaptureCheckFullyExtended,
+                                       4, //preferences.encoderCaptureCheckFullyExtendedValue,
+                                       "LINEAR", //encoderConfigurationCurrent,
+                                       "0.7", //Util.ConvertToPoint(preferences.encoderSmoothCon),      //R 
decimal: '.'
+                                       0,                      //curve is not used here
+                                       600, 600, //image_encoder_width, image_encoder_height,
+                                       "," //preferences.CSVExportDecimalSeparator 
+                                       );
+
+                       EncoderStruct es = new EncoderStruct(
+                                       UtilEncoder.GetEncoderDataTempFileName(),
+                                       UtilEncoder.GetEncoderGraphTempFileName(),
+                                       UtilEncoder.GetEncoderCurvesTempFileName(),
+                                       UtilEncoder.GetEncoderScriptsPathWithoutLastSep(),
+                                       UtilEncoder.GetEncoderTempPathWithoutLastSep(),
+                                       ep);
+
+                       Console.WriteLine("copying file: " + dbPath + "/../" + eSQL.url + "/" + 
eSQL.filename);
+                       UtilEncoder.CopyEncoderDataToTemp(dbPath + "/../" + eSQL.url, eSQL.filename);
+                       Console.WriteLine("copying file done. Calling R... ");
+
+                       new CallR(es);
+                       Console.WriteLine("CallR done!");
+
+                       //output file is: /tmp/chronojump-last-encoder-curves.txt
+                       //1st two lines are:
+                       
//,series,exercise,massBody,massExtra,start,width,height,meanSpeed,maxSpeed,maxSpeedT,meanPower,peakPower,peakPowerT,pp_ppt,meanForce,maxForce,maxForceT,maxForce_maxForceT,workJ,impulse,laterality,inertiaM
+                       
//1,1,exerciseName,57.9,0,971,498,755,1.51152519574657,3.20590883396153,307,1694.08480044046,4423.25671303514,243,18202.7025227784,1108.13701938937,1754.09683966977,232,7560.7622399559,1980.64161525193,365.685216398493,,-1e-04
+
+                       //
+                       //now we have to parse it to fill the big file
+                       string filename = "/tmp/chronojump-last-encoder-curves.txt";
+                       List<string> lines = Util.ReadFileAsStringList(filename);
+                       bool firstLine = true;
+                       foreach(string line in lines)
+                       {
+                               if(firstLine)
+                                       firstLine = false;
+                               else {
+                                       string line2 = "BARCELONA,SITTOSTAND," + eSQL.personID + ", 
(moment)," + line; //TODO: note this personID is not correct because persons sometimes where evaluated on 
different chronojump machines
+                                       writer.WriteLine(line2);
+                                       writer.Flush();
+                               }
+                       }
+
+                       count ++;
+                       /*
+                       if(count >= 5)
+                               break;
+                               */
+
+                       System.Threading.Thread.Sleep(200); //rest a bit
+               }
+
+               writer.Close();
+               ((IDisposable)writer).Dispose();
+               Console.WriteLine("processDatabase done!");
+       }
+
+       // ---- sqlite main methods ----
+
+       private void CreateAndOpen()
+       {
+               sqliteCreateConnection();
+               sqliteOpen();
+       }
+
+       private void sqliteCreateConnection()
+       {
+               dbcon = new SqliteConnection ();
+               string sqlFile = dbPath + Path.DirectorySeparatorChar + database;
+               Console.WriteLine(sqlFile);
+               dbcon.ConnectionString = "version = 3; Data source = " + sqlFile;
+               dbcmd = dbcon.CreateCommand();
+       }
+       private void sqliteOpen()
+       {
+               dbcon.Open();
+       }
+       private void sqliteClose()
+       {
+               dbcon.Close();
+       }
+
+       private double SelectPersonWeight (int personID)
+       {
+               dbcmd.CommandText = "SELECT weight FROM personSession77 WHERE personID = " + personID;
+               SqliteDataReader reader;
+               reader = dbcmd.ExecuteReader();
+
+               double myReturn = 0;
+                if(reader.Read()) {
+                        myReturn = Convert.ToDouble(Util.ChangeDecimalSeparator(reader[0].ToString()));
+                }
+                reader.Close();
+
+                return myReturn;
+       }
+
+       //TODO: will need session to process this by sessions or compare with filenames
+       private List<EncoderSQL> SelectEncoder (int exerciseID)
+        {
+               dbcmd.CommandText = "SELECT * FROM encoder WHERE signalOrCurve = 'signal' AND exerciseID = " 
+ exerciseID;
+               SqliteDataReader reader;
+               reader = dbcmd.ExecuteReader();
+
+               List<EncoderSQL> list = new List<EncoderSQL>();
+               while(reader.Read())
+               {
+                       EncoderSQL eSQL = new EncoderSQL (
+                                       reader[0].ToString(),                   //uniqueID
+                                       Convert.ToInt32(reader[1].ToString()),  //personID      
+                                       Convert.ToInt32(reader[2].ToString()),  //sessionID
+                                       Convert.ToInt32(reader[3].ToString()),  //exerciseID
+                                       reader[4].ToString(),                   //eccon
+                                       reader[5].ToString(),//laterality
+                                       Util.ChangeDecimalSeparator(reader[6].ToString()),      //extraWeight
+                                       reader[7].ToString(),                   //signalOrCurve
+                                       reader[8].ToString(),                   //filename
+                                       fixOSpath(reader[9].ToString()), 
//Util.MakeURLabsolute(fixOSpath(reader[9].ToString())),  //url
+                                       Convert.ToInt32(reader[10].ToString()), //time
+                                       Convert.ToInt32(reader[11].ToString()), //minHeight
+                                       reader[12].ToString(),                  //description
+                                       reader[13].ToString(),                  //status
+                                       reader[14].ToString(), //videoURL,                               
//videoURL
+                                       reader[15].ToString(), //econf,                                  
//encoderConfiguration
+                                       Util.ChangeDecimalSeparator(reader[16].ToString()),     //future1 
(meanPower on curves)
+                                       reader[17].ToString(),                  //future2
+                                       reader[18].ToString()//,                  //future3
+                                       //reader[19].ToString()                   //EncoderExercise.name
+                                               );
+                       list.Add (eSQL);
+               }
+               reader.Close();
+               return list;
+       }
+
+       private static string fixOSpath(string url) {
+               //if(UtilAll.IsWindows())
+               //      return url.Replace("/","\\");
+               //else
+                       return url.Replace("\\","/");
+       }
+
+       
+       // ---- end of sqlite main methods ----
+
+}
+
+
diff --git a/processMultiDatabases/util.cs b/processMultiDatabases/util.cs
new file mode 100644
index 00000000..e7f806bb
--- /dev/null
+++ b/processMultiDatabases/util.cs
@@ -0,0 +1,130 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+using System.Collections.Generic; //List<T>
+using System.IO; //"File" things. TextWriter. Path
+using System.Diagnostics;      //for detect OS and for Process
+using System.Text; //StringBuilder
+
+public class Util
+{
+        //all numbers are saved in database with '.' as decimal separator (method for numbers)
+        public static string ConvertToPoint (double myDouble)
+        {
+                StringBuilder myStringBuilder = new StringBuilder(myDouble.ToString());
+                myStringBuilder.Replace(",", ".");
+                return myStringBuilder.ToString();              
+        }                       
+
+        //all numbers are saved in database with '.' as decimal separator
+        //method for the tvString, tcString, and runIntervalTimesString
+        public static string ConvertToPoint (string myString)
+        {                       
+                StringBuilder myStringBuilder = new StringBuilder(myString);
+                myStringBuilder.Replace(",", ".");
+                return myStringBuilder.ToString();
+        }
+
+       public static string ChangeDecimalSeparator(string myString) {
+               if(myString == "") {
+                       return "0";
+               }
+               System.Globalization.NumberFormatInfo localeInfo = new 
System.Globalization.NumberFormatInfo();
+               localeInfo = System.Globalization.NumberFormatInfo.CurrentInfo;
+               
+               StringBuilder myStringBuilder = new StringBuilder(myString);
+               if(localeInfo.NumberDecimalSeparator != ".") {
+                       myStringBuilder.Replace(".", localeInfo.NumberDecimalSeparator);
+               }
+               return myStringBuilder.ToString();
+       }
+
+       /*
+       public static string MakeURLabsolute(string url) {
+               string parentDir = Util.GetParentDir(true); //add final '/' or '\'
+               if( ! url.StartsWith(parentDir) )
+                       url = parentDir + url;
+
+               return url;
+       }
+       */
+
+       public static void DeleteFile(string filename)
+       {
+               Console.WriteLine("Deleting... " + filename);
+               if (File.Exists(filename))
+                       File.Delete(filename);
+               Console.WriteLine("Deleted " + filename);
+       }
+
+       public static bool FileReadable(string filename)
+       {
+               //http://stackoverflow.com/a/17318735
+               try {
+                       File.Open(filename, FileMode.Open, FileAccess.Read).Dispose();
+                       //LogB.Information("success at Util.FileReadable: " + filename);
+                       return true;
+               }
+               catch (IOException) {
+                       System.Threading.Thread.Sleep(10);
+                       return false;
+               }
+       }
+
+       public static string GetPrefixDir(){
+               string baseDirectory = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, 
"..");
+               if (! Directory.Exists(Path.Combine(baseDirectory, "lib" + Path.DirectorySeparatorChar + 
"chronojump"))) {
+                       baseDirectory = System.IO.Path.Combine(baseDirectory, "..");
+               }
+               return baseDirectory;
+       }
+
+       public static string GetDataDir(){
+               return System.IO.Path.Combine(GetPrefixDir(),
+                       "share" + Path.DirectorySeparatorChar + "chronojump");
+       }
+
+       public static string BoolToRBool (bool myBool) {
+               if(myBool)
+                       return "TRUE";
+               else
+                       return "FALSE";
+       }
+
+       public static List<string> ReadFileAsStringList(string fileName)
+       {
+               try {
+                       List<string> lines = new List<string>();
+                       using (var sr = new StreamReader(fileName))
+                       {
+                               while (sr.Peek() >= 0)
+                               {
+                                       lines.Add(sr.ReadLine());
+                               }
+                       }
+                       return(lines);
+               } catch {
+                       return null;
+               }
+       }
+
+}
+
diff --git a/processMultiDatabases/utilEncoder.cs b/processMultiDatabases/utilEncoder.cs
new file mode 100644
index 00000000..266b9a58
--- /dev/null
+++ b/processMultiDatabases/utilEncoder.cs
@@ -0,0 +1,154 @@
+/*
+ * This file is part of ChronoJump
+ *
+ * ChronoJump is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *   the Free Software Foundation; either version 2 of the License, or   
+ *    (at your option) any later version.
+ *              
+ * ChronoJump is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
+ *    GNU General Public License for more details.
+ *                      
+ * You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software 
+ *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *              
+ * Copyright (C) 2019   Xavier de Blas <xaviblas gmail com> 
+ */
+
+using System;
+using System.IO;               //for detect OS
+
+public class UtilEncoder
+{
+       public static EncoderGraphROptions PrepareEncoderGraphOptions(
+                       string title, EncoderStruct es, bool neuromuscularProfileDo, bool translate, bool 
debug, bool crossValidate,
+                       bool cutByTriggers, string triggerStr, bool separateSessionInDays, 
EncoderGraphROptions.AnalysisModes analysisMode)
+       {
+               string operatingSystem = OperatingSystemForRGraphs();
+               
+               /*      
+               title = Util.RemoveBackSlash(title);
+               title = Util.RemoveChar(title, '\''); 
+               */
+               title = "hola";
+       
+               /*      
+               if (UtilAll.IsWindows()) {
+                       //convert accents to Unicode in order to be plotted correctly on R windows
+                       title = Util.ConvertToUnicode(title);
+
+                       //On win32 R understands backlash as an escape character and 
+                       //a file path uses Unix-like path separator '/'         
+                       es.InputData = es.InputData.Replace("\\","/");
+                       es.OutputGraph = es.OutputGraph.Replace("\\","/");
+                       es.OutputData1 = es.OutputData1.Replace("\\","/");
+                       //es.OutputData2 = es.OutputData2.Replace("\\","/");
+                       //es.SpecialData = es.SpecialData.Replace("\\","/");
+                       es.EncoderTempPath = es.EncoderTempPath.Replace("\\","/");
+               }
+               */
+               
+               //if translators add ";", it will be converted to ','
+               //if translators add a "\n", it will be converted to " "
+               /*
+               int count = 0;
+               string temp = "";
+               string [] encoderTranslatedWordsOK = new String [Constants.EncoderTranslatedWords.Length];
+
+               //if ! translate, then just print the english words
+               if(translate) {
+                       foreach(string etw in Constants.EncoderTranslatedWords) {
+                               temp = Util.ChangeChars(Catalog.GetString(etw), ";", ",");
+                               temp = Util.RemoveChar(temp, '\'');
+                               temp = Util.RemoveNewLine(temp, true);
+                               temp = Util.RemoveChar(temp, '#'); //needed to distinguish comments '#' than 
normal lines like the EncoderTranslatedWords
+               
+                               if (UtilAll.IsWindows()) {
+                                       LogB.Debug(" (1) Unicoding:", temp);
+                                       temp = Util.ConvertToUnicode(temp);
+                                       LogB.Debug(" (2) Unicoded:", temp);
+                               }
+
+                               encoderTranslatedWordsOK[count++] = temp;
+
+                       }
+               } else
+                       encoderTranslatedWordsOK = Constants.EncoderEnglishWords;
+                       */
+
+               return new EncoderGraphROptions( 
+                               es.InputData, es.OutputGraph, es.OutputData1, 
+                               //es.OutputData2, es.SpecialData, 
+                               es.EncoderRPath, es.EncoderTempPath,
+                               es.Ep,
+                               title, operatingSystem,
+                               "hola2", // Util.StringArrayToString(Constants.EncoderEnglishWords,";"),
+                               "hola3", // Util.StringArrayToString(encoderTranslatedWordsOK,";"),
+                               debug, crossValidate, cutByTriggers, triggerStr, separateSessionInDays, 
analysisMode
+                               );
+       }
+
+       public static string OperatingSystemForRGraphs()
+       {
+               string operatingSystem = "Linux";
+               //if (UtilAll.IsWindows())
+               //      operatingSystem = "Windows";
+
+               return operatingSystem;
+       }
+       
+       public static string GetEncoderDataTempFileName() {
+               return Path.Combine(Path.GetTempPath(), Constants.EncoderDataTemp);
+       }
+       public static string GetEncoderCurvesTempFileName() {
+               return Path.Combine(Path.GetTempPath(), Constants.EncoderCurvesTemp);
+       }
+       public static string GetEncoderGraphTempFileName() {
+               return Path.Combine(Path.GetTempPath(), Constants.EncoderGraphTemp);
+       }
+       public static string GetEncoderScriptsPathWithoutLastSep()
+       {
+               /*
+               string s = System.IO.Path.Combine(Util.GetDataDir(), "encoder");
+
+               //but send it without the final '\' or '/' (if found)
+               if(s.EndsWith("/") || s.EndsWith("\\"))
+                       s = s.Substring(0, s.Length -1);
+
+               return s;
+               */
+               //harcoded:
+               return "/usr/local/lib/chronojump/../../share/chronojump/encoder";
+       }
+       public static string GetEncoderTempPathWithoutLastSep() {
+               string s = Path.GetTempPath(); //is just temp path
+
+               //but send it without the final '\' or '/' (if found)
+               if(s.EndsWith("/") || s.EndsWith("\\"))
+                       s = s.Substring(0, s.Length -1);
+
+               return s;
+       }
+
+       public static bool CopyEncoderDataToTemp(string url, string fileName)
+       {
+               string origin = url + Path.DirectorySeparatorChar + fileName;
+               string dest = GetEncoderDataTempFileName();
+               if(File.Exists(origin)) {
+                       try {
+                               File.Copy(origin, dest, true);
+                       } catch {
+                               Console.WriteLine(Constants.FileCopyProblemStr());
+                               return false;
+                       }
+                       return true;
+               }
+
+               Console.WriteLine(Constants.FileNotFoundStr());
+               return false;
+       }
+
+}



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