Пример #1
0
    /// <summary>
    /// Writes a sim file for the specified component. Will throw on error.
    /// </summary>
    ///
    public static XmlDocument GetSimDoc(Component Child, Configuration.architecture arch)
    {
        // See if there is an overriding plugins component within scope of the Child passed in.
        // If so then tell PlugIns to load the plugins.
        Component PluginsOverride = ComponentUtility.FindComponentWithinScopeOf(Child, "PlugIns");

        if (PluginsOverride != null)
        {
            PlugIns.LoadAllFromComponent(PluginsOverride);
        }

        XmlDocument SimXML  = new XmlDocument();
        string      simText = WriteSimScript(Child, arch);

        SimXML.LoadXml(simText);
        SortSimContents(SimXML.DocumentElement);

        // Reinstate the original plugins if we overrode them at the start of this method.
        if (PluginsOverride != null)
        {
            PlugIns.LoadAll();
        }

        SimXML.InsertBefore(SimXML.CreateXmlDeclaration("1.0", "UTF-8", null), SimXML.DocumentElement);
        return(SimXML);
    }
        public SimulationRunnerForm(string[] Args)
        {
            InitializeComponent();
            Height = 213;
            Clear();

            this.Args = Args;

            // Load all plugins.
            PlugIns.LoadAll();

            // Position window correctly.
            if (Configuration.Instance.Setting("Top") != "")
            {
                Top  = Convert.ToInt32(Configuration.Instance.Setting("Top"));
                Left = Convert.ToInt32(Configuration.Instance.Setting("Left"));
            }
            if (Configuration.Instance.Setting("Minimised") == "yes")
            {
                WindowState = FormWindowState.Minimized;
            }
            try
            {
                this.PerformanceCounter = new System.Diagnostics.PerformanceCounter();
                this.PerformanceCounter.CategoryName = "Processor";
                this.PerformanceCounter.CounterName  = "% Processor Time";
                this.PerformanceCounter.InstanceName = "_Total";
            }
            catch
            {
                this.PerformanceCounter = null;
            }
        }
