예제 #1
0
        //! Calculate number of Conflicts in the schedule

        /*!
         *  \param ContactWindowVector schedule to calculate fairness
         *  \return int number of overall conflicting contact windows
         */
        public static int getNrOfConflicts(ContactWindowsVector contacts)
        {
            int            nrOfConflicts = 0;
            HashSet <Guid> hashConflict  = new HashSet <Guid>();

            for (int i = 0; i < contacts.Count(); i++)
            {
                for (int k = 0; k < contacts.Count(); k++)
                {
                    if (i != k && contacts.getAt(i).getSheduledInfo() &&
                        contacts.getAt(k).getSheduledInfo() &&
                        contacts.getAt(i).checkConflikt(contacts.getAt(k)))
                    {
                        if (contacts.getAt(k).getSatName() == contacts.getAt(i).getSatName() ||
                            contacts.getAt(k).getStationName() == contacts.getAt(i).getStationName())
                        {
                            if (!hashConflict.Contains(contacts.getAt(k).getID()))
                            {
                                nrOfConflicts++;
                                hashConflict.Add(contacts.getAt(i).getID());
                            }
                        }
                    }
                }
            }
            hashConflict.Clear();
            return(nrOfConflicts);
        }
예제 #2
0
        //! calculate the fitness value of the given contactvectors if a contact is added

        /*!
         * \param ContactWindowsVector contact windows to check
         * \param CotnactWindowsVector contacts of the complete problem
         * \param int max number of Contacts of the Scheduling problem
         * \param ContactWindow to add
         */
        // Call to calculate Objective Values for Fitness
        public void calculateValues(ContactWindowsVector currentSolution, ContactWindowsVector completeContacts, int numberOfAllContacts,
                                    ContactWindow contactToAdd)
        {
            currentSolution.add(contactToAdd);
            calculate(currentSolution, calcualteMaxPrioValue(completeContacts), numberOfAllContacts, null, completeContacts);
            currentSolution.deleteAt(currentSolution.Count() - 1);
        }
예제 #3
0
        private int calcualteMaxPrioValue(ContactWindowsVector contacts, int[] population = null)
        {
            int[] priorityCounts = new int[5] {
                0, 0, 0, 0, 0,
            };
            int res = 0;

            for (int i = 0; i < contacts.Count(); i++)
            {
                int p = 0;
                if (population != null)
                {
                    if (population[i] == 1)
                    {
                        p = (int)contacts.getAt(i).getPriority();
                    }
                }
                else
                {
                    p = (int)contacts.getAt(i).getPriority();
                }
                priorityCounts[p]++;
            }
            for (int i = 0; i < priorityCounts.Count(); i++)
            {
                res += priorityCounts[i] * (5 - i);
            }
            return(res);
        }
예제 #4
0
 private void fillContacts(ContactWindowsVector contacts)
 {
     for (int i = 0; i < contacts.Count(); i++)
     {
         bool confilcts = false;
         if (!contacts.getAt(i).getSheduledInfo())
         {
             for (int j = 0; j < contacts.Count(); j++)
             {
                 if (contacts.getAt(j).getSheduledInfo() && i != j && contacts.getAt(i).checkConflikt(contacts.getAt(j)))
                 {
                     if (contacts.getAt(i).getStationName() == contacts.getAt(j).getStationName() ||
                         contacts.getAt(i).getSatName() == contacts.getAt(j).getSatName())
                     {
                         confilcts = true;
                         break;
                     }
                 }
             }
         }
         if (!confilcts)
         {
             contacts.getAt(i).setSheduled();
         }
     }
 }
