Exemple #1
0
        private static bool checkSub(Subsystem subsystem, SystemSchedule proposedSchedule, Universe environment)
        {
            // new system state of the proposedSchedule (by asset).  Empty to start, fully populated after Checker.CheckSchedule is done
            //SystemState newState = proposedSchedule.AllStates.GetLastState();
            // the system state at the end of the last event on the proposedSchedule
            // SystemState oldState = newState.Previous;
            // the proposed Task
            //  Dictionary<Asset, Task> proposedTask = new Dictionary<Asset, Task>();
            // proposedTask.Add(subsystem.Asset, proposedSchedule.getSubsytemNewTask(subsystem.Asset));

            //NEED A PROPOSED EVENT-- this is just a place holder
            //  Event proposedEvent = new Event(proposedSchedule.AllStates.Events.Peek()., newState);
            // the dynamicState of the proposedSchedule
            //   DynamicState assetDynamicState = subsystem.Asset.AssetDynamicState;

            // Check all subsystems to see if they canPerform the task
            // Recursion of the subsystem dependencies is managed by the subsystems
            SystemState oldState = proposedSchedule.AllStates.Events.Peek().State.Previous;

            if (oldState == null)
            {
                oldState = proposedSchedule.AllStates.InitialState;
            }
            if (!subsystem.canPerform(proposedSchedule.AllStates.Events.Peek(), environment))
            {
                return(false);
            }

            return(true);
        }
Exemple #2
0
        /// <summary>
        /// Determine if the system can execute the proposed schedule
        /// </summary>
        /// <param name="system"></param>
        /// <param name="proposedSchedule"></param>
        /// <returns></returns>
        public static bool CheckSchedule(SystemClass system, SystemSchedule proposedSchedule)
        {
            // Iterate through Subsystem Nodes and set that they havent run
            foreach (var subsystem in system.Subsystems)
            {
                subsystem.IsEvaluated = false;
            }

            // Iterate through constraints
            foreach (var constraint in system.Constraints)
            {
                foreach (Subsystem sub in constraint.Subsystems)
                {
                    if (!checkSub(sub, proposedSchedule, system.Environment))
                    {
                        return(false);
                    }
                    if (!CheckConstraints(system, proposedSchedule, constraint))
                    {
                        return(false);
                    }
                    //if (!constraint.accepts(proposedSchedule))
                    //    return false;
                }
            }
            // Check the remaining Subsystems that aren't included in any Constraints
            if (!checkSubs(system.Subsystems, proposedSchedule, system.Environment))
            {
                return(false);
            }

            return(true);
        }
Exemple #3
0
 /// <summary>
 /// Check if the constraint has been violated in progressing the state of the system
 /// </summary>
 /// <param name="system"></param>
 /// <param name="proposedSchedule"></param>
 /// <param name="constraint"></param>
 /// <returns></returns>
 private static bool CheckConstraints(SystemClass system, SystemSchedule proposedSchedule, Constraint constraint)
 {
     if (!constraint.Accepts(proposedSchedule.AllStates.GetLastState()))
     {
         // TODO: Change this to logger
         // HSFLogger.Log(new HSFLogData(constraint, subsystem, task, value, time));
         Console.WriteLine("Constraint Failed");
         return(false);
     }
     return(true);
 }
Exemple #4
0
 /// <summary>
 /// See if all the subsystems can perform the most recent task that was added to the schedule
 /// </summary>
 /// <param name="subsystems"></param>
 /// <param name="proposedSchedule"></param>
 /// <param name="environment"></param>
 /// <returns></returns>
 private static bool checkSubs(List <Subsystem> subsystems, SystemSchedule proposedSchedule, Universe environment)
 {
     foreach (var sub in subsystems)
     {
         if (!sub.IsEvaluated && !checkSub(sub, proposedSchedule, environment))
         {
             return(false);
         }
     }
     return(true);
 }
Exemple #5
0
        private static bool CheckConstraints(SystemClass system, SystemSchedule proposedSchedule, Constraint constraint)
        {
            // pass the state for checking
            if (!constraint.Accepts(proposedSchedule.AllStates.GetLastState()))
            {
                Logger.Report("Constraint Failed: " + constraint.GetType().ToString());
                return(false);
            }


            return(true);
        }
