コード例 #1
0
        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));
        }
コード例 #2
0
        //******************************************************************************//
        // Demonstrates how to build a scenario from scratch.
        //******************************************************************************//
        static void BuildScenario()
        {
            int i;
            int spe; // species index
            mbsPosition pos;

            /*--------------------------------------------------------------------------//
             * Clear the information from the previous scenario
             *-----------------------------------------------------//
             *  If a new scenario were to be build from scratch with a previous scenario
             *  still in memory a call to the ClearScenario function is a fast and easy
             *  way to clear out present species models, bathymetry data, animats, and so
             *  on to start clean.  It is called within 3mb itself automatically if the
             *  LoadScenario function is called so isn't actually needed here.
             *--------------------------------------------------------------------------*/
            s_mb.ClearScenario();


            // Set the output file (needed only if there is to be ouput)
            if(mbsRESULT.OK != (s_result = s_mb.SetOutputDirectory(OUTPUTDIR)))
            {
                Console.WriteLine("\nFailed to set output directory");
                return;
            }

            /*--------------------------------------------------------------------------//
             * Load in Bathymetry data.
             *-------------------------//
             * Notes:
             *  (1) 3MB now requires its own copy of the bathymetry map in memory.  The
             *      The shore following animat behavior has the animats look ahead in time
             *      to determine if they will collide with the shore so it is no longer
             *      sufficient to pass to the animat the bathymetry value at its current
             *      location.
             *      
             *  (2) Bathymetry files with a ".bth" extension must be formatted with
             *      postive depth values and those with a .txt extension must be formatted
             *      with a negative depth values.  Both .bth and .txt files are text
             *      files.
             *--------------------------------------------------------------------------*/
            if(mbsRESULT.OK != (s_result = s_mb.LoadBathymetryFromTextFile(DEMODIR + BATHYMETRY_FILE)))
            {
                Console.WriteLine("\nBathymetry load Error");
                Process.GetCurrentProcess().Kill();
                return;
            }

            /*--------------------------------------------------------------------------//
             * Add two species
             *----------------*/
            if(mbsRESULT.OK != (s_result = s_mb.AddSpecies(DEMODIR + SPECIES1_FILE)))
            {
                Console.WriteLine("\nSpecies " + SPECIES1_FILE + " load Error");
                Process.GetCurrentProcess().Kill();
            }
            if(mbsRESULT.OK != (s_result = s_mb.AddSpecies(DEMODIR + SPECIES2_FILE)))
            {
                Console.WriteLine("\nSpecies " + SPECIES2_FILE + " load Error");
                Process.GetCurrentProcess().Kill();
            }


            /*--------------------------------------------------------------------------//
             * Populate each species with animats
             *-----------------------------------//
             * Notes
             *  (1) There are a few functions for populating animats into a species:
             *      (a) AddIndividualAnimat(int SpeciesIndex, mbsPosition Position)
             *      (b) AddIndividualAnimats(int SpeciesIndex, int NumAnimats, mbsPosition[] Position)
             *      (c) AddPod(int SpeciesIndex)
             *      (d) AddPod(int SpeciesIndex, mbsPODLEADERTYPE LeaderType, double FocalDistance, int NumAnimats, mbsPosition[] Position)
             *      (e) AddPodAnimat(int SpeciesIndex, int PodIndex, mbsPosition Position)
             *      (f) AddPodAnimats(int SpeciesIndex, int PodIndex, int NumAnimats, mbsPosition[] Position);
             *--------------------------------------------------------------------------*/
            pos = new mbsPosition();
            pos.latitude = .4;  // Faked initial lat
            pos.longitude = .4; // Faked initial lon
            for(spe=0; spe < s_mb.GetSpeciesCount(); spe++)
            {
                for(i=0; i<NUMANIMATS; i++)
                {
                    if(mbsRESULT.OK != (s_result = s_mb.AddIndividualAnimat(spe, pos)))
                    {
                        Console.WriteLine("Error populating species: " + s_mb.MbsResultToString(s_result));
                        Process.GetCurrentProcess().Kill();
                        return;
                    }
                }
            }

            // Feedback
            for(spe=0; spe<s_mb.GetSpeciesCount(); spe++)
            {
                Console.WriteLine("\nSpecies " + (spe+1) + " Animat Count: " +
                    s_mb.GetAnimatCount(spe));
                if(s_mb.GetAnimatCount(spe) < 1)
                {
                    Console.WriteLine("\nAn unpopulated species is present");
                    Process.GetCurrentProcess().Kill();
                    return;
                }
            }


            /*--------------------------------------------------------------------------//
             * Set the duration of the scenario.
             *---------------------------------//
             * Notes
             * (1) Setting the duration isn't required if setting the scenario to run in
             *     durationless mode.
             * (2) ESME should set 3MB to run in durationless mode so that 3MB does not
             *     output any data to file and so ESME may run as long as it wishes
             *     without having to tell 3MB ahead of time how long to run.
             *
             *--------------------------------------------------------------------------*/
            s_mb.SetDuration(SCENARIO_DURATION_SECONDS);

            /*--------------------------------------------------------------------------//
             * Set 3MB to run for a specified duration or run durationless.
             *--------------------------------------------------------------//
             * Notes
             *  (1) See notes and call to SetDuration() about setting the duration.
             *  (2) Setting the duration isn't required if setting the scenario to run in
             *      durationless mode.
             *  (3) Setting 3MB to run duration less prevents it from outputting any data
             *      to file.
             *--------------------------------------------------------------------------*/
            mbsCONFIG c = s_mb.GetConfiguration();
            c.durationLess = s_durationless;
            s_mb.SetConfiguration(c);
        }