예제 #5
0
        //! Create and save all scheduling data

        /*!
         * \param string path and name of file to save
         * \param ContactWindowsVector contacts to save
         */
        public static void saveToFile(string filePathName, ContactWindowsVector contacts, Main f)
        {
            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            XmlWriter writer = XmlWriter.Create(filePathName, settings);

            writer.WriteStartDocument();
            writer.WriteStartElement("Contacts");
            writer.WriteElementString("StartYear", contacts.getStartTime().getYear().ToString());
            writer.WriteElementString("StartEpoch", contacts.getStartTime().getEpoch().ToString());
            writer.WriteElementString("StopYear", contacts.getStopTime().getYear().ToString());
            writer.WriteElementString("StopEpoch", contacts.getStopTime().getEpoch().ToString());
            List <ContactWindow> cwList = contacts.getAllContacts();

            f.setProgressBar(cwList.Count());
            int count = 0;

            foreach (ContactWindow cw in cwList)
            {
                writer.WriteStartElement("ContactWindow");
                writer.WriteElementString("SatName", cw.getSatName());
                writer.WriteElementString("StaName", cw.getStationName());
                writer.WriteElementString("StartTime", cw.getStartTime().getEpoch().ToString());
                writer.WriteElementString("StartYear", cw.getStartTime().getYear().ToString());
                writer.WriteElementString("StopTime", cw.getStopTime().getEpoch().ToString());
                writer.WriteElementString("StopYear", cw.getStopTime().getYear().ToString());
                writer.WriteElementString("Scheduled", cw.getSheduledInfo().ToString());
                writer.WriteElementString("Excluded", cw.getExclusion().ToString());
                writer.WriteElementString("ID", cw.getID().ToString());
                writer.WriteElementString("RequID", cw.getRequestID().ToString());
                writer.WriteElementString("Priority", cw.getPriority().ToString());

                writer.WriteStartElement("TrackingData");
                List <TrackingData> tdList = cw.getTrackingData();
                foreach (TrackingData td in tdList)
                {
                    writer.WriteStartElement("Data");
                    writer.WriteElementString("Azimuth", td.getAzimuth().ToString());
                    writer.WriteElementString("Elevation", td.getElevation().ToString());
                    writer.WriteElementString("Range", td.getRange().ToString());
                    writer.WriteElementString("RangeRate", td.getRangeRate().ToString());
                    writer.WriteElementString("TimeStamp", td.getTimeStamp());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
                f.updateProgressBar(count++);
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
            writer.Dispose();
            f.resetProgressBar();
        }
예제 #6
0
        public static double getDurationOfScheduledContacts(ContactWindowsVector contacts)
        {
            double duration = 0.0;

            for (int i = 0; i < contacts.Count(); i++)
            {
                if (contacts.getAt(i).getSheduledInfo())
                {
                    duration += contacts.getAt(i).getDuration();
                }
            }
            return(duration);
        }
예제 #7
0
        //! Set the finall schedule

        /*!
         *  \param int[] current populus
         *  \param ContactWindowsVector starting contactwindows
         *  Each contact windows will be scheduled or unscheduled defined by the found solution
         */
        private void setSchedule(int[] pop, ContactWindowsVector contacts)
        {
            for (int i = 0; i < nrOfContacts; i++)
            {
                if (pop[i] == 1)
                {
                    contacts.getAt(i).setSheduled();
                }
                else
                {
                    contacts.getAt(i).unShedule();
                }
            }
        }
예제 #8
0
        //Test Function
        public static string getNrOfUweContacts(ContactWindowsVector contacts)
        {
            int count = 0;

            for (int i = 0; i < contacts.Count(); i++)
            {
                if (contacts.getAt(i).getSheduledInfo() &&
                    contacts.getAt(i).getSatName() == "UWE-3")
                {
                    count++;
                }
            }
            return("UWE-3: " + count);
        }
예제 #9
0
        //!GreedyScheduler constructor.

        /*!
         *  constructs a basic greedy scheduler
         */
        public GreedyScheduler()
        {
            generateLog      = Properties.Settings.Default.global_SaveLogs_Path;
            generatePlotData = Properties.Settings.Default.PlotData;
            plotPath         = Properties.Settings.Default.global_Save_Path;
            if (generatePlotData > 0)
            {
                //create File to write in to
                string plotname = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
                                  + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Hour.ToString()
                                  + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                plotname = plotname + "-FairGreedy";
                plotWr   = new System.IO.StreamWriter(plotPath + "\\" + plotname, true);
            }
            schedule = new ContactWindowsVector();
        }
예제 #10
0
        //! set the Scheduling Problem

        /*!
         *  /param ContactWindowsVector contacts to schedule
         *  /param ObjectiveFunction obective to solve problems
         */
        public static SchedulingProblem setSchedulingProblem(ContactWindowsVector contacts, ObjectiveFunction objective)
        {
            SchedulingProblem problem = new SchedulingProblem();

            problem.setContactWindows(contacts);
            problem.removeUnwantedContacts(Properties.Settings.Default.orbit_Minimum_Contact_Duration_sec);
            problem.setObjectiveFunction(objective);

            /*
             * The contact windows that have been calculate are randomized
             * to imporve the result of the greedy algorithms. If the
             * turning the randomiziation off will lead to the greedy
             * algorithms to only schedule contacts for the first few
             * groundstation ignoring others.
             */
            problem.getContactWindows().randomize(Properties.Settings.Default.global_Random_Seed);
            return(problem);
        }
        //! Calculates a schedule from the defined problem

        /*!
         *  \pram ScheduleProblemInterface defined problem with contactwindows
         *  This Function will calculate the solution to the problem defined in
         *  Schedule Problem Interface
         */
        public void CalculateSchedule(ScheduleProblemInterface problem)
        {
            set      = problem.getContactWindows();
            schedule = new ContactWindowsVector();
            set.sort(Structs.sortByField.TIME);
            while (!isComplete())
            {
                for (int i = 0; i < set.Count(); i++)
                {
                    bool       collisionFound = false;
                    List <int> collisionSet   = new List <int>();
                    collisionSet.Add(i);
                    for (int j = 1; j < set.Count() - 1; j++)
                    {
                        collisionFound = checkCollision(set.getAt(i), set.getAt(j));
                        collisionSet.Add(j);
                    }
                    if (collisionFound)
                    {
                        set.getAt(i).setSheduled();
                        for (int k = 0; k < collisionSet.Count - 1; k++)
                        {
                            set.getAt(collisionSet[k]).unShedule();
                        }
                    }
                    else
                    {
                        schedule.add(set.getAt(i));
                        set.deleteAt(i);
                        i--;
                    }
                }
            }
            //retrive all the contactwindows that need to be scheduled
            //ContactWindowsVector set = problem.getContactWindows();
            //Scheduler Magic until is Complete returns true
            //No Element of the ContactWindowsVector set should be deleted
            //To Schedule a item call set.getAt(index).setSheduled()
            //To Unschedule a item call set.getAt(index).unShedule()
        }
예제 #12
0
        //! Open and Load saved scheduling data

        /*!
         * \param string path to Load file
         * \param Main Form to update loading bar
         */
        public static ContactWindowsVector loadFile(string filepath, Main f)
        {
            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(filepath);
            XmlNodeList dataNodes = xmlDoc.SelectNodes("//Contacts/ContactWindow");

            f.setProgressBar(dataNodes.Count);

            int    startYear  = Int32.Parse(xmlDoc.SelectSingleNode("//Contacts/StartYear").InnerText);
            double startEpoch = double.Parse(xmlDoc.SelectSingleNode("//Contacts/StartEpoch").InnerText);
            int    stopYear   = Int32.Parse(xmlDoc.SelectSingleNode("//Contacts/StopYear").InnerText);
            double stopEpoch  = double.Parse(xmlDoc.SelectSingleNode("//Contacts/StopEpoch").InnerText);

            One_Sgp4.EpochTime start = new One_Sgp4.EpochTime(startYear, startEpoch);
            One_Sgp4.EpochTime stop  = new One_Sgp4.EpochTime(stopYear, stopEpoch);

            ContactWindowsVector saved = new ContactWindowsVector();

            saved.setStartTime(start);
            saved.setStopTime(stop);
            int count = 0;

            foreach (XmlNode node in dataNodes)
            {
                string             sa        = node.SelectSingleNode("SatName").InnerText;
                string             st        = node.SelectSingleNode("StaName").InnerText;
                int                year      = Int32.Parse(node.SelectSingleNode("StartYear").InnerText);
                double             epoch     = double.Parse(node.SelectSingleNode("StartTime").InnerText);
                ContactWindow      cw        = new ContactWindow(sa, st);
                One_Sgp4.EpochTime starttime = new One_Sgp4.EpochTime(year, epoch);
                cw.setStartTime(starttime);
                year  = Int32.Parse(node.SelectSingleNode("StopYear").InnerText);
                epoch = double.Parse(node.SelectSingleNode("StopTime").InnerText);
                One_Sgp4.EpochTime stoptime = new One_Sgp4.EpochTime(year, epoch);
                cw.setStopTime(stoptime);
                if (node.SelectSingleNode("Scheduled").InnerText != "False")
                {
                    cw.setSheduled();
                }
                cw.setExclusion(bool.Parse(node.SelectSingleNode("Scheduled").InnerText));
                cw.setID(Guid.Parse(node.SelectSingleNode("ID").InnerText));
                cw.setRequestID(Guid.Parse(node.SelectSingleNode("RequID").InnerText));
                cw.setPriority(Global.Funktions.ParseEnum <Global.Structs.priority>(node.SelectSingleNode("Priority").InnerText));

                XmlNodeList children = node.SelectNodes("TrackingData/Data");
                foreach (XmlNode childNode in children)
                {
                    double       azi  = double.Parse(childNode.SelectSingleNode("Azimuth").InnerText);
                    double       ele  = double.Parse(childNode.SelectSingleNode("Elevation").InnerText);
                    double       ran  = double.Parse(childNode.SelectSingleNode("Range").InnerText);
                    double       ranR = double.Parse(childNode.SelectSingleNode("RangeRate").InnerText);
                    string       time = childNode.SelectSingleNode("TimeStamp").InnerText;
                    TrackingData td   = new TrackingData(azi, ele, ran, time);
                    cw.addTrackingData(td);
                }
                f.updateProgressBar(count++);
                System.Windows.Forms.Application.DoEvents();
                saved.add(cw);
            }
            f.resetProgressBar();
            return(saved);
        }
예제 #13
0
        public bool runThisRun()
        {
            results = new List <string>();
            DataBase.DataBase db = new DataBase.DataBase();
            bool status          = true;
            List <Ground.Station> stationData = new List <Ground.Station>();

            for (int i = 0; i < stationList.Count; i++)
            {
                Ground.Station station = db.getStationFromDB(stationList[i]);
                stationData.Add(station);
                //updateLog(logfile, "Adding Station: " + station.getName());
            }
            System.Windows.Forms.Application.DoEvents();
            List <One_Sgp4.Tle> tleData = new List <Tle>();

            for (int i = 0; i < satelliteList.Count; i++)
            {
                One_Sgp4.Tle sattle = db.getTleDataFromDB(satelliteList[i]);
                tleData.Add(sattle);
                //updateLog(logfile, "Adding Satellite: " + sattle.getName());
            }
            System.Windows.Forms.Application.DoEvents();
            ContactWindowsVector contactsVector = MainFunctions2.calculateContactWindows(tleData, stationData, startTime, stopTime);

            System.Windows.Forms.Application.DoEvents();
            scheduler = null;
            switch (schedulerName)
            {
            case "Genetic":
                string[] settString = settings.Split(';');
                scheduler = new GeneticScheduler(Convert.ToInt32(settString[0]), Convert.ToInt32(settString[1]),
                                                 Convert.ToInt32(settString[2]), Convert.ToInt32(settString[4]), Convert.ToBoolean(settString[5]),
                                                 Convert.ToDouble(settString[6]), Convert.ToBoolean(settString[7]), Convert.ToBoolean(settString[8]));
                break;

            case "Greedy":
                scheduler = new GreedyScheduler();
                break;

            case "EFT-Greedy":
                scheduler = new EftGreedyScheduler();
                break;

            case "Hill-Climber":
                string[] settString2 = settings.Split(';');
                scheduler = new HillClimberScheduler(Convert.ToBoolean(settString2[0]), Convert.ToBoolean(settString2[2]),
                                                     Convert.ToInt32(settString2[1]));
                break;
            }
            ObjectiveFunction objective = new ObjectiveFunction(Forms.ObjectiveBuilderForm.getObjectiveEnumsByName(objectiveFunction));

            System.Windows.Forms.Application.DoEvents();
            SchedulingProblem problem = new SchedulingProblem();

            problem.setContactWindows(contactsVector);
            problem.removeUnwantedContacts(Properties.Settings.Default.orbit_Minimum_Contact_Duration_sec);
            problem.setObjectiveFunction(objective);
            problem.getContactWindows().randomize(Properties.Settings.Default.global_Random_Seed);
            getScenario(problem, scenario);
            System.Windows.Forms.Application.DoEvents();
            TimeMeasurement tm = new TimeMeasurement();

            tm.activate();
            scheduler.CalculateSchedule(problem);
            string time = tm.getValueAndDeactivate();

            System.Windows.Forms.Application.DoEvents();
            contactsVector = scheduler.getFinischedSchedule();
            System.Windows.Forms.Application.DoEvents();


            if (scheduler != null)
            {
                ObjectiveFunction objfunc = scheduler.getObjectiveFunction();
                if (objfunc == null)
                {
                    objfunc = new ObjectiveFunction();
                }
                objfunc.calculateValues(scheduler.getFinischedSchedule());

                double fitness = objfunc.getObjectiveResults();

                int    _H  = scheduler.getFinischedSchedule().getNrOfScheduled();
                double _H1 = objfunc.getScheduledContactsValue();
                int    _H2 = GeneralMeasurments.getNrOfConflicts(scheduler.getFinischedSchedule());
                double _H3 = objfunc.getStationFairnessValue();
                double _H4 = objfunc.getSatelliteFairnessValue();
                double _H5 = GeneralMeasurments.getDurationOfScheduledContacts(scheduler.getFinischedSchedule());

                results.Add("Run: " + schedulerName);
                results.Add("Fitness Value:" + objfunc.getObjectiveResults().ToString());
                results.Add("Scheduled Contacts: " + scheduler.getFinischedSchedule().getNrOfScheduled().ToString() + " / " + contactsVector.Count().ToString());
                results.Add("Collisions: " + GeneralMeasurments.getNrOfConflicts(scheduler.getFinischedSchedule()).ToString());
                results.Add("Fairnes Stations: " + objfunc.getStationFairnessValue().ToString());
                results.Add("Fairnes Satellites: " + objfunc.getSatelliteFairnessValue().ToString());
                results.Add("Duration: " + GeneralMeasurments.getDurationOfScheduledContacts(scheduler.getFinischedSchedule()).ToString() + " sec.");
                results.Add("Calculation Time: " + time);
                results.Add("Scheduled By Priority: " + GeneralMeasurments.getNrOfPrioritysScheduled(scheduler.getFinischedSchedule()));
                results.Add("Scheduled UWE-3: " + GeneralMeasurments.getNrOfUweContacts(scheduler.getFinischedSchedule()).ToString());

                //Log.writeResults(logfile, schedulerName, results);
                if (results == null)
                {
                    status = false;
                }
            }
            else
            {
                status = false;
            }
            cancel = false;
            return(status);
        }
예제 #14
0
        //! Calculate scheduling solution from certain startpoint

        /*!
         *  calculate a schedule from a certain starting point
         *  if iterating trhough every contact window can be used to brute force
         *  the scheduling solution
         *  \param ScheduleProblemInterface to solve scheduling problem
         *  \param int point from which to start from
         */
        public void BruteForceSchedule(ScheduleProblemInterface problem, int step)
        {
            objective = problem.getObjectiveFunction();
            set       = problem.getContactWindows();
            int nrOfAllContacts = set.Count();

            ContactWindowsVector set1 = new ContactWindowsVector();
            ContactWindowsVector set2 = new ContactWindowsVector();

            //double maxFitness = 0.0;
            int count = 0;

            set1.add(set.getAt(step));
            set.deleteAt(step);

            while (!isComplete())
            {
                int    pos        = -1;
                double maxFitness = 0.0;
                for (int i = 0; i < set.Count(); i++)
                {
                    objective.calculateValues(set1, set, nrOfAllContacts, set.getAt(i));
                    double fitness = objective.getObjectiveResults();
                    if (fitness > maxFitness)
                    {
                        maxFitness = fitness;
                        pos        = i;
                    }
                    if (Properties.Settings.Default.global_MaxPerf == false)
                    {
                        System.Windows.Forms.Application.DoEvents();
                    }
                }

                bool found = false;
                if (pos >= 0)
                {
                    for (int i = 0; i < set1.Count(); i++)
                    {
                        if (set.getAt(pos).checkConflikt(set1.getAt(i)))
                        {
                            if (set.getAt(pos).getSatName() == set1.getAt(i).getSatName() ||
                                set.getAt(pos).getStationName() == set1.getAt(i).getStationName())
                            {
                                set2.add(set.getAt(pos));
                                set2.getLast().unShedule();
                                set.deleteAt(pos);
                                found = true;
                                break;
                            }
                        }
                        if (Properties.Settings.Default.global_MaxPerf == false)
                        {
                            System.Windows.Forms.Application.DoEvents();
                        }
                    }
                    if (!found)
                    {
                        set1.add(set.getAt(pos));
                        set1.getLast().setSheduled();
                        set.deleteAt(pos);
                    }
                }
                else
                {
                    count++;
                }
            }
            set.add(set1);
            set.add(set2);
            schedule = set;
        }
예제 #15
0
        //! calculate the fitness value of the contact windows with population of the genetic scheduler

        /*!
         * \param ContactWindowsVector contact windows to check
         * \param int[] population representation of the Genetic scheduler default NULL
         */
        public void calculateValues(ContactWindowsVector contactWindows, int[] population)
        {
            calculate(contactWindows, calcualteMaxPrioValue(contactWindows, population), contactWindows.Count(), population);
        }
예제 #16
0
        //! Starts the process of finding the best solution through genetor

        /*!
         *  \param ScheduleProblemInterface definition of the problem to solve
         */
        public void CalculateSchedule(ScheduleProblemInterface problem)
        {
            objective = problem.getObjectiveFunction();
            set       = problem.getContactWindows();
            //Sort by time
            set.sort(Structs.sortByField.TIME);

            nrOfContacts   = set.Count();
            nrOfStation    = set.getNumberOfStation();
            nrOfSatellites = set.getNumberOfSatellites();
            satelliteList  = new List <string>(set.getSatelliteNames());
            stationList    = new List <string>(set.getStationNames());

            fitness      = new double[popSize];
            bestSolution = new int[nrOfContacts];

            if (runUnitlTime)
            {
                startrunTime = DateTime.Now;
                double h = hours;
                startrunTime = startrunTime.AddHours(h);
            }
            generation = 0;

            //create 5-10 random schedules from the Data
            population = new List <int[]>();
            for (int i = 0; i < popSize; i++)
            {
                population.Add(new int[nrOfContacts]);
                fitness[i] = Constants.maxInt;
            }
            //Randomize the starting Population
            Random rnd = new Random();

            for (int k = 0; k < popSize; k++)
            {
                for (int i = 0; i < nrOfContacts; i++)
                {
                    int randStart = rnd.Next(0, 100);
                    if (randStart <= genCrea)
                    {
                        population[k][i] = 1;
                    }
                }
            }
            //--
            bool foundSolution = false;

            while (!foundSolution)
            {
                generation++;
                //Console.WriteLine("Generation: " + generation.ToString() );
                //elliminate all collsions either by using random chance or
                //by priority.
                //check fitness of each one (survival rate)
                for (int i = 0; i < popSize; i++)
                {
                    surviveConflicts(population[i], rnd, conflictValue);
                    fitness[i] = checkFitness(population[i]);
                }

                if (Properties.Settings.Default.global_MaxPerf == false)
                {
                    System.Windows.Forms.Application.DoEvents();
                }

                //take only the fittest
                survivalOfFittest(fitness, population);

                //Combine randomly and generate children
                createChildren(population, fitness, rnd);


                //Mutate (remove or add requests by slight change)
                for (int i = 0; i < popSize; i++)
                {
                    mutate(population[i], rnd);
                }

                //check if Solution has been found
                foundSolution = isComplete();

                if (generatePlotData > 0)
                {
                    WriteLog();
                }

                if (Properties.Settings.Default.global_MaxPerf == false)
                {
                    System.Windows.Forms.Application.DoEvents();
                }

                if (f != null)
                {
                    f.incrementProgressBar();
                }
            }
            if (solveConflict)
            {
                surviveConflicts(bestSolution, rnd, conflictValue);
            }
            //

            //surviveConflicts(bestSolution, rnd);
            setSchedule(bestSolution, set);
            Console.WriteLine("Found Solution after " + generation.ToString() + " Generations");
            result = set;
            result.randomize();
            fillGaps();
            if (generatePlotData > 0)
            {
                plotWr.Close();
            }
            if (f != null)
            {
                f.resetProgressBar();
            }
        }
예제 #17
0
        //! Calculates a schedule from the defined problem

        /*!
         *  \pram ScheduleProblemInterface defined problem with contactwindows
         *  This Function will calculate the solution to the problem defined in
         *  Schedule Problem Interface
         */
        public void CalculateSchedule(ScheduleProblemInterface problem)
        {
            objective = problem.getObjectiveFunction();
            result    = problem.getContactWindows();

            if (adaptiveMaxIterations)
            {
                maxNumberOfIteration = result.Count() * 4;
            }

            if (randomStart)
            {
                result.randomize();
                fillContacts(result);
            }

            if (mainform != null)
            {
                mainform.setProgressBar(maxNumberOfIteration);
            }

            currentFitness = 0.0;
            result.getAt(0).setSheduled();
            while (!isComplete())
            {
                for (int i = 0; i < result.Count(); i++)
                {
                    iterations++;
                    for (int j = 0; j < result.Count(); j++)
                    {
                        if (i != j && result.getAt(i).checkConflikt(result.getAt(j)))
                        {
                            if (result.getAt(i).getStationName() == result.getAt(j).getStationName() ||
                                result.getAt(i).getSatName() == result.getAt(j).getSatName())
                            {
                                //collision detected
                                result.getAt(i).unShedule();
                                result.getAt(j).setSheduled();
                                double newFitness = getFitness(result);
                                if (newFitness < currentFitness)
                                {
                                    result.getAt(j).unShedule();
                                    result.getAt(i).setSheduled();
                                }
                                else
                                {
                                    currentFitness = newFitness;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (Properties.Settings.Default.global_MaxPerf == false)
                {
                    System.Windows.Forms.Application.DoEvents();
                }
                if (mainform != null)
                {
                    mainform.updateProgressBar(iterations);
                }

                currentFitness = getFitness(result);
                fillContacts(result);
            }
        }
예제 #18
0
        //! returns the fitness value of current set

        /*!
         *  /param Contact Windows Vector
         *  /return double fitnessValue
         */
        private double getFitness(ContactWindowsVector contacts)
        {
            objective.calculateValues(contacts);
            return(objective.getObjectiveResults());
        }
예제 #19
0
        //!GreedyScheduler constructor.

        /*!
         *  constructs a basic greedy scheduler
         */
        public EftGreedyScheduler()
        {
            schedule = new ContactWindowsVector();
        }
예제 #20
0
        //! calculate the fitness value of the given contact windows

        /*!
         * \param ContactWindowsVector
         */
        public void calculateValues(ContactWindowsVector contactWindows)
        {
            calculate(contactWindows, calcualteMaxPrioValue(contactWindows));
        }
예제 #21
0
        //! Calculate Contact windows

        /*!
         * /param List<TLE> list of Tle data
         * /param List<Statons> list of Stations
         * /param EpochTime starting time
         * /param Epoch Time stoping time
         * /param string Logfile = null
         * /param Main mainform to update = null
         * cacluated the orbits of selected satellites and then the contact windows
         * for each station in the given time frame
         */
        public static ContactWindowsVector calculateContactWindows(List <Tle> tleData,
                                                                   List <Station> stations, EpochTime start, EpochTime stop, string logfile = null,
                                                                   Main mainform = null)
        {
            ContactWindowsVector contacts = new ContactWindowsVector();
            double accuracy = Properties.Settings.Default.orbit_Calculation_Accuracy;

            //Calculate Orbits of the selected Satellites

            Sgp4[] tasks   = new Sgp4[tleData.Count()];
            Task[] threads = new Task[tleData.Count()];
            for (int i = 0; i < tleData.Count(); i++)
            {
                tasks[i] = new One_Sgp4.Sgp4(tleData[i], Properties.Settings.Default.orbit_Wgs);
                tasks[i].setStart(start, stop, accuracy / 60.0);
                threads[i] = new Task(tasks[i].starThread);
            }
            for (int i = 0; i < threads.Count(); i++)
            {
                //start each Thread
                threads[i].Start();
            }
            try
            {
                //wait till all threads are finished
                Task.WaitAll(threads);
            }
            catch (AggregateException ae)
            {
                //Logg any exceptions thrown
                if (logfile != null)
                {
                    MainFunctions.updateLog(logfile, "Orbit Predictions Exception: " + ae.InnerExceptions[0].Message, mainform);
                }
            }

            //Calculate Contact Windows
            if (logfile != null)
            {
                MainFunctions.updateLog(logfile, "Starting Contact Window Calculation:", mainform);
            }
            for (int i = 0; i < tleData.Count(); i++)
            {
                Ground.InView[] inViews   = new Ground.InView[stations.Count()];
                Task[]          inThreads = new Task[stations.Count()];
                for (int k = 0; k < stations.Count(); k++)
                {
                    inViews[k]   = new Ground.InView(stations[k], start, tasks[i].getRestults(), tleData[i].getName(), accuracy);
                    inThreads[k] = new Task(inViews[k].calcContactWindows);
                }
                for (int k = 0; k < stations.Count(); k++)
                {
                    //start every thread
                    inThreads[k].Start();
                }
                try
                {
                    //whait for all threads to finish
                    Task.WaitAll(inThreads);
                }
                catch (AggregateException ae)
                {
                    if (logfile != null)
                    {
                        MainFunctions.updateLog(logfile, "Contact Windows Calculation Exception: " + ae.InnerExceptions[0].Message, mainform);
                    }
                }
                for (int k = 0; k < stations.Count(); k++)
                {
                    contacts.add(inViews[k].getResults());
                }
            }
            contacts.setStartTime(start);
            contacts.setStopTime(stop);
            return(contacts);
        }
예제 #22
0
        //! calculate the fitness value of ALL defined objetive values

        /*!
         * \param ContactWindowsVector contact windows to check
         * \param int max number of Contacts of the Scheduling problem
         * \param int[] population representation of the Genetic scheduler default NULL
         */
        private void calculate(ContactWindowsVector contactWindows, int priorityValue, int nrOfAllContacts = 0, int[] population = null, ContactWindowsVector allcontactWindows = null)
        {
            //list of stations and Satellites
            List <string> stationList   = contactWindows.getStationNames();
            List <string> satelliteList = contactWindows.getSatelliteNames();

            //number of times sation and satellite is scheduled
            int nrOfStation    = contactWindows.getNumberOfStation();
            int nrOfSatellites = contactWindows.getNumberOfSatellites();

            //
            int[] nrOfContactsPerSatellite = new int[nrOfSatellites];
            int[] nrOfContactsPerStation   = new int[nrOfStation];

            //number of Contacts Scheduled
            int nrOfScheduledContacts = 0;

            //Overall Scheduled Time
            double scheduledDuration = 0.0;
            //Complete Time of ALL contacts
            double allDuaration = 0.0;
            //Priority counts
            int priorityMax = priorityValue;
            int prio        = calcualteMaxPrioValue(contactWindows);

            for (int i = 0; i < contactWindows.Count(); i++)
            {
                int stapo = -1;
                int satpo = -1;
                if (population != null)
                {
                    if (population[i] == 1)
                    {
                        stapo = stationList.IndexOf(contactWindows.getAt(i).getStationName());
                        satpo = satelliteList.IndexOf(contactWindows.getAt(i).getSatName());
                        nrOfScheduledContacts++;
                        scheduledDuration += contactWindows.getAt(i).getDuration();
                    }
                }
                else
                {
                    if (nrOfAllContacts == 0)
                    {
                        if (contactWindows.getAt(i).getSheduledInfo())
                        {
                            stapo              = stationList.IndexOf(contactWindows.getAt(i).getStationName());
                            satpo              = satelliteList.IndexOf(contactWindows.getAt(i).getSatName());
                            scheduledDuration += contactWindows.getAt(i).getDuration();
                            nrOfScheduledContacts++;
                        }
                    }
                    else
                    {
                        stapo              = stationList.IndexOf(contactWindows.getAt(i).getStationName());
                        satpo              = satelliteList.IndexOf(contactWindows.getAt(i).getSatName());
                        scheduledDuration += contactWindows.getAt(i).getDuration();
                        nrOfScheduledContacts++;
                    }
                }
                if (allcontactWindows == null)
                {
                    allDuaration += contactWindows.getAt(i).getDuration();
                }

                if (stapo > -1)
                {
                    nrOfContactsPerStation[stapo]++;
                }
                if (satpo > -1)
                {
                    nrOfContactsPerSatellite[satpo]++;
                }
            }

            //calculate Fairness for Stations
            double a_station = 0.0;
            double b_station = 0.0;

            for (int i = 0; i < nrOfStation; i++)
            {
                a_station = a_station + nrOfContactsPerStation[i];
                b_station = b_station + Math.Pow(nrOfContactsPerStation[i], 2);
            }
            val_FairStations = Math.Pow(a_station, 2) / (nrOfStation * b_station);

            //calculate Fairnes for Satellites
            double a_satellites = 0.0;
            double b_satellites = 0.0;

            for (int i = 0; i < nrOfSatellites; i++)
            {
                a_satellites = a_satellites + nrOfContactsPerSatellite[i];
                b_satellites = b_satellites + Math.Pow(nrOfContactsPerSatellite[i], 2);
            }
            val_FairSatellites = Math.Pow(a_satellites, 2) / (nrOfSatellites * b_satellites);

            if (nrOfAllContacts == 0)
            {
                nrOfAllContacts = contactWindows.Count();
            }

            val_Scheduled = nrOfScheduledContacts / (double)nrOfAllContacts;

            val_Duration = scheduledDuration / allDuaration;

            val_Priority = (double)prio / (double)priorityMax;
        }
예제 #23
0
        //! returns the number of contacts for each priority

        /*!
         *  \param ContactWindowVector schedule to calculate fairness
         *  \return string containing number of contacts schedule for each priorty
         */
        public static string getNrOfPrioritysScheduled(ContactWindowsVector contacts)
        {
            int p0  = 0;
            int p1  = 0;
            int p2  = 0;
            int p3  = 0;
            int p4  = 0;
            int sp0 = 0;
            int sp1 = 0;
            int sp2 = 0;
            int sp3 = 0;
            int sp4 = 0;

            for (int i = 0; i < contacts.Count(); i++)
            {
                int p = (int)contacts.getAt(i).getPriority();
                switch (p)
                {
                case 0:
                    p0++;
                    break;

                case 1:
                    p1++;
                    break;

                case 2:
                    p2++;
                    break;

                case 3:
                    p3++;
                    break;

                case 4:
                    p4++;
                    break;
                }
                if (contacts.getAt(i).getSheduledInfo())
                {
                    switch (p)
                    {
                    case 0:
                        sp0++;
                        break;

                    case 1:
                        sp1++;
                        break;

                    case 2:
                        sp2++;
                        break;

                    case 3:
                        sp3++;
                        break;

                    case 4:
                        sp4++;
                        break;
                    }
                }
            }
            return(sp0 + "/" + p0 + " - " + sp1 + "/" + p1 + " - " + sp2 + "/" + p2 + " - " + sp3 + "/" + p3 + " - " + sp4 + "/" + p4);
        }
예제 #24
0
        //! Set ContactWindows to current Problem

        /*!
         *  \pram ContactWindowsVector all contacts
         */
        public void setContactWindows(ContactWindowsVector contacts)
        {
            schedulerContacts = contacts;
        }
예제 #25
0
        //! Checks if the algorithm has found a solution

        /*!
         *  \return bool true if a solution is found
         */
        public bool isComplete()
        {
            if (cancel)
            {
                return(true);
            }
            if (!runUnitlTime)
            {
                bool   result      = false;
                double bestCurrent = fitness[0];
                int    pos         = 0;
                for (int i = 0; i < fitness.Count(); i++)
                {
                    if (fitness[i] >= bestCurrent)
                    {
                        bestCurrent = fitness[i];
                        pos         = i;
                    }
                }
                if (bestCurrent > bestFitness)
                {
                    bestFitness             = bestCurrent;
                    countSolutionGeneration = 0;
                    Array.Copy(population[pos], bestSolution, nrOfContacts);
                }
                else
                {
                    countSolutionGeneration++;
                    if (countSolutionGeneration >= nrOfGenerationsForCompletion)
                    {
                        result = true;
                    }
                }
                return(result);
            }
            else
            {
                double bestCurrent = fitness[0];
                int    pos         = 0;
                for (int i = 0; i < fitness.Count(); i++)
                {
                    if (fitness[i] >= bestCurrent)
                    {
                        bestCurrent = fitness[i];
                        pos         = i;
                    }
                }
                if (bestCurrent > bestFitness)
                {
                    bestFitness             = bestCurrent;
                    countSolutionGeneration = 0;
                    Array.Copy(population[pos], bestSolution, nrOfContacts);
                }
                if (DateTime.Now >= startrunTime)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
예제 #26
0
        //! Assigns a list of Request to the ContactWindows

        /*!
         *  \param ContactWindowsVector contact
         *  \param List<Request> request
         */
        public void calcRequToContacts(ContactWindowsVector contacts, List <Request> requests)
        {
            //assign Contacts to Requests
            //setExclusion for unasigned ContactWindows
        }
예제 #27
0
        //! Calculates a schedule from the defined problem

        /*!
         *  \pram ScheduleProblemInterface defined problem with contactwindows
         *  Greedy approach earliest job first.
         */
        public void CalculateSchedule(ScheduleProblemInterface problem)
        {
            set = problem.getContactWindows();
            ContactWindowsVector set1 = new ContactWindowsVector();
            ContactWindowsVector set2 = new ContactWindowsVector();

            List <string> staName = set.getStationNames();

            //while set is not empty do
            while (!isComplete())
            {
                //loop through all Stations
                for (int i = 0; i < staName.Count(); i++)
                {
                    int    pos      = -1;
                    double earliest = 9999.99;
                    int    priority = 4;
                    //loop through all Contacts and find the item that finisches
                    //first and has the highest priority.
                    for (int k = 0; k < set.Count(); k++)
                    {
                        if (set.getAt(k).getStationName() == staName[i])
                        {
                            if (set.getAt(k).getStopTime().getEpoch() < earliest
                                &&
                                (int)set.getAt(k).getPriority() <= priority)
                            {
                                pos      = k;
                                earliest = set.getAt(k).getStopTime().getEpoch();
                                priority = (int)set.getAt(k).getPriority();
                            }
                        }
                    }
                    //update Progress Bar on Main Form
                    if (Properties.Settings.Default.global_MaxPerf == false)
                    {
                        System.Windows.Forms.Application.DoEvents();
                    }
                    if (f != null)
                    {
                        f.incrementProgressBar();
                    }
                    //the found earliest job is added to set1 if its empty
                    //or no other contact in set1 is conflicting with it
                    //if there is a conflict add this element to set2
                    //Then the element is deleted from set1
                    if (pos > -1)
                    {
                        if (set1.isEmpty())
                        {
                            set1.add(set.getAt(pos));
                            set.deleteAt(pos);
                        }
                        else
                        {
                            bool found = false;
                            for (int k = 0; k < set1.Count(); k++)
                            {
                                if (set.getAt(pos).checkConflikt(set1.getAt(k)))
                                {
                                    if (set.getAt(pos).getSatName() == set1.getAt(k).getSatName())
                                    {
                                        set2.add(set.getAt(pos));
                                        set.deleteAt(pos);
                                        found = true;
                                        break;
                                    }
                                }
                            }
                            if (!found)
                            {
                                set1.add(set.getAt(pos));
                                set.deleteAt(pos);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < set1.Count(); i++)
            {
                set1.getAt(i).setSheduled();
            }
            for (int i = 0; i < set2.Count(); i++)
            {
                set2.getAt(i).unShedule();
            }
            set.add(set1);
            set.add(set2);
            schedule = set;
            solveConflictsByPriority();
            if (f != null)
            {
                f.resetProgressBar();
            }
        }
예제 #28
0
        //! Draw Conatact Windows.

        /*!
         * \param ContactWindowsVector Contacts
         * \param bool Draw All if false only scheduled contacts will be drawn
         * \return Image bmp-Image
         * Creates a bmp Image and returns it
         */
        public static Image drawContacts(ContactWindowsVector contacts, bool drawAll)
        {
            if (contacts != null)
            {
                //sort by Groundstations
                contacts.sort(Structs.sortByField.GROUNDSTATION);

                List <string> satNameList = contacts.getSatelliteNames();
                List <string> staNameList = contacts.getStationNames();

                int x_offset     = 100;
                int y_offset     = 20;
                int satBoxheight = 20;

                //calculate Size of Image
                double timeLength = contacts.getStopTime().getEpoch() - contacts.getStartTime().getEpoch();
                int    imWidth    = Convert.ToInt32(timeLength = 8640 * timeLength);
                int    imHeight   = satNameList.Count() * staNameList.Count() * 20;
                Image  dest       = new Bitmap(imWidth + x_offset, imHeight + y_offset);

                //Generate Front and Brusch for drawing
                System.Drawing.Graphics g;
                System.Drawing.Pen      pen = new System.Drawing.Pen(Color.Black, 1F);
                Font       drawFont         = new Font("Arial", 10);
                SolidBrush brush            = new SolidBrush(Color.Black);
                g = Graphics.FromImage(dest);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;

                //Start Drawing Contact Windows
                for (int i = 0; i < contacts.Count(); i++)
                {
                    //Draw only if scheduled unless drawAll = true
                    if (contacts.getAt(i).getSheduledInfo() || drawAll)
                    {
                        int satPosY = satNameList.IndexOf(contacts.getAt(i).getSatName());
                        int staPosY = staNameList.IndexOf(contacts.getAt(i).getStationName());

                        int y            = 0;
                        int x            = 0;
                        int satBoxhWidth = 0;

                        y = satPosY * 20 + staPosY * satNameList.Count() * 20 + y_offset;
                        double satx = 8640 * (contacts.getAt(i).getStartTime().getEpoch() - contacts.getStartTime().getEpoch());
                        x            = Convert.ToInt32(satx) + x_offset;
                        satBoxhWidth = Convert.ToInt32(contacts.getAt(i).getDuration() / 10.0);

                        //brush = new SolidBrush(Color.FromArgb(contacts.getAt(i).getHash()));
                        if (drawAll && !contacts.getAt(i).getSheduledInfo())
                        {
                            brush = new SolidBrush(Color.FromArgb(215, 215, 215));
                            g.FillRectangle(brush, new Rectangle(x, y, satBoxhWidth, satBoxheight));
                            g.DrawString(contacts.getAt(i).getSatName(), drawFont, new SolidBrush(Color.DarkGray), x, y);
                        }
                        else
                        {
                            brush = new SolidBrush(Color.FromArgb(contacts.getAt(i).getHash()));
                            g.FillRectangle(brush, new Rectangle(x, y, satBoxhWidth, satBoxheight));
                            g.DrawString(contacts.getAt(i).getSatName(), drawFont, new SolidBrush(Color.Black), x, y);
                        }
                    }
                }

                System.Drawing.Pen stationPen;
                stationPen = new System.Drawing.Pen(Color.DarkGray, 1);

                g.DrawLine(stationPen, x_offset, 0, x_offset, imHeight);

                //Start Drawing Stations Names
                for (int i = 0; i < staNameList.Count(); i++)
                {
                    int x1 = 0;
                    int y1 = (i + 1) * satNameList.Count() * 20;
                    int x2 = imWidth;
                    int y2 = (i + 1) * satNameList.Count() * 20;
                    g.DrawString(staNameList[i], drawFont, new SolidBrush(Color.Black), 5, y1 - ((satNameList.Count() / 2) * 20));
                    g.DrawLine(stationPen, x1, y1 + y_offset, x2, y2 + y_offset);
                }

                One_Sgp4.EpochTime time = new One_Sgp4.EpochTime(contacts.getStartTime());
                g.DrawString(contacts.getStartTime().ToString(), drawFont, new SolidBrush(Color.Black), x_offset, 5);

                for (int i = x_offset; i < imWidth; i += 180)
                {
                    g.DrawString(time.ToString(), drawFont, new SolidBrush(Color.Black), i, 5);
                    g.DrawLine(stationPen, i, 0, i, imHeight);
                    time.addTick(10 * 180);
                }

                //g.Dispose();
                drawFont.Dispose();
                brush.Dispose();
                pen.Dispose();

                dest.Save("Contacts.bmp");

                return(dest);
            }
            else
            {
                int   imWidth  = 8640;
                int   imHeight = 20;
                Image dest     = new Bitmap(imWidth, imHeight);
                return(dest);
            }
        }