Пример #3
0
        public MainUI(string[] cmdArgs)
            : base()
        {
            Closing += OnMainFormClosing;
            Load    += OnMainFormLoad;


            try
            {
                //This call is required by the Windows Form Designer.
                InitializeComponent();

                // Get application name.
                ApplicationName = "";
                if ((cmdArgs.Length != 0))
                {
                    foreach (string Arg in cmdArgs)
                    {
                        if ((string.IsNullOrEmpty(ApplicationName) && (Arg[0] == '/')))
                        {
                            ApplicationName = Arg.Substring(1);
                        }
                        else
                        {
                            Args.Add(Arg);
                        }
                    }
                }
                if (string.IsNullOrEmpty(ApplicationName))
                {
                    ApplicationName = "ApsimUI";
                }
                RunToolStrip.Visible = ApplicationName == "ApsimUI";

                // Create our controller
                Configuration.Instance.ApplicationName = ApplicationName;
                PlugIns.LoadAll();
                SimulationController = new BaseController(this, ApplicationName, true);

                // Display splash screen
                if (!string.IsNullOrEmpty(Configuration.Instance.Setting("SplashScreen")) && (Args.Count == 0))
                {
                    Form SplashForm = (Form)BaseController.CreateClass(Configuration.Instance.Setting("SplashScreen"));
                    if (Configuration.Instance.Setting("SplashScreenButtonVisible").ToLower() == "yes")
                    {
                        SplashForm.ShowDialog();
                    }
                    else
                    {
                        SplashForm.Show();
                        Application.DoEvents();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #4
0
        public void Init()
        {
            PlugIns.LoadAll();

            Simulations = new ApsimFile();
            XmlDocument Doc = new XmlDocument();

            Doc.LoadXml(ApsimFileContents.Replace("$version$", APSIMChangeTool.CurrentVersion.ToString()));
            Simulations.Open(Doc.DocumentElement);
            Assert.IsTrue(Simulations.IsDirty);
            Assert.AreEqual(Simulations.FileName, "Untitled");
        }
Пример #5
0
        public static void Options(BaseController Controller)
        {
            // ---------------------------------------------------------------
            // User wants to modify user interface options.
            // ---------------------------------------------------------------
            OptionsForm Form = new OptionsForm();

            Form.ShowDialog();
            MainUI F = (MainUI)Controller.MainForm;

            PlugIns.LoadAll();
            F.PopulateToolBoxStrip();
            F.SimulationToolStrip.Visible = Configuration.Instance.Setting("HideMainMenu") != "Yes";
        }
Пример #6
0
    /// <summary>
    /// Main program - will return non zero on error.
    /// </summary>
    static int Main(string[] args)
    {
        try
        {
            PlugIns.LoadAll();
            if (args.Length == 0)
            {
                Types.Instance.RefreshProbeInfoForAll();
            }

            else if (args.Length == 1)
            {
                Types.Instance.RefreshProbeInfo(args[0]);
            }

            else
            {
                throw new Exception("Usage: UpdateDotNetProxies [XMLPlugInFileName]");
            }
            return(0);
        }
        catch (TargetInvocationException err)
        {
            string msg = err.InnerException.Message;
            if (args.Length > 0)
            {
                msg += "Component name: " + args[0];
            }
            Console.WriteLine(msg);
            Console.Write(err.StackTrace);
            return(1);
        }

        catch (Exception err)
        {
            string msg = err.Message;
            if (args.Length > 0)
            {
                msg += "Component name: " + args[0];
            }

            Console.WriteLine(msg);
            Console.Write(err.StackTrace);
            return(1);
        }
    }
Пример #7
0
        public static void Run(BaseController Controller)
        {
            // ------------------------------------------------
            // Go looking for simulations to run. Look at the
            // currently selected nodes first and progressively
            // their parents until some simulations are found.
            // ------------------------------------------------
            if (Configuration.Instance.Setting("ReloadPlugInsBeforeRunningAPSIM") == "Yes")
            {
                PlugIns.LoadAll();
            }

            if ((bool)BaseActions.FileSave(Controller))
            {
                Control[] RunPanels = Controller.MainForm.Controls.Find("RunToolStrip", true);
                if (RunPanels.Length == 1)
                {
                    ApsimRunToolStrip.Instance.RunApsim((ToolStrip)RunPanels[0], Controller);
                    //_
                    //Controller.ApsimData, _
                    //Controller.SelectedPaths)
                }
            }
        }
Пример #8
0
    private void ConvertApsimToSim(string ApsimFileName, string SimName, bool dontWriteSimFiles)
    {
        //if the filename is not 'rooted' then assume that the user intends to use the current working directory as the root
        ApsimFileName = ApsimFileName.Replace("\"", "");
        if (!Path.IsPathRooted(ApsimFileName))
        {
            ApsimFileName = Path.Combine(Directory.GetCurrentDirectory(), ApsimFileName);
        }

        //double-check file actually exists before proceeding
        if (!File.Exists(ApsimFileName))
        {
            throw new Exception("Error: Specified APSIM File does not exist!\n\t" + ApsimFileName);
        }

        PlugIns.LoadAll();

        Directory.SetCurrentDirectory(Path.GetDirectoryName(ApsimFileName));

        // convert the specified simulations in the specified apsim file name
        // into a separate .sim file for each.
        ApsimFile.ApsimFile Apsim = new ApsimFile.ApsimFile();
        Apsim.OpenFile(ApsimFileName);

        if (Apsim.FactorComponent == null)
        {
            FindSimsAndConvert(Apsim.RootComponent, SimName, dontWriteSimFiles);
        }
        else
        {
            bool factorialActive = XmlHelper.Value(Apsim.FactorComponent.ContentsAsXML, "active") == "1";
            if (SimName.Contains("@factorial="))
            {
                foreach (string simFileName in Factor.CreateSimFiles(Apsim, new string[] { SimName }, Directory.GetCurrentDirectory()))
                {
                    Console.Error.WriteLine("Written " + simFileName);
                }
            }
            else if (factorialActive)
            {
                List <string> simulationPaths = new List <string>();
                ApsimFile.ApsimFile.ExpandSimsToRun(Apsim.RootComponent, ref simulationPaths);
                foreach (string simXmlPath in simulationPaths)
                {
                    FactorBuilder b             = new FactorBuilder(Apsim.FactorComponent);
                    Component     Simulation    = Apsim.Find(simXmlPath);
                    List <string> allFactorials = Factor.CalcFactorialList(Apsim, simXmlPath);
                    int           totalCount    = allFactorials.Count;
                    Parallel.For(1, totalCount + 1, instanceCount =>
                                 //for (int instanceCount = 0; instanceCount <= totalCount; instanceCount++)
                    {
                        string rootName = Simulation.Name;
                        if (b.SaveExtraInfoInFilename)
                        {
                            rootName += ";" + allFactorials[instanceCount - 1];
                        }
                        else
                        {
                            //write a spacer to list sims in order eg: 01 or 001 or 0001 depending on count
                            string sPad = "";
                            double tot  = Math.Floor(Math.Log10(totalCount) + 1);
                            double file = Math.Floor(Math.Log10(instanceCount) + 1);
                            for (int i = 0; i < (int)(tot - file); ++i)
                            {
                                sPad += "0";
                            }

                            rootName += "_" + sPad + instanceCount;
                        }

                        string fullSimPath = simXmlPath + "@factorial=" + allFactorials[instanceCount - 1];
                        if (dontWriteSimFiles)
                        {
                            Console.WriteLine("Written " + fullSimPath);
                        }
                        else
                        {
                            Factor.CreateSimFiles(Apsim, new string[] { fullSimPath }, Directory.GetCurrentDirectory());
                        }
                    });
                }
            }
            else
            {
                FindSimsAndConvert(Apsim.RootComponent, SimName, dontWriteSimFiles);
            }
        }
    }
Пример #9
0
        // Add individual .apsim files to the job
        public void AddFiles(XmlNode job, List <string> FilesToRun, ProgressNotifier Notifier)
        {
            PlugIns.LoadAll();
            foreach (string FileName in FilesToRun)
            {
                if (Notifier != null)
                {
                    Notifier(0, "Reading " + FileName);
                }
                XmlDocument Doc = new XmlDocument();
                Doc.Load(FileName);

                XmlNode apsimFileNode = job.AppendChild(job.OwnerDocument.CreateElement("apsimfile"));
                XmlHelper.SetAttribute(apsimFileNode, "source", FileName);

                List <string> globalInputs = new List <string>();
                foreach (XmlNode pluginNode in Doc.DocumentElement.OwnerDocument.SelectNodes("//PlugIns/PlugIn[@enabled='yes']"))
                {
                    if (pluginNode.InnerText.IndexOf("%apsim%") < 0)
                    {
                        if (!File.Exists(pluginNode.InnerText))
                        {
                            throw new Exception("Plugin file '" + pluginNode.InnerText + "' doesnt exist - cant send it to the cluster.");
                        }
                        File.Copy(pluginNode.InnerText, Path.Combine(WorkingFolder, Path.GetFileName(pluginNode.InnerText)));
                        pluginNode.InnerText = Path.GetFileName(pluginNode.InnerText);
                        if (!globalInputs.Contains(pluginNode.InnerText))
                        {
                            globalInputs.Add(pluginNode.InnerText);
                        }
                    }
                }

                List <XmlNode> simulations = new List <XmlNode>();
                XmlHelper.FindAllRecursivelyByType(Doc.DocumentElement, "simulation", ref simulations);
                foreach (XmlNode simulation in simulations)
                {
                    if (XmlHelper.Attribute(simulation, "enabled") != "no")
                    {
                        List <string> simsToRun     = new List <string>();
                        XmlNode       factorialNode = XmlHelper.FindByType(Doc.DocumentElement, "factorial");
                        if (factorialNode == null)
                        {
                            simsToRun.Add(XmlHelper.FullPath(simulation));
                        }
                        else
                        {
                            ApsimFile F = new ApsimFile();
                            F.OpenFile(FileName);
                            simsToRun = Factor.CreateSimulationNames(F, new string [] { XmlHelper.FullPath(simulation) }, Notifier);
                        }
                        foreach (string simToRun in simsToRun)
                        {
                            XmlNode simulationNode = apsimFileNode.AppendChild(apsimFileNode.OwnerDocument.CreateElement("simulation"));
                            XmlHelper.SetAttribute(simulationNode, "name", simToRun);
                            XmlHelper.SetAttribute(simulationNode, "source", XmlHelper.Attribute(apsimFileNode, "source"));

                            foreach (var g in globalInputs)
                            {
                                XmlNode input = simulationNode.AppendChild(simulationNode.OwnerDocument.CreateElement("input"));
                                XmlHelper.SetAttribute(input, "source", g);
                                XmlHelper.SetAttribute(input, "name", g);
                            }

                            var filenames = new List <XmlNode>();
                            filenames = simulation.SelectNodes(".//filename").Cast <XmlNode>().ToList();
                            if (factorialNode != null)
                            {
                                // Send all input files to each job
                                foreach (XmlNode n in factorialNode.SelectNodes(".//filename"))
                                {
                                    if (n.InnerText.IndexOf(",") > 0)
                                    {
                                        foreach (string f in n.InnerText.Split(','))
                                        {
                                            XmlNode d = n.CloneNode(false);
                                            d.InnerText = f;
                                            filenames.Add(d);
                                        }
                                    }

                                    else
                                    {
                                        filenames.Add(n);
                                    }
                                }
                            }
                            foreach (XmlNode linkedNode in simulation.SelectNodes(".//*[string(@shortcut)]"))
                            {
                                XmlNode target = XmlHelper.Find(linkedNode,
                                                                linkedNode.Attributes["shortcut"].Value);
                                if (target != null)
                                {
                                    foreach (XmlNode targetFilename in target.SelectNodes(".//filename"))
                                    {
                                        filenames.Add(targetFilename);
                                    }
                                }
                            }

                            foreach (XmlNode node in filenames)
                            {
                                if (XmlHelper.Attribute(node, "output") != "yes" &&
                                    XmlHelper.Attribute(node.ParentNode, "enabled") != "no")
                                {
                                    string  src   = Configuration.RemoveMacros(node.InnerText);
                                    string  dest  = Path.GetFileName(src);
                                    XmlNode input = simulationNode.AppendChild(simulationNode.OwnerDocument.CreateElement("input"));

                                    if (!File.Exists(src) && !File.Exists(Path.Combine(WorkingFolder, dest)))
                                    {
                                        // When this is called by web service then can't assume src is relative to working
                                        // directory. Instead see if the file is relative to where the main file file.
                                        src = Path.Combine(Path.GetDirectoryName(FileName), Path.GetFileName(src));
                                        if (!File.Exists(src))
                                        {
                                            throw new Exception("File '" + src + "' doesnt exist - cant send it to the cluster.");
                                        }
                                    }

                                    XmlHelper.SetAttribute(input, "source", src);
                                    XmlHelper.SetAttribute(input, "name", dest);
                                    node.InnerText = dest;
                                    if (!File.Exists(Path.Combine(WorkingFolder, dest)))
                                    {
                                        File.Copy(src, Path.Combine(WorkingFolder, dest));
                                    }
                                }
                                else
                                {
                                    XmlNode output = simulationNode.AppendChild(simulationNode.OwnerDocument.CreateElement("output"));
                                    XmlHelper.SetAttribute(output, "name", node.InnerText);
                                }
                            }
                        }
                    }
                }
                Doc.Save(Path.Combine(WorkingFolder, Path.GetFileName(FileName)));
            }
        }
Пример #10
0
        /// <summary>
        /// Create, and add to ApsimJobs, a series of jobs to run APSIM for each simulation.
        /// </summary>
        private void CreateJobsFromAPSIM(string FileName, string[] SimulationPaths, ref List <IJob> jobs, bool doAllFactors)
        {
            // Load all plugin (.xml) files.
            if (Types.Instance.TypeNames.Length == 0)
            {
                PlugIns.LoadAll();
            }

            ApsimFile AFile = new ApsimFile(FileName);

            // Look for factorials.
            if (FillProjectWithSpecifiedFactorialJobs(AFile, FileName, SimulationPaths, ref jobs) > 0)
            {
                return;
            }
            else if (doAllFactors && FillProjectWithAllFactorialJobs(AFile, FileName, ref jobs) > 0)
            {
                return;
            }

            // No factorials.
            if (SimulationPaths == null || SimulationPaths.Length == 0)
            {
                // No simulation specified. Run everything.
                string  ApsimToSimExe = Path.Combine(Configuration.ApsimBinDirectory(), "ApsimToSim.exe");
                Process ApsimToSim    = new Process();
                ApsimToSim.StartInfo.FileName         = ApsimToSimExe;
                ApsimToSim.StartInfo.Arguments        = StringManip.DQuote(Path.GetFileName(FileName));
                ApsimToSim.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
                ApsimToSim.StartInfo.CreateNoWindow   = true;
                ApsimToSim.StartInfo.UseShellExecute  = false;
                ApsimToSim.Start();
                ApsimToSim.WaitForExit();

                List <String> AllPaths = new List <String>();
                ApsimFile.ExpandSimsToRun(AFile.RootComponent, ref AllPaths);
                for (int i = 0; i < AllPaths.Count; i++)
                {
                    int lastSlash = AllPaths[i].LastIndexOf('/');
                    if (lastSlash != -1)
                    {
                        AllPaths[i] = Path.Combine(Directory.GetCurrentDirectory(), AllPaths[i].Substring(lastSlash + 1)) + ".sim";
                    }
                }

                // Create a series of jobs for each simulation in the .con file.
                foreach (string SimFileName in AllPaths)
                {
                    Job J = CreateJob(SimFileName, SimFileName.Replace(".sim", ".sum"));
                    jobs.Add(J);
                    J = CleanupJob(SimFileName, J.Name);
                    jobs.Add(J);
                }
            }
            else if (SimulationPaths.Length == 1)
            {
                string SumFileName  = SimulationPaths[0];
                int    PosLastSlash = SumFileName.LastIndexOf('/');
                if (PosLastSlash != -1)
                {
                    SumFileName = SumFileName.Substring(PosLastSlash + 1);
                }
                SumFileName += ".sum";
                SumFileName  = Path.Combine(Path.GetDirectoryName(FileName), SumFileName);

                Job J = CreateJob(FileName, SumFileName, SimulationPaths[0]);
                J.IgnoreErrors = false;
                jobs.Add(J);
            }
            else if (SimulationPaths.Length > 1)
            {
                // For each path, create a simfile, and a job in our target.
                foreach (string SimulationPath in SimulationPaths)
                {
                    string simName      = SimulationPath;
                    int    PosLastSlash = simName.LastIndexOf('/');
                    if (PosLastSlash != -1)
                    {
                        simName = simName.Substring(PosLastSlash + 1);
                    }
                    string simFileName = Path.Combine(Path.GetDirectoryName(FileName), simName + ".sim");
                    try
                    {
                        Job J = CreateJob(FileName,
                                          Path.Combine(Path.GetDirectoryName(FileName), simName + ".sum"),
                                          SimulationPath);
                        J.IgnoreErrors = false;
                        jobs.Add(J);
                        J = CleanupJob(simFileName, J.Name);
                        jobs.Add(J);
                    }
                    catch (Exception err)
                    {
                        string sumFileName = Path.ChangeExtension(simFileName, ".sum");
                        WriteErrorToSummaryFile(sumFileName, err.Message);
                    }
                }
            }
        }