コード例 #3
0
        static void RunScenario2()
        {
            int elapsedIterations = 0;
            int scenarioAnimatCount = s_mb.GetAnimatCount();
            int speciesCount = s_mb.GetSpeciesCount();
            int i;
            double acousticSrclat=0;
            double acousticSrclon=0;
            mbsRUNSTATE rs;
            mbsSCESTATE ss;
            mbsCONFIG config;
            int loop;
            uint numThrottleIterations = NUM_THROTTLE_ITERATIONS;

            // You don't want to set throttle durations to zero, especially if 3MB is run in
            // durationless mode.
            if(numThrottleIterations == 0)
                numThrottleIterations = 1;

            // Create the needed arrays (animat position plus any environmental data needing to be
            // set.  Only acoustic exposure and bathymetry are the only environmental data supported
            // right now, and bathymetry isn't functional yet.
            mbsPosition[] positionArray = new mbsPosition[scenarioAnimatCount];
            double[] acousticExposureArray = new double[scenarioAnimatCount];
            double[] bathymetryArray = new double[scenarioAnimatCount];
            config = s_mb.GetConfiguration();


            /*--------------------------------------------------------------------------//
             * Print a nice startup banner
             *----------------------------*/
            PrintStartupBanner();

            /*--------------------------------------------------------------------------//
             * Make sure 3MB isn't doing anything.
             *------------------------------------//
             *  The run state is set to FINISHED only when
             *  (a) the 3MB libraries are instantiated
             *  (b) at the end of a scenario run.
             *  Verifying that the run state is in finished here is just a check in case
             *  a scenario was previously run and shouldn't ever be the case unless a 
             *  mistake was made in the libary code somewhere or a unusual condition was
             *  encountered.
             *--------------------------------------------------------------------------*/
            while(mbsRUNSTATE.FINISHED != (rs = s_mb.GetRunState()))
            {
                Console.Write("Waiting on 3MB " + DrawPinwheel() + "      \r");
                Thread.Sleep(50);
            }

            /*--------------------------------------------------------------------------//
             * Initialize the scenario.
             *-------------------------*/
            if(mbsRESULT.OK != (s_result = s_mb.InitializeRun()))
            {
                Console.WriteLine("\nCritical Error Initializing 3mbs: " + s_mb.MbsResultToString(s_result));
                Process.GetCurrentProcess().Kill();
                return;
            }

            /*--------------------------------------------------------------------------//
             * Wait for the scenario and animats to initialize
             *------------------------------------------------//
             * Initialization sets up the scenario internally and determines the animats
             * initial state (location, dive activity, depth and so on).
             *--------------------------------------------------------------------------*/
            while((rs = s_mb.GetRunState()) == mbsRUNSTATE.INITIALIZING)
            {
                Console.Write("Initializing 3MB " + DrawPinwheel() + "    \r");
                Thread.Sleep(50);
            }

            /*--------------------------------------------------------------------------//
             * Get the animat's initial location (if desired... may not be any need yet)
             *--------------------------------------------------------------------------*/
            if(mbsRESULT.OK != (s_result = s_mb.GetAnimatCoordinates(positionArray)))
            {
                s_mb.AbortRun(); // kills the thread.
                Console.WriteLine("\nCritical Error Fetching Animat Coordinates: " + s_mb.MbsResultToString(s_result));
                return;
            }

            /*--------------------------------------------------------------------------//
             * Set the animat's initial acoustic expore if desired.
             *-----------------------------------------------------*/
            for(i=0; i<scenarioAnimatCount; i++)
                acousticExposureArray[i] = i; // fake the data for this demo.
            s_result = s_mb.SetAnimatAcousticExposure(acousticSrclat, acousticSrclon, acousticExposureArray);
            if(mbsRESULT.OK != s_result)
            {
                s_mb.AbortRun(); // kills the 3MB thread.
                Console.WriteLine("\nCritical Error Setting Acoustic Exposure: " + s_mb.MbsResultToString(s_result));
                return;
            }



            /*----------------------------------------------------------------------//
             * Start the 3MB.
             *-----------------//
             * (1) The calling application sets the number if iterations 3MB iterates
             *     and is permitted to vary.
             * (2) The StepRun() function will be only briefily blocked pending the
             *     release of an mutex then returns while the 3MB iterates for the
             *     number of iterations it was set to.
             * (3) Entering a 0 for the number of iterations to throttle is legal but
             *     nothing will happen.
             *----------------------------------------------------------------------*/
            Debug.Assert(numThrottleIterations != 0); // Pointless and causes needless looping.
            Console.Write("Starting 3MB                                \r");
            if(mbsRESULT.OK != (s_result = s_mb.StepRun(numThrottleIterations)))
            {
                s_mb.AbortRun();
                Console.WriteLine("\nCritical Error running 3mbs: " + s_mb.MbsResultToString(s_result) + " at " +
                            elapsedIterations + " of " + s_mb.GetDurationSeconds());
                Process.GetCurrentProcess().Kill();
                return;
            }


            /*--------------------------------------------------------------------------//
            // Advance the 3MB
             *-----------------//
             * At this point the animats are still in their initial state with a possble
             * initial acoustic exposre value set for them.  The following loop shows how
             * to advance the 3MB a specific number of iterations then pause so the
             * animat locations can be again accessed and their acoustic again set.
             *--------------------------------------------------------------------------*/
            Console.Write("3MB Running                                \r");
            while((rs = s_mb.GetRunState()) != mbsRUNSTATE.FINISHED)
            {

                if((rs = s_mb.GetRunState()) == mbsRUNSTATE.RUNPAUSED)
                {

                    /*----------------------------------------------------------------------//
                     * Get the animats' current location and set acoustic exposure
                     *------------------------------------------------------------//
                     * Notes
                     *  (1) Once the scenario is running the ONLY VALID opportunity to set the
                     *      animats' acoustic state values is when 3MB is paused as it waits
                     *      to be throttled.  Retrieving the animat's locations, however, is
                     *      permited even if the 3MB isn't paused.
                     *----------------------------------------------------------------------*/
                    if(mbsRESULT.OK != (s_result = s_mb.GetAnimatCoordinates(positionArray)))
                    {
                        s_mb.AbortRun(); // kills the thread.
                        Console.WriteLine("\nCritical Error Fetching Animat Coordinates: " + s_mb.MbsResultToString(s_result));
                        Process.GetCurrentProcess().Kill();
                        return;
                    }


                    // Acoustic source location is faked for this demo.
                    acousticSrclat += 0.00001;
                    acousticSrclon -= 0.00001;

                    for(i=0; i<scenarioAnimatCount; i++)
                        acousticExposureArray[i] = i; // fake the acoustic exposure data again for this demo

                    // Set the acoustic source location and animat aoustic exposure.
                    try
                    {
                        if(mbsRESULT.OK != (s_result = s_mb.SetAnimatAcousticExposure(acousticSrclat, acousticSrclon, acousticExposureArray)))
                        {
                            s_mb.AbortRun(); // kills the thread.
                            Console.WriteLine("\nCritical Error Setting Acoustic Exposure: " + s_mb.MbsResultToString(s_result));
                            Process.GetCurrentProcess().Kill();
                            return;
                        }
                    }
                    catch
                    {
                        s_mb.AbortRun(); // kills the thread.
                        Console.WriteLine("\nCritical Error Setting Acoustic Exposure: " + s_mb.MbsResultToString(s_result));
                        Process.GetCurrentProcess().Kill();
                        return;
                    }


                    /*----------------------------------------------------------------------//
                     * Throttle the 3MB.
                     *-----------------//
                     * (1) The calling application sets the number if iterations 3MB iterates
                     *     and is permitted to vary.
                     * (2) The StepRun() function will be only briefily blocked pending the
                     *     release of an mutex then returns while the 3MB iterates for the
                     *     number of iterations it was set to.
                     * (3) Entering a 0 for the number of iterations to throttle is legal but
                     *     nothing will happen.
                     *----------------------------------------------------------------------*/
                    Debug.Assert(numThrottleIterations != 0); // Pointless and causes needless looping.
                    if(mbsRESULT.OK != (s_result = s_mb.StepRun(numThrottleIterations)))
                    {
                        s_mb.AbortRun();
                        Console.WriteLine("\nCritical Error running 3mbs: " + s_mb.MbsResultToString(s_result) + " at " +
                            elapsedIterations + " of " + s_mb.GetDurationSeconds());
                        Process.GetCurrentProcess().Kill();
                        return;
                    }
                }


                /*----------------------------------------------------------------------//
                 * Setting 3MB to throttle was successful.  Now do stuff until 3MB
                 * completes this round of throttled iterations.
                 *----------------------------------------------------------------------*/
                loop = 0;
                while((rs = s_mb.GetRunState()) == mbsRUNSTATE.RUNNING)
                {
                    // Do a dance, sing a song, update GUI states ....

                    Thread.Sleep(1);
                    ss = s_mb.GetScenarioState();
                    //ss.activity == mbsSCEACTIVITY.SCE_PAUSED
                    elapsedIterations = (int)ss.currentIteration;
                    Console.Write("3MB iterating in background " + loop++ + " " + elapsedIterations + " of " + SCENARIO_DURATION_SECONDS + "              \r");
                }

                /*----------------------------------------------------------------------//
                 * Track the number of iterations elapsed and handle it based on if the
                 * calling application set 3MB to run durationless or with a specific
                 * duration.
                 *---------------------------------------------------------------------//
                 * Notes
                 *  (1) ESME is expected to run in a durationless mode where it simply
                 *      keeps 3MB running as long as the ESME application is running.
                 *  (2) If 3MB configured to run in durationless mode it will have to
                 *      signal to 3MB when to cease.
                 *----------------------------------------------------------------------*/
                if(config.durationLess == true)
                {
                    elapsedIterations += (int)NUM_THROTTLE_ITERATIONS;
                    if(elapsedIterations >= SCENARIO_DURATION_SECONDS)
                    {
                        Console.WriteLine("\nInstructing 3MB to cease running\n");
                        s_mb.AbortRun(); // Tell 3MB to shut down.
                        while((rs = s_mb.GetRunState()) != mbsRUNSTATE.FINISHED)
                        {
                            Console.Write("Waiting on 3MB to shut down " + DrawPinwheel() + "           \r");
                            Thread.Sleep(5);
                        }
                    }
                }
                else
                {
                    ss = s_mb.GetScenarioState();
                    elapsedIterations = (int)ss.currentIteration;
                }
            }
            Console.WriteLine("\nDone\n");
        }
