//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; SiteVars.Initialize(); ParametersParser parser = new ParametersParser(Model.Core.StartTime, Model.Core.EndTime); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; managementAreas = parameters.ManagementAreas; UI.WriteLine("Reading management-area map {0} ...", parameters.ManagementAreaMap); ManagementAreas.ReadMap(parameters.ManagementAreaMap, managementAreas); UI.WriteLine("Reading stand map {0} ...", parameters.StandMap); Stands.ReadMap(parameters.StandMap); foreach (ManagementArea mgmtArea in managementAreas) mgmtArea.FinishInitialization(); prescriptionMaps = new PrescriptionMaps(parameters.PrescriptionMapNames); UI.WriteLine("Opening harvest log file \"{0}\" ...", parameters.EventLog); log = Data.CreateTextFile(parameters.EventLog); log.AutoFlush = true; log.WriteLine("Time,Stand,Total Sites,Damaged Sites,Cohorts Killed"); }
//--------------------------------------------------------------------- /// <summary> /// Initializes the instance and its associated site variables. /// </summary> protected void Initialize(PlugIns.ICore modelCore, double[,] establishProbabilities, SeedingAlgorithms seedAlg, Reproduction.Delegates.AddNewCohort addNewCohort) { Model.Core = modelCore; SiteVars.Initialize(); Seeding.InitializeMaxSeedNeighborhood(); disturbedSites = new DisturbedSiteEnumerator(Model.Core.Landscape, SiteVars.Disturbed); SeedingAlgorithm algorithm; switch (seedAlg) { case SeedingAlgorithms.NoDispersal: algorithm = NoDispersal.Algorithm; break; case SeedingAlgorithms.UniversalDispersal: algorithm = UniversalDispersal.Algorithm; break; case SeedingAlgorithms.WardSeedDispersal: algorithm = WardSeedDispersal.Algorithm; break; default: throw new ArgumentException(string.Format("Unknown seeding algorithm: {0}", seedAlg)); } Reproduction.Initialize(establishProbabilities, algorithm, addNewCohort == null ? null : new Reproduction.Delegates.AddNewCohort(addNewCohort)); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { this.modelCore = modelCore; ParametersParser.SpeciesDataset = modelCore.Species; ParametersParser parser = new ParametersParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNames; ILandscapeCohorts cohorts = modelCore.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); selectedSpecies = new List<SpeciesMaxAgeCalculator>(); foreach (ISpecies species in parameters.SelectedSpecies) selectedSpecies.Add(new SpeciesMaxAgeCalculator(species, cohorts)); siteMaxAgeCalculator = new SiteMaxAgeCalculator(cohorts); ageBuffer = new BlockRowBuffer<ushort>(modelCore.Landscape); }
private void LoadPlugin(Assembly assembly) { try { foreach (Type type in assembly.GetTypes()) { if (type.IsSubclassOf(typeof(Plugin))) { NClassEnvironment environment = new NClassEnvironment(Workspace.Default, DocumentManager); Plugin plugin = (Plugin)Activator.CreateInstance(type, environment); PlugIns.Add(plugin); } } } catch (Exception ex) { #if DEBUG Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); #endif OnError?.Invoke(this, new NClassEventArgs { Message = assembly.FullName + "\n" + ex.Message }); } }
//--------------------------------------------------------------------- /// <summary> /// Initializes the plug-in with a data file. /// </summary> /// <param name="dataFile"> /// Path to the file with initialization data. /// </param> /// <param name="startTime"> /// Initial timestep (year): the timestep that will be passed to the /// first call to the component's Run method. /// </param> public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParameterParser.EcoregionsDataset = Model.Core.Ecoregions; ParameterParser parser = new ParameterParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNamesTemplate; cohorts = Model.Core.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); SiteVars.Initialize(); Model.Core.RegisterSiteVar(SiteVars.TimeOfLastEvent, "Wind.TimeOfLastEvent"); Event.Initialize(parameters.EventParameters, parameters.WindSeverities); UI.WriteLine("Opening wind log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; log.WriteLine("Time,Initiation Site,Total Sites,Damaged Sites,Cohorts Killed,Mean Severity"); }
/// <summary> /// Конструктор - основной (без параметров) public FormMain() : base() { InitializeComponent(); s_plugIns = new PlugIns(FormMain_EvtDataAskedHost); //??? принять наименование файла из командной строки s_fileConnSett = new FIleConnSett(@"connsett.ini", FIleConnSett.MODE.FILE); s_listFormConnectionSettings = new List <ASUTP.Forms.FormConnectionSettings> (); s_listFormConnectionSettings.Add(new ASUTP.Forms.FormConnectionSettings(-1, s_fileConnSett.ReadSettingsFile, s_fileConnSett.SaveSettingsFile)); int idListener = DbSources.Sources().Register(s_listFormConnectionSettings[(int)CONN_SETT_TYPE.MAIN_DB].getConnSett(), false, CONN_SETT_TYPE.MAIN_DB.ToString()); if (!(idListener < 0)) { initProfiles(idListener); //ConnectionSettingsSource connSettSource = new ConnectionSettingsSource(idListener); //s_listFormConnectionSettings.Add(new FormConnectionSettings(idListener, connSettSource.Read, connSettSource.Save)); } else { ; } DbSources.Sources().UnRegister(idListener); m_TabCtrl.EventHTabCtrlExClose += new ASUTP.Control.HTabCtrlEx.DelegateHTabCtrlEx(onCloseTabPage); }
/// <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 override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; InputParametersParser.SpeciesDataset = Model.Core.Species; InputParametersParser parser = new InputParametersParser(); IInputParameters parameters = Data.Load<IInputParameters>(dataFile, parser); if(parameters == null) UI.WriteLine("Parameters are not loading."); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapFileNames; pctConiferMapNameTemplate = parameters.PctConiferFileName; pctDeadFirMapNameTemplate = parameters.PctDeadFirFileName; fuelTypes = parameters.FuelTypes; disturbanceTypes = parameters.DisturbanceTypes; fuelCoefs = parameters.FuelCoefficients; hardwoodMax = parameters.HardwoodMax; deadFirMaxAge = parameters.DeadFirMaxAge; cohorts = modelCore.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support LEAF BIOMASS interface"); SiteVars.Initialize(); }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public void Initialize(PlugIns.ICore modelCore) { Initialize(modelCore, null, // double[,] establishProbabilities, SeedingAlgorithms.NoDispersal, (Reproduction.AddNewCohortMethod) null); // addNewCohort -- obsolete overload }
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; } }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public void Initialize(PlugIns.ICore modelCore) { Initialize(modelCore, null, // double[,] establishProbabilities, SeedingAlgorithms.NoDispersal, null); // Reproduction.Delegates.AddNewCohort }
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); } }
//--------------------------------------------------------------------- /// <summary> /// Initializes the extension with a data file. /// </summary> public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; InputParameterParser parser = new InputParameterParser(); IInputParameters parameters = Data.Load<IInputParameters>(dataFile, parser); Timestep = 1; //parameters.Timestep; mapNameTemplate = parameters.MapNamesTemplate; manyInsect = parameters.ManyInsect; SiteVars.Initialize(); Defoliate.Initialize(parameters); GrowthReduction.Initialize(parameters); // Add local event handler for cohorts death due to age-only // disturbances. Biomass.Cohort.AgeOnlyDeathEvent += CohortKilledByAgeOnlyDisturbance; foreach(IInsect insect in manyInsect) { if(insect == null) UI.WriteLine("Insect Parameters NOT loading correctly."); insect.Neighbors = GetNeighborhood(insect.NeighborhoodDistance); int i=0; foreach(RelativeLocation location in insect.Neighbors) i++; if(insect.Neighbors != null) UI.WriteLine(" Dispersal Neighborhood = {0} neighbors.", i); } UI.WriteLine("Opening BiomassInsect log file \"{0}\" ...", parameters.LogFileName); try { log = Data.CreateTextFile(parameters.LogFileName); } catch (Exception err) { string mesg = string.Format("{0}", err.Message); throw new System.ApplicationException(mesg); } log.AutoFlush = true; log.Write("Time,InsectName,StartYear,StopYear,MeanDefoliation,NumSitesDefoliated"); //foreach (IEcoregion ecoregion in Ecoregions.Dataset) // log.Write(",{0}", ecoregion.MapCode); log.WriteLine(""); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { //initialize event id event_id = 1; Model.Core = modelCore; SiteVars.Initialize(); ParametersParser parser = new ParametersParser(Model.Core.Species, Model.Core.StartTime, Model.Core.EndTime); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); if (parser.RoundedRepeatIntervals.Count > 0) { UI.WriteLine("NOTE: The following repeat intervals were rounded up to"); UI.WriteLine(" ensure they were multiples of the harvest timestep:"); UI.WriteLine(" File: {0}", dataFile); foreach (RoundedInterval interval in parser.RoundedRepeatIntervals) UI.WriteLine(" At line {0}, the interval {1} rounded up to {2}", interval.LineNumber, interval.Original, interval.Adjusted); } //set timestep Timestep = parameters.Timestep; //set management areas managementAreas = parameters.ManagementAreas; UI.WriteLine("Reading management-area map {0} ...", parameters.ManagementAreaMap); //read management area map ManagementAreas.ReadMap(parameters.ManagementAreaMap, managementAreas); UI.WriteLine("Reading stand map {0} ...", parameters.StandMap); //readMap reads the stand map and adds all the stands to a management area Stands.ReadMap(parameters.StandMap); //finish each managementArea's initialization foreach (ManagementArea mgmtArea in managementAreas) //after reading the stand map, finish the initializations mgmtArea.FinishInitialization(); prescriptionMaps = new PrescriptionMaps(parameters.PrescriptionMapNames); //open log file and write header UI.WriteLine("Opening harvest log file \"{0}\" ...", parameters.EventLog); log = Data.CreateTextFile(parameters.EventLog); log.AutoFlush = true; //include a column for each species in the species dictionary string species_header_names = ""; int i = 0; for (i = 0; i < Model.Core.Species.Count; i++) { species_header_names += Model.Core.Species[i].Name + ","; } log.WriteLine("Time,Management Area,Prescription,Stand,Event Id,Stand Age,Stand Rank,Total Sites,Damaged Sites,Cohorts Killed,{0}", species_header_names); }
//--------------------------------------------------------------------- // Create a 2-D array of establish probabilities that are all 1.0 private static double[,] CreateEstablishProbabilities(PlugIns.ICore modelCore) { double[,] estabProbs = new double[modelCore.Ecoregions.Count, modelCore.Species.Count]; foreach(IEcoregion ecoregion in modelCore.Ecoregions) { foreach (ISpecies species in modelCore.Species) estabProbs[ecoregion.Index, species.Index] = 1.0; } return estabProbs; }
//--------------------------------------------------------------------- /// <summary> /// Registers a read method for plug-in names with the input values /// modules in the FLEL utility library. /// </summary> /// <param name="installedPlugIns"> /// The dataset of information about plug-ins installed on the local /// machine. Used by the read method to validate plug-in names. /// </param> public static void RegisterReadMethod(PlugIns.IDataset installedPlugIns) { if (installedPlugIns == null) throw new System.ArgumentNullException(); PlugInInfo.installedPlugIns = installedPlugIns; if (! registered) { Type.SetDescription<PlugIns.PlugInInfo>("plug-in name"); InputValues.Register<PlugIns.PlugInInfo>(Read); registered = true; } }
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"); }
public void LoadPlugIn(Assembly a) { var plugInType = typeof(TPlugIn); var allTypes = a.GetTypes(); foreach (var type in allTypes) { if (plugInType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract) { PlugIns.Add(new ApplicationPlugIn <TPlugIn>(this, type)); } } }
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"; }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParameterParser.EcoregionsDataset = Model.Core.Ecoregions; ParameterParser parser = new ParameterParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNamesTemplate; summaryEcoregionEventCount = new int[Model.Core.Ecoregions.Count]; cohorts = Model.Core.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); SiteVars.Initialize(cohorts); Event.Initialize(parameters.FireParameters, parameters.FireCurves, parameters.WindCurves, parameters.FireDamages); UI.WriteLine("Opening Fire log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; log.Write("Time,Initiation Site,Sites Checked,Cohorts Killed,Mean Severity,"); foreach (IEcoregion ecoregion in Model.Core.Ecoregions) { if (ecoregion.Active) log.Write("{0},", ecoregion.Name); } log.Write("TotalSiteInEvent"); log.WriteLine(""); summaryLog = Data.CreateTextFile(parameters.SummaryLogFileName); summaryLog.AutoFlush = true; summaryLog.Write("TimeStep,TotalSitesBurned,TotalNumberEvents"); foreach (IEcoregion ecoregion in Model.Core.Ecoregions) { if (ecoregion.Active) summaryLog.Write(",{0}", ecoregion.Name); } summaryLog.WriteLine(""); }
protected void Initialize(PlugIns.ICore modelCore, double[,] establishProbabilities, SeedingAlgorithms seedAlg, Reproduction.AddNewCohortMethod addNewCohort) { Reproduction.Delegates.AddNewCohort wrappedMethod = delegate(ISpecies species, ActiveSite site) { addNewCohort(species, site); }; Initialize(modelCore, establishProbabilities, seedAlg, wrappedMethod); //new Reproduction.Delegates.AddNewCohort(addNewCohort)); // System.Delegate.CreateDelegate(typeof (Reproduction.Delegates.AddNewCohort), // addNewCohort.Method)); }
/// <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); } }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { this.modelCore = modelCore; InputParametersParser parser = new InputParametersParser(modelCore.Species); IInputParameters parameters = Data.Load<IInputParameters>(dataFile, parser); Timestep = parameters.Timestep; this.selectedSpecies = parameters.SelectedSpecies; this.speciesMapNameTemplate = parameters.SpeciesMapNames; this.ageClasses = parameters.AgeClasses; cohorts = modelCore.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support biomass interface"); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { this.modelCore = modelCore; ParametersParser.SpeciesDataset = modelCore.Species; ParametersParser parser = new ParametersParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNames; selectedSpecies = parameters.SelectedSpecies; cohorts = modelCore.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); }
public MockSuccession(PlugIns.ICore modelCore) : base("MockSuccession") { // Initialize the succession library with the core. The other // 3 parameters are passed to Reproduction's Initialize method // but we want to use a mock seeding algorithm. Since the // base class' Initialize method uses an enumerated type to // specify the seeding algorithm, we just pass in an arbitrary // value, and then call Reproduction's Initialize method // directly with the mock seeding algorithm. Initialize(modelCore, null, // establishment probabilities SeedingAlgorithms.NoDispersal, null); // AddNewCohort delegate Reproduction.Initialize(CreateEstablishProbabilities(modelCore), MySeedingAlgorithm, MyAddNewCohort); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; SiteVars.Initialize(); ParametersParser parser = new ParametersParser(Model.Core.Species, Model.Core.StartTime, Model.Core.EndTime); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); if (parser.RoundedRepeatIntervals.Count > 0) { UI.WriteLine("NOTE: The following repeat intervals were rounded up to"); UI.WriteLine(" ensure they were multiples of the harvest timestep:"); UI.WriteLine(" File: {0}", dataFile); foreach (RoundedInterval interval in parser.RoundedRepeatIntervals) UI.WriteLine(" At line {0}, the interval {1} rounded up to {2}", interval.LineNumber, interval.Original, interval.Adjusted); } Timestep = parameters.Timestep; managementAreas = parameters.ManagementAreas; UI.WriteLine("Reading management-area map {0} ...", parameters.ManagementAreaMap); ManagementAreas.ReadMap(parameters.ManagementAreaMap, managementAreas); UI.WriteLine("Reading stand map {0} ...", parameters.StandMap); Stands.ReadMap(parameters.StandMap); foreach (ManagementArea mgmtArea in managementAreas) mgmtArea.FinishInitialization(); prescriptionMaps = new PrescriptionMaps(parameters.PrescriptionMapNames); UI.WriteLine("Opening harvest log file \"{0}\" ...", parameters.EventLog); log = Data.CreateTextFile(parameters.EventLog); log.AutoFlush = true; log.WriteLine("Time,Stand,Total Sites,Damaged Sites,Cohorts Killed"); }
//--------------------------------------------------------------------- /// <summary> /// Initializes the component with a data file. /// </summary> /// <param name="dataFile"> /// Path to the file with initialization data. /// </param> /// <param name="startTime"> /// Initial timestep (year): the timestep that will be passed to the /// first call to the component's Run method. /// </param> public override void Initialize(string dataFile, PlugIns.ICore modelCore) { this.modelCore = modelCore; ParametersParser.SpeciesDataset = modelCore.Species; ParametersParser parser = new ParametersParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; //this.nextTimeToRun = startTime - 1; this.mapNameTemplate = parameters.MapFileNames; this.mapDefs = parameters.ReclassMaps; cohorts = modelCore.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support biomass interface"); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; cohorts = Model.Core.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); SiteVars.Initialize(cohorts); ParameterParser parser = new ParameterParser(); IInputParameters parameters = Data.Load<IInputParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNamesTemplate; dynamicEcos = parameters.DynamicFireRegions; summaryFireRegionEventCount = new int[FireRegions.Dataset.Count]; Event.Initialize(parameters.FireDamages); UI.WriteLine("Opening Fire log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; log.Write("Time,InitialSiteRow,InitialSiteColumn,SitesChecked,CohortsKilled,MeanSeverity,"); foreach (IFireRegion ecoregion in FireRegions.Dataset) log.Write("{0},", ecoregion.Name); log.Write("TotalBurnedSites"); log.WriteLine(""); summaryLog = Data.CreateTextFile(parameters.SummaryLogFileName); summaryLog.AutoFlush = true; summaryLog.Write("Time,TotalSitesBurned,TotalNumberEvents"); foreach (IFireRegion ecoregion in FireRegions.Dataset) summaryLog.Write(",{0}", ecoregion.Name); summaryLog.WriteLine(""); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParametersParser parser = new ParametersParser(Model.Core.Ecoregions, Model.Core.Species); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; // Cohorts must be created before the base class is initialized // because the base class' reproduction module uses the core's // SuccessionCohorts property in its Initialization method. Biomass.Cohorts.Initialize(Timestep, new CohortBiomass()); cohorts = Model.Core.Landscape.NewSiteVar<SiteCohorts>(); landscapeCohorts = new LandscapeCohorts(cohorts); Cohorts = landscapeCohorts; InitialBiomass.Initialize(Timestep); Dead.Pools.Initialize(modelCore, parameters.WoodyDecayRate, parameters.LeafLitterDecayRate); double[,] estabProbabilities = new double[Model.Core.Ecoregions.Count, Model.Core.Species.Count]; foreach (ISpecies species in Model.Core.Species) { foreach (IEcoregion ecoregion in Model.Core.Ecoregions) { estabProbabilities[ecoregion.Index, species.Index] = parameters.EstablishProbability[species][ecoregion]; } } base.Initialize(modelCore, estabProbabilities, parameters.SeedAlgorithm, AddNewCohort); LivingBiomass.Initialize(parameters, cohorts); Cohort.DeathEvent += CohortDied; AgeOnlyDisturbances.Module.Initialize(parameters.AgeOnlyDisturbanceParms); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParametersParser parser = new ParametersParser(Model.Core.Ecoregions, Model.Core.Species, Model.Core.StartTime, Model.Core.EndTime); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; // Cohorts must be created before the base class is initialized // because the base class' reproduction module uses the core's // SuccessionCohorts property in its Initialization method. Biomass.Cohorts.Initialize(Timestep, new CohortBiomass()); cohorts = Model.Core.Landscape.NewSiteVar<SiteCohorts>(); landscapeCohorts = new LandscapeCohorts(cohorts); Cohorts = landscapeCohorts; InitialBiomass.Initialize(Timestep); Dead.Pools.Initialize(modelCore, parameters.WoodyDecayRate, parameters.LeafLitterDecayRate); base.Initialize(modelCore, Util.ToArray<double>(parameters.EstablishProbability), parameters.SeedAlgorithm, (Reproduction.Delegates.AddNewCohort) AddNewCohort); LivingBiomass.Initialize(parameters, cohorts); Cohort.DeathEvent += CohortDied; AgeOnlyDisturbances.Module.Initialize(parameters.AgeOnlyDisturbanceParms); ClimateChange.Module.Initialize(parameters.ClimateChangeUpdates); }
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) } } }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; SiteVars.Initialize(); ParametersParser parser = new ParametersParser(Model.Core.StartTime, Model.Core.EndTime); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; managementAreas = parameters.ManagementAreas; UI.WriteLine("Reading management-area map {0} ...", parameters.ManagementAreaMap); ManagementAreas.ReadMap(parameters.ManagementAreaMap, managementAreas); UI.WriteLine("Reading stand map {0} ...", parameters.StandMap); Stands.ReadMap(parameters.StandMap); foreach (ManagementArea mgmtArea in managementAreas) mgmtArea.FinishInitialization(); }
/// <summary> /// Loads all PlugIns in PlugInFolder directory. /// </summary> public void LoadPlugIns() { if (string.IsNullOrEmpty(PlugInFolder) || !Directory.Exists(PlugInFolder)) { throw new ApplicationException("PlugInFoler must be a valid folder path"); } var assemblyFiles = SpsHelper.FindAssemblyFiles(PlugInFolder); var plugInType = typeof(TPlugIn); foreach (var assemblyFile in assemblyFiles) { var allTypes = Assembly.LoadFrom(assemblyFile).GetTypes(); foreach (var type in allTypes) { if (plugInType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract) { PlugIns.Add(new ApplicationPlugIn <TPlugIn>(this, type)); } } } PlugInsLoaded = true; }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParametersParser parser = new ParametersParser(); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; // Cohorts must be created before the base class is initialized // because the base class' reproduction module uses the core's // SuccessionCohorts property in its Initialization method. cohorts = modelCore.Landscape.NewSiteVar<SiteCohorts>(); landscapeCohorts = new LandscapeCohorts(cohorts); Cohorts = landscapeCohorts; Cohort.DeathEvent += CohortDied; base.Initialize(modelCore, parameters.EstablishProbabilities, parameters.SeedAlgorithm, AddNewCohort); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { this.modelCore = modelCore; ParametersParser.SpeciesDataset = modelCore.Species; ParametersParser parser = new ParametersParser(); IParameters parameters = Data.Load<IParameters>(dataFile,parser); if (parameters==null) throw new ApplicationException("Error: Missing required parameters. Check the input parameter file"); Timestep = parameters.Timestep; sppagestats_mapNames = parameters.SppAgeStats_MapNames; siteagestats_mapNames = parameters.SiteAgeStats_MapNames; sitesppstats_mapNames = parameters.SiteSppStats_MapNames; ageStatSpecies = parameters.AgeStatSpecies; siteAgeStats = parameters.SiteAgeStats; siteSppStats = parameters.SiteSppStats; cohorts = modelCore.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); }
/// <summary> /// Scan through a given Directory for all PlugIns, and load and Initialize them /// </summary> /// <param name="directory">Full path of directory to scan</param> public void Find(string directory) { Type typeInterface = typeof(PlugInType); try { PlugIns.Clear(); if (Directory.Exists(directory) == false) { return; } string[] dllFiles = Directory.GetFiles(directory, "*.dll", SearchOption.TopDirectoryOnly); foreach (string file in dllFiles) { Assembly pluginAssembly = Assembly.LoadFrom(file); foreach (Type pluginType in pluginAssembly.GetTypes()) { Type testType = pluginType.GetInterface(typeInterface.FullName); if ((pluginType.IsSubclassOf(typeInterface) == true) || (testType != null)) { PlugInType instance = (PlugInType)Activator.CreateInstance(pluginType); instance.Initialize(Host); PlugIns.Add(instance); } } } } catch (Exception ex) { this.Host.ThrowException(ex); } }
/// <summary> /// Function to read the current settings into their respective controls. /// </summary> public override void InitializeSettings() { if (_pendingDisabled == null) { _pendingDisabled = new HashSet <string>(StringComparer.OrdinalIgnoreCase); _sysDisabled = new HashSet <string>(StringComparer.OrdinalIgnoreCase); // Get user plug-in disabled names. foreach (var plugInName in Program.Settings.DisabledPlugIns) { if (_pendingDisabled.Contains(plugInName)) { continue; } _pendingDisabled.Add(plugInName); } // Get system disabled plug-ins. foreach (var plugIn in Gorgon.PlugIns.Where(item => (item is GorgonFileSystemProviderPlugIn || item is EditorPlugIn) && (!_pendingDisabled.Contains(item.Name)) && (PlugIns.IsDisabled(item)))) { if (_sysDisabled.Contains(plugIn.Name)) { continue; } _sysDisabled.Add(plugIn.Name); } } listContentPlugIns.BeginUpdate(); listDisabledPlugIns.BeginUpdate(); listDisabledPlugIns.Items.Clear(); listContentPlugIns.Items.Clear(); foreach (var plugIn in Gorgon.PlugIns) { if ((!(plugIn is EditorPlugIn)) && (!(plugIn is GorgonFileSystemProviderPlugIn))) { continue; } var item = new ListViewItem { Name = plugIn.Name, Text = plugIn.Description, Tag = plugIn }; if (plugIn is ContentPlugIn) { item.SubItems.Add(Resources.GOREDIT_TEXT_CONTENT); } if (plugIn is FileWriterPlugIn) { item.SubItems.Add(Resources.GOREDIT_TEXT_FILE_WRITER); } if (plugIn is GorgonFileSystemProviderPlugIn) { item.SubItems.Add(Resources.GOREDIT_TEXT_FILE_READER); } if (_pendingDisabled.Contains(plugIn.Name)) { item.SubItems[1].Text = Resources.GOREDIT_TEXT_DISABLED; item.ForeColor = Color.FromKnownColor(KnownColor.DimGray); } else if (_sysDisabled.Contains(plugIn.Name)) { item.SubItems[1].Text = Resources.GOREDIT_TEXT_ERROR; item.ForeColor = Color.DarkRed; // We've got a disabled plug-in, add to the secondary list view // to show why the plug-in was disabled. var disabledItem = new ListViewItem { Name = plugIn.Name, Text = plugIn.Description, Tag = plugIn }; disabledItem.SubItems.Add(PlugIns.GetDisabledReason(plugIn)); disabledItem.SubItems.Add(plugIn.PlugInPath); listDisabledPlugIns.Items.Add(disabledItem); } item.SubItems.Add(plugIn.PlugInPath); listContentPlugIns.Items.Add(item); } listContentPlugIns.EndUpdate(); listContentPlugIns.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); listDisabledPlugIns.EndUpdate(); listDisabledPlugIns.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParametersParser parser = new ParametersParser(Model.Core.Ecoregions, Model.Core.Species, Model.Core.StartTime, Model.Core.EndTime); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; sufficientLight = parameters.LightClassProbabilities; CohortBiomass.SpinupMortalityFraction = parameters.SpinupMortalityFraction; SiteVars.Initialize(); // Initialize climate. A list of ecoregion indices is passed so that // the climate library can operate independently of the LANDIS-II core. List<int> ecoregionIndices = new List<int>(); foreach(IEcoregion ecoregion in Model.Core.Ecoregions) { ecoregionIndices.Add(ecoregion.Index); UI.WriteLine(" Century: preparing climate data: {0} = ecoregion index {1}", ecoregion.Name, ecoregion.Index); } Climate.Initialize(parameters.ClimateFile, ecoregionIndices, false); EcoregionData.Initialize(parameters); SpeciesData.Initialize(parameters); EcoregionData.ChangeParameters(parameters); OtherData.Initialize(parameters); FunctionalType.Initialize(parameters); Outputs.Initialize(parameters); Outputs.InitializeMonthly(parameters); // Cohorts must be created before the base class is initialized // because the base class' reproduction module uses the core's // SuccessionCohorts property in its Initialization method. Biomass.Cohorts.Initialize(Timestep, new CohortBiomass()); //cohorts = Model.Core.Landscape.NewSiteVar<SiteCohorts>(); landscapeCohorts = new LandscapeCohorts(SiteVars.SiteCohorts); //cohorts); Cohorts = landscapeCohorts; Reproduction.SufficientLight = SufficientLight; InitialBiomass.Initialize(Timestep); base.Initialize(modelCore, Util.ToArray<double>(SpeciesData.EstablishProbability), parameters.SeedAlgorithm, (Reproduction.Delegates.AddNewCohort) AddNewCohort); Cohort.DeathEvent += CohortDied; AgeOnlyDisturbances.Module.Initialize(parameters.AgeOnlyDisturbanceParms); Dynamic.Module.Initialize(parameters.DynamicUpdates); //EcoregionData.Initialize(parameters); FireEffects.Initialize(parameters); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParametersParser parser = new ParametersParser(Model.Core.Ecoregions, Model.Core.Species, Model.Core.StartTime, Model.Core.EndTime); IParameters parameters = Landis.Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; sufficientLight = parameters.LightClassProbabilities; SiteVars.Initialize(); SpeciesData.Initialize(parameters); EcoregionData.Initialize(parameters); CalibrateMode = parameters.CalibrateMode; CohortBiomass.SpinupMortalityFraction = parameters.SpinupMortalityFraction; // Cohorts must be created before the base class is initialized // because the base class' reproduction module uses the core's // SuccessionCohorts property in its Initialization method. Biomass.Cohorts.Initialize(Timestep, new CohortBiomass()); //cohorts = SiteVars.Cohorts; landscapeCohorts = new LandscapeCohorts(SiteVars.Cohorts); Cohorts = landscapeCohorts; Reproduction.SufficientLight = SufficientLight; InitialBiomass.Initialize(Timestep); base.Initialize(modelCore, Util.ToArray<double>(parameters.EstablishProbability), parameters.SeedAlgorithm, (Reproduction.Delegates.AddNewCohort) AddNewCohort); Cohort.DeathEvent += CohortDied; AgeOnlyDisturbances.Module.Initialize(parameters.AgeOnlyDisturbanceParms); ClimateChange.Module.Initialize(parameters.ClimateChangeUpdates); }
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); } } }
/// <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); } } } }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { // Initialize the Base Harvest's Model.Core property. // HACK: Because that property is internal, we must // call the Initialize method on an instance of Base // Harvest's PlugIn class. But don't want that // Initialize method parsing the data file. So we // pass in a null string to force an exception to // be raised; hence aborting the initialization at // a point that's acceptable. PlugIns.PlugIn baseHarvest = new BaseHarvest.PlugIn(); try { baseHarvest.Initialize(null, modelCore); } catch (System.ArgumentNullException) { // ignore } Model.Core = modelCore; PartialHarvestDisturbance.Initialize(); SiteVars.Initialize(); // Add local event handler for cohorts death due to age-only // disturbances. Cohort.AgeOnlyDeathEvent += CohortKilledByAgeOnlyDisturbance; ParametersParser parser = new ParametersParser(Model.Core.Species, Model.Core.StartTime, Model.Core.EndTime); BaseHarvest.IParameters baseParameters = Landis.Data.Load<BaseHarvest.IParameters>(dataFile, parser); IParameters parameters = baseParameters as IParameters; if (parser.RoundedRepeatIntervals.Count > 0) { UI.WriteLine("NOTE: The following repeat intervals were rounded up to"); UI.WriteLine(" ensure they were multiples of the harvest timestep:"); UI.WriteLine(" File: {0}", dataFile); foreach (RoundedInterval interval in parser.RoundedRepeatIntervals) UI.WriteLine(" At line {0}, the interval {1} rounded up to {2}", interval.LineNumber, interval.Original, interval.Adjusted); } //set timestep Timestep = parameters.Timestep; //set management areas managementAreas = parameters.ManagementAreas; UI.WriteLine("Reading management-area map {0} ...", parameters.ManagementAreaMap); //read management area map ManagementAreas.ReadMap(parameters.ManagementAreaMap, managementAreas); UI.WriteLine("Reading stand map {0} ...", parameters.StandMap); //readMap reads the stand map and adds all the stands to a management area Stands.ReadMap(parameters.StandMap); //finish each managementArea's initialization foreach (ManagementArea mgmtArea in managementAreas) //after reading the stand map, finish the initializations mgmtArea.FinishInitialization(); //prescriptionMaps = new PrescriptionMaps(parameters.PrescriptionMapNames); nameTemplate = parameters.PrescriptionMapNames; if (parameters.BiomassMapNames != null) biomassMaps = new BiomassMaps(parameters.BiomassMapNames); //open log file and write header UI.WriteLine("Opening harvest log file \"{0}\" ...", parameters.EventLog); log = Data.CreateTextFile(parameters.EventLog); log.AutoFlush = true; //include a column for each species in the species dictionary string species_header_names = ""; int i = 0; for (i = 0; i < Model.Core.Species.Count; i++) { species_header_names += "," + Model.Core.Species[i].Name; } log.WriteLine("Time,ManagementArea,Prescription,StandMapCode,EventId,StandAge,StandRank,StandSiteCount,DamagedSites,MgBiomassRemoved,MgBioRemovedPerDamagedHa,CohortsDamaged,CohortsKilled{0}", species_header_names); UI.WriteLine("Opening summary harvest log file \"{0}\" ...", parameters.SummaryLog); summaryLog = Data.CreateTextFile(parameters.SummaryLog); summaryLog.AutoFlush = true; summaryLog.WriteLine("Time,ManagementArea,Prescription,TotalDamagedSites,TotalCohortsDamaged,TotalCohortsKilled{0}", species_header_names); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { }
// 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))); } }
//--------------------------------------------------------------------- public override void InitializeSites(string initialCommunities, string initialCommunitiesMap, PlugIns.ICore modelCore) { Landis.Model.iui.WriteLine("Loading initial communities from file \"{0}\" ...", initialCommunities); InitialCommunities.DatasetParser parser = new InitialCommunities.DatasetParser(Timestep, Model.Core.Species); InitialCommunities.IDataset communities = modelCore.Load<InitialCommunities.IDataset>(initialCommunities, parser); Landis.Model.iui.WriteLine("Reading initial communities map \"{0}\" ...", initialCommunitiesMap); IInputRaster<InitialCommunities.Pixel> map; map = Model.Core.OpenRaster<InitialCommunities.Pixel>(initialCommunitiesMap); using (map) { foreach (Site site in Model.Core.Landscape.AllSites) { InitialCommunities.Pixel pixel = map.ReadPixel(); if (!site.IsActive) continue; ActiveSite activeSite = (ActiveSite)site; ushort mapCode = pixel.Band0; ICommunity community = communities.Find(mapCode); if (community == null) { throw new PixelException(activeSite.Location, "Unknown map code for initial community: {0}", mapCode); } InitializeSite(activeSite, community); } } }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { if (isDebugEnabled) UI.WriteLine("Initializing {0} ...", Name); Model.Core = modelCore; cohorts = Model.Core.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); SiteVars.Initialize(cohorts); InputParameterParser parser = new InputParameterParser(); IInputParameters parameters = Data.Load<IInputParameters>(dataFile, parser); Timestep = parameters.Timestep; fireSizeType = parameters.FireSizeType; bui = parameters.BUI; mapNameTemplate = parameters.MapNamesTemplate; dynamicWeather = parameters.DynamicWeather; severityCalibrate = parameters.SeverityCalibrate; WeatherDataTable = Weather.ReadWeatherFile(parameters.InitialWeatherPath, FireRegions.Dataset, parameters.SeasonParameters); UI.WriteLine(" Initializing Fire Events..."); Event.Initialize(parameters.SeasonParameters, parameters.FuelTypeParameters, parameters.FireDamages); seasonParameters = parameters.SeasonParameters; dynamicEcos = parameters.DynamicFireRegions; summaryFireRegionEventCount = new int[FireRegions.Dataset.Count]; summaryFireRegionSeverity = new int[FireRegions.Dataset.Count]; ecoregionSitesCount = new int[FireRegions.Dataset.Count]; //foreach (IFireRegion fire_region in FireRegions.Dataset) //UI.WriteLine(" FireSize={0}, SD={1}", fire_region.MeanSize, fire_region.StandardDeviation); // Count the number of sites per fire_region: foreach (Site site in Model.Core.Landscape) { if (site.IsActive) { IFireRegion fire_region = SiteVars.FireRegion[site]; ecoregionSitesCount[fire_region.Index] ++; } } UI.WriteLine(" Opening and Initializing Fire log files \"{0}\" and \"{1}\"...", parameters.LogFileName, parameters.SummaryLogFileName); try { log = Data.CreateTextFile(parameters.LogFileName); } catch (Exception err) { string mesg = string.Format("{0}", err.Message); throw new System.ApplicationException(mesg); } log.AutoFlush = true; log.Write("Time,InitSite,InitFireRegion,InitFuel,InitPercentConifer,SelectedSizeOrDuration,SizeBin,Duration,FireSeason,WindSpeed,WindDirection,FFMC,BUI,PercentCuring,ISI,SitesChecked,CohortsKilled,MeanSeverity,"); foreach (IFireRegion fire_region in FireRegions.Dataset) { log.Write("eco-{0},", fire_region.MapCode); } log.Write("TotalSitesInEvent"); log.WriteLine(""); try { summaryLog = Data.CreateTextFile(parameters.SummaryLogFileName); } catch (Exception err) { string mesg = string.Format("{0}", err.Message); throw new System.ApplicationException(mesg); } summaryLog.AutoFlush = true; summaryLog.Write("TimeStep, TotalSitesBurned, NumberFires"); foreach (IFireRegion fire_region in FireRegions.Dataset) { summaryLog.Write(", eco-num-sites-{0}", fire_region.MapCode); } foreach (IFireRegion fire_region in FireRegions.Dataset) { summaryLog.Write(", eco-mean-severity-{0}", fire_region.MapCode); } summaryLog.WriteLine(""); summaryLog.Write("0, 0, 0"); foreach (IFireRegion fire_region in FireRegions.Dataset) { summaryLog.Write(", {0}", ecoregionSitesCount[fire_region.Index]); } foreach (IFireRegion fire_region in FireRegions.Dataset) { summaryLog.Write(", 0.0"); } summaryLog.WriteLine(""); if (isDebugEnabled) UI.WriteLine("Initialization done"); }