Ejemplo n.º 1
0
        public void ImporterTests_SurfaceOMImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <surfaceom name=\"SurfaceOrganicMatter\">" +
                "      <PoolName type=\"text\" description=\"Organic Matter pool name\">wheat</PoolName >" +
                "      <type type=\"list\" listvalues=\"TropicalPasture,barley,base_type,broccoli,camaldulensis,canola,centro,chickpea,chikenmanure_base,cm,cmA,cmB,constants,cotton,cowpea,danthonia,fababean,fieldpea,fym,gbean,globulus,goatmanure,grandis,grass,horsegram,inert,lablab,lentil,lucerne,lupin,maize,manB,manure,medic,millet,mucuna,nativepasture,navybean,oats,orobanche,peanut,pigeonpea,potato,rice,sorghum,soybean,stylo,sugar,sunflower,sweetcorn,sweetsorghum,tillage,tithonia,vetch,weed,wheat\" description=\"Organic Matter type\">wheat</type>" +
                "      <mass type=\"text\" description=\"Initial surface residue (kg/ha)\">1000</mass>" +
                "      <cnr type=\"text\" description=\"C:N ratio of initial residue\">80</cnr>" +
                "      <standing_fraction type=\"text\" description=\"Fraction of residue standing\">0</standing_fraction>" +
                "    </surfaceom>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            var som = sims.Children[0].Children[0] as SurfaceOrganicMatter;

            Assert.IsNotNull(som);
            Assert.AreEqual(som.InitialResidueMass, 1000);
            Assert.AreEqual(som.InitialCNR, 80);
            Assert.AreEqual(som.InitialResidueName, "wheat");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Event handler invoked when user clicks on 'Import'
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">Event arguments</param>
        private void OnImport(object sender, EventArgs e)
        {
            string fileName = this.view.AskUserForOpenFileName("*.apsim|*.apsim");

            APSIMImporter importer = new APSIMImporter();

            try
            {
                this.view.ShowWaitCursor(true);
                try
                {
                    importer.ProcessFile(fileName);

                    string newFileName      = Path.ChangeExtension(fileName, ".apsimx");
                    bool   onLeftTabControl = this.view.IsControlOnLeft(sender);
                    this.OpenApsimXFileInTab(newFileName, onLeftTabControl);
                }
                finally
                {
                    this.view.ShowWaitCursor(false);
                }
            }
            catch (Exception exp)
            {
                throw new Exception("Failed import: " + exp.Message);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Event handler invoked when user clicks on 'Import'
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">Event arguments</param>
        private void OnImport(object sender, EventArgs e)
        {
            string fileName = this.view.AskUserForFileName(string.Empty, "*.apsim|*.apsim");

            APSIMImporter importer = new APSIMImporter();

            try
            {
                this.view.WaitCursor = true;
                try
                {
                    importer.ProcessFile(fileName);

                    string newFileName = Path.ChangeExtension(fileName, ".apsimx");
                    this.OpenApsimXFileInTab(newFileName);
                }
                finally
                {
                    this.view.WaitCursor = false;
                }
            }
            catch (Exception exp)
            {
                throw new Exception("Failed import: " + exp.Message);
            }
        }
Ejemplo n.º 4
0
        public void ImporterTests_Manager2Imports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <manager2 name=\"Economics\">" +
                "      <ui>" +
                "        <category type=\"category\" description=\"Dummy module\" />" +
                "        <labourCost type=\"text\" description=\"Cost of labour($/ hr)\">0.0</labourCost>" +
                "      </ui>" +
                "      <text>" +
                "    using System;" +
                "    using ModelFramework;" +
                "    public class Script" +
                "    {" +
                "       [EventHandler] public void OnBuyCows() {Console.WriteLine(\"Buying a cow\");}" +
                "       [EventHandler] public void OnSellCows() {Console.WriteLine(\"Selling a cow\");}" +
                "       [EventHandler] public void OnBuyShoats() {Console.WriteLine(\"Buying a goat\");}" +
                "       [EventHandler] public void OnSellShoats() {Console.WriteLine(\"Selling a goat\");}" +
                "    }   " +
                "      </text>" +
                "    </manager2>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            var m = sims.Children[0].Children[0] as Manager;

            Assert.IsNotNull(m);
            Assert.IsTrue(m.Code != string.Empty);
            Assert.IsNotNull(m.Code);
            Assert.AreEqual(m.Children.Count, 1);
        }
Ejemplo n.º 5
0
        public void ImporterTests_MicroMetImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <micromet name=\"MicroMet\">" +
                "      <soilalbedo name=\"soilalbedo\">0.23</soilalbedo>" +
                "      <a_interception name=\"a_interception\">0.1</a_interception>" +
                "      <b_interception name=\"b_interception\">0.2</b_interception>" +
                "      <c_interception name=\"c_interception\">0.3</c_interception>" +
                "      <d_interception name=\"d_interception\">0.4</d_interception>" +
                "    </micromet>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            var m = sims.Children[0].Children[0] as MicroClimate;

            Assert.IsNotNull(m);
            Assert.AreEqual(m.soil_albedo, 0.23);
            Assert.AreEqual(m.a_interception, 0.1);
            Assert.AreEqual(m.b_interception, 0.2);
            Assert.AreEqual(m.c_interception, 0.3);
            Assert.AreEqual(m.d_interception, 0.4);
        }