Exemple #6
0
        public SystemSchedule(SystemSchedule oldSchedule, Stack <Access> newAccessList, double newEventStartTime)
        {
            Dictionary <Asset, Task>   tasks       = new Dictionary <Asset, Task>();
            Dictionary <Asset, double> taskStarts  = new Dictionary <Asset, double>();
            Dictionary <Asset, double> taskEnds    = new Dictionary <Asset, double>();
            Dictionary <Asset, double> eventStarts = new Dictionary <Asset, double>();
            Dictionary <Asset, double> eventEnds   = new Dictionary <Asset, double>();

            foreach (var access in newAccessList)
            {
                tasks.Add(access.Asset, access.Task); //shold this be a deep copy
                if (access.AccessStart < newEventStartTime && newEventStartTime < access.AccessEnd)
                {
                    taskStarts.Add(access.Asset, newEventStartTime);
                }
                else
                {
                    taskStarts.Add(access.Asset, access.AccessStart);
                }
                taskEnds.Add(access.Asset, access.AccessEnd);
                eventStarts.Add(access.Asset, newEventStartTime);
                eventEnds.Add(access.Asset, newEventStartTime + SchedParameters.SimStepSeconds);
            }
            Event eventToAdd = new Event(tasks, new SystemState(oldSchedule.GetEndState())); //all references

            eventToAdd.SetEventEnd(eventEnds);
            eventToAdd.SetTaskEnd(taskEnds);
            eventToAdd.SetEventStart(eventStarts);
            eventToAdd.SetTaskStart(taskStarts);
            AllStates = new StateHistory(oldSchedule.AllStates, eventToAdd);

            /* commented out because it doesn't work yet
             * // TODO (EAM):  Changed this so we need to double check/test
             * //int i = 0; //need a double iterator
             * foreach(var assetSchedAccess in newAccessList)
             * {
             * Task task = DeepCopy.Copy<Task>(assetSchedAccess.Task);
             * if (task != null)
             * {
             * Event eventToAdd = new Event(task, new SystemState(assetSchedAccess.Item1.GetLastState(), newTaskStartTime));
             * AssetScheds.Add(new StateHistory(assetSchedAccess.Item1, eventToAdd, assetSchedAccess.Item2.Asset));
             * //TODO: double check c# implementation above
             * // shared_ptr<Event> eventToAdd(new Event(*tIt, new State((*assSchedIt)->getLastState(), newTaskStartTime)));
             * // assetscheds.push_back(new assetSchedule(*assSchedIt, eventToAdd));
             * }
             * else
             * AssetScheds.Add(DeepCopy.Copy<StateHistory>(assetSchedAccess.Item1));
             * }
             */
        }
        public override double Evaluate(SystemSchedule schedule)
        {
            double sum = 0;

            foreach (Event eit in schedule.AllStates.Events)
            {
                foreach (KeyValuePair <Asset, Task> assetTask in eit.Tasks)
                {
                    Task task = assetTask.Value;
                    sum += 5 - task.Target.Value;
                    if (task.Type == TaskType.COMM)
                    {
                        sum += (double)Dependencies.getDependencyFunc("EvalfromSSDR").DynamicInvoke(eit);
                    }
                }
            }
            return(sum);
        }
Exemple #8
0
        public SystemSchedule(SystemSchedule oldSchedule, List <Task> newTaskList, double newTaskStartTime)
        {
            int i = 0; //need a double iterator

            foreach (AssetSchedule asIt in oldSchedule.AssetScheds)
            {
                Task tIt = newTaskList[i];
                if (tIt == null)
                {
                    Event eventToAdd = new Event(tIt, new SystemState(asIt.getLastState(), newTaskStartTime));
                    AssetScheds.Add(new AssetSchedule(asIt, eventToAdd));
                    //TODO: double check c# implementation above
                    // shared_ptr<Event> eventToAdd(new Event(*tIt, new State((*assSchedIt)->getLastState(), newTaskStartTime)));
                    // assetscheds.push_back(new assetSchedule(*assSchedIt, eventToAdd));
                }
                else
                {
                    AssetScheds.Add(DeepCopy.Copy <AssetSchedule>(asIt));
                }
                i++;
            }
        }
