static void Main(string[] args) { C3mbs _mmmbs = new C3mbs(); string animatScenarioFile = "jaxdolphin.sce"; animatScenarioFile = "jax3species.sce"; mbsRESULT mbsResult; mbsCONFIG config = _mmmbs.GetConfiguration(); mbsRUNSTATE runState; //load the .sce file if (mbsRESULT.OK != (mbsResult = _mmmbs.LoadScenario(animatScenarioFile))) Console.WriteLine("LoadScenario Error:" + _mmmbs.MbsResultToString(mbsResult)); //make sure we're in durationless mode. config.durationLess = true; _mmmbs.SetConfiguration(config); //get species count int speciesCount = _mmmbs.GetSpeciesCount(); //make a species list. #if false SpeciesList = new SpeciesList(); for (var i = 0; i <= speciesCount; i++) { SpeciesList.Add(new Species{SpeciesName = _mmmbs.GetSpeciesDisplayTitle(i), ReferenceCount = _mmmbs.GetIndivdualCount(i),}); } #endif //set up the position array from the values in the .sce file (not the ones in animatList, which doesn't exist yet..) int animatCount = _mmmbs.GetAnimatCount(); var posArray = new mbsPosition[animatCount]; //initialize the run, and wait until it's fully initialized. if(mbsRESULT.OK != (mbsResult = _mmmbs.InitializeRun())) Console.WriteLine("InitializeRun Error:" + _mmmbs.MbsResultToString(mbsResult)); while ((runState = _mmmbs.GetRunState()) == mbsRUNSTATE.INITIALIZING) { //wait until initializing is done. Thread.Sleep(1); } //get the initial positions of every animat if(mbsRESULT.OK != (mbsResult = _mmmbs.GetAnimatCoordinates(posArray))) Console.WriteLine("Error Fetching Initial Animat Coordinates: " + _mmmbs.MbsResultToString(mbsResult)); //bump the positions once, otherwise depths aren't set. if(mbsRESULT.OK != (mbsResult = _mmmbs.RunScenarioNumIterations(1))) Console.WriteLine("RunScenario Error:" + _mmmbs.MbsResultToString(mbsResult)); //get the initial positions of every animat if (mbsRESULT.OK != (mbsResult = _mmmbs.GetAnimatCoordinates(posArray))) Console.WriteLine("Error Fetching Initial Animat Coordinates: " + _mmmbs.MbsResultToString(mbsResult)); }
static void Main(string[] args) { int i; int j; int nNumInstances = 1; // Number of 3mb processes to run in parallel. int numAnimatsPerInstance = 1000; // Number of animats in each 3mb instance. uint duration = (uint)(5 * 3600); // Number of simulated seconds 3mb is to run. int mmbSetDuration = (int)0; // Number of simulated seconds 3mb is to run. uint numIterations = duration+1; ; // The number of iterations is always the duration +1. string speFileName = "generic_mysticete.spe"; // demo species to use. Boolean feedback = true; C3mbs[] mmmbs; mbsPosition mbInitialPosition; // Animt lat/lon. Used here to set and retrieve animat population lat/lon. mbsPosition[][] mbStepPosition; // Animt lat/lon. Used here to set and retrieve animat population lat/lon. mbsRESULT mbResult = mbsRESULT.OK; // 3mb function call result. mbsCONFIG mbConfig; // various configuration parameters for 3mb. mbsRUNSTATE mbRunState; string sz; // Initialize each 3mb instance mmmbs = new C3mbs[nNumInstances]; mbStepPosition = new mbsPosition[nNumInstances][]; //--------------------------------------------------------------------------// // Instantiate 3mb loop. //-----------------------// for(i = 0; i < mmmbs.Length && mbsRESULT.OK == mbResult; i++) mmmbs[i] = new C3mbs(); //--------------------------------------------------------------------------// // Initialize 3mb loop. //-----------------------// for(i = 0; i < mmmbs.Length && mbsRESULT.OK == mbResult; i++) { //----------------------------------------------------------------------// // Configure the scenario //------------------------// mbConfig = mmmbs[i].GetConfiguration(); // Probably wise to set each 3mb instance to a unique randomizer seed value. mbConfig.seedValue = (uint)i; // ESME should set enabled to false and durationless to TRUE. mbConfig.enabled = false; // binary output enabled/disabled mbConfig.durationLess = true; // ESME runs 3mb in a durationless mode. mmmbs[i].SetConfiguration(mbConfig); mmmbs[i].SetDuration(mmbSetDuration); //----------------------------------------------------------------------// // Load bathymetry file //----------------------// /* use either: * LoadBathymetryFromTextFile() if it has a .txt extension or * LoadFromBinFile() if the file has a .bth extension. * * Or for development and testing it is OK to instead use: * mmmbs[i].SetBaythyConstantDepth(); * that sets a constant depth throughout. */ mbResult = mmmbs[i].LoadBathymetryFromTextFile("Bahamas.txt"); if(mbsRESULT.OK != mbResult) { Console.WriteLine("\nError Loading Bathymetry File: " + mmmbs[i].MbsResultToString(mbResult)); foreach(C3mbs mmb in mmmbs) mmb.ClearScenario(); // Deallocates memory, closes files, resets 3MB. return; } //----------------------------------------------------------------------// // Add a species to the scenario //-------------------------------// mbResult = mmmbs[i].AddSpecies(Directory.GetCurrentDirectory() + "\\" + speFileName); if(mbsRESULT.OK != mbResult) { Console.WriteLine("\nError species(" + speFileName +"), instance(" + i +"): " + mmmbs[i].MbsResultToString(mbResult)); foreach(C3mbs mmb in mmmbs) mmb.ClearScenario(); // Deallocates memory, closes files, resets 3MB. return; } // Set the scenario's duration. // (ESME runs in durationless mode so there's no need to set a duration). //mmmbs[i].SetDuration((int)duration); //----------------------------------------------------------------------// // Add animats to the species //----------------------------// // Faking an initial location for each animat on the Bahamas map for this demo mbInitialPosition.latitude = 26.193023; // Actual latitude value on the Bahamas map mbInitialPosition.longitude = -78.251953; // Actual longitude value on the Bahamas map mbInitialPosition.depth = 0; // You can't actually set the animat's initial depth for(j=0; j<numAnimatsPerInstance; j++) { // Providing a little feedback every 100 animats. if(j%100 == 0) { sz = string.Format( "Adding Animats: 3mb instance {0:0}/{1:0} animat {2:000}/{3:000}\r", i+1, mmmbs.Length, j+1, numAnimatsPerInstance); Console.Write(sz); } // Added mbResult = mmmbs[i].SeedingCoordinateIsValid((int)0, mbInitialPosition); if(mbsRESULT.OK != mbResult) { Console.WriteLine("\nError with animat(" + j +"), initial coordinate, instance (" + i +"): " + mmmbs[i].MbsResultToString(mbResult)); foreach(C3mbs mmb in mmmbs) mmb.ClearScenario(); // Deallocates memory, closes files, resets 3MB. return; } // First param (0) is the species index. This demo only loads a single species. mbResult = mmmbs[i].AddIndividualAnimat(0, mbInitialPosition); if(mbsRESULT.OK != mbResult) { Console.WriteLine("\nError adding animat(" + j +"), instance(" + i +"): " + mmmbs[i].MbsResultToString(mbResult)); foreach(C3mbs mmb in mmmbs) mmb.ClearScenario(); // Deallocates memory, closes files, resets 3MB. return; } } sz = string.Format( "Adding Animats: 3mb instance {0:0}/{1:0} animat {2:000}/{3:000}", i+1, mmmbs.Length, j, numAnimatsPerInstance); Console.WriteLine(sz); //----------------------------------------------------------------------// // Initialize the scenario. //----------------------------// mbResult = mmmbs[i].InitializeRun(); if(mbsRESULT.OK == mbResult) { // Wait for reach 3mb instance to finish initialzing (run state won't // be mbsRUNSTATE.INITIALIZING) before initializing the next instance. do { Thread.Sleep(50); mbRunState = mmmbs[i].GetRunState(); } while(mbsRUNSTATE.INITIALIZING == mbRunState); } else { Console.WriteLine("\nCritical Error Initializing 3mbs: " + mmmbs[i].MbsResultToString(mbResult)); return; } // Allocate space for this 3mb intance's animat positional data. mbStepPosition[i] = new mbsPosition[numAnimatsPerInstance]; // Get Initial animat data. mbResult = mmmbs[i].GetAnimatCoordinates(mbStepPosition[i]); sz = string.Format( "Initial Location Proc ({1}/{2}) animat({3}/{4}): [{5,11:0.0000000}, {6,11:0.0000000}, {7,7:0.00}]", i, // 0: step j+1, // 1: process nNumInstances, // 2: number of proceses 0+1, // 3: animat number (animat index + 1) numAnimatsPerInstance, // 4: number of animats (per 3mb instance) mbStepPosition[i][0].latitude, // 5: lat of animat at index 0 mbStepPosition[i][0].longitude, // 6: lon of animat at index 0 mbStepPosition[i][0].depth); // 7: depth of animat at index 0 Console.WriteLine(sz); } //--------------------------------------------------------------------------// // Step through the 3mb instances //--------------------------------// for(i=0; i<duration && mbResult == mbsRESULT.OK; i++) { // Step the instances of 3mb in parallel. mbResult = Step3MB(mmmbs, i); if(mbsRESULT.OK != mbResult) return; if(true == feedback) { Console.Clear(); } else { if((i+1)%10 == 0) { sz = string.Format("iteration {0} of {1}\r", i+1, duration); Console.Write(sz); } } // Retrieve the animat position after each step (and do something with it). for(j=0; j<mmmbs.Length && mbsRESULT.OK == mbResult; j++) { mbResult = mmmbs[j].GetAnimatCoordinates(mbStepPosition[j]); if(mbsRESULT.OK != mbResult) { Console.WriteLine("Problem reading animat position data on 3mb instance " + i); } else if(true == feedback) { // Print out the first animat (index 0) of each instance every 100 iterations. sz = string.Format( "Step({0}) Proc ({1}/{2}) animat({3}/{4}): [{5,11:0.0000000}, {6,11:0.0000000}, {7,7:0.00}]", i, // 0: step j+1, // 1: process nNumInstances, // 2: number of proceses 0+1, // 3: animat number (animat index + 1) numAnimatsPerInstance, // 4: number of animats (per 3mb instance) mbStepPosition[j][0].latitude, // 5: lat of animat at index 0 mbStepPosition[j][0].longitude, // 6: lon of animat at index 0 mbStepPosition[j][0].depth); // 7: depth of animat at index 0 Console.WriteLine(sz); } } } //--------------------------------------------------------------------------// // Considerately tell the instances of 3mb to shut down //------------------------------------------------------// for(i = 0; i < mmmbs.Length && mbsRESULT.OK == mbResult; i++) mmmbs[i].AbortRun(); //--------------------------------------------------------------------------// // Verify all 3mb instances have shut down //-----------------------------------------// for(i = 0; i < mmmbs.Length && mbsRESULT.OK == mbResult; i++) { do { Thread.Sleep(5); mbRunState = mmmbs[i].GetRunState(); } while(mbsRUNSTATE.FINISHED != mbRunState); } // Can't hurt to do a clear scenario... foreach(C3mbs mmb in mmmbs) mmb.ClearScenario(); // Deallocates memory, closes files, resets 3MB. }
public static mbsRESULT Step3MB(C3mbs[] mbsArray, int CallNum) { int i = 0; mbsRESULT mbResult = mbsRESULT.OK; // 3mb function call result. mbsRUNSTATE mbRunState; i=0; Parallel.ForEach(mbsArray, curMbs => { mbResult = curMbs.RunScenarioNumIterations(1); if(mbResult != mbsRESULT.OK) Console.WriteLine("Failed on instance " + i + ", call " + CallNum + ": " + curMbs.MbsResultToString(mbResult)); i++; }); // Wait on all 3mb instances to finish the current step. for(i=0; i<mbsArray.Length; i++) { do { Thread.Sleep(2); mbRunState = mbsArray[i].GetRunState(); mbResult = mbsArray[i].GetErrorStatus(); if(mbsRUNSTATE.DATAEXTRACTING == mbRunState || mbsRUNSTATE.FINISHED == mbRunState || mbsRESULT.OK != mbResult) { Console.WriteLine("Failed on instance " + i + ", call " + CallNum + ": " + mbsArray[i].MbsResultToString(mbResult)); return mbResult; } } while(mbsRUNSTATE.RUNPAUSED != mbRunState); } return mbResult; }
void SetUpFresh() { //CDepthSpan spanRef; m_mmmbs = new C3mbs(); //mbsCONFIG config; //--------------------------------------------------------------------------// // Set up the intial species model. //---------------------------------// m_speMdl = new C3mbSpeciesModel(); m_szFileName = "NewSpeciesModel.spe"; FileNameLabel.Text = m_szFileName; m_fileNamed = false; m_fileEverWasNamed = false; m_szTitleBar = "3MB Species Builder Version " + m_speMdl.speciesCurrentSuperVer + "." + String.Format("{0:00}", m_speMdl.speciesCurrentSubVer) + " - Biomimetica"; // A new species model is being created. A default normal behavior will be // automatically added. Change its name. //beh = m_speMdl.GetBehaviorDuplicate(0); Text = m_szTitleBar; SpeciesVersopmLabel.Text = "species version:"; SaveVerLabel.Text = "" + m_speMdl.speciesCurrentSuperVer + "." + String.Format("{0:00}", m_speMdl.speciesCurrentSubVer); UpdateEntireForm(); m_bathyDepth = DEFAULT_BATHYMETRY_DEPTH; /* Set the initial scenario duration (hours). */ m_durationHrsUser = INIT_HRS_PER_BEHAVIOR * (uint)m_speMdl.BehaviorCount; m_durationLastActual = m_durationHrsUser; DurationHoursTextBox.Text = "" + m_durationLastActual; /* Set the initial seed value for the scenario randomizer. */ //config = m_mmmbs.GetConfiguration(); m_seedUser = DEFAULT_RANDOMIZER_SEED; RandomizerTextBox.Text = "" + DEFAULT_RANDOMIZER_SEED; InitializeBitMapVars(m_durationHrsUser*SECS_PER_HOUR + 1); ToggleTargetDepthDisplayButton.BackColor = m_bitmapMgr.TargetDepthColor; ToggleBathymetryDisplayButton.BackColor = m_bitmapMgr.BathyColor; DepthInputButton.Text = "Bathy Depth:" + String.Format("{0:00}", m_bathyDepth); ConfirmDurationButton.Enabled = false; Run3MB(false, false); }
public async static Task<Animat> SeedAsync(ScenarioSpecies species, GeoRect geoRect, Bathymetry bathymetry) { var yxzFileName = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".txt"); bathymetry.ToYXZ(yxzFileName, -1); var mbs = new C3mbs(); mbsRESULT mbsResult; if (mbsRESULT.OK != (mbsResult = mbs.SetOutputDirectory(Path.GetTempPath()))) throw new AnimatInterfaceMMBSException("SetOutputDirectory Error:" + mbs.ResultToTc(mbsResult)); var config = mbs.GetConfiguration(); config.enabled = false; // binary output enabled/disabled config.durationLess = true; // make sure we're in durationless mode. mbs.SetConfiguration(config); mbsResult = mbs.LoadBathymetryFromTextFile(yxzFileName); if (mbsRESULT.OK != mbsResult) throw new AnimatInterfaceMMBSException("Bathymetry failed to load: " + mbs.ResultToTc(mbsResult)); mbsResult = mbs.AddSpecies(species.SpeciesDefinitionFilePath); if (mbsRESULT.OK != mbsResult) throw new AnimatInterfaceMMBSException(string.Format("C3mbs::AddSpecies FATAL error {0} for species {1}", mbs.ResultToTc(mbsResult), species.SpeciesDefinitionFilePath)); var bounds = new GeoArray(geoRect.NorthWest, geoRect.NorthEast, geoRect.SouthEast, geoRect.SouthWest, geoRect.NorthWest); var result = new Animat { ScenarioSpecies = species }; var area = bounds.Area; //Debug.WriteLine("Area: {0}",area); var transformManyBlock = new TransformManyBlock<int, Geo<float>>(count => { var geos = new List<Geo<float>>(); for (var i = 0; i < count; i++) { var location = bounds.RandomLocationWithinPerimeter(); var depth = bathymetry.Samples.GetNearestPointAsync(location).Result.Data; mbsRESULT retval; lock (mbs) retval = mbs.AddIndividualAnimat(0, new mbsPosition { latitude = location.Latitude, longitude = location.Longitude, depth = 0 }); if (mbsRESULT.OK == retval) geos.Add(new Geo<float>(location.Latitude, location.Longitude, (float)(depth * Random.NextDouble()))); } return geos; }, new ExecutionDataflowBlockOptions { TaskScheduler = TaskScheduler.Default, BoundedCapacity = -1, MaxDegreeOfParallelism = -1, }); var bufferBlock = new BufferBlock<Geo<float>>(); transformManyBlock.LinkTo(bufferBlock); var population = (int)Math.Round(area * species.PopulationDensity); result.TotalAnimats = population; const int blockSize = 100; while (population > 0) { transformManyBlock.Post(population > blockSize ? blockSize : population); population -= blockSize; } transformManyBlock.Complete(); await transformManyBlock.Completion; //mbsResult = mbs.InitializeRun(); //if (mbsRESULT.OK == mbsResult) while (mbsRUNSTATE.INITIALIZING == mbs.GetRunState()) Thread.Sleep(1); //else throw new AnimatInterfaceMMBSException("C3mbs::Initialize FATAL error " + mbs.ResultToTc(mbsResult)); mbsResult = mbs.FinishRun(); if (mbsRESULT.OK != mbsResult) throw new AnimatInterfaceMMBSException("C3mbs::FinishRun FATAL error " + mbs.ResultToTc(mbsResult)); IList<Geo<float>> animatGeos; if (bufferBlock.TryReceiveAll(out animatGeos)) result.Locations.AddRange(animatGeos); return result; }
//double[] _animatSoundExposure; void Initialize3MB() { var nextSpeciesIndex = 0; var yxzFileName = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".txt"); Scenario.BathymetryData.ToYXZ(yxzFileName, -1); var contexts = new List<AnimatContext>(); foreach (var species in Scenario.ScenarioSpecies) { if (!_speciesNameToIndex.ContainsKey(species.SpeciesDefinitionFilePath)) _speciesNameToIndex.Add(species.SpeciesDefinitionFilePath, nextSpeciesIndex++); var speciesInstanceIndex = _speciesNameToIndex[species.SpeciesDefinitionFilePath]; var curSpecies = species; species.ReloadOrReseedAnimats(); contexts.AddRange(species.Animat.Locations.Select((t, speciesIndex) => new AnimatContext { Species = curSpecies, SpeciesInstanceIndex = speciesInstanceIndex, SpeciesAnimatIndex = speciesIndex })); } //var splitContext = contexts.Split(System.Environment.ProcessorCount).ToList(); var splitContext = contexts.Split(1).ToList(); _mbs = new C3mbs[splitContext.Count]; _animatContext = new AnimatContext[splitContext.Count][]; for (var mbsIndex = 0; mbsIndex < splitContext.Count; mbsIndex++) { mbsRESULT result; var mbs = new C3mbs(); _mbs[mbsIndex] = mbs; // set the output directory if (mbsRESULT.OK != (result = mbs.SetOutputDirectory(_simulationDirectory))) throw new AnimatInterfaceMMBSException("SetOutputDirectory Error:" + mbs.ResultToTc(result)); var config = mbs.GetConfiguration(); config.seedValue = (uint)mbsIndex; // Probably wise to set each 3mb instance to a unique randomizer seed value. config.enabled = false; // binary output enabled/disabled config.durationLess = true; // make sure we're in durationless mode. mbs.SetConfiguration(config); result = mbs.LoadBathymetryFromTextFile(yxzFileName); if (mbsRESULT.OK != result) throw new AnimatInterfaceMMBSException("Bathymetry failed to load: " + mbs.ResultToTc(result)); foreach (var speciesFilePath in _speciesNameToIndex.Keys) { result = mbs.AddSpecies(speciesFilePath); if (mbsRESULT.OK != result) throw new AnimatInterfaceMMBSException(string.Format("C3mbs::AddSpecies FATAL error {0} for species {1}", mbs.ResultToTc(result), speciesFilePath)); } var context = splitContext[mbsIndex].ToList(); _animatContext[mbsIndex] = new AnimatContext[context.Count]; //_animatPositions[mbsIndex] = new mbsPosition[context.Count]; //Debug.WriteLine("Thread {0} contains {1} animats", mbsIndex, context.Count); for (var animatIndex = 0; animatIndex < context.Count; animatIndex++) { var species = context[animatIndex].Species; var geo = species.Animat.Locations[context[animatIndex].SpeciesAnimatIndex]; _animatContext[mbsIndex][animatIndex] = new AnimatContext { Species = species, SpeciesAnimatIndex = context[animatIndex].SpeciesAnimatIndex }; result = mbs.AddIndividualAnimat(context[animatIndex].SpeciesInstanceIndex, new mbsPosition { latitude = geo.Latitude, longitude = geo.Longitude, depth = 0 }); if (mbsRESULT.OK != result) throw new AnimatInterfaceMMBSException(string.Format("An error was found with animat species {0}. Please verify that this species is appropriate for use in the location \"{1}\".C3mbs::AddIndividualAnimat FATAL error {2}", species.LatinName, Scenario.Location.Name,mbs.ResultToTc(result))); //throw new AnimatInterfaceMMBSException("this is a test error."); //Debug.WriteLine("Animat {0} lat: {1:0.####} lon: {2:0.####} depth: {3:0.#}, bathy: {4:0.#}", animatIndex, geo.Latitude, geo.Longitude, geo.Data, Scenario.BathymetryData.Samples.GetNearestPoint(geo).Data); } mbs.SetDuration((int)((TimeSpan)Scenario.Duration).TotalSeconds); result = mbs.SaveScenario(Path.Combine(_simulationDirectory, "test.sce")); if (mbsRESULT.OK != result) throw new AnimatInterfaceMMBSException(string.Format("C3mbs::SaveScenario FATAL error {0}", mbs.ResultToTc(result))); //----------------------------------------------------------------------// // Initialize the scenario. //----------------------------// if (mbsRESULT.OK == result) while (mbsRUNSTATE.INITIALIZING == mbs.GetRunState()) Thread.Sleep(1); else throw new AnimatInterfaceMMBSException("C3mbs::Initialize FATAL error " + mbs.ResultToTc(result)); } UpdateAnimatPositions(); }