Ejemplo n.º 1
0
        /// <summary>
        /// Excecutes tool and returns results as parameters.
        /// </summary>
        /// <param name="inputParams">Inputs.</param>
        /// <returns>DescriptiveResult.</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            DescriptiveResult result = new DescriptiveResult();

            try
            {
                var    input = inputParams as DescriptiveInputParams;
                string descriptiveProject = Path.Combine(inputParams.Env.RootPath, "DescModel");

                // If tool was ran in Edit -tab.
                if (input.Method == "EditedFile")
                {
                    descriptiveProject = Path.Combine(descriptiveProject, input.Tab1ExtensionFolder);
                }
                // If tool was ran in New -tab.
                else if (input.Method == "NewFile")
                {
                    descriptiveProject = Path.Combine(descriptiveProject, input.Tab2ExtensionFolder);
                }
                if (!Directory.Exists(descriptiveProject))
                {
                    Directory.CreateDirectory(descriptiveProject);
                }
                input.Save(Path.Combine(descriptiveProject, "descriptive_input_params.json"));

                if (input.Method == "WordFile")
                {
                    if (!Directory.Exists(Path.Combine(descriptiveProject, "SelectedResult")))
                    {
                        Directory.CreateDirectory(Path.Combine(descriptiveProject, "SelectedResult"));
                    }
                    result.WordOutputFile = Path.Combine(descriptiveProject, "SelectedResult", "DescriptiveWordModel(docx).docx");
                }
                if (input.Method == "EditedFile")
                {
                    result.OutputFile     = Path.Combine(descriptiveProject, "DescriptiveModel.txt");
                    result.CharOutputFile = Path.Combine(descriptiveProject, "DescriptiveModel(Chars).txt");
                    result.WordOutputFile = Path.Combine(descriptiveProject, "DescriptiveModel(docx).docx");
                }
                else if (input.Method == "NewFile")
                {
                    result.OutputFile     = Path.Combine(descriptiveProject, "DescriptiveNewModel.txt");
                    result.CharOutputFile = Path.Combine(descriptiveProject, "DescriptiveNewModel(Chars).txt");
                    result.WordOutputFile = Path.Combine(descriptiveProject, "DescriptiveNewModel(docx).docx");
                }
            }
            catch (Exception ex)
            {
                result.OutputFile = ex.ToString();
                throw new Exception("Output file failed: " + result, ex);
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Excecutes tool and returns results as parameters
        /// </summary>
        /// <param name="inputParams">Input parameters</param>
        /// <returns>Result as DepositDensityResult</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            DepositDensityInputParams input = inputParams as DepositDensityInputParams;
            string outputFolder             = Path.Combine(input.Env.RootPath, "UndiscDep", input.TractId);

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }
            //input.Save(Path.Combine(outputFolder, "deposit_density_input_params.json"));
            modelId = input.ExistingDepositDensityModelID;
            Area    = Convert.ToDouble(input.AreaOfTrack);
            MedTons = Convert.ToDouble(input.MedianTonnage);
            NKnown  = input.NumbOfKnownDeposits != "" ? Convert.ToDouble(input.NumbOfKnownDeposits) : 0;
            TractId = input.TractId;
            DepositDensityResult result = new DepositDensityResult();
            string CSVPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "scripts", "DepositDensity");

            if (input.ExistingDepositDensityModelID == "General")
            {
                CSVPath = Path.Combine(CSVPath, "General_data.csv");
            }
            else if (input.ExistingDepositDensityModelID == "PodiformCr")
            {
                CSVPath = Path.Combine(CSVPath, "PodiformCr_data.csv");
            }
            else if (input.ExistingDepositDensityModelID == "VMS")
            {
                CSVPath = Path.Combine(CSVPath, "VMS_data.csv");
            }
            else if (input.ExistingDepositDensityModelID == "PorCu")
            {
                CSVPath = Path.Combine(CSVPath, "PorphyryCu_data.csv");  // TAGGED: Fix path.
            }
            ReadinputParamsFromCSV(CSVPath);
            //Calculate values based as which deposit type selected
            if (input.ExistingDepositDensityModelID == "General")
            {
                result = GeneralCalculation();
            }
            else
            {
                result = DepositTypeCalculation(input.ExistingDepositDensityModelID);
            }
            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Permissive Tract tool execution
        /// </summary>
        /// <param name="inputParams">Input parameters as ToolParameters</param>
        /// <returns>ToolResult as PermissiveTractResult</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            projectFolder = Path.Combine(inputParams.Env.RootPath, "TractDelineation");
            if (!Directory.Exists(projectFolder))
            {
                Directory.CreateDirectory(projectFolder);
            }

            var input = inputParams as PermissiveTractInputParams;

            input.Save(projectFolder + @"\permissive_tract_input_params.json");
            PermissiveTractResult result = new PermissiveTractResult();

            if (input.MethodId == "fuzzy" || input.MethodId == "fuzzyClassification")
            {
                result = FuzzyOverlay(input, result);
            }
            else if (input.MethodId == "delineation")
            {
                result = Delineation(input, result);
            }
            else if (input.MethodId == "delineation_polygon")
            {
                result = DelineationPolygon(input, result);
            }
            else if (input.MethodId == "wofe" || input.MethodId == "wofeClassification")
            {
                result = WofE(input, result);
            }
            else if (input.MethodId == "generatetracts")
            {
                result = GenerateTracts(input, result);
            }
            else if (input.MethodId == "calculatetreshold")
            {
                result = CalculateTreshold(input, result);
            }
            else if (input.MethodId == "classification")
            {
                result = Classificate(input, result);
            }
            return(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Excecutes tool and returns results as parameters.
        /// </summary>
        /// <param name="inputParams">Inputs.</param>
        /// <returns>AssesmentReportResult.</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            ReportingAssesmentInputParams input = inputParams as ReportingAssesmentInputParams;
            string outputFolder = Path.Combine(inputParams.Env.RootPath, "Reporting");

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }
            input.Save(Path.Combine(outputFolder, "assesment_report_input_params.json"));
            ReportingAssesmentResult result = new ReportingAssesmentResult(); // This should return the output file.

            try
            {
                if (!Directory.Exists(Path.Combine(outputFolder, input.SelectedTractCombination)))
                {
                    Directory.CreateDirectory(Path.Combine(outputFolder, input.SelectedTractCombination));
                }
                string docOutputFile = Path.Combine(outputFolder, input.SelectedTractCombination, "AssesmentReport" + input.SelectedTractCombination + ".docx");
                using (var document = DocX.Create(docOutputFile))
                {
                    document.PageLayout.Orientation = Orientation.Portrait;
                    WriteInputs(input, document);
                    WriteUndiscoveredDeposits(input, document);
                    WriteMonteCarlo(input, document);
                    WriteEconomicFilter(input, document);
                    WriteAppendixes(input, document);
                    document.Save();
                }
                result.OutputDocument = docOutputFile;
            }
            catch (Exception ex)
            {
                throw new Exception("Word file creation failed: ", ex);
            }
            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Run tool
        /// </summary>
        /// <param name="inputParams"> Input parameters</param>
        /// <returns>Result as ToolResult</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            var input = inputParams as EconomicFilterInputParams;
            EconomicFilterResult result = new EconomicFilterResult();

            //If type is EconFilter/Screener
            if (input.ModelIndex == "1")
            {
                try
                {
                    string projectFolder = Path.Combine(inputParams.Env.RootPath, "EconFilter", "Screener", input.ScreenerExtensionFolder);
                    try
                    {
                        if (!Directory.Exists(projectFolder))
                        {
                            Directory.CreateDirectory(projectFolder);
                        }

                        input.Save(Path.Combine(inputParams.Env.RootPath, "EconFilter", "economic_filter_input_params.json"));
                        input.Save(Path.Combine(projectFolder, "economic_filter_input_params.json")); //save also to screener folder for selecting result
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Failed to initialize project folder: " + ex);
                    }
                    Double percent;
                    string pType;
                    pType   = input.perType == "Count %" ? "1" : "2";
                    percent = Convert.ToDouble(input.percentage) / 100;
                    var    path                  = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
                    var    rCodeFilePath         = "\"" + path + "scripts/econf.r" + "\"";
                    string rScriptExecutablePath = inputParams.Env.RPath;
                    string tmpPlot               = Path.Combine(input.Env.RootPath, "EconFilter", "Screener", input.ScreenerExtensionFolder);
                    string procResult            = string.Empty;
                    var    info                  = new ProcessStartInfo();
                    info.FileName               = rScriptExecutablePath;
                    info.WorkingDirectory       = path + "scripts/";
                    info.Arguments              = rCodeFilePath + " " + "\"" + input.MCResults + "\"" + " " + pType + " " + input.percentage.ToString() + " " + "\"" + tmpPlot + "\"" + " " + input.MetalIndex + " " + input.MetalsToCalculate;
                    info.RedirectStandardInput  = false;
                    info.RedirectStandardOutput = true;
                    info.RedirectStandardError  = true;
                    info.UseShellExecute        = false;
                    info.CreateNoWindow         = true;

                    using (var proc = new Process())
                    {
                        proc.StartInfo = info;
                        proc.Start();
                        using (StreamReader errorReader = proc.StandardError)
                        {
                            using (StreamReader myStreamReader = proc.StandardOutput)
                            {
                                string errors = errorReader.ReadToEnd();
                                if (errors.Length > 1 && errors.ToLower().Contains("error"))  //Don't throw exception over warnings or empty error message.
                                {
                                    logger.Error(errors);
                                    throw new Exception("R script failed, check log file for details.");
                                }
                                string stream = myStreamReader.ReadToEnd();
                                procResult = proc.StandardOutput.ReadToEnd();
                            }
                        }
                        proc.Close();
                        result.EcoTonnage      = Path.Combine(projectFolder, "eco_tonnages.csv");
                        result.EcoTonnageStats = Path.Combine(projectFolder, "eco_tonnage_stat.csv");
                        result.EcoTonHistogram = Path.Combine(projectFolder, "eco_ton_histogram.jpeg");
                        result.ResultPlot      = Path.Combine(projectFolder, "result_plot.jpeg");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Economic filter screener tool failed: ");  // TAGGED: Fix exception handling.
                }
                return(result);
            }
            else //If type is RAEF
            {
                if (input.RaefEmpiricalModel == "True")//tähä runtype==empirical checki
                {
                    //tehdäkö oma pätkä tälle kokonaan vai yhdistää raefin kaa? vaikka onki vähän toistoa, niin ehkä fiksumpi tehä silti oma pätkä.
                    //MM4File < --args[1] #     SIM file
                    //GTMEmp << -args[2]# GTM file
                    //InputFolder2 << -args[3]#output directory
                    //TestNameEmp << -args[4] # test/run name
                    try
                    {
                        string projectFolder = Path.Combine(inputParams.Env.RootPath, "EconFilter", "RAEF", input.TractID, input.RaefExtensionFolder);//tohon vois tietty laittaa esim EMP?
                        string packageFolder = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "scripts", "RAEF", "Package");
                        try
                        {
                            if (!Directory.Exists(projectFolder))
                            {
                                Directory.CreateDirectory(projectFolder);
                            }
                            var projectFolderInfo = new DirectoryInfo(projectFolder);
                            foreach (FileInfo file in projectFolderInfo.GetFiles())
                            {
                                file.Delete();
                            }
                            input.Save(Path.Combine(inputParams.Env.RootPath, "EconFilter", "economic_filter_input_params.json"));
                            input.Save(Path.Combine(projectFolder, "economic_filter_input_params.json")); //Save also to raef folder for selecting results
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Failed to initialize project folder: " + ex);
                        }
                        var    path                  = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
                        var    rCodeFilePath         = "\"" + path + "scripts/RaefEmpModel.r" + "\"";
                        string rScriptExecutablePath = inputParams.Env.RPath;
                        string procResult            = string.Empty;
                        var    info                  = new ProcessStartInfo();
                        info.FileName         = rScriptExecutablePath;
                        info.WorkingDirectory = Path.Combine(path, "scripts");
                        //kato näiden pathit että ei oo backslashei
                        info.Arguments = rCodeFilePath + " " + "\"" + input.RaefEconFilterFile + "\"" + " " + "\"" + input.RaefGtmFile + "\"" + " " + "\"" + projectFolder + "\"" + " " + "\"" + input.RaefRunName + "\"";//input.RaefExtensionFolder

                        info.RedirectStandardInput  = false;
                        info.RedirectStandardOutput = true;
                        info.RedirectStandardError  = true;
                        info.UseShellExecute        = false;
                        info.CreateNoWindow         = true;

                        using (var proc = new Process())
                        {
                            proc.StartInfo = info;
                            proc.Start();
                            using (StreamReader myStreamReader = proc.StandardOutput)
                            {
                                string procErrors = "";
                                proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                                {
                                    if (!String.IsNullOrEmpty(e.Data))
                                    {
                                        procErrors += (e.Data);
                                    }
                                });
                                proc.BeginErrorReadLine();
                                string stream = myStreamReader.ReadToEnd();
                                logger.Trace(stream);
                                if (procErrors.Length > 1 && procErrors.ToLower().Contains("error"))  //Don't throw exception over warnings or empty error message.
                                {
                                    logger.Error(procErrors);
                                    throw new Exception("R script failed, check log file for details");
                                }
                                procResult = proc.StandardOutput.ReadToEnd();
                            }
                            proc.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Trace("Error: " + ex);
                        throw new Exception("Economic filter RAEF tool failed: ");
                    }
                    return(result);
                }
                else
                {
                    try
                    {
                        string projectFolder = Path.Combine(inputParams.Env.RootPath, "EconFilter", "RAEF", input.TractID, input.RaefExtensionFolder);
                        string packageFolder = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "scripts", "RAEF", "Package");
                        try
                        {
                            if (!Directory.Exists(projectFolder))
                            {
                                Directory.CreateDirectory(projectFolder);
                            }
                            var projectFolderInfo = new DirectoryInfo(projectFolder);
                            foreach (FileInfo file in projectFolderInfo.GetFiles())
                            {
                                file.Delete();
                            }
                            input.Save(Path.Combine(inputParams.Env.RootPath, "EconFilter", "economic_filter_input_params.json"));
                            input.Save(Path.Combine(projectFolder, "economic_filter_input_params.json")); //Save also to raef folder for selecting results
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Failed to initialize project folder: " + ex);
                        }
                        var    path                  = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
                        var    rCodeFilePath         = "\"" + path + "scripts/RAEF_MW.r" + "\"";
                        string rScriptExecutablePath = inputParams.Env.RPath;
                        string procResult            = string.Empty;
                        var    info                  = new ProcessStartInfo();
                        info.FileName               = rScriptExecutablePath;
                        info.WorkingDirectory       = Path.Combine(path, "scripts");
                        info.Arguments              = rCodeFilePath + " " + "\"" + packageFolder + "\"" + " " + "\"" + input.RaefPresetFile + "\"" + " " + "\"" + projectFolder + "\"" + " " + "\"" + input.RaefEconFilterFile + "\"";
                        info.RedirectStandardInput  = false;
                        info.RedirectStandardOutput = true;
                        info.RedirectStandardError  = true;
                        info.UseShellExecute        = false;
                        info.CreateNoWindow         = true;

                        using (var proc = new Process())
                        {
                            proc.StartInfo = info;
                            proc.Start();
                            using (StreamReader myStreamReader = proc.StandardOutput)
                            {
                                string procErrors = "";
                                proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                                {
                                    if (!String.IsNullOrEmpty(e.Data))
                                    {
                                        procErrors += (e.Data);
                                    }
                                });
                                proc.BeginErrorReadLine();
                                string stream = myStreamReader.ReadToEnd();
                                logger.Trace(stream);
                                if (procErrors.Length > 1 && procErrors.ToLower().Contains("error"))  //Don't throw exception over warnings or empty error message.
                                {
                                    logger.Error(procErrors);
                                    throw new Exception("R script failed, check log file for details");
                                }
                                procResult = proc.StandardOutput.ReadToEnd();
                            }
                            proc.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Trace("Error: " + ex);
                        throw new Exception("Economic filter RAEF tool failed: ");
                    }
                    return(result);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///  Excecutes tool and returns results as parameters.
        /// </summary>
        /// <param name="inputParams">Input parameters</param>
        /// <returns>Result as MonteCarloSimulationResult</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            var input = inputParams as MonteCarloSimulationInputParams;
            MonteCarloSimulationResult result = new MonteCarloSimulationResult();
            //string projectFolder = Path.Combine(inputParams.Env.RootPath, "MCSim", input.ExtensionFolder);
            string MCSimFolder   = Path.Combine(inputParams.Env.RootPath, "MCSim");
            string projectFolder = Path.Combine(MCSimFolder, input.TractID, input.ExtensionFolder);

            try
            {
                if (!Directory.Exists(projectFolder))
                {
                    Directory.CreateDirectory(projectFolder);
                }
                input.Save(Path.Combine(MCSimFolder, "monte_carlo_simulation_input_params.json"));
                input.Save(Path.Combine(projectFolder, "monte_carlo_simulation_input_params.json"));
                ////Create possible extension folder
                //if (input.ExtensionFolder != null && input.ExtensionFolder != "")
                //{
                //    projectFolder = Path.Combine(projectFolder,input.ExtensionFolder);
                //    if (!Directory.Exists(projectFolder))
                //    {
                //        Directory.CreateDirectory(projectFolder);
                //    }
                //}
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to initialize model folder:" + ex);
            }
            var    path                  = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
            var    rCodeFilePath         = path + "scripts/MonteCarloSimulationWrapper.R";
            var    scriptPath            = path + "scripts/MonteCarloSimulation/";
            var    summaryTxt            = Path.Combine(projectFolder, "summary.txt");
            string rScriptExecutablePath = result.Env.RPath;
            string procResult            = string.Empty;
            string tractName             = input.TractID;
            string tonnagePDF            = input.TonnagePlot.Contains("Please select") ? "NA" : input.TonnagePlot;
            string gradePDF              = input.GradePlot.Contains("Please select") ?   "NA" : input.GradePlot;
            string gradeTonnagePDF       = input.GradeTonnagePlot.Contains("Please select") ? "NA" : input.GradeTonnagePlot;

            var info = new ProcessStartInfo();

            info.FileName               = rScriptExecutablePath;
            info.WorkingDirectory       = path + "scripts/";
            info.Arguments              = "\"" + rCodeFilePath + "\" \"" + input.NDepositsPmf + "\" \"" + tonnagePDF + "\" \"" + gradePDF + "\" \"" + gradeTonnagePDF + "\" \"" + scriptPath + "oMeta.rds" + "\" \"" + summaryTxt + "\" \"" + projectFolder + "\"";
            info.Arguments             += " " + tractName;
            info.RedirectStandardInput  = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError  = true;
            info.UseShellExecute        = false;
            info.CreateNoWindow         = true;

            using (var proc = new Process())
            {
                try
                {
                    proc.StartInfo = info;
                    proc.Start();
                    string procErrors = "";
                    proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                    {                                                                      //Also, this approach makes it easier to implement a possible log window in the future
                        if (!String.IsNullOrEmpty(e.Data))
                        {
                            procErrors += (e.Data);
                        }
                    });
                    proc.BeginErrorReadLine();
                    procResult = proc.StandardOutput.ReadToEnd();
                    proc.Close();
                    if (procErrors.Length > 1)
                    {
                        logger.Error(procErrors);
                    }
                    result.SummaryTotalTonnage  = File.ReadAllText(Path.Combine(projectFolder, "summary.txt"));
                    result.SimulatedDepositsCSV = Path.Combine(projectFolder, tractName + "_05_SIM_EF.csv");
                    result.TotalTonPlot         = Path.Combine(projectFolder, "plot.jpeg");
                    result.MarginalPlot         = Path.Combine(projectFolder, "plotMarginals.jpeg");
                }
                catch (Exception ex)
                {
                    throw new Exception("R script failed, check log file for details.");
                }
            }
            return(result);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Excecutes tool and returns results as parameters
        /// </summary>
        /// <param name="inputParams">Input parameters</param>
        /// <returns>Result as UndiscoveredDepositsResult</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            var input = inputParams as UndiscoveredDepositsInputParams;
            UndiscoveredDepositsResult result = new UndiscoveredDepositsResult();
            string usedMethod      = "";
            string pathToCsv       = "";
            string pathToTxt       = "";
            string undiscDepFolder = Path.Combine(inputParams.Env.RootPath, "UndiscDep");
            string projectFolder   = Path.Combine(undiscDepFolder, input.TractID);

            if (!Directory.Exists(projectFolder))
            {
                Directory.CreateDirectory(projectFolder);
            }
            //Create estimation based on input data and method
            try
            {
                if (input.Method == "Negative")
                {
                    projectFolder = Path.Combine(projectFolder, "NegativeBinomial", input.NegBinomialExtensionFolder);
                    if (!Directory.Exists(projectFolder))
                    {
                        Directory.CreateDirectory(projectFolder);
                    }
                    DirectoryInfo di = new DirectoryInfo(projectFolder); // clear
                    foreach (FileInfo file in di.GetFiles())
                    {
                        if (file.Name != Path.Combine("plot.jpeg"))
                        {
                            file.Delete();
                        }
                    }
                    usedMethod = "NegBinomial";
                    pathToCsv  = projectFolder + @"\nDepEst.csv";
                    CreateEstimationCsv(pathToCsv, input.DepositsNegativeCSV);
                    pathToTxt = projectFolder + @"\EstRationale.txt";
                    CreateRationaleTxt(pathToTxt, input.EstRationaleTXT);
                }
                else if (input.Method == "Custom")
                {
                    projectFolder = Path.Combine(projectFolder, "Custom", input.CustomExtensionFolder);
                    if (!Directory.Exists(projectFolder))
                    {
                        Directory.CreateDirectory(projectFolder);
                    }
                    DirectoryInfo di = new DirectoryInfo(projectFolder);
                    foreach (FileInfo file in di.GetFiles())
                    {
                        if (file.Name != Path.Combine("plot.jpeg"))
                        {
                            file.Delete();
                        }
                    }
                    usedMethod = "CustomMark4";
                    pathToCsv  = projectFolder + @"\nDepEstCustom.csv";
                    CreateEstimationCsv(pathToCsv, input.DepositsCustomCSV);
                    pathToTxt = projectFolder + @"\EstRationale.txt";
                    CreateRationaleTxt(pathToTxt, input.CustomEstRationaleTXT);
                }
                else if (input.Method == "Middle")
                {
                    projectFolder = Path.Combine(projectFolder, "MARK3", input.Mark3ExtensionFolder);
                    if (!Directory.Exists(projectFolder))
                    {
                        Directory.CreateDirectory(projectFolder);
                    }
                    DirectoryInfo di = new DirectoryInfo(projectFolder);
                    foreach (FileInfo file in di.GetFiles())
                    {
                        if (file.Name != Path.Combine("plot.jpeg"))
                        {
                            file.Delete();
                        }
                    }
                    usedMethod = "CustomMark3";
                    pathToCsv  = projectFolder + @"\nDepEstMiddle.csv";
                    string customEstimations = "";// "N90,N50,N10,N5,N1\n";
                    customEstimations += input.N90 + "\n" + input.N50 + "\n" + input.N10 + "\n" + input.N5 + "\n" + input.N1 + "\n";
                    CreateEstimationCsv(pathToCsv, customEstimations);
                    pathToTxt = projectFolder + @"\EstRationale.txt";
                    CreateRationaleTxt(pathToTxt, input.Mark3EstRationaleTXT);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to create estimation: " + ex);
            }
            input.Save(Path.Combine(undiscDepFolder, "undiscovered_deposits_input_params.json"));
            try
            {
                var    path                  = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
                var    rCodeFilePath         = path + "scripts/UndiscoveredDepositsWrapper.R";
                string rScriptExecutablePath = inputParams.Env.RPath;
                string procResult            = string.Empty;
                var    info                  = new ProcessStartInfo();
                info.FileName = rScriptExecutablePath;

                info.WorkingDirectory = path + "scripts/";
                string tmpSummary = Path.Combine(projectFolder, "summary.txt");
                string describ    = "describ";
                string tractName  = new DirectoryInfo(projectFolder).Name;
                //string outputCsv = Path.Combine(projectFolder, tractName + input.TractID + ".csv");
                string outputCsv = Path.Combine(projectFolder, "TractPmf.csv");
                string tract     = input.TractID;

                info.Arguments = "\"" + rCodeFilePath + "\" \"" + usedMethod + "\" \"" + pathToCsv + "\" \"" + tmpSummary + "\" \"" + describ + "\" \"" + projectFolder + "\" \"" + outputCsv + "\" \"" + tract;

                info.RedirectStandardInput  = false;
                info.RedirectStandardOutput = true;
                info.RedirectStandardError  = true;
                info.UseShellExecute        = false;
                info.CreateNoWindow         = true;

                using (var proc = new Process())
                {
                    proc.StartInfo = info;
                    proc.Start();
                    using (StreamReader errorReader = proc.StandardError)
                    {
                        //StreamReader myStreamReader = proc.StandardOutput; TAGGED: no usage?
                        string errors = errorReader.ReadToEnd();
                        //string stream = myStreamReader.ReadToEnd(); TAGGED: no usage?
                        procResult = proc.StandardOutput.ReadToEnd();
                        proc.Close();
                        logger.Error("Errors:" + errors);
                        if (errors.Length > 1 && errors.ToLower().Contains("error"))  //Don't throw exception over warnings or empty error message.
                        {
                            logger.Error(errors);
                            throw new Exception("R script execution failed. Check log file for details");
                        }
                    }
                    result.Summary         = File.ReadAllText(Path.Combine(projectFolder, "summary.txt"));
                    result.PlotImage       = Path.Combine(projectFolder, "plot.jpeg");
                    result.NDepositsPmf    = Path.Combine(projectFolder, "oPmf.rds");
                    result.EstRationaleTXT = Path.Combine(projectFolder, "EstRationale.txt");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to run Undiscovered deposits tool: " + ex);
            }
            return(result);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Call R script to run the tool.
        /// </summary>
        /// <param name="inputParams"> Input parameters as ToolParameters</param>
        /// <returns> ToolResult as TractAggregationTool result</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            string procResult            = string.Empty;
            var    input                 = inputParams as TractAggregationInputParams;
            string rScriptExecutablePath = inputParams.Env.RPath;
            var    path = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
            var    info = new ProcessStartInfo();

            info.FileName = rScriptExecutablePath;
            var projectFolder = Path.Combine(inputParams.Env.RootPath, "TractAggregation");

            if (!Directory.Exists(projectFolder))
            {
                Directory.CreateDirectory(projectFolder);
            }
            input.Save(Path.Combine(projectFolder, "tract_aggregation_input_params.json"));
            var    tractAggregationProject = Path.Combine(inputParams.Env.RootPath, "TractAggregation", "AggResults");
            string rProjectPath            = tractAggregationProject.Replace("\\", "/");
            var    rTractAggregationPath   = Path.Combine(path, "scripts", "TractAggregation.R");
            TractAggregationResult result  = new TractAggregationResult();
            var AggResultsPath             = Path.Combine(inputParams.Env.RootPath, "TractAggregation", "AggResults", "AGG" + input.TractCombinationName);
            var TractCorrelationsFile      = Path.Combine(AggResultsPath, "TractCorrelations.csv");
            var TractProbDistsFile         = Path.Combine(AggResultsPath, "TractProbDists.csv");

            if (!Directory.Exists(AggResultsPath))
            {
                Directory.CreateDirectory(AggResultsPath);
            }
            if (File.Exists(input.CorrelationMatrix))
            {
                if (File.Exists(TractCorrelationsFile))
                {
                    File.Delete(TractCorrelationsFile);
                }
                File.Copy(input.CorrelationMatrix, Path.Combine(AggResultsPath, "TractCorrelations.csv"));
            }
            if (File.Exists(input.ProbDistFile))
            {
                if (File.Exists(TractProbDistsFile))
                {
                    File.Delete(TractProbDistsFile);
                }
                File.Copy(input.ProbDistFile, Path.Combine(AggResultsPath, "TractProbDists.csv"));
            }
            //If probability distribution file is created from separate files, run this script to create the proper input file before the main script.
            if (input.CreateInputFile == "True")
            {
                try
                {
                    var info2 = new ProcessStartInfo();
                    info2.FileName = rScriptExecutablePath;
                    var CombineFilesFolder      = Path.Combine(input.Env.RootPath, "AggTempFolder");
                    var rCreateProbDistFilePath = Path.Combine(path, "scripts", "TractAggregationCreateDPFile.R");
                    rCreateProbDistFilePath     = rCreateProbDistFilePath = rCreateProbDistFilePath.Replace("\\", "/");
                    info.Arguments              = "\"" + rCreateProbDistFilePath + "\" \"" + CombineFilesFolder + "\"";
                    info.RedirectStandardInput  = false;
                    info.RedirectStandardOutput = true;
                    info.UseShellExecute        = false;
                    info.CreateNoWindow         = true;
                    info.RedirectStandardError  = true;
                    info.WorkingDirectory       = CombineFilesFolder;

                    using (var proc = new Process())
                    {
                        proc.StartInfo = info;
                        proc.Start();
                        //StreamReader errorReader = proc.StandardError; TAGGED: no usage?
                        //StreamReader myStreamReader = proc.StandardOutput; TAGGED: no usage?
                        string procErrors = "";
                        proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                        {                                                                      //Also, this approach makes it easier to implement a possible log window in the future
                            if (!String.IsNullOrEmpty(e.Data))
                            {
                                procErrors += (e.Data);
                            }
                        });
                        //string stream = myStreamReader.ReadToEnd(); TAGGED: no usage?
                        procResult = proc.StandardOutput.ReadToEnd();
                        proc.Close();
                        if (procErrors.Length > 1 && procErrors.ToLower().Contains("error"))  //Don't throw exception over warnings or empty error message.
                        {
                            logger.Error(procErrors);
                            //throw new Exception("R script execution failed. Check log file for details");  // TAGGED: Check error management and make it better.
                        }
                        logger.Trace("Tract Aggregation return value:" + procResult);
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Failed to create probability distribution file: " + e);
                }
            }

            //Run tract aggregation script
            info.Arguments              = "\"" + rTractAggregationPath + "\"" + " " + "Agg" + " " + "\"" + AggResultsPath + "\" \"" + input.ProbDistFile + "\" \"" + input.CorrelationMatrix + "\"";
            info.RedirectStandardInput  = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError  = true;
            info.UseShellExecute        = false;
            info.CreateNoWindow         = true;
            info.WorkingDirectory       = AggResultsPath;
            try
            {
                using (var proc = new Process())
                {
                    proc.StartInfo = info;
                    proc.Start();
                    string procErrors = "";
                    proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                    {                                                                      //Also, this approach makes it easier to implement a possible log window in the future
                        if (!String.IsNullOrEmpty(e.Data))
                        {
                            procErrors += (e.Data);
                        }
                    });
                    proc.BeginErrorReadLine();
                    procResult = proc.StandardOutput.ReadToEnd();
                    proc.Close();
                    if (procErrors.Length > 1)
                    {
                        logger.Error(procErrors);
                    }
                    logger.Trace(procResult);
                    var resultFilePath = Path.Combine(AggResultsPath, "AggEstSummary.csv");
                    var resultString   = File.ReadAllText(resultFilePath);
                    result.TractAggregationSummary = resultString.Replace(",", "\t");
                    result.TractAggregationSummary = result.TractAggregationSummary.Replace("\"", "");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Tract Aggregation run failed: " + ex);
            }
            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// GradeTonnage Tool execution
        /// </summary>
        /// <param name="inputParams">Input parameters as ToolParameters</param>
        /// <returns>ToolResult as GradeTonnageResult</returns>
        public ToolResult Execute(ToolParameters inputParams)
        {
            //Initialize variables
            var input = inputParams as GradeTonnageInputParams;

            gradeProject = Path.Combine(inputParams.Env.RootPath, "GTModel", input.ExtensionFolder);
            if (!Directory.Exists(gradeProject))
            {
                Directory.CreateDirectory(gradeProject);
            }
            GradeTonnageResult result = new GradeTonnageResult();
            var path              = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");
            var rGradePath        = path + "scripts/GradeWrapper.R";
            var rTonnagePath      = path + "scripts/TonnageWrapper.R";
            var rGradeTonnagePath = path + "scripts/TonGradeWrapper.R";
            var workingDir        = System.AppDomain.CurrentDomain.BaseDirectory.Replace(@"\", @"/");

            workingDir = workingDir + "scripts";
            workingDir.Replace(@"\n", @"");
            string rScriptExecutablePath = inputParams.Env.RPath;
            string procResult            = string.Empty;

            var gtProject = Path.Combine(inputParams.Env.RootPath, "GTModel", input.ExtensionFolder);
            var gtDirInfo = new DirectoryInfo(gtProject);

            try
            {
                if (!Directory.Exists(gtProject))
                {
                    Directory.CreateDirectory(gtProject);
                }
                else
                {
                    foreach (FileInfo f in gtDirInfo.GetFiles())
                    {
                        f.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw new Exception("Could not initialize project folder: ", ex);
            }
            input.Save(Path.Combine(gradeProject, "GradeTonnage_input_params.json"));
            if (input.RunGrade == "True")  //Run grade
            {
                try
                {
                    string inputFileDest = Path.Combine(gradeProject, "GT_InputFile.csv");
                    File.Copy(input.CSVPath, Path.Combine(gradeProject, "GT_InputFile.csv"), true);
                    gradeProject = Path.Combine(inputParams.Env.RootPath, "GTModel", input.ExtensionFolder);
                    var info = new ProcessStartInfo();
                    info.FileName = rScriptExecutablePath;
                    string rProjectPath = gradeProject.Replace("\\", "/");
                    info.Arguments = "\"" + rGradePath + "\" \"" + input.CSVPath + "\" " + input.Seed + " " + input.PDFType + " " + input.IsTruncated + " " + input.MinDepositCount + " " + input.RandomSampleCount + " \"" + gradeProject + "\" \"" + workingDir + "\"";

                    info.RedirectStandardInput  = false;
                    info.RedirectStandardOutput = true;
                    info.RedirectStandardError  = true;
                    info.UseShellExecute        = false;
                    info.CreateNoWindow         = true;
                    info.WorkingDirectory       = path + "scripts/";
                    using (var proc = new Process())
                    {
                        proc.StartInfo = info;
                        proc.Start();
                        string procErrors = "";
                        proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                        {
                            if (!String.IsNullOrEmpty(e.Data))
                            {
                                procErrors += (e.Data);
                            }
                        });
                        proc.BeginErrorReadLine();
                        procResult = proc.StandardOutput.ReadToEnd();
                        proc.Close();
                        result.Warnings = "";
                        if (procErrors.Length > 1 && procErrors.ToLower().Contains("error")) //Don't throw exception over warnings or empty error message.
                        {
                            logger.Error(procErrors);
                            throw new Exception(" R script failed, check output for details.");
                        }
                        else if (procErrors.Length > 1 && procErrors.ToLower().Contains("the input grade-tonnage data file contains less than 20 deposits"))
                        {
                            result.Warnings = "The input grade - tonnage data file contains less than 20 deposits.This might reduce the representativeness of the generated pdfs.";
                        }
                        result.GradeSummary = File.ReadAllText(Path.Combine(gradeProject, "grade_summary.txt"));
                        result.GradePlot    = Path.Combine(gradeProject, "grade_plot.jpeg");
                        logger.Trace("Grade tonnage return value: " + procResult);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to excecute Grade tool: " + ex);
                }
            }
            if (input.RunTonnage == "True")  //Run tonnage
            {
                try
                {
                    var info = new ProcessStartInfo();
                    info.FileName  = rScriptExecutablePath;
                    tonnageProject = Path.Combine(inputParams.Env.RootPath, "GTModel", input.ExtensionFolder);
                    if (!Directory.Exists(tonnageProject))
                    {
                        Directory.CreateDirectory(tonnageProject);
                    }
                    string inputFileDest = Path.Combine(tonnageProject, "GT_InputFile.csv");
                    File.Copy(input.CSVPath, Path.Combine(tonnageProject, "GT_InputFile.csv"), true);
                    string rProjectPath = tonnageProject.Replace("\\", "/");
                    info.Arguments = "\"" + rTonnagePath + "\" \"" + input.CSVPath + "\" " + input.Seed + " " + input.PDFType + " " + input.IsTruncated + " " + input.MinDepositCount + " " + input.RandomSampleCount + " \"" + tonnageProject + "\" \"" + workingDir + "\"";

                    info.RedirectStandardInput  = false;
                    info.RedirectStandardOutput = true;
                    info.RedirectStandardError  = true;
                    info.UseShellExecute        = false;
                    info.CreateNoWindow         = true;
                    info.WorkingDirectory       = path + "scripts/";

                    using (var proc = new Process())
                    {
                        proc.StartInfo = info;
                        proc.Start();

                        string procErrors = "";
                        proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                        {                                                                      //Also, this approach makes it easier to implement a possible log window in the future
                            if (!String.IsNullOrEmpty(e.Data))
                            {
                                procErrors += (e.Data);
                            }
                        });
                        proc.BeginErrorReadLine();
                        procResult = proc.StandardOutput.ReadToEnd();
                        proc.Close();
                        result.Warnings = "";
                        if (procErrors.Length > 1 && procErrors.ToLower().Contains("error"))
                        {
                            logger.Error(procErrors);
                            throw new Exception("R script failed. Check log file for details.");
                        }
                        else if (procErrors.Length > 1 && procErrors.ToLower().Contains("the input grade-tonnage data file contains less than 20 deposits"))
                        {
                            result.Warnings = "The input grade - tonnage data file contains less than 20 deposits.This might reduce the representativeness of the generated pdfs.";
                        }
                        logger.Trace("Grade Tonnage return value: " + procResult);
                        if (File.Exists(Path.Combine(tonnageProject, "tonnage_summary.txt")))
                        {
                            result.TonnageSummary = File.ReadAllText(Path.Combine(tonnageProject, "tonnage_summary.txt"));
                        }
                        result.TonnagePlot = Path.Combine(tonnageProject, "tonnage_plot.jpeg");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to execute Tonnage tool:" + ex);
                }
                //Write metaDataFile
                try
                {
                    var metaFile = new StringBuilder();
                    metaFile.AppendLine(input.ModelType);
                    var gtProjectRoot = Path.Combine(inputParams.Env.RootPath, "GTModel", input.ExtensionFolder);
                    var metaPath      = Path.Combine(gtProjectRoot, "MetaData.csv");
                    File.WriteAllText(metaPath, input.ToString());
                }
                catch (Exception ex)
                {
                    throw new Exception("Writing MetaData.csv failed: " + ex);
                }
                finally
                {
                }
            }
            if (input.RunGradeTonnage == "True")  //Run grade-tonnage
            {
                try
                {
                    string inputFileDest = Path.Combine(gradeProject, "GT_InputFile.csv");
                    File.Copy(input.CSVPath, Path.Combine(gradeProject, "GT_InputFile.csv"), true);
                    gradeProject = Path.Combine(inputParams.Env.RootPath, "GTModel", input.ExtensionFolder);
                    var info = new ProcessStartInfo();
                    info.FileName = rScriptExecutablePath;
                    string rProjectPath = gradeProject.Replace("\\", "/");
                    info.Arguments = "\"" + rGradeTonnagePath + "\" \"" + input.CSVPath + "\" " + input.Seed + " " + input.PDFType + " " + input.IsTruncated + " " + input.MinDepositCount + " " + input.RandomSampleCount + " \"" + rProjectPath + "\" \"" + workingDir + "\"";

                    info.RedirectStandardInput  = false;
                    info.RedirectStandardOutput = true;
                    info.RedirectStandardError  = true;
                    info.UseShellExecute        = false;
                    info.CreateNoWindow         = true;
                    info.WorkingDirectory       = path + "scripts/";
                    using (var proc = new Process())
                    {
                        proc.StartInfo = info;
                        proc.Start();
                        string procErrors = "";
                        proc.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>  //Use DataReceivedEventHandler to read error data, simply using proc.StandardError would sometimes freeze, due to buffer filling up
                        {
                            if (!String.IsNullOrEmpty(e.Data))
                            {
                                procErrors += (e.Data);
                            }
                        });
                        proc.BeginErrorReadLine();
                        procResult = proc.StandardOutput.ReadToEnd();
                        proc.Close();
                        result.Warnings = "";
                        if (procErrors.Length > 1 && procErrors.ToLower().Contains("error")) //Don't throw exception over warnings or empty error message.
                        {
                            logger.Error(procErrors);
                            throw new Exception(" R script failed, check output for details.");
                        }
                        else if (procErrors.Length > 1 && procErrors.ToLower().Contains("the input grade-tonnage data file contains less than 20 deposits"))
                        {
                            result.Warnings = "The input grade - tonnage data file contains less than 20 deposits.This might reduce the representativeness of the generated pdfs.";
                        }
                        //grade results
                        result.GradeSummary = File.ReadAllText(Path.Combine(gradeProject, "grade_summary.txt"));
                        result.GradePlot    = Path.Combine(gradeProject, "grade_plot.jpeg");
                        //tonnage results
                        if (File.Exists(Path.Combine(gradeProject, "tonnage_summary.txt")))
                        {
                            result.TonnageSummary = File.ReadAllText(Path.Combine(gradeProject, "tonnage_summary.txt"));
                        }
                        result.TonnagePlot = Path.Combine(gradeProject, "tonnage_plot.jpeg");
                        //grade-tonnage results
                        result.GradeTonnagePlot = Path.Combine(gradeProject, "tongrade_plot.jpeg");
                        logger.Trace("Grade tonnage return value: " + procResult);
                    }
                }
                catch (Exception ex)
                {
                    //throw new Exception("Failed to excecute Grade tool: " + ex);
                }
            }

            return(result);
        }