Exemple #9
0
        /// <summary>
        /// Method to check if the subsystem can perform the most recent task that was added to the schedule
        /// </summary>
        /// <param name="subsystem"></param>
        /// <param name="proposedSchedule"></param>
        /// <param name="environment"></param>
        /// <returns></returns>
        private static bool checkSub(Subsystem subsystem, SystemSchedule proposedSchedule, Universe environment)
        {
            if (subsystem.IsEvaluated)
            {
                return(true);
            }
            var events = proposedSchedule.AllStates.Events;

            if (events.Count != 0)
            {
                //if (events.Count > 1)
                //    subsystem._oldState = events.ElementAt(events.Count - 2).State;
                //else
                //    subsystem._oldState = null;

                if (!subsystem.CanPerform(events.Peek(), environment))
                {
                    return(false);
                }
                events.Peek().isEvaluated += 1;
            }
            return(true);
        }
Exemple #10
0
        /// <summary>
        /// Remove Schedules with the worst scores from the List of SystemSchedules so that there are only _maxNumSchedules.
        /// </summary>
        /// <param name="schedulesToCrop"></param>
        /// <param name="scheduleEvaluator"></param>
        /// <param name="emptySched"></param>
        void CropSchedules(List <SystemSchedule> schedulesToCrop, Evaluator scheduleEvaluator, SystemSchedule emptySched)
        {
            // Evaluate the schedules and set their values
            foreach (SystemSchedule systemSchedule in schedulesToCrop)
            {
                systemSchedule.ScheduleValue = scheduleEvaluator.Evaluate(systemSchedule);
            }

            // Sort the sysScheds by their values
            schedulesToCrop.Sort((x, y) => x.ScheduleValue.CompareTo(y.ScheduleValue));
            //  schedulesToCrop.ToList();
            // Delete the sysScheds that don't fit
            int j        = 0;
            int numSched = schedulesToCrop.Count;

            for (int i = numSched - 1; j < numSched - _maxNumSchedules; i--)
            {
                if (schedulesToCrop[i] != emptySched)
                {
                    schedulesToCrop.Remove(schedulesToCrop[i]);
                    j++;
                }
            }
        }