Ejemplo n.º 6
0
        public void ImporterTests_ManagerImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <manager name=\"Sowing fertiliser\">" +
                "      <ui>" +
                "        <category description=\"When should fertiliser be applied\" type=\"category\" />" +
                "        <modulename type=\"modulename\" description=\"On which module should the event come from : \">wheat</modulename>" +
                "        <eventname type=\"text\" description=\"On which event should fertiliser be applied : \">sowing</eventname>" +
                "        <category description=\"Fertiliser application details\" type=\"category\" />" +
                "        <fertmodule type=\"modulename\" description=\"Module used to apply the fertiliser : \">fertiliser</fertmodule>" +
                "        <fert_amount_sow type=\"text\" description=\"Amount of starter fertiliser at sowing (kg/ha) : \">150</fert_amount_sow>" +
                "        <fert_type_sow type=\"list\" listvalues=\"NO3_N, NH4_N, NH4NO3, urea_N, urea_no3, urea, nh4so4_n, rock_p, banded_p, broadcast_p\" description=\"Sowing fertiliser type : \">urea_N</fert_type_sow>" +
                "      </ui>" +
                "      <script name=\"[modulename].[eventname]\">" +
                "        <text>" +
                "    [fertmodule] apply amount = [fert_amount_sow] (kg/ha), depth = 50 (mm), type = [fert_type_sow]" +
                "        </text>" +
                "        <event>[modulename].[eventname]</event>" +
                "      </script>" +
                "    </manager>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            var m = sims.Children[0].Children[0] as Manager;

            Assert.IsNotNull(m);
            Assert.IsTrue(m.Code != string.Empty);
            Assert.IsNotNull(m.Code);
            Assert.AreEqual(m.Children.Count, 1);
        }
