private void PostPhenology(object sender, EventArgs e) { if (DMPlantMax > 9990) { double ttNow = accumTT; double ttToFlowering = (double)Apsim.Get(this, "[Phenology].TTToFlowering.Value()"); double dmPlantMaxTT = (double)Apsim.Get(this, "[Grain].PgrT1.Value()"); if (ttNow > dmPlantMaxTT + ttToFlowering) { DMPlantMax = (double)Apsim.Get(this, "[Stem].Live.Wt"); } } }
/// <summary>User has attempted to move the current node up.</summary> /// <param name="sender">Sender object</param> /// <param name="e">Event arguments</param> private void OnMoveUp(object sender, EventArgs e) { Model model = Apsim.Get(this.ApsimXFile, this.view.SelectedNode) as Model; if (model != null && model.Parent != null) { IModel firstModel = model.Parent.Children[0]; if (model != firstModel) { CommandHistory.Add(new Commands.MoveModelUpDownCommand(model, true, this.view)); } } }
/// <summary>User has attempted to move the current node down.</summary> /// <param name="sender">The sender</param> /// <param name="e">The args</param> private void OnMoveDown(object sender, EventArgs e) { Model model = Apsim.Get(this.ApsimXFile, this.view.SelectedNode) as Model; if (model != null && model.Parent != null) { IModel lastModel = model.Parent.Children[model.Parent.Children.Count - 1]; if (model != lastModel) { CommandHistory.Add(new Commands.MoveModelUpDownCommand(model, false, this.view)); } } }
public void CheckSoil(object sender, EventArgs e) { Soil currentSoil = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Soil; if (currentSoil != null) { string errorMessages = currentSoil.Check(false); if (errorMessages != string.Empty) { this.explorerPresenter.MainPresenter.ShowMessage(errorMessages, Simulation.ErrorLevel.Error); } } }
public void WriteDebugDocument(object sender, EventArgs e) { try { Simulation model = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath) as Simulation; WriteDebugDoc writeDocument = new WriteDebugDoc(explorerPresenter, model); writeDocument.Do(null); } catch (Exception err) { explorerPresenter.MainPresenter.ShowMessage(err.ToString(), Simulation.ErrorLevel.Error); } }
public void OnGenerateApsimXFiles(object sender, EventArgs e) { IModel node = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath) as IModel; List <IModel> children; if (node is Experiment) { children = new List <IModel> { node }; } else { children = Apsim.ChildrenRecursively(node, typeof(Experiment)); } string outDir = ViewBase.AskUserForDirectory("Select a directory to save model files to."); if (outDir == null) { return; } if (!Directory.Exists(outDir)) { Directory.CreateDirectory(outDir); } string err = ""; int i = 0; children.ForEach(expt => { explorerPresenter.MainPresenter.ShowMessage("Generating simulation files: ", Simulation.ErrorLevel.Information); explorerPresenter.MainPresenter.ShowProgress(100 * i / children.Count, false); while (GLib.MainContext.Iteration()) { ; } err += (expt as Experiment).GenerateApsimXFile(outDir); i++; }); if (err.Length < 1) { explorerPresenter.MainPresenter.ShowMessage("Successfully generated .apsimx files under " + outDir + ".", Simulation.ErrorLevel.Information); } else { explorerPresenter.MainPresenter.ShowMessage(err, Simulation.ErrorLevel.Error); } }
public void ShowModelStructure(object sender, EventArgs e) { IModel model = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath) as IModel; if (model != null) { foreach (IModel child in Apsim.ChildrenRecursively(model)) { child.IsHidden = !child.IsHidden; } explorerPresenter.PopulateContextMenu(explorerPresenter.CurrentNodePath); explorerPresenter.Refresh(); } }
public void SetTest() { Assert.AreEqual(this.simulation.Get("[Weather].Rain"), 0.0); this.simulation.Set("[Weather].Rain", 111.0); Assert.AreEqual(this.simulation.Get("[Weather].Rain"), 111.0); double[] thicknessBefore = (double[])Apsim.Get(simulation, "[Physical].Thickness"); Assert.AreEqual(6, thicknessBefore.Length); // If APITest.xml is modified, this test will fail and must be updated. Apsim.Set(simulation, "[Physical].Thickness[1]", "20"); double[] thicknessAfter = (double[])Apsim.Get(simulation, "[Physical].Thickness"); Assert.AreEqual(thicknessBefore.Length, thicknessAfter.Length); Assert.AreEqual(20, thicknessAfter[0]); }
public void MoveUpDown() { CommandHistory commandHistory = new CommandHistory(); Model modelToMove = Apsim.Get(simulations, "APS14.Factors.Permutation.NRate") as Model; MoveModelUpDownCommand moveCommand = new MoveModelUpDownCommand(modelToMove, true, null); moveCommand.Do(commandHistory); Model modelToMove2 = Apsim.Get(simulations, "APS14.Factors.NRate") as Model; Assert.AreEqual(simulations.Children[2].Children[0].Children[0].Children[0].Name, "NRate"); Assert.AreEqual(simulations.Children[2].Children[0].Children[0].Children[0].Children.Count, 4); }
/// <summary>Return data using reflection</summary> /// <param name="fieldName">The field name to get data for.</param> /// <returns>The return data or null if not found</returns> private IEnumerable GetDataFromModels(string fieldName) { if (fieldName != null && fieldName.StartsWith("[")) { int posCloseBracket = fieldName.IndexOf(']'); if (posCloseBracket == -1) { throw new Exception("Invalid graph field name: " + fieldName); } string modelName = fieldName.Substring(1, posCloseBracket - 1); string namePath = fieldName.Remove(0, posCloseBracket + 2); IModel modelWithData = Apsim.Find(this, modelName) as IModel; if (modelWithData == null) { // Try by assuming the name is a type. Type t = ReflectionUtilities.GetTypeFromUnqualifiedName(modelName); if (t != null) { IModel parentOfGraph = this.Parent.Parent; if (t.IsAssignableFrom(parentOfGraph.GetType())) { modelWithData = parentOfGraph; } else { modelWithData = Apsim.Find(parentOfGraph, t); } } } if (modelWithData != null) { // Use reflection to access a property. object obj = Apsim.Get(modelWithData, namePath); if (obj != null && obj.GetType().IsArray) { return(obj as Array); } } } else { return(Apsim.Get(this, fieldName) as IEnumerable); } return(null); }
/// <summary> /// Event handler for the run on cloud action /// </summary> /// <param name="sender">Sender of the event</param> /// <param name="e">Event arguments</param> public void RunOnCloud(object sender, EventArgs e) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { object model = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath); explorerPresenter.HideRightHandPanel(); explorerPresenter.ShowInRightHandPanel(model, "UserInterface.Views.NewAzureJobView", "UserInterface.Presenters.NewAzureJobPresenter"); } else { explorerPresenter.MainPresenter.ShowError("Microsoft Azure functionality is currently only available under Windows."); } }
public void AddModel(object sender, EventArgs e) { try { object model = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath); explorerPresenter.HideRightHandPanel(); explorerPresenter.ShowInRightHandPanel(model, "ApsimNG.Resources.Glade.AddModelView.glade", new AddModelPresenter()); } catch (Exception err) { explorerPresenter.MainPresenter.ShowError(err); } }
public void OnMoveDownClick(object sender, EventArgs e) { try { IModel model = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as IModel; if (model != null && model.GetType().Name != "Simulations") { this.explorerPresenter.MoveDown(model); } } catch (Exception err) { explorerPresenter.MainPresenter.ShowError(err); } }
public void Enabled(object sender, EventArgs e) { IModel model = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath) as IModel; if (model != null) { model.Enabled = !model.Enabled; foreach (IModel child in Apsim.ChildrenRecursively(model)) { child.Enabled = model.Enabled; } explorerPresenter.PopulateContextMenu(explorerPresenter.CurrentNodePath); explorerPresenter.Refresh(); } }
/// <summary> /// The view is asking for variable names. /// </summary> /// <param name="relativeTo">Model in the simulations tree which owns the editor.</param> /// <param name="objectName">Fully- or partially-qualified object name for which we want completion options.</param> /// <param name="properties">If true, property suggestions will be generated.</param> /// <param name="methods">If true, method suggestions will be generated.</param> /// <param name="events">If true, event suggestions will be generated.</param> /// <returns>List of completion options.</returns> public static List <ContextItem> ExamineModelForNames(IModel relativeTo, string objectName, bool properties, bool methods, bool events) { // TODO : refactor cultivar and report activity ledger presenters so they use the intellisense presenter. // These are the only two presenters which still use this intellisense method. if (objectName == string.Empty) { objectName = "."; } object o = null; IModel replacementModel = Apsim.Get(relativeTo, ".Simulations.Replacements") as IModel; if (replacementModel != null) { try { o = Apsim.Get(replacementModel, objectName) as IModel; } catch (Exception) { } } if (o == null) { try { o = Apsim.Get(relativeTo, objectName); } catch (Exception) { } } if (o == null && relativeTo.Parent is Replacements) { // Model 'relativeTo' could be under replacements. Look for the first simulation and try that. IModel simulation = Apsim.Find(relativeTo.Parent.Parent, typeof(Simulation)); try { o = Apsim.Get(simulation, objectName) as IModel; } catch (Exception) { } } if (o != null) { return(ExamineObjectForContextItems(o, properties, methods, events)); } return(new List <ContextItem>()); }
/// <summary> /// Parse the specification into paths and values. /// </summary> /// <param name="specification">The specification to parse.</param> /// <param name="allPaths">The list of paths to add to.</param> /// <param name="allValues">The list of values to add to.</param> private void ParseSpecification(string specification, List <string> allPaths, List <object> allValues) { if (string.IsNullOrEmpty(specification)) { return; } string path = specification; object value; if (path.Contains("=")) { value = StringUtilities.SplitOffAfterDelimiter(ref path, "=").Trim(); if (value == null) { throw new Exception("Cannot find any values on the specification line: " + specification); } allPaths.Add(path.Trim()); allValues.Add(value.ToString().Trim()); } else { // Find the model that we are to replace. var experiment = Apsim.Parent(this, typeof(Experiment)) as Experiment; var baseSimulation = Apsim.Child(experiment, typeof(Simulation)); var modelToReplace = Apsim.Get(baseSimulation, path) as IModel; if (modelToReplace == null) { throw new Exception($"Error in CompositeFactor {Name}: Unable to find a model to replace from path '{path}'"); } // Now find a child of that type. var possibleMatches = Apsim.Children(this, modelToReplace.GetType()); if (possibleMatches.Count > 1) { value = possibleMatches.Find(m => m.Name == modelToReplace.Name); } else { value = possibleMatches[0]; } allPaths.Add(path.Trim()); allValues.Add(value); } }
/// <summary>Perform the actual replacement.</summary> /// <param name="simulation">The simulation to perform the replacements on.</param> public void Replace(IModel simulation) { if (path == null) { // Temporarily remove DataStore because we don't want to do any // replacements under DataStore. var dataStore = simulation.Children.Find(model => model is DataStore); if (dataStore != null) { simulation.Children.Remove(dataStore); } // Do replacements. foreach (IModel match in Apsim.ChildrenRecursively(simulation)) { if (match.Name.Equals(replacement.Name, StringComparison.InvariantCultureIgnoreCase)) { ReplaceModel(match); } } // Reinstate DataStore. if (dataStore != null) { simulation.Children.Add(dataStore); } } else { IModel match = Apsim.Get(simulation, path) as IModel; if (match == null) { throw new Exception("Cannot find a model on path: " + path); } ReplaceModel(match); // In a multi-paddock context, we want to attempt to // replace the model in all paddocks. foreach (IModel paddock in Apsim.ChildrenRecursively(simulation, typeof(Zone))) { match = Apsim.Get(paddock, path) as IModel; if (match != null) { ReplaceModel(match); } } } }
/// <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>Set the scripts parameters from the 'xmlElement' passed in.</summary> private void SetParametersInScriptModel() { if (Enabled && Children.Count > 0) { var script = Children[0]; if (Parameters != null) { List <Exception> errors = new List <Exception>(); foreach (var parameter in Parameters) { try { PropertyInfo property = script.GetType().GetProperty(parameter.Key); if (property != null) { object value; if (parameter.Value.StartsWith(".") || parameter.Value.StartsWith("[")) { value = Apsim.Get(this, parameter.Value); } else if (property.PropertyType == typeof(IPlant)) { value = Apsim.Find(this, parameter.Value); } else { value = ReflectionUtilities.StringToObject(property.PropertyType, parameter.Value); } property.SetValue(script, value, null); } } catch (Exception err) { errors.Add(err); } } if (errors.Count > 0) { string message = ""; foreach (Exception error in errors) { message += error.Message; } throw new Exception(message); } } } }
/// <summary>Run APSIM.</summary> /// <param name="multiProcessRunner">Use the multi-process runner?</param> private void RunAPSIMInternal(bool multiProcessRunner) { if (this.explorerPresenter.Save()) { Runner.RunTypeEnum typeOfRun = Runner.RunTypeEnum.MultiThreaded; if (multiProcessRunner) { typeOfRun = Runner.RunTypeEnum.MultiProcess; } Model model = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Model; var runner = new Runner(model, runType: typeOfRun, wait: false); this.command = new RunCommand(model.Name, runner, this.explorerPresenter); this.command.Do(null); } }
public void CheckSoil(object sender, EventArgs e) { try { Soil currentSoil = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Soil; if (currentSoil != null) { SoilChecker.CheckWithStandardisation(currentSoil); explorerPresenter.MainPresenter.ShowMessage("Soil water parameters are valid.", Simulation.MessageType.Information); } } catch (Exception err) { explorerPresenter.MainPresenter.ShowError(err); } }
/// <summary>A node has begun to be dragged.</summary> /// <param name="sender">Sending object</param> /// <param name="e">Drag arguments</param> private void OnDragStart(object sender, DragStartArgs e) { Model obj = Apsim.Get(this.ApsimXFile, e.NodePath) as Model; if (obj != null) { string st = FileFormat.WriteToString(obj); this.SetClipboardText(st); DragObject dragObject = new DragObject(); dragObject.NodePath = e.NodePath; dragObject.ModelType = obj.GetType(); dragObject.ModelString = st; e.DragObject = dragObject; } }
/// <summary>A node has begun to be dragged.</summary> /// <param name="sender">Sending object</param> /// <param name="e">Drag arguments</param> private void OnDragStart(object sender, DragStartArgs e) { Model obj = Apsim.Get(this.ApsimXFile, e.NodePath) as Model; if (obj != null) { string xml = Apsim.Serialise(obj); this.SetClipboardText(xml); DragObject dragObject = new DragObject(); dragObject.NodePath = e.NodePath; dragObject.ModelType = obj.GetType(); dragObject.Xml = xml; e.DragObject = dragObject; } }
/// <summary>The view is asking for variable names.</summary> public static List <ContextItem> ExamineModelForNames(IModel relativeTo, string objectName, bool properties, bool methods, bool events) { if (objectName == string.Empty) { objectName = "."; } object o = null; IModel replacementModel = Apsim.Get(relativeTo, ".Simulations.Replacements") as IModel; if (replacementModel != null) { try { o = Apsim.Get(replacementModel, objectName) as IModel; } catch (Exception) { } } if (o == null) { try { o = Apsim.Get(relativeTo, objectName); } catch (Exception) { } } if (o == null && relativeTo.Parent is Replacements) { // Model 'relativeTo' could be under replacements. Look for the first simulation and try that. IModel simulation = Apsim.Find(relativeTo.Parent.Parent, typeof(Simulation)); try { o = Apsim.Get(simulation, objectName) as IModel; } catch (Exception) { } } if (o != null) { return(NeedContextItemsArgs.ExamineObjectForContextItems(o, properties, methods, events)); } return(new List <ContextItem>()); }
/// <summary>Gets the value.</summary> /// <value>The value.</value> public double Value(int arrayIndex = -1) { object o = Apsim.Get(this, VariableName.Trim()); if (o is IFunction) { return((o as IFunction).Value(arrayIndex)); } else if (o is Array) { return(Convert.ToDouble((o as Array).GetValue(arrayIndex))); } else { return(Convert.ToDouble(o)); } }
public void CheckSoil(object sender, EventArgs e) { Soil currentSoil = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Soil; if (currentSoil != null) { string errorMessages = currentSoil.Check(false); if (!string.IsNullOrEmpty(errorMessages)) { explorerPresenter.MainPresenter.ShowError(errorMessages); } else { explorerPresenter.MainPresenter.ShowMessage("Soil water parameters are valid.", Simulation.MessageType.Information); } } }
public void CopyPathToNode(object sender, EventArgs e) { try { string nodePath = explorerPresenter.CurrentNodePath; if (Apsim.Get(explorerPresenter.ApsimXFile, nodePath) is IFunction) { nodePath += ".Value()"; } explorerPresenter.SetClipboardText(Path.GetFileNameWithoutExtension(explorerPresenter.ApsimXFile.FileName) + nodePath, "CLIPBOARD"); } catch (Exception err) { explorerPresenter.MainPresenter.ShowError(err); } }
public void ShowPageOfGraphs(object sender, EventArgs e) { try { Folder folder = Apsim.Get(explorerPresenter.ApsimXFile, explorerPresenter.CurrentNodePath) as Folder; folder.ShowPageOfGraphs = !folder.ShowPageOfGraphs; foreach (Folder child in Apsim.ChildrenRecursively(folder, typeof(Folder))) { child.ShowPageOfGraphs = folder.ShowPageOfGraphs; } explorerPresenter.PopulateContextMenu(explorerPresenter.CurrentNodePath); } catch (Exception err) { explorerPresenter.MainPresenter.ShowError(err); } }
/// <summary> /// This method takes a value from the grid and formats it appropriately, /// based on the data type of the property to which the value is going to /// be assigned. /// </summary> /// <param name="property">Property to which the value will be assigned.</param> /// <param name="value">Value which is going to be assigned to property.</param> public static object FormatValueForProperty(IVariable property, object value) { if (property.DataType.IsArray && value != null) { string[] stringValues = value.ToString().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (property.DataType == typeof(double[])) { value = MathUtilities.StringsToDoubles(stringValues); } else if (property.DataType == typeof(int[])) { value = MathUtilities.StringsToDoubles(stringValues); } else if (property.DataType == typeof(string[])) { value = stringValues; } else if (property.DataType == typeof(DateTime[])) { value = stringValues.Select(d => DateTime.Parse(d, CultureInfo.InvariantCulture)).ToArray(); } else { throw new ApsimXException(property.Object as IModel, "Invalid property type: " + property.DataType.ToString()); } } else if (typeof(IPlant).IsAssignableFrom(property.DataType)) { value = Apsim.Find(property.Object as IModel, value.ToString()) as IPlant; } else if (property.DataType == typeof(DateTime)) { value = Convert.ToDateTime(value, CultureInfo.InvariantCulture); } else if (property.DataType.IsEnum) { value = VariableProperty.ParseEnum(property.DataType, value.ToString()); } else if (property.Display != null && property.Display.Type == DisplayType.Model) { value = Apsim.Get(property.Object as IModel, value.ToString()); } return(value); }
/// <summary>Run APSIM.</summary> /// <param name="multiProcessRunner">Use the multi-process runner?</param> private void RunAPSIMInternal(bool multiProcessRunner) { if (this.explorerPresenter.Save()) { List <string> duplicates = this.explorerPresenter.ApsimXFile.FindDuplicateSimulationNames(); if (duplicates.Count > 0) { string errorMessage = "Duplicate simulation names found " + StringUtilities.BuildString(duplicates.ToArray(), ", "); explorerPresenter.MainPresenter.ShowError(errorMessage); } else { Model model = Apsim.Get(this.explorerPresenter.ApsimXFile, this.explorerPresenter.CurrentNodePath) as Model; this.command = new RunCommand(model, this.explorerPresenter, multiProcessRunner); this.command.Do(null); } } }