/// <summary>Rebuild the script model and return error message if script cannot be compiled.</summary> public void RebuildScriptModel() { if (Enabled && afterCreation && !string.IsNullOrEmpty(Code)) { // If the script child model exists. Then get its parameter values. if (Children.Count != 0) { GetParametersFromScriptModel(); } var results = Compiler().Compile(Code, this); if (results.ErrorMessages == null) { if (Children.Count != 0) { Children.Clear(); } var newModel = results.Instance as IModel; if (newModel != null) { newModel.IsHidden = true; Structure.Add(newModel, this); } } else { throw new Exception($"Errors found in manager model {Name}{Environment.NewLine}{results.ErrorMessages}"); } SetParametersInScriptModel(); } }
/// <summary>Perform the command</summary> /// <param name="commandHistory">The command history.</param> public void Do(CommandHistory commandHistory) { try { parent = presenter.ApsimXFile.FindByPath(parentPath)?.Value as IModel; if (parent == null) { throw new Exception("Cannot find model " + parentPath); } if (xmlOrJson != null) { modelToAdd = Structure.Add(xmlOrJson, parent); } else { modelToAdd = Structure.Add(child, parent); } presenter.AddChildToTree(parentPath, modelToAdd); modelAdded = true; } catch (Exception err) { presenter.MainPresenter.ShowError(err); modelAdded = false; } }
/// <summary>Perform the command</summary> /// <param name="commandHistory">The command history.</param> public void Do(CommandHistory commandHistory) { try { parent = Apsim.Get(presenter.ApsimXFile, parentPath) as IModel; if (parent == null) { throw new Exception("Cannot find model " + parentPath); } modelToAdd = child; if (modelToAdd is Simulations && modelToAdd.Children.Count == 1) { modelToAdd = modelToAdd.Children[0]; } Structure.Add(modelToAdd, parent); var nodeDescription = presenter.GetNodeDescription(modelToAdd); view.Tree.AddChild(Apsim.FullPath(parent), nodeDescription); modelAdded = true; } catch (Exception err) { presenter.MainPresenter.ShowError(err); modelAdded = false; } }
/// <summary>Perform the command</summary> /// <param name="commandHistory">The command history.</param> public void Do(CommandHistory commandHistory) { try { parent = Apsim.Get(presenter.ApsimXFile, parentPath) as IModel; if (parent == null) { throw new Exception("Cannot find model " + parentPath); } IModel newModel = FileFormat.ReadFromString <IModel>(childString, out List <Exception> exceptions); if (exceptions != null && exceptions.Count > 0) { presenter.MainPresenter.ShowError(exceptions); return; } modelToAdd = newModel; if (modelToAdd is Simulations && modelToAdd.Children.Count == 1) { modelToAdd = modelToAdd.Children[0]; } Structure.Add(modelToAdd, parent); var nodeDescription = presenter.GetNodeDescription(modelToAdd); view.Tree.AddChild(Apsim.FullPath(parent), nodeDescription); modelAdded = true; } catch (Exception err) { presenter.MainPresenter.ShowError(err); modelAdded = false; } }
public void OpenTestFileInTab() { // Open a simple .apsimx file in the GUI. explorerPresenter = UITestUtilities.OpenResourceFileInTab(Assembly.GetExecutingAssembly(), "UnitTests.ApsimNG.Resources.SampleFiles.BasicSimulation.apsimx"); // Create a table model. model = new DualTableModel(); model.Name = "Table"; // Create a datatable and assign it to the model. DataTable table = new DataTable(); table.Columns.Add("test_col", typeof(string)); table.Rows.Add("test"); model.Tables = new List <DataTable>() { table, table.Copy() }; // Add the model to the .apsimx file. Structure.Add(model, explorerPresenter.ApsimXFile); explorerPresenter.Refresh(); // Select the table model in the GUI. explorerPresenter.SelectNode(model); GtkUtilities.WaitForGtkEvents(); }
private static void Main() { var structure = new Structure(); structure.Add(new Person { Name = "TestPerson", Number = "123456" }); structure.Add(new Company { Name = "TestCompany", Number = "09876", RegNumber = "123098" }); structure.Add(new Company { Name = "TestCompany2", Number = "1209876", RegNumber = "12123098" }); structure.Accept(new DictionaryVisitor()); structure.Accept(new ListVisitor()); }
public void Initialise() { Simulations basicFile = Utilities.GetRunnableSim(); IModel simulation = Apsim.Find(basicFile, typeof(Simulation)); IModel paddock = Apsim.Find(basicFile, typeof(Zone)); // Add a weather component. Models.Weather weather = new Models.Weather(); weather.Name = "Weather"; weather.FileName = "asdf.met"; Structure.Add(weather, simulation); // Add a second weather component. Models.Weather weather2 = new Models.Weather(); weather2.FileName = "asdf.met"; weather2.Name = "Weather2"; Structure.Add(weather2, simulation); // Add a third weather component. Models.Weather weather3 = new Models.Weather(); weather3.FileName = "asdf.met"; weather3.Name = "Weather3"; Structure.Add(weather3, simulation); // Add a third weather component. Models.Weather weather4 = new Models.Weather(); weather4.FileName = "asdf.met"; weather4.Name = "Weather4"; Structure.Add(weather4, simulation); // Add a report. Models.Report report = new Models.Report(); report.Name = "Report"; Structure.Add(report, paddock); basicFile.Write(basicFile.FileName); fileName = basicFile.FileName; // Create a new .apsimx file containing two weather nodes. Simulations test = Utilities.GetRunnableSim(); IModel sim = Apsim.Find(test, typeof(Simulation)); Models.Weather w1 = new Models.Weather(); w1.FileName = "w1.met"; w1.Name = "w1"; Structure.Add(w1, sim); Models.Weather w2 = new Models.Weather(); w2.Name = "w2"; w2.FileName = "w2.met"; Structure.Add(w2, sim); extFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".apsimx"); test.Write(extFile); }
private void OnStartOfSimulation(object sender, EventArgs e) { // Create a new nutrient patch. var newPatch = new NutrientPatch(soilPhysical.Thickness, this); newPatch.CreationDate = clock.Today; newPatch.Name = "base"; patches.Add(newPatch); Structure.Add(newPatch.Nutrient, this); }
public void AddNodeWithMissingLink() { Simulations sims = Utilities.GetRunnableSim(); Zone sim = sims.FindDescendant <Zone>(); Structure.Add(new Model0(), sim); Runner runner = new Runner(sims); List <Exception> errors = runner.Run(); Assert.AreEqual(1, errors.Count); }
private void AddStructure(TreeReport report, int pageSize, bool calculateExactSizes) { Structure.Add(report); var allocatedSpaceInBytes = report.PageCount * pageSize; AllocatedSpaceInBytes += allocatedSpaceInBytes; if (calculateExactSizes) { UsedSizeInBytes += (long)(allocatedSpaceInBytes * report.Density); } }
public void AddSimulationsNode() { // Get official wheat model. string json = ReflectionUtilities.GetResourceAsString(typeof(IModel).Assembly, "Models.Resources.Wheat.json"); Simulations file = new Simulations(); Structure.Add(json, file); // Should have 1 child, of type replacements. Assert.NotNull(file.Children); Assert.AreEqual(1, file.Children.Count); Assert.AreEqual(typeof(Models.PMF.Plant), file.Children[0].GetType()); }
private void AddStructure(TreeReport report, int pageSize, bool includeDetails) { Structure.Add(report); var allocatedSpaceInBytes = report.PageCount * pageSize; AllocatedSpaceInBytes += allocatedSpaceInBytes; if (includeDetails) { UsedSizeInBytes += (long)(allocatedSpaceInBytes * report.Density); } }
/// <summary>Perform the command</summary> /// <param name="commandHistory">The command history.</param> public void Do(CommandHistory commandHistory) { if (xmlOrJson != null) { modelToAdd = Structure.Add(xmlOrJson, parent); } else { modelToAdd = Structure.Add(child, parent); } modelAdded = true; }
public void StructureTests_HandleBadStringGracefully() { Simulation simulation = new Simulation() { ReadOnly = true }; string json = "INVALID STRING"; Exception err = Assert.Throws <Exception>(() => Structure.Add(json, simulation)); Assert.AreEqual(err.Message, "Unknown string encountered. Not JSON or XML. String: INVALID STRING"); }
/// <summary> /// User has clicked the add soil button. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnAddSoilButtonClicked(object sender, EventArgs e) { foreach (int selectedIndex in dataView.SelectedIndicies) { var values = dataView.GetRow(selectedIndex); var soilName = (string)values[0]; var matchingSoil = allSoils.First(s => s.Soil.Name == soilName).Soil as IModel; if (matchingSoil != null) { Structure.Add(matchingSoil as IModel, model); } } explorerPresenter.Refresh(); }
/// <summary>Perform the command</summary> /// <param name="tree">A tree view to which the changes will be applied.</param> /// <param name="modelChanged">Action to be performed if/when a model is changed.</param> public void Do(ITreeView tree, Action <object> modelChanged) { if (xmlOrJson != null) { modelToAdd = Structure.Add(xmlOrJson, parent); } else { modelToAdd = Structure.Add(child, parent); } modelAdded = true; tree.AddChild(parent.FullPath, describeModel(modelToAdd)); tree.SelectedNode = modelToAdd.FullPath; }
public void StructureTests_EnsureAPSOILSoilHasInitWaterAndSampleAdded() { Simulation simulation = new Simulation(); string soilXml = ReflectionUtilities.GetResourceAsString("UnitTests.Core.ApsimFile.StructureTestsAPSoilSoil.xml"); Structure.Add(soilXml, simulation); Assert.AreEqual(simulation.Children.Count, 1); Soil soil = simulation.Children[0] as Soil; Assert.AreEqual(soil.Children.Count, 6); Assert.IsTrue(soil.Children[4] is InitialWater); Assert.IsTrue(soil.Children[5] is Sample); }
public static Structure AssemblyFromFileOrCode(string file, PdbLoadOptions loadOptions = PdbLoadOptions.Default) { Structure protein = new Structure(); IEnumerable <AtomRecord> records = GetPdbRecords(file, false).Select(r => r as AtomRecord).Where(r => r != null).Where(r => r as HetatmRecord == null); List <char> letters = records.Select(record => record.ChainId).Distinct().ToList(); foreach (char chainId in records.Select(record => record.ChainId).Distinct()) { IEnumerable <AtomRecord> chainRecords = records.Where(record => record.ChainId == chainId); IChain chain = ChainFromRecords(chainRecords); protein.Add(chain); } return(protein); }
/// <summary> /// Replace a model with a model from another file. /// </summary> /// <param name="topLevel">The top-level model of the file being modified.</param> /// <param name="modelToReplace">Path to the model which is to be replaced.</param> /// <param name="replacementFile">Path of the .apsimx file containing the model which will be inserted.</param> /// <param name="replacementPath">Path to the model in replacementFile which will be used to replace a model in topLevel.</param> private static void ReplaceModelFromFile(Simulations topLevel, string modelToReplace, string replacementFile, string replacementPath) { IModel toBeReplaced = Apsim.Get(topLevel, modelToReplace) as IModel; if (toBeReplaced == null) { throw new Exception($"Unable to find model which is to be replaced ({modelToReplace}) in file {topLevel.FileName}"); } IModel extFile = FileFormat.ReadFromFile <IModel>(replacementFile, out List <Exception> errors); if (errors?.Count > 0) { throw new Exception($"Error reading replacement file {replacementFile}", errors[0]); } IModel replacement; if (string.IsNullOrEmpty(replacementPath)) { replacement = Apsim.ChildrenRecursively(extFile, toBeReplaced.GetType()).FirstOrDefault(); if (replacement == null) { throw new Exception($"Unable to find replacement model of type {toBeReplaced.GetType().Name} in file {replacementFile}"); } } else { replacement = Apsim.Get(extFile, replacementPath) as IModel; if (replacement == null) { throw new Exception($"Unable to find model at path {replacementPath} in file {replacementFile}"); } } IModel parent = toBeReplaced.Parent; int index = parent.Children.IndexOf((Model)toBeReplaced); parent.Children.Remove((Model)toBeReplaced); // Need to call Structure.Add to add the model to the parent. Structure.Add(replacement, parent); // Move the new model to the index in the list at which the // old model previously resided. parent.Children.Remove((Model)replacement); parent.Children.Insert(index, (Model)replacement); }
/// <summary>Copy constructor.</summary> public NutrientPatch(NutrientPatch from) { soilThickness = from.soilThickness; patchManager = from.patchManager; Nutrient = Apsim.Clone(from.Nutrient) as Nutrient; Structure.Add(Nutrient, from.Nutrient.Parent); // Find all solutes. foreach (ISolute solute in Nutrient.FindAllChildren <ISolute>()) { solutes.Add(solute.Name, solute); } lignin = from.lignin; cellulose = from.cellulose; carbohydrate = from.carbohydrate; }
public void StructureTests_EnsureAddOldXMLWorks() { Simulation simulation = new Simulation(); string xml = "<Memo>" + " <Name>TitlePage</Name>" + " <IncludeInDocumentation>true</IncludeInDocumentation>" + " <Text>Some text</Text>" + "</Memo>"; Structure.Add(xml, simulation); Assert.AreEqual(simulation.Children.Count, 1); Memo memo = simulation.Children[0] as Memo; Assert.AreEqual(memo.Text, "Some text"); }
public void EnsureAddXMLFromOldAPSIMWorks() { Simulation simulation = new Simulation(); var xml = "<clock>" + " <start_date type=\"date\">01/01/1990</start_date>" + " <end_date type=\"date\">31/12/2000</end_date>" + "</clock>"; Structure.Add(xml, simulation); Assert.AreEqual(simulation.Children.Count, 1); var clock = simulation.Children[0] as Clock; Assert.IsNotNull(clock); Assert.AreEqual(clock.StartDate, new DateTime(1990, 1, 1)); Assert.AreEqual(clock.EndDate, new DateTime(2000, 12, 31)); }
public void StructureTests_EnsureCannotAddModelToReadonlyParent() { Simulation simulation = new Simulation() { ReadOnly = true }; string xml = "<Memo>" + " <Name>TitlePage</Name>" + " <IncludeInDocumentation>true</IncludeInDocumentation>" + " <MemoText>Some text</MemoText>" + "</Memo>"; Exception err = Assert.Throws <Exception>(() => Structure.Add(xml, simulation)); Assert.AreEqual(err.Message, "Unable to modify Simulation - it is read-only."); }
public void EnsureDataIsNotWrittenTwice() { Simulations sims = Utilities.GetRunnableSim(); Simulation sim = sims.FindChild <Simulation>(); Summary summary = sim.FindChild <Summary>(); // Write 2 messages to the DB during StartOfSimulation. string message1 = "message 1"; string message2 = "A slightly longer message"; string message3 = "Written in OnCompleted"; SummaryWriter writer = new SummaryWriter(); writer.AddMessage("[Clock].StartOfSimulation", message1); writer.AddMessage("[Clock].StartOfSimulation", message2); writer.AddMessage("[Simulation].Completed", message3); Structure.Add(writer, sim); Runner runner = new Runner(sims); List <Exception> errors = runner.Run(); if (errors != null && errors.Count > 0) { throw errors[0]; } IDataStore storage = sims.FindChild <IDataStore>(); DataTable messages = storage.Reader.GetData("_Messages"); // Clock will write its own "Simulation terminated normally" message. Assert.AreEqual(5, messages.Rows.Count); // The first row will be a warning caused by the lack of a // microclimate model. Assert.AreEqual(message1, messages.Rows[1][6]); Assert.AreEqual(message2, messages.Rows[2][6]); // The fourth row should not be written by SummaryWriter. Assert.AreNotEqual(writer.Name, messages.Rows[3]["ComponentName"]); // The fifth will be the "Simulation terminated normally" message. Assert.AreEqual(message3, messages.Rows[4][6]); }
public void StructureTests_EnsureAddAvoidsDuplicateNames() { Simulation simulation = new Simulation(); string xml = "<Memo>" + " <Name>TitlePage</Name>" + " <IncludeInDocumentation>true</IncludeInDocumentation>" + " <MemoText>Some text</MemoText>" + "</Memo>"; Structure.Add(xml, simulation); Structure.Add(xml, simulation); Assert.AreEqual(simulation.Children.Count, 2); Memo memo1 = simulation.Children[0] as Memo; Memo memo2 = simulation.Children[1] as Memo; Assert.AreEqual(memo1.Name, "TitlePage"); Assert.AreEqual(memo2.Name, "TitlePage1"); }
public void StructureTests_EnsureAddNewJSONWorks() { Simulation simulation = new Simulation(); string json = "{" + " \"$type\": \"Models.Clock, Models\"," + " \"StartDate\": \"1900-01-01T00:00:00\"," + " \"EndDate\": \"2000-12-31T00:00:00\"," + " \"Name\": \"Clock\"," + " \"Children\": []," + " \"IncludeInDocumentation\": true," + " \"Enabled\": true," + " \"ReadOnly\": false" + "}"; Structure.Add(json, simulation); Assert.AreEqual(simulation.Children.Count, 1); Clock clock = simulation.Children[0] as Clock; Assert.AreEqual(clock.Name, "Clock"); }
public static Structure AssemblyFromText(string text, PdbLoadOptions loadOptions = PdbLoadOptions.Default) { using (TextReader stream = new StringReader(text)) { IEnumerable <AtomRecord> records = LoadRecords(stream).Where(record => record is AtomRecord).Cast <AtomRecord>(); List <char> letters = records.Select(record => record.ChainId).Distinct().ToList(); Structure protein = new Structure(); foreach (char chainId in letters) { IEnumerable <AtomRecord> chainRecords = records.Where(record => record.ChainId == chainId); IChain chain = ChainFromRecords(chainRecords); protein.Add(chain); } if (protein.Count == 0) { return(null); } return(protein); } }
public void AddResourceModelToReplacements() { ExplorerPresenter explorerPresenter = UITestUtilities.OpenBasicFileInGui(); GtkUtilities.WaitForGtkEvents(); // Add a replacements node. Replacements replacements = new Replacements(); Structure.Add(replacements, explorerPresenter.ApsimXFile); explorerPresenter.Refresh(); // Select the replacements node, then activate the 'add model' context menu item. explorerPresenter.SelectNode(replacements); explorerPresenter.ContextMenu.AddModel(explorerPresenter, EventArgs.Empty); GtkUtilities.WaitForGtkEvents(); TreeView addModelsTree = (TreeView)ReflectionUtilities.GetValueOfFieldOrProperty("tree", explorerPresenter.CurrentPresenter); // Now, we double click on the fertiliser node. This should add a fertiliser model. // For some reason, sending a double click event doesn't trigger the ActivateRow signal. // Therefore, we need to manually activate the row. //GtkUtilities.ClickOnTreeView(treeView, path, 0, EventType.TwoButtonPress, ModifierType.None, GtkUtilities.ButtonPressType.LeftClick); ActivateNode(addModelsTree, ".Models.PMF.Wheat"); Assert.AreEqual(1, replacements.Children.Count, "Replacements should now have 1 child after adding wheat, but it doesn't"); Assert.AreEqual(typeof(Models.PMF.Plant), replacements.Children[0].GetType()); // Wheat should have some children (read in from the resource file). IModel wheat = replacements.Children[0]; Assert.NotZero(wheat.Children.Count); // The children should all be visible. foreach (IModel child in wheat.Children) { Assert.False(child.IsHidden); } }
/// <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); }
public void Initialise() { Simulations basicFile = Utilities.GetRunnableSim(); IModel simulation = Apsim.Find(basicFile, typeof(Simulation)); IModel paddock = Apsim.Find(basicFile, typeof(Zone)); // Add a weather component. Models.Weather weather = new Models.Weather(); weather.Name = "Weather"; weather.FileName = "asdf.met"; Structure.Add(weather, simulation); // Add a second weather component. Models.Weather weather2 = new Models.Weather(); weather2.FileName = "asdf.met"; weather2.Name = "Weather2"; Structure.Add(weather2, simulation); // Add a third weather component. Models.Weather weather3 = new Models.Weather(); weather3.FileName = "asdf.met"; weather3.Name = "Weather3"; Structure.Add(weather3, simulation); // Add a third weather component. Models.Weather weather4 = new Models.Weather(); weather4.FileName = "asdf.met"; weather4.Name = "Weather4"; Structure.Add(weather4, simulation); // Add a report. Models.Report report = new Models.Report(); report.Name = "Report"; Structure.Add(report, paddock); // Add the wheat model. string json = ReflectionUtilities.GetResourceAsString(typeof(IModel).Assembly, "Models.Resources.Wheat.json"); Plant wheat = FileFormat.ReadFromString <IModel>(json, out _).Children[0] as Plant; wheat.ResourceName = "Wheat"; Structure.Add(wheat, paddock); Manager manager = new Manager(); manager.Code = @"using Models.PMF; using Models.Core; using System; namespace Models { [Serializable] public class Script : Model { [Description(""an amount"")] public double Amount { get; set; } } }"; Structure.Add(manager, paddock); Physical physical = new Physical(); physical.BD = new double[5]; physical.AirDry = new double[5]; physical.LL15 = new double[5]; Structure.Add(physical, paddock); basicFile.Write(basicFile.FileName); fileName = basicFile.FileName; // Create a new .apsimx file containing two weather nodes. Simulations test = Utilities.GetRunnableSim(); IModel sim = Apsim.Find(test, typeof(Simulation)); Models.Weather w1 = new Models.Weather(); w1.FileName = "w1.met"; w1.Name = "w1"; Structure.Add(w1, sim); Models.Weather w2 = new Models.Weather(); w2.Name = "w2"; w2.FileName = "w2.met"; Structure.Add(w2, sim); extFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".apsimx"); test.Write(extFile); }