Exemple #11
0
        public virtual List <SystemSchedule> GenerateSchedules(SystemClass system, Stack <MissionElements.Task> tasks, SystemState initialStateList, Evaluator scheduleEvaluator)
        {
            //system.setThreadNum(1);
            //DWORD startTickCount = GetTickCount();
            //accumSchedTimeMs = 0;

            // get the global dependencies object
            //Dependencies dependencies = new Dependencies().Instance();

            Console.WriteLine("SIMULATING... ");
            // Create empty systemSchedule with initial state set
            SystemSchedule        emptySchedule   = new SystemSchedule(initialStateList);
            List <SystemSchedule> systemSchedules = new List <SystemSchedule>();

            systemSchedules.Add(emptySchedule);

            // if all asset position types are not dynamic types, can pregenerate accesses for the simulation
            bool canPregenAccess = true;

            foreach (var asset in system.Assets)
            {
                if (asset.AssetDynamicState != null)
                {
                    canPregenAccess &= asset.AssetDynamicState.Type != HSFUniverse.DynamicStateType.DYNAMIC_ECI && asset.AssetDynamicState.Type != HSFUniverse.DynamicStateType.DYNAMIC_LLA;
                }
                else
                {
                    canPregenAccess = false;
                }
            }

            // if accesses can be pregenerated, do it now
            Stack <Access>          preGeneratedAccesses = new Stack <Access>();
            Stack <Stack <Access> > scheduleCombos       = new Stack <Stack <Access> >();

            if (canPregenAccess)
            {
                Console.Write("Pregenerating Accesses...");
                //DWORD startPregenTickCount = GetTickCount();

                preGeneratedAccesses = Access.pregenerateAccessesByAsset(system, tasks, _startTime, _endTime, _stepLength);
                //DWORD endPregenTickCount = GetTickCount();
                //pregenTimeMs = endPregenTickCount - startPregenTickCount;
                //writeAccessReport(access_pregen, tasks); - TODO:  Finish this code - EAM
                Console.WriteLine(" DONE!");
            }
            // otherwise generate an exhaustive list of possibilities for assetTaskList
            else
            {
                Console.Write("Generating Exhaustive Task Combinations... ");
                Stack <Stack <Access> > exhaustive  = new Stack <Stack <Access> >();
                Stack <Access>          allAccesses = new Stack <Access>(tasks.Count);

                foreach (var asset in system.Assets)
                {
                    foreach (var task in tasks)
                    {
                        allAccesses.Push(new Access(asset, task));
                    }

                    exhaustive.Push(allAccesses);
                    allAccesses.Clear();
                }

                scheduleCombos = (Stack <Stack <Access> >)exhaustive.CartesianProduct();
                Console.WriteLine(" DONE!");
            }

            /// \todo TODO: Delete (or never create in the first place) schedules with inconsistent asset tasks (because of asset dependencies)

            // Find the next timestep for the simulation
            //DWORD startSchedTickCount = GetTickCount();

            for (double currentTime = _startTime; currentTime < _endTime; currentTime += _stepLength)
            {
                Console.WriteLine(currentTime);
                // if accesses are pregenerated, look up the access information and update assetTaskList
                if (canPregenAccess)
                {
                    scheduleCombos = GenerateExhaustiveSystemSchedules(preGeneratedAccesses, system, currentTime);
                }

                // Check if it's necessary to crop the systemSchedule list to a more managable number
                if (systemSchedules.Count > _maxNumSchedules)
                {
                    CropSchedules(systemSchedules, scheduleEvaluator, emptySchedule);
                }

                // Create a new system schedule list by adding each of the new Task commands for the Assets onto each of the old schedules
                // Start timing
                // Generate an exhaustive list of new tasks possible from the combinations of Assets and Tasks
                //TODO: Parallelize this.

                List <SystemSchedule> potentialSystemSchedules = new List <SystemSchedule>();

                foreach (var oldSystemSchedule in systemSchedules)
                {
                    foreach (var newAccessStack in scheduleCombos)
                    {
                        if (oldSystemSchedule.CanAddTasks(newAccessStack, currentTime))
                        {
                            SystemSchedule newSched = new SystemSchedule(oldSystemSchedule, newAccessStack, currentTime);
                            potentialSystemSchedules.Add(newSched);
                        }
                    }
                    potentialSystemSchedules.Add(new SystemSchedule(oldSystemSchedule));
                    //deep copy
                }

                // TODO EAM: Remove this and only add new SystemScedule if canAddTasks and CanPerform are both true.  That way we don't need to delete SystemSchedules after the fact below.
                List <SystemSchedule> systemCanPerformList = new List <SystemSchedule>();
                //for (list<systemSchedule*>::iterator newSchedIt = newSysScheds.begin(); newSchedIt != newSysScheds.end(); newSchedIt++)
                // The parallel version
                // Should we use a Partitioner?
                // Need to test this...

                /*
                 * Stopwatch stopWatch = new Stopwatch();
                 * stopWatch.Start();
                 * // The Scheduler has to call the CanPerform for a SystemClass, SystemSchedule combo.  The SystemClass
                 * Parallel.ForEach(potentialSystemSchedules, (currentSchedule) =>
                 * {
                 *  // dependencies.updateStates(newSchedule.getEndStates());
                 *  if (Checker.CheckSchedule(system, currentSchedule))
                 *      systemCanPerformList.Add(currentSchedule);
                 *  Console.WriteLine("Processing {0} on thread {1}", currentSchedule.ToString(), Thread.CurrentThread.ManagedThreadId);
                 * });
                 * stopWatch.Stop();
                 *
                 * TimeSpan ts = stopWatch.Elapsed;
                 * // Format and display the TimeSpan value.
                 * string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                 *  ts.Hours, ts.Minutes, ts.Seconds,
                 *  ts.Milliseconds / 10);
                 * Console.WriteLine("Parallel Scheduler RunTime: " + elapsedTime);
                 */
                foreach (var potentialSchedule in potentialSystemSchedules)
                {
                    if (Checker.CheckSchedule(system, potentialSchedule))
                    {
                        systemCanPerformList.Add(potentialSchedule);
                    }
                    //dependencies.updateStates(newSchedule.getEndStates());
                    //systemCanPerformList.Push(system.canPerform(potentialSchedule));
                }

                // End timing

                /*
                 * // delete systemSchedules (and corresponding lower level classes) that are not possible
                 * list<systemSchedule*>::iterator eraseIt = newSysScheds.begin();
                 * for (vector<bool>::iterator successIt = systemCanPerformList.begin(); successIt != systemCanPerformList.end(); successIt++)
                 * {
                 *  if (*successIt) { eraseIt++; }
                 *  else {
                 *      delete* eraseIt;
                 *      eraseIt = newSysScheds.erase(eraseIt);
                 *  }
                 * }
                 */

                // Merge old and new systemSchedules
                systemSchedules.InsertRange(0, systemCanPerformList);//<--This was potentialSystemSchedules
                potentialSystemSchedules.Clear();
                // Print completion percentage in command window
                Console.Write("Scheduler Status: {0} done; {1} schedules generated.", 100 * currentTime / _endTime, systemSchedules.Count);
            }


            if (systemSchedules.Count > _maxNumSchedules)
            {
                CropSchedules(systemSchedules, scheduleEvaluator, emptySchedule);
            }

            // THIS GOES AWAY IF CAN EXTEND HAPPENS IN THE SUBSYSTEM - EAM
            // extend all schedules to the end of the simulation

            /*
             * foreach (var schedule in systemSchedules)
             * {
             *  bool canExtendUntilEnd = true;
             *  // Iterate through Subsystem Nodes and set that they havent run
             *  foreach (var subsystem in system.Subsystems)
             *      subsystem.IsEvaluated = false;
             *
             *  int subAssetNum;
             *  foreach (var subsystem in system.Subsystems)
             *      canExtendUntilEnd &= subsystem.canPerform(schedule.getSubsystemNewState(subsystem.Asset), schedule.getSubsytemNewTask(subsystem.Asset), system.Environment, _endTime, true);
             *
             *  // Iterate through constraints
             *  foreach (var constraint in system.Constraints)
             *  {
             *      canExtendUntilEnd &= constraint.Accepts(schedule);
             *  }
             *  //                for (vector <const Constraint*>::const_iterator constraintIt = system.getConstraints().begin(); constraintIt != system.getConstraints().end(); constraintIt++)
             *  //            canExtendUntilEnd &= (*constraintIt)->accepts(*schedIt);
             *  if (!canExtendUntilEnd) {
             *      //delete *schedIt;
             *      Console.WriteLine("Schedule may not be valid");
             *  }
             * }
             */

            //DWORD endSchedTickCount = GetTickCount();
            //schedTimeMs = endSchedTickCount - startSchedTickCount;

            //DWORD endTickCount = GetTickCount();
            //totalTimeMs = endTickCount - startTickCount;

            return(systemSchedules);
        }