コード例 #4
0
        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.


        }
コード例 #5
0
        void Run3MB(Boolean MaintainDataExtremes, Boolean MaintainScaling)
        {
            // Record if, prior to running the model, the model needed to be saved.
            Boolean neededSave = m_speMdl.NeedSave;
            string speFileName = Directory.GetCurrentDirectory() + "\\sztemp.spe";
            int i;
            mbsPosition position;
            mbsPosition[] positionArray = new mbsPosition[1];
            mbsRESULT result;
            uint duration;

            position.latitude = 0;
            position.longitude = 0;
            position.depth = 0;// (initial animat depth cannot be set but must be done so
                               // here to avoid compiler error.

            // eventually, instead of saving to file, directly transfer the model to the
            // 3mb libraries
            m_speMdl.SaveToBinFile(speFileName, false);

            // If the user had made changes to the model before it auto ran (to update the
            // display) "touch" the species model so its status changes to needing to be
            // saved.
            if(neededSave == true)
            {
                m_speMdl.Touch();
                UpdateModifiedStatus();
            }

            m_mmmbs.ClearScenario();
            duration = m_durationLastActual * SECS_PER_HOUR;
            m_stateArray = new mbsANIMAT_STATE[duration + 1];

            if(mbsRESULT.OK != (result = m_mmmbs.AddSpecies(speFileName)))
                return;

            // The zero value in AddIndividualAnimat refers to the specie's index.  There
            // is only a single species, thus, index 0.
            position.latitude = 0;
            position.longitude = 0;
            if(mbsRESULT.OK != (result = m_mmmbs.AddIndividualAnimat(0, position)))
                return;

            m_mmmbs.SetDuration((int)duration);

            mbsCONFIG config = m_mmmbs.GetConfiguration();
            config.enabled = false; // binary ouput disengaged.
            config.maintainFirstAnimatState = true;
            config.seedValue = m_seedUser;
            m_mmmbs.SetConfiguration(config);
            m_mmmbs.SetBaythyConstantDepth(m_bathyDepth);


            // Run the entire scenario.  
            if(mbsRESULT.OK != (result = m_mmmbs.RunScenarioEntireDuration())) // 3mbsWrapper.cpp
            {
                m_mmmbs.ClearScenario();
                return;
            }

            //Thread.Sleep(3);
            while(mbsRUNSTATE.FINISHED != m_mmmbs.GetRunState())
            {
                Thread.Sleep(3);
                if(mbsRESULT.OK != (result = m_mmmbs.GetErrorStatus()))
                {
                    m_mmmbs.ClearScenario();
                    return;
                }
            }


            // retrieve the animats preserved states
            for(i=0; i<duration+1; i++)
            {
                m_stateArray[i] = m_mmmbs.RetrieveFirstAnimatStateAtIndex((uint)i);
            }
            // Display the generated data
            SetBitmapDisplayData(MaintainDataExtremes, MaintainScaling);
            if(File.Exists(speFileName))
                File.Delete(speFileName);
        }
コード例 #6
0
 void UpdateAnimatPositions()
 {
     for (var mbsIndex = 0; mbsIndex < _mbs.Length; mbsIndex++)
     {
         mbsRESULT result;
         var positions = new mbsPosition[_animatContext[mbsIndex].Length];
         if (mbsRESULT.OK != (result = _mbs[mbsIndex].GetAnimatCoordinates(positions)))
         {
             _mbs[mbsIndex].AbortRun(); // kills the thread.
             throw new AnimatInterfaceMMBSException("C3mbs::GetAnimatCoordinates FATAL error " + _mbs[mbsIndex].ResultToTc(result));
         }
         for (var contextIndex = 0; contextIndex < _animatContext[mbsIndex].Length; contextIndex++)
         {
             var species = _animatContext[mbsIndex][contextIndex].Species;
             var position = positions[contextIndex];
             species.Animat.Locations[_animatContext[mbsIndex][contextIndex].SpeciesAnimatIndex] = new Geo<float>(position.latitude, position.longitude) { Data = -(float)position.depth };
         }
     }
 }