Ejemplo n.º 7
0
        public void ImporterTests_SoilImports()
        {
            string oldXml = ReflectionUtilities.GetResourceAsString("UnitTests.ImporterTestsSoilImports.xml");

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            Soil s = sims.Children[0].Children[0] as Soil;

            Assert.AreEqual(s.Name, "Soil");

            InitialWater initWater = s.Children[0] as InitialWater;

            Assert.AreEqual(initWater.FractionFull, 0.5);
            Assert.AreEqual(initWater.PercentMethod, InitialWater.PercentMethodEnum.FilledFromTop);

            Water w = s.Children[1] as Water;

            Assert.AreEqual(w.Thickness, new double[] { 150, 150, 300, 300 });
            Assert.AreEqual(w.BD, new double[] { 1.02, 1.03, 1.02, 1.02 });
            Assert.AreEqual(w.LL15, new double[] { 0.29, 0.29, 0.29, 0.29 });

            SoilWater sw = s.Children[2] as SoilWater;

            Assert.AreEqual(sw.Thickness, new double[] { 150, 150, 300, 300 });
            Assert.AreEqual(sw.SWCON, new double[] { 0.3, 0.3, 0.3, 0.3 });
            Assert.AreEqual(sw.SummerCona, 3.5);
            Assert.AreEqual(sw.SummerU, 6);
            Assert.AreEqual(sw.WinterCona, 2);
            Assert.AreEqual(sw.WinterU, 2);

            Assert.IsTrue(s.Children[3] is SoilNitrogen);

            SoilOrganicMatter som = s.Children[4] as SoilOrganicMatter;

            Assert.AreEqual(som.Thickness, new double[] { 150, 150, 300, 300 });
            Assert.AreEqual(som.OC, new double[] { 1.04, 0.89, 0.89, 0.89 });
            Assert.AreEqual(som.FBiom, new double[] { 0.025, 0.02, 0.015, 0.01 });

            Analysis a = s.Children[5] as Analysis;

            Assert.AreEqual(a.Thickness, new double[] { 150, 150, 300, 300 });
            Assert.AreEqual(a.EC, new double[] { 0.2, 0.25, 0.31, 0.40 });
            Assert.AreEqual(a.PH, new double[] { 8.4, 8.8, 9.0, 9.2 });

            Sample sam = s.Children[6] as Sample;

            Assert.AreEqual(sam.Thickness, new double[] { 150, 150, 300 });
            Assert.AreEqual(sam.NO3, new double[] { 6.5, 2.1, 2.1 });
            Assert.AreEqual(sam.NH4, new double[] { 0.5, 0.1, 0.1 });

            SoilCrop crop = s.Children[1].Children[0] as SoilCrop;

            Assert.AreEqual(crop.Thickness, new double[] { 150, 150, 300, 300 });
            Assert.AreEqual(crop.LL, new double[] { 0.29, 0.29, 0.32, 0.38 });
            Assert.AreEqual(crop.KL, new double[] { 0.1, 0.1, 0.08, 0.06 });
            Assert.AreEqual(crop.XF, new double[] { 1, 1, 1, 1 });
        }
Ejemplo n.º 8
0
        public void EnsureOldAPSIMFileLoads()
        {
            string oldXml = ReflectionUtilities.GetResourceAsString("UnitTests.ImporterTestsOldAPSIM.xml");

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            Assert.IsNotNull(sims);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Runs the importer on a file, then opens it in a new tab.
 /// </summary>
 /// <param name="fileName">Path to the file to be imported.</param>
 /// <param name="leftTab">Should the file be opened in the left tabset?</param>
 public void Import(string fileName)
 {
     try
     {
         APSIMImporter importer = new APSIMImporter();
         importer.ProcessFile(fileName);
     }
     catch (Exception err)
     {
         ShowError(err);
     }
 }
Ejemplo n.º 10
0
        public void ImportOldAPSIM()
        {
            // test the importing of an example simulation from APSIM 7.6
            APSIMImporter importer = new APSIMImporter();

            importer.ProcessFile("Continuous_Wheat.apsim");

            Simulations testrunSimulations = Simulations.Read("Continuous_Wheat.apsimx");

            Assert.IsNotNull(Apsim.Find(testrunSimulations, "wheat"));
            Assert.IsNotNull(Apsim.Find(testrunSimulations, "clock"));
            Assert.IsNotNull(Apsim.Find(testrunSimulations, "SoilNitrogen"));
            Assert.IsNotNull(Apsim.Find(testrunSimulations, "SoilWater"));
        }
Ejemplo n.º 11
0
        public void ImporterTests_WheatImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <wheat />" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            var f = sims.Children[0].Children[0] as Plant;

            Assert.IsNotNull(f);
        }
Ejemplo n.º 12
0
        public void ImporterTests_AreaImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <area name=\"paddock\">" +
                "      <paddock_area>100</paddock_area>" +
                "    </area>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            Zone z = sims.Children[0].Children[0] as Zone;

            Assert.AreEqual(z.Area, 100);
        }
Ejemplo n.º 13
0
        public void ImporterTests_MetFileImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <metfile name=\"met\">" +
                "      <filename name=\"filename\" input=\"yes\">%apsim%/Examples/MetFiles/Goond.met</filename>" +
                "    </metfile>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            var w = sims.Children[0].Children[0] as Models.Weather;

            Assert.AreEqual(w.FileName, @"\Examples\MetFiles\Goond.met");
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            APSIMImporter importer  = new APSIMImporter();
            string        apsimPath = "";

            if ((args.Length > 0) && (args[0].Length > 0))
            {
                for (int i = 0; i < args.Length; i++)
                {
                    String filename = args[i];

                    if (filename[0] == '-')     // if this is a parameter
                    {
                        if (filename[1] == 'a') // apsim path macro replacement
                        {
                            apsimPath = filename.Substring(2, filename.Length - 2);
                        }
                    }
                    else
                    {
                        // get the file attributes for file or directory
                        FileAttributes attr = File.GetAttributes(filename);

                        importer.ApsimPath = apsimPath;
                        //detect whether its a directory or file
                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            importer.ProcessDir(filename);
                        }
                        else
                        {
                            importer.ProcessFile(filename);
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("Useage: Importer [options] file.apsim [file2.apsim ....]\n    Or: Importer [options] directoryname [dir2 ...]\n");
                Console.Write("Where options are\n\t-a to set the base apsim path. e.g. -aC:\\apsim \n");
            }
        }
Ejemplo n.º 15
0
        public void ImporterTests_OutputFileImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <outputfile>" +
                "      <filename output=\"yes\">Continuous Wheat.out</filename>" +
                "      <title>Continuous Wheat</title>" +
                "      <variables name=\"Variables\">" +
                "        <variable array=\" ?\" description=\"Date (dd/mm/yyyy)\">dd/mm/yyyy as Date</variable>" +
                "        <variable array=\" ?\" description=\"Biomass\">biomass</variable>" +
                "        <variable array=\" ?\" description=\"Yield\">yield</variable>" +
                "        <variable array=\" ?\" description=\"grain protein content\">grain_protein</variable>" +
                "        <variable array=\" ?\" description=\"Size of each grain\">grain_size</variable>" +
                "        <variable array=\" ?\" description=\"Extractable Soil Water (mm)\">esw</variable>" +
                "      </variables>" +
                "      <events name=\"Reporting Frequency\">" +
                "        <event description=\"\">harvesting</event>" +
                "      </events>" +
                "    </outputfile>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            var r = sims.Children[0].Children[0] as Models.Report.Report;

            Assert.IsNotNull(r);
            Assert.AreEqual(r.VariableNames[0], "[Clock].Today");
            Assert.AreEqual(r.VariableNames[1], "biomass");
            Assert.AreEqual(r.VariableNames[2], "yield");
            Assert.AreEqual(r.VariableNames[3], "grain_protein");
            Assert.AreEqual(r.VariableNames[4], "grain_size");
            Assert.AreEqual(r.VariableNames[5], "esw");

            Assert.AreEqual(r.EventNames[0], "[Clock].DoReport");
        }
Ejemplo n.º 16
0
        public void ImporterTests_ClockImports()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <clock>" +
                "      <start_date type=\"date\" description=\"Enter the start date of the simulation\">01/01/1940</start_date>" +
                "      <end_date type=\"date\" description=\"Enter the end date of the simulation\">31/12/1950</end_date> " +
                "    </clock>" +
                "  </simulation>" +
                "</folder>";

            APSIMImporter importer = new APSIMImporter();
            Simulations   sims     = importer.CreateSimulationsFromXml(oldXml);

            Assert.IsTrue(sims.Children[0] is Simulation);
            Assert.IsTrue(sims.Children[1] is DataStore);

            Clock c = sims.Children[0].Children[0] as Clock;

            Assert.AreEqual(c.StartDate, new DateTime(1940, 1, 1));
            Assert.AreEqual(c.EndDate, new DateTime(1950, 12, 31));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Generates a new ApsimX Soil object from an Xml soil description in "classic" APSIM format
        /// </summary>
        /// <param name="soil">The xml "soil" node holding the description</param>
        /// <returns>True if successful</returns>
        private Soil SoilFromApsoil(XmlNode soil)
        {
            Soil soilObj = null;

            try
            {
                XmlDocument   soilDoc  = new XmlDocument();
                XmlNode       rootNode = soilDoc.CreateNode("element", "root", "");
                APSIMImporter importer = new APSIMImporter();
                XmlNode       newNode  = null;
                newNode = importer.ImportSoil(soil, rootNode, newNode);

                List <Exception> errors = null;
                soilObj = (Soil)FileFormat.ReadFromString <Soil>(newNode.OuterXml, out errors);

                // Looks like we also need a soil temperature model as well....
                Structure.Add(new CERESSoilTemperature(), soilObj);
                soilObj.OnCreated();
            }
            catch (Exception e) // Needs better error handling. We should inform the user of any problems.
            {
            }
            return(soilObj);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Pastes the contents of the clipboard.
        /// </summary>
        /// <param name="xml">The XML document text</param>
        /// <param name="parentPath">Path to the parent</param>
        public void Add(string xml, string parentPath)
        {
            try
            {
                XmlDocument document = new XmlDocument();
                try
                {
                    document.LoadXml(xml);
                }
                catch (XmlException)
                {
                    MainPresenter.ShowMessage("Invalid XML. Are you sure you're trying to paste an APSIM model?", Simulation.ErrorLevel.Error);
                }

                object newModel = XmlUtilities.Deserialise(document.DocumentElement, this.ApsimXFile.GetType().Assembly);

                // See if the presenter is happy with this model being added.
                Model         parentModel   = Apsim.Get(this.ApsimXFile, parentPath) as Model;
                AllowDropArgs allowDropArgs = new AllowDropArgs();
                allowDropArgs.NodePath   = parentPath;
                allowDropArgs.DragObject = new DragObject()
                {
                    NodePath  = null,
                    ModelType = newModel.GetType(),
                    Xml       = this.GetClipboardText()
                };

                this.OnAllowDrop(null, allowDropArgs);

                // If it is happy then issue an AddModelCommand.
                if (allowDropArgs.Allow)
                {
                    // If the model xml is a soil object then try and convert from old
                    // APSIM format to new.
                    if (document.DocumentElement.Name == "Soil" && XmlUtilities.Attribute(document.DocumentElement, "Name") != string.Empty)
                    {
                        XmlDocument newDoc = new XmlDocument();
                        newDoc.AppendChild(newDoc.CreateElement("D"));
                        APSIMImporter importer = new APSIMImporter();
                        importer.ImportSoil(document.DocumentElement, newDoc.DocumentElement, newDoc.DocumentElement);
                        XmlNode soilNode = XmlUtilities.FindByType(newDoc.DocumentElement, "Soil");
                        if (soilNode != null &&
                            XmlUtilities.FindByType(soilNode, "Sample") == null &&
                            XmlUtilities.FindByType(soilNode, "InitialWater") == null)
                        {
                            // Add in an initial water and initial conditions models.
                            XmlNode initialWater = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("InitialWater"));
                            XmlUtilities.SetValue(initialWater, "Name", "Initial water");
                            XmlUtilities.SetValue(initialWater, "PercentMethod", "FilledFromTop");
                            XmlUtilities.SetValue(initialWater, "FractionFull", "1");
                            XmlUtilities.SetValue(initialWater, "DepthWetSoil", "NaN");
                            XmlNode initialConditions = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("Sample"));
                            XmlUtilities.SetValue(initialConditions, "Name", "Initial conditions");
                            XmlUtilities.SetValue(initialConditions, "Thickness/double", "1800");
                            XmlUtilities.SetValue(initialConditions, "NO3/double", "10");
                            XmlUtilities.SetValue(initialConditions, "NH4/double", "1");
                            XmlUtilities.SetValue(initialConditions, "NO3Units", "kgha");
                            XmlUtilities.SetValue(initialConditions, "NH4Units", "kgha");
                            XmlUtilities.SetValue(initialConditions, "SWUnits", "Volumetric");
                        }

                        document.LoadXml(newDoc.DocumentElement.InnerXml);
                    }

                    IModel child = XmlUtilities.Deserialise(document.DocumentElement, this.ApsimXFile.GetType().Assembly) as IModel;

                    AddModelCommand command = new AddModelCommand(parentModel, document.DocumentElement, this.GetNodeDescription(child), this.view);
                    this.CommandHistory.Add(command, true);
                }
            }
            catch (Exception exception)
            {
                this.MainPresenter.ShowMessage(exception.Message, Simulation.ErrorLevel.Error);
            }
        }