Exemple #12
0
 public SystemSchedule(SystemSchedule oldSchedule, Event emptyEvent)
 {
     AllStates = new StateHistory(oldSchedule.AllStates);
     AllStates.Events.Push(emptyEvent);
 }
Exemple #13
0
        /// <summary>
        /// Utilitiy method to write the schedule to csv file
        /// </summary>
        /// <param name="schedule"></param>
        /// <param name="scheduleWritePath"></param>
        public static void WriteSchedule(SystemSchedule schedule, String scheduleWritePath)
        {
            var csv = new StringBuilder();
            Dictionary <StateVarKey <double>, SortedList <double, double> > stateTimeDData = new Dictionary <StateVarKey <double>, SortedList <double, double> >();
            Dictionary <StateVarKey <int>, SortedList <double, int> >       stateTimeIData = new Dictionary <StateVarKey <int>, SortedList <double, int> >();
            Dictionary <StateVarKey <int>, SortedList <double, int> >       stateTimeBData = new Dictionary <StateVarKey <int>, SortedList <double, int> >(); // need 0s and 1 for matlab to read in csv
            Dictionary <StateVarKey <Matrix <double> >, SortedList <double, Matrix <double> > > stateTimeMData = new Dictionary <StateVarKey <Matrix <double> >, SortedList <double, Matrix <double> > >();

            string stateTimeData = "Time,";
            string stateData     = "";

            csv.Clear();
            SystemState sysState = schedule.AllStates.Events.Peek().State;

            while (sysState != null)
            {
                foreach (var kvpDoubleProfile in sysState.Ddata)
                {
                    foreach (var data in kvpDoubleProfile.Value.Data)
                    {
                        if (!stateTimeDData.ContainsKey(kvpDoubleProfile.Key))
                        {
                            var lt = new SortedList <double, double>();
                            lt.Add(data.Key, data.Value);
                            stateTimeDData.Add(kvpDoubleProfile.Key, lt);
                        }
                        else if (!stateTimeDData[kvpDoubleProfile.Key].ContainsKey(data.Key))
                        {
                            stateTimeDData[kvpDoubleProfile.Key].Add(data.Key, data.Value);
                        }
                        else
                        {
                            Console.WriteLine("idk");
                        }
                    }
                }

                foreach (var kvpIntProfile in sysState.Idata)
                {
                    foreach (var data in kvpIntProfile.Value.Data)
                    {
                        if (!stateTimeIData.ContainsKey(kvpIntProfile.Key))
                        {
                            var lt = new SortedList <double, int>();
                            lt.Add(data.Key, data.Value);
                            stateTimeIData.Add(kvpIntProfile.Key, lt);
                        }
                        else if (!stateTimeIData[kvpIntProfile.Key].ContainsKey(data.Key))
                        {
                            stateTimeIData[kvpIntProfile.Key].Add(data.Key, data.Value);
                        }
                    }
                }

                foreach (var kvpBoolProfile in sysState.Bdata)
                {
                    foreach (var data in kvpBoolProfile.Value.Data)
                    {
                        if (!stateTimeBData.ContainsKey(kvpBoolProfile.Key))
                        {
                            var lt = new SortedList <double, int>();
                            lt.Add(data.Key, (data.Value ? 1 : 0)); //convert to int for matlab to read in for csv
                            stateTimeBData.Add((StateVarKey <int>)kvpBoolProfile.Key, lt);
                        }
                        else if (!stateTimeBData[kvpBoolProfile.Key].ContainsKey(data.Key))
                        {
                            stateTimeBData[(StateVarKey <int>)kvpBoolProfile.Key].Add(data.Key, data.Value ? 1 : 0);
                        }
                    }
                }

                foreach (var kvpMatrixProfile in sysState.Mdata)
                {
                    foreach (var data in kvpMatrixProfile.Value.Data)
                    {
                        if (!stateTimeMData.ContainsKey(kvpMatrixProfile.Key))
                        {
                            var lt = new SortedList <double, Matrix <double> >();
                            lt.Add(data.Key, data.Value);
                            stateTimeMData.Add(kvpMatrixProfile.Key, lt);
                        }
                        else if (!stateTimeMData[kvpMatrixProfile.Key].ContainsKey(data.Key))
                        {
                            stateTimeMData[kvpMatrixProfile.Key].Add(data.Key, data.Value);
                        }
                    }
                }
                sysState = sysState.Previous;
            }

            System.IO.Directory.CreateDirectory(scheduleWritePath);

            foreach (var list in stateTimeDData)
            {
                writeStateVariable(list, scheduleWritePath);
            }

            foreach (var list in stateTimeIData)
            {
                writeStateVariable(list, scheduleWritePath);
            }

            foreach (var list in stateTimeBData)
            {
                writeStateVariable(list, scheduleWritePath);
            }

            foreach (var list in stateTimeMData)
            {
                writeStateVariable(list, scheduleWritePath);
            }
        }
Exemple #14
0
 /// <summary>
 /// Determine if the first schedule value is greater than the second
 /// </summary>
 /// <param name="elem1"></param>
 /// <param name="elem2"></param>
 /// <returns></returns>
 bool SchedGreater(SystemSchedule elem1, SystemSchedule elem2)
 {
     return(elem1.ScheduleValue > elem2.ScheduleValue);
 }
Exemple #15
0
        /// <summary>
        /// Remove Schedules with the worst scores from the List of SystemSchedules so that there are only _maxNumSchedules.
        /// </summary>
        /// <param name="schedulesToCrop"></param>
        /// <param name="scheduleEvaluator"></param>
        /// <param name="emptySched"></param>
        public void CropSchedules(List <SystemSchedule> schedulesToCrop, Evaluator scheduleEvaluator, SystemSchedule emptySched)
        {
            // Evaluate the schedules and set their values
            foreach (SystemSchedule systemSchedule in schedulesToCrop)
            {
                systemSchedule.ScheduleValue = scheduleEvaluator.Evaluate(systemSchedule);
            }

            // Sort the sysScheds by their values
            schedulesToCrop.Sort((x, y) => x.ScheduleValue.CompareTo(y.ScheduleValue));

            // Delete the sysScheds that don't fit
            int numSched = schedulesToCrop.Count;

            for (int i = 0; i < numSched - _numSchedCropTo; i++)
            {
                schedulesToCrop.Remove(schedulesToCrop[0]);
            }

            schedulesToCrop.TrimExcess();
        }
Exemple #16
0
 /// <summary>
 /// Anstract class that analyzes the given schedule and assigns a value to it.
 /// </summary>
 /// <param name="schedule"></param>
 /// <returns></returns>
 public abstract double Evaluate(SystemSchedule schedule);
Exemple #17
0
 /// <summary>
 /// Copy constructor to preserve the without adding a task
 /// </summary>
 /// <param name="oldSchedule"></param>
 public SystemSchedule(SystemSchedule oldSchedule)
 {
     AllStates = new StateHistory(oldSchedule.AllStates);
 }
Exemple #18
0
        /// <summary>
        /// Generate schedules by adding a new event to the end of existing ones
        /// Create a new system schedule list by adding each of the new Task commands for the Assets onto each of the old schedules
        /// </summary>
        /// <param name="system"></param>
        /// <param name="tasks"></param>
        /// <param name="initialStateList"></param>
        /// <returns></returns>
        public virtual List <SystemSchedule> GenerateSchedules(SystemClass system, Stack <Task> tasks, SystemState initialStateList)
        {
            log.Info("SIMULATING... ");
            // Create empty systemSchedule with initial state set
            SystemSchedule        emptySchedule   = new SystemSchedule(initialStateList);
            List <SystemSchedule> systemSchedules = new List <SystemSchedule>();

            systemSchedules.Add(emptySchedule);

            // if all asset position types are not dynamic types, can pregenerate accesses for the simulation
            bool canPregenAccess = true;

            foreach (var asset in system.Assets)
            {
                if (asset.AssetDynamicState != null)
                {
                    canPregenAccess &= asset.AssetDynamicState.Type != HSFUniverse.DynamicStateType.DYNAMIC_ECI && asset.AssetDynamicState.Type != HSFUniverse.DynamicStateType.DYNAMIC_LLA;
                }
                else
                {
                    canPregenAccess = false;
                }
            }

            // if accesses can be pregenerated, do it now
            Stack <Access>          preGeneratedAccesses = new Stack <Access>();
            Stack <Stack <Access> > scheduleCombos       = new Stack <Stack <Access> >();

            if (canPregenAccess)
            {
                log.Info("Pregenerating Accesses...");
                //DWORD startPregenTickCount = GetTickCount();

                preGeneratedAccesses = Access.pregenerateAccessesByAsset(system, tasks, _startTime, _endTime, _stepLength);
                //DWORD endPregenTickCount = GetTickCount();
                //pregenTimeMs = endPregenTickCount - startPregenTickCount;
                //writeAccessReport(access_pregen, tasks); - TODO:  Finish this code - EAM
                log.Info("Done pregenerating accesses");
            }
            // otherwise generate an exhaustive list of possibilities for assetTaskList
            else
            {
                log.Info("Generating Exhaustive Task Combinations... ");
                Stack <Stack <Access> > exhaustive  = new Stack <Stack <Access> >();
                Stack <Access>          allAccesses = new Stack <Access>(tasks.Count);

                foreach (var asset in system.Assets)
                {
                    foreach (var task in tasks)
                    {
                        allAccesses.Push(new Access(asset, task));
                    }
                    allAccesses.Push(new Access(asset, null));
                    exhaustive.Push(allAccesses);
                    allAccesses.Clear();
                }

                scheduleCombos = (Stack <Stack <Access> >)exhaustive.CartesianProduct();
                log.Info("Done generating exhaustive task combinations");
            }

            /// TODO: Delete (or never create in the first place) schedules with inconsistent asset tasks (because of asset dependencies)

            // Find the next timestep for the simulation
            //DWORD startSchedTickCount = GetTickCount();
            int i = 1;
            List <SystemSchedule> potentialSystemSchedules = new List <SystemSchedule>();
            List <SystemSchedule> systemCanPerformList     = new List <SystemSchedule>();

            for (double currentTime = _startTime; currentTime < _endTime; currentTime += _stepLength)
            {
                log.Info("Simulation Time " + currentTime);
                // if accesses are pregenerated, look up the access information and update assetTaskList
                if (canPregenAccess)
                {
                    scheduleCombos = GenerateExhaustiveSystemSchedules(preGeneratedAccesses, system, currentTime);
                }

                // Check if it's necessary to crop the systemSchedule list to a more managable number
                if (systemSchedules.Count > _maxNumSchedules)
                {
                    log.Info("Cropping " + systemSchedules.Count + " Schedules.");
                    CropSchedules(systemSchedules, ScheduleEvaluator, emptySchedule);
                    systemSchedules.Add(emptySchedule);
                }

                // Generate an exhaustive list of new tasks possible from the combinations of Assets and Tasks
                //TODO: Parallelize this.
                int k = 0;

                foreach (var oldSystemSchedule in systemSchedules)
                {
                    potentialSystemSchedules.Add(new SystemSchedule(new StateHistory(oldSystemSchedule.AllStates)));
                    foreach (var newAccessStack in scheduleCombos)
                    {
                        k++;
                        if (oldSystemSchedule.CanAddTasks(newAccessStack, currentTime))
                        {
                            var CopySchedule = new StateHistory(oldSystemSchedule.AllStates);
                            potentialSystemSchedules.Add(new SystemSchedule(CopySchedule, newAccessStack, currentTime));
                            // oldSched = new SystemSchedule(CopySchedule);
                        }
                    }
                }

                int numSched = 0;
                foreach (var potentialSchedule in potentialSystemSchedules)
                {
                    if (Checker.CheckSchedule(system, potentialSchedule))
                    {
                        systemCanPerformList.Add(potentialSchedule);
                    }
                    numSched++;
                }
                foreach (SystemSchedule systemSchedule in systemCanPerformList)
                {
                    systemSchedule.ScheduleValue = ScheduleEvaluator.Evaluate(systemSchedule);
                }

                systemCanPerformList.Sort((x, y) => x.ScheduleValue.CompareTo(y.ScheduleValue));
                systemCanPerformList.Reverse();
                // Merge old and new systemSchedules
                var oldSystemCanPerfrom = new List <SystemSchedule>(systemCanPerformList);
                systemSchedules.InsertRange(0, oldSystemCanPerfrom);//<--This was potentialSystemSchedules
                potentialSystemSchedules.Clear();
                systemCanPerformList.Clear();
                // Print completion percentage in command window
                Console.WriteLine("Scheduler Status: {0}% done; {1} schedules generated.", 100 * currentTime / _endTime, systemSchedules.Count);
            }
            return(systemSchedules);
        }
        /// <summary>
        /// Implementation of the evaluate method
        /// </summary>
        /// <param name="schedule"></param>
        /// <returns></returns>
        public override double Evaluate(SystemSchedule schedule)
        {
            dynamic eval = _pythonInstance.Evaluate(schedule);

            return((double)eval);
        }