Exemplo n.º 1
0
 public static Tour GetTourStatusByTourStatusID(int TourStatusID)
 {
     Tour tour = new Tour();
     SqlTourProvider sqlTourProvider = new SqlTourProvider();
     tour = sqlTourProvider.GetTourByTourStatusID(TourStatusID);
     return tour;
 }
    protected override void Manipulate(IRandom random, GVREncoding individual) {
      int customer = random.Next(1, individual.Cities + 1);
      Tour tour;
      int position;
      individual.FindCustomer(customer, out tour, out position);

      tour.Stops.RemoveAt(position);

      //with a probability of 1/(2*V) create a new tour, else insert at another position
      if (individual.GetTours().Count > 0 &&
        individual.GetTours().Count < ProblemInstance.Vehicles.Value &&
        random.Next(individual.GetTours().Count * 2) == 0) {
        Tour newTour = new Tour();
        newTour.Stops.Add(customer);

        individual.Tours.Add(newTour);
      } else {
        Tour newTour = individual.Tours[random.Next(individual.Tours.Count)];
        int newPosition = random.Next(newTour.Stops.Count + 1);

        newTour.Stops.Insert(newPosition, customer);
      }

      if (tour.Stops.Count == 0)
        individual.Tours.Remove(tour);
    }
Exemplo n.º 3
0
//--------------------------------------------------------------------------------------------------
    public bool SearchCircle( 
        Map                 map, 
        int                 radius, 
        ClockDirection      clockDirection,
        Tour                tour 
        )
    {
        SearchSet           ss = m_SearchSets[radius];

        SortedList<double,CircleEntry> entries = ss.Entries;

        if( entries == null ) return false;

        IList<CircleEntry> values;

        if( clockDirection == ClockDirection.Clockwise )
        {
            List<CircleEntry> list = new List<CircleEntry>( entries.Values );
            list.Reverse();
            values = list;
        }
        else 
            values = entries.Values;

        foreach( CircleEntry entry in values )
        {
            if( tour( map, entry.X, entry.Y ) ) return true;
        }

        return false;
    }
Exemplo n.º 4
0
    protected override void EvaluateTour(VRPEvaluation eval, IVRPProblemInstance instance, Tour tour, IVRPEncoding solution) {
      TourInsertionInfo tourInfo = new TourInsertionInfo(solution.GetVehicleAssignment(solution.GetTourIndex(tour)));
      eval.InsertionInfo.AddTourInsertionInfo(tourInfo);

      double distance = 0.0;
      double quality = 0.0;

      //simulate a tour, start and end at depot
      for (int i = 0; i <= tour.Stops.Count; i++) {
        int start = 0;
        if (i > 0)
          start = tour.Stops[i - 1];
        int end = 0;
        if (i < tour.Stops.Count)
          end = tour.Stops[i];

        //drive there
        double currentDistace = instance.GetDistance(start, end, solution);
        distance += currentDistace;

        StopInsertionInfo stopInfo = new StopInsertionInfo(start, end);
        tourInfo.AddStopInsertionInfo(stopInfo);
      }

      //Fleet usage
      quality += instance.FleetUsageFactor.Value;
      //Distance
      quality += instance.DistanceFactor.Value * distance;

      eval.Distance += distance;
      eval.VehicleUtilization += 1;

      tourInfo.Quality = quality;
      eval.Quality += quality;
    }
Exemplo n.º 5
0
        public Population(int populationSize, Boolean initialise, Paths pgs, IntPoint m_startPoint,Tour greedtour)
        {
            this.oripaths = pgs;   //保存传入的路劲集合,用来计算适应度,及距离
            this.startPoint = m_startPoint;

            tours = new Tour[populationSize];        //种群路劲集合

            int greedseedsize = 15;
            // If we need to initialise a population of tours do so
            if (initialise)
            {
                for (int j = 0; j < greedseedsize; j++)
                {
                    saveTour(j, greedtour);
                }

                // Loop and create individuals
                for (int i = greedseedsize; i < populationSize; i++)
                {
                    Tour newTour = new Tour(pgs.Count);
                    newTour.generateIndividual();
                    saveTour(i, newTour);
                }
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Конструктор который задает параметры
 /// </summary>
 /// <param name="cityList"></param>
 /// <param name="bestTour"></param>
 /// <param name="generation"></param>
 /// <param name="complete"></param>
 public TspEventArgs(Cities cityList, Tour bestTour, int generation, bool complete)
 {
     this.cityList = cityList;
     this.bestTour = bestTour;
     this.generation = generation;
     this.complete = complete;
 }
Exemplo n.º 7
0
    public override List<Tour> GetTours() {
      Repair();
      List<Tour> result = new List<Tour>();

      int cities = ProblemInstance.Cities.Value;

      Tour tour = new Tour();
      for (int i = 0; i < this.array.Length; i++) {
        if (this.array[i] >= cities) {
          if (tour.Stops.Count > 0) {
            result.Add(tour);

            tour = new Tour();
          }
        } else {
          tour.Stops.Add(this.array[i] + 1);
        }
      }

      if (tour.Stops.Count > 0) {
        result.Add(tour);
      }

      return result;
    }
    protected override void Manipulate(IRandom random, GVREncoding individual) {
      Tour tour = individual.Tours[random.Next(individual.Tours.Count)];
      int breakPoint1 = random.Next(tour.Stops.Count);
      int length = random.Next(1, tour.Stops.Count - breakPoint1 + 1);

      List<int> displaced = tour.Stops.GetRange(breakPoint1, length);
      tour.Stops.RemoveRange(breakPoint1, length);
      //with a probability of 1/(2*V) create a new tour, else insert at another position
      if (individual.GetTours().Count > 0 &&
        individual.GetTours().Count < ProblemInstance.Vehicles.Value &&
        random.Next(individual.GetTours().Count * 2) == 0) {
        Tour newTour = new Tour();
        newTour.Stops.InsertRange(0, displaced);

        individual.Tours.Add(newTour);
      } else {
        Tour newTour = individual.Tours[random.Next(individual.Tours.Count)];
        int newPosition = newTour.Stops.Count;

        newTour.Stops.InsertRange(newPosition, displaced);
      }

      if (tour.Stops.Count == 0)
        individual.Tours.Remove(tour);
    }
Exemplo n.º 9
0
 public static Tour GetTourByCustomerID(int CustomerID)
 {
     Tour tour = new Tour();
     SqlTourProvider sqlTourProvider = new SqlTourProvider();
     tour = sqlTourProvider.GetTourByCustomerID(CustomerID);
     return tour;
 }
Exemplo n.º 10
0
    public bool SearchOctant( 
        Map                 map, 
        Compass             compass,
        int                 start,
        SearchDirection     direction,
        Tour                tour 
        )
    {
        SearchSet           oc = m_Octants[(int)compass];
        int                 incr = direction == SearchDirection.Outwards ? 1 : -1;

        for( int i=start;;i+=incr)
        {
            if( i < 0 || i > m_Radius ) return false;

            EntrySet entrySet = oc.GetEntrySet( i );

            if( entrySet == null ) continue;

            List<Entry> entries = entrySet.Entries;

            foreach( OctantEntry entry in entries )
            {
                if( tour( map, entry.X, entry.Y ) )
                    return true;
            }

            return false;
        }
    }
        internal bool CreateTour(Tour tour, string[] arrayDaysOfTheWeek)
        {
            //ToDo: Проверка
            if (db.Tours.FirstOrDefault(x => x.title == tour.title) != null)
                return false;

            try
            {
                db.Tours.Add(tour);
                db.SaveChanges();

                for (int i = 0; i < arrayDaysOfTheWeek.Length; i++)
                    if (!string.IsNullOrEmpty(arrayDaysOfTheWeek[i]))
                        db.Tour_DaysOfTheWeek.Add(
                            new Tour_DaysOfTheWeek { DaysOfTheWeekID = Convert.ToByte(arrayDaysOfTheWeek[i]), TourID = tour.Id });

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
Exemplo n.º 12
0
//--------------------------------------------------------------------------------------------------
//  SearchCircle -- search around the radius
//--------------------------------------------------------------------------------------------------
    public bool SearchCircle( 
        Map                 map, 
        int                 radius, 
        Tour                tour 
        )
    {
        return SearchCircle( map, radius, ClockDirection.CounterClockwise, tour );
    }
Exemplo n.º 13
0
//------------------------------------------------------------------------------
//  SearchCircle -- search all cells in a circle, around the center
//------------------------------------------------------------------------------
    public static bool Circle( 
        Map                 map, 
        int                 radius, 
        Tour                tour 
        )
    {
        return m_CircleSearch.SearchCircle( map, radius, tour );
    }
Exemplo n.º 14
0
    protected override void EvaluateTour(VRPEvaluation eval, IVRPProblemInstance instance, Tour tour, IVRPEncoding solution) {
      TourInsertionInfo tourInfo = new TourInsertionInfo(solution.GetVehicleAssignment(solution.GetTourIndex(tour))); ;
      eval.InsertionInfo.AddTourInsertionInfo(tourInfo);
      double originalQuality = eval.Quality;

      IHomogenousCapacitatedProblemInstance cvrpInstance = instance as IHomogenousCapacitatedProblemInstance;
      DoubleArray demand = instance.Demand;

      double delivered = 0.0;
      double overweight = 0.0;
      double distance = 0.0;

      double capacity = cvrpInstance.Capacity.Value;
      for (int i = 0; i <= tour.Stops.Count; i++) {
        int end = 0;
        if (i < tour.Stops.Count)
          end = tour.Stops[i];

        delivered += demand[end];
      }

      double spareCapacity = capacity - delivered;

      //simulate a tour, start and end at depot
      for (int i = 0; i <= tour.Stops.Count; i++) {
        int start = 0;
        if (i > 0)
          start = tour.Stops[i - 1];
        int end = 0;
        if (i < tour.Stops.Count)
          end = tour.Stops[i];

        //drive there
        double currentDistace = instance.GetDistance(start, end, solution);
        distance += currentDistace;

        CVRPInsertionInfo stopInfo = new CVRPInsertionInfo(start, end, spareCapacity);
        tourInfo.AddStopInsertionInfo(stopInfo);
      }

      eval.Quality += instance.FleetUsageFactor.Value;
      eval.Quality += instance.DistanceFactor.Value * distance;

      eval.Distance += distance;
      eval.VehicleUtilization += 1;

      if (delivered > capacity) {
        overweight = delivered - capacity;
      }

      (eval as CVRPEvaluation).Overload += overweight;
      double penalty = overweight * cvrpInstance.OverloadPenalty.Value;
      eval.Penalty += penalty;
      eval.Quality += penalty;
      tourInfo.Penalty = penalty;
      tourInfo.Quality = eval.Quality - originalQuality;
    }
Exemplo n.º 15
0
 public static bool Circle( 
     Map                 map, 
     int                 radius, 
     ClockDirection      clockDirection,
     Tour                tour 
     )
 {
     return m_CircleSearch.SearchCircle( map, radius, clockDirection, tour );
 }
Exemplo n.º 16
0
//------------------------------------------------------------------------------
//  SearchConcentric -- search all cells in a circle, around the center
//------------------------------------------------------------------------------
    public static bool ConcentricCircles( 
        Map                 map, 
        int                 start, 
        SearchDirection     searchDirection,
        Tour                tour 
        )
    {
        return m_CircleSearch.SearchConcentricCircles( map, start, searchDirection, tour );
    }
Exemplo n.º 17
0
//--------------------------------------------------------------------------------------------------
//  SearchContentricCircles -- search around the radii, moving in or out
//--------------------------------------------------------------------------------------------------
    public bool SearchConcentricCircles( 
        Map                 map, 
        int                 start, 
        SearchDirection     searchDirection,
        Tour                tour 
        )
    {
        return SearchConcentricCircles( map, start, ClockDirection.CounterClockwise, searchDirection, tour );
    }
Exemplo n.º 18
0
//------------------------------------------------------------------------------
//  SearchLine   -- search all cells on a line, from begin to end. Search will
//                 terminate if the Search delegate returns false any time during
//                 the tour
//------------------------------------------------------------------------------
    public static bool Line( 
        Map                 map, 
        Point2D             begin, 
        Point2D             end, 
        Tour                tour 
        )
    {
        return m_LineSearch.SearchLine( map, begin, end, tour );
    }
Exemplo n.º 19
0
    public override List<Tour> GetTours() {
      List<Tour> result = new List<Tour>();

      Tour newTour = new Tour();

      for (int i = 0; i < this.Length; i++) {
        int city = this[i] + 1;
        newTour.Stops.Add(city);
        if (!ProblemInstance.TourFeasible(newTour, this)) {
          newTour.Stops.Remove(city);
          if (newTour.Stops.Count > 0)
            result.Add(newTour);

          newTour = new Tour();
          newTour.Stops.Add(city);
        }
      }

      if (newTour.Stops.Count > 0)
        result.Add(newTour);

      //if there are too many vehicles - repair
      while (result.Count > ProblemInstance.Vehicles.Value) {
        Tour tour = result[result.Count - 1];

        //find predecessor / successor in permutation
        int predecessorIndex = Array.IndexOf(this.array, tour.Stops[0] - 1) - 1;
        if (predecessorIndex >= 0) {
          int predecessor = this[predecessorIndex] + 1;

          foreach (Tour t in result) {
            int insertPosition = t.Stops.IndexOf(predecessor) + 1;
            if (insertPosition != -1) {
              t.Stops.InsertRange(insertPosition, tour.Stops);
              break;
            }
          }
        } else {
          int successorIndex = Array.IndexOf(this.array,
            tour.Stops[tour.Stops.Count - 1] - 1) + 1;
          int successor = this[successorIndex] + 1;

          foreach (Tour t in result) {
            int insertPosition = t.Stops.IndexOf(successor);
            if (insertPosition != -1) {
              t.Stops.InsertRange(insertPosition, tour.Stops);
              break;
            }
          }
        }

        result.Remove(tour);
      }

      return result;
    }
Exemplo n.º 20
0
        public void TotalDistanceReturnsSumOfRouteDistances()
        {
            var tour = new Tour(
                new City(0, 0),
                new City(3, 4),
                new City(-3, 4)
                );

            tour.TotalDistance.Should().Be(16d);
        }
Exemplo n.º 21
0
        // Applies crossover to a set of parents and creates offspring
        public static Tour[] crossover(Tour parent1, Tour parent2)
        {
            // Create new child tour
            Tour[] child = new Tour[2];
            child[0] = new Tour();
            child[1] = new Tour();

            // Get start and end sub tour positions for parent1's tour
            int startPos = rdm1.Next(parent1.tourSize());
            int endPos = rdm1.Next(startPos, parent1.tourSize());

            //startPos = 0;

            // Loop and add the sub tour from parent1 to our child
            for (int i = 0; i < child[0].tourSize(); i++)
            {
                if ( i > startPos && i < endPos)
                    child[0].setCity(i, parent1.getCity(i));
                else
                    child[1].setCity(i, parent1.getCity(i));
            }

            // Loop through parent2's city tour
            for (int i = 0; i < parent2.tourSize(); i++)
            {
                // If child doesn't have the city add it
                if (!child[0].containsCity(parent2.getCity(i)))
                {
                    // Loop to find a spare position in the child's tour
                    for (int ii = 0; ii < child[0].tourSize(); ii++)
                    {
                        // Spare position found, add city
                        if (child[0].getCity(ii) == null)
                        {
                            child[0].setCity(ii, parent2.getCity(i));
                            break;
                        }
                    }
                }
                else
                {
                    for (int ii = 0; ii < child[1].tourSize(); ii++)
                    {
                        // Spare position found, add city
                        if (child[1].getCity(ii) == null)
                        {
                            child[1].setCity(ii, parent2.getCity(i));
                            break;
                        }
                    }
                }
            }
            return child;
        }
Exemplo n.º 22
0
    public int GetTourIndex(Tour tour) {
      int index = -1;

      for (int i = 0; i < Tours.Count; i++) {
        if (Tours[i].IsEqual(tour)) {
          index = i;
          break;
        }
      }

      return index;
    }
Exemplo n.º 23
0
//------------------------------------------------------------------------------
//  SearchOctant -- search all cells in an octant, from start range, going Inwards
//                 or going Outwards. Search will terminate if the Search delegate
//                 returns false any time during the tour
//------------------------------------------------------------------------------
    public static bool Octant( 
        Map                 map, 
        Direction           direction,
        int                 start,
        SearchDirection     searchDirection,
        Tour                tour 
        )
    {
        Compass compass = m_CompassLookup[(int)direction];

        return m_OctantSearch.SearchOctant( map, compass, start, searchDirection, tour );
    }
Exemplo n.º 24
0
        public void SwapingCitiesModifiesSequenceOfCitiesInTheRoute()
        {
            City s1, s2, s3;
            var tour = new Tour(
                s1 = new City(0, 0),
                s2 = new City(3, 4),
                s3 = new City(-3, 4)
                );

            var tour2 = tour.Swap(0, 2);
            tour2.Route.First().Should().Be(s3);
            tour2.Route.Last().Should().Be(s1);
        }
Exemplo n.º 25
0
    public virtual int GetTourIndex(Tour tour) {
      int index = -1;

      List<Tour> tours = GetTours();
      for (int i = 0; i < tours.Count; i++) {
        if (tours[i].IsEqual(tour)) {
          index = i;
          break;
        }
      }

      return index;
    }
Exemplo n.º 26
0
 // Construct a population
 public Population(int populationSize, bool initialise)
 {
     tours = new Tour[populationSize];
     // If we need to initialise a population of tours do so
     if (initialise)
     {
         // Loop and create individuals
         for (int i = 0; i < populationSize; i++)
         {
             Tour newTour = new Tour();
             newTour.generateIndividual();
             saveTour(i, newTour);
         }
     }
 }
    public static PotvinEncoding Apply(IRandom random, PotvinEncoding parent1, PotvinEncoding parent2, IVRPProblemInstance problemInstance, bool allowInfeasible) {
      PotvinEncoding child = parent1.Clone() as PotvinEncoding;
      Tour newTour = new Tour();

      int cities = problemInstance.Cities.Value;

      if (cities > 0) {
        int breakPoint1 = random.Next(1, cities + 1);
        Tour tour1 = FindRoute(child, breakPoint1);
        breakPoint1 = tour1.Stops.IndexOf(breakPoint1);

        for (int i = 0; i < breakPoint1; i++)
          newTour.Stops.Add(tour1.Stops[i]);

        int breakPoint2 = random.Next(1, cities + 1);
        Tour tour2 = FindRoute(parent2, breakPoint2);
        breakPoint2 = tour2.Stops.IndexOf(breakPoint2);

        for (int i = breakPoint2; i < tour2.Stops.Count; i++)
          newTour.Stops.Add(tour2.Stops[i]);

        int tour1Index = child.Tours.IndexOf(tour1);
        child.Tours.Remove(tour1);
        child.Tours.Insert(tour1Index, newTour);

        foreach (int city in tour1.Stops)
          if (FindRoute(child, city) == null && !child.Unrouted.Contains(city))
            child.Unrouted.Add(city);

        foreach (int city in tour2.Stops)
          if (FindRoute(child, city) == null && !child.Unrouted.Contains(city))
            child.Unrouted.Add(city);

        if (Repair(random, child, newTour, problemInstance, allowInfeasible) || allowInfeasible) {
          return child;
        } else {
          if (random.NextDouble() < 0.5)
            return parent1.Clone() as PotvinEncoding;
          else
            return parent2.Clone() as PotvinEncoding;
        }
      } else {
        return child;
      }
    }
        public ActionResult AddTour(Tour tour, bool isAnyTime, string DaysOfTheWeek, HttpPostedFileBase[] Pictures)
        {
            var user = Storage.currentUser;

            tour.userID = user.id;
            if (isAnyTime)// || string.IsNullOrEmpty(tour.startsAt))
                tour.startsAt = "Any time";

            GetPictureForTour(tour, Pictures);

            if (!manager.CreateTour(tour, DaysOfTheWeek.Split(',')))
            {
                ModelState.AddModelError(
            @"TourIsHave", "Sorry , this tour already exists. Please, change the title of the tour. ");
                return View();
            }

            return RedirectToAction("Index");
        }
Exemplo n.º 29
0
//--------------------------------------------------------------------------------------------------
//  Spiral search
//--------------------------------------------------------------------------------------------------
    public bool SearchSpiral( 
        Map                 map, 
        int                 start,
        SearchDirection     direction,
        bool                randomStart,
        Tour                tour 
        )
    {
        int                 incr = ( direction == SearchDirection.Outwards ? 1 : -1 );
        bool                firstpass = true;

        for( int i=start;;i+=incr)
        {
            if( i < 0 || i > MAXRANGE ) break;

            SearchSet           ss      = m_SearchSets[i];
            List<SpiralEntry>   entries = ss.Entries;

            int startpos;
            
            if( randomStart && firstpass ) 
            { 
                startpos = Utility.RandomMinMax( 0, entries.Count ); 
            }
            else
            { 
                startpos = ( direction == SearchDirection.Outwards ? 0 : entries.Count - 1 );
            }

            for( int pos = startpos;;pos+=incr )
            {
                if( pos < 0 || pos > entries.Count-1 ) break;

                SpiralEntry entry = entries[pos];

                if( tour( map, entry.X, entry.Y ) ) return true;
            }

            firstpass = false;
        }

        return false;
    }
Exemplo n.º 30
0
    public override List<Tour> GetTours() {
      List<Tour> tours = new List<Tour>();

      foreach (Tour tour in base.Tours) {
        Tour newTour = new Tour();
        double currentDemand = 0;

        DoubleValue capacity = new DoubleValue(double.MaxValue);
        if (ProblemInstance is IHomogenousCapacitatedProblemInstance) {
          capacity.Value = (ProblemInstance as IHomogenousCapacitatedProblemInstance).Capacity.Value;
        }


        foreach (int city in tour.Stops) {
          currentDemand += ProblemInstance.GetDemand(city);

          if (currentDemand > capacity.Value) {
            if (newTour.Stops.Count > 0)
              tours.Add(newTour);

            newTour = new Tour();
            newTour.Stops.Add(city);
            currentDemand = ProblemInstance.GetDemand(city);
          } else {
            newTour.Stops.Add(city);
          }
        }

        if (newTour.Stops.Count > 0)
          tours.Add(newTour);
      }

      //repair if there are too many vehicles used
      while (tours.Count > ProblemInstance.Vehicles.Value) {
        Tour tour = tours[tours.Count - 1];
        tours[tours.Count - 2].Stops.AddRange(tour.Stops);

        tours.Remove(tour);
      }

      return tours;
    }
Exemplo n.º 31
0
 static string CustomTourPath(Tour tour)
 {
     return(Paths.customToursPath + "tour_" + tour.uniqueId + ".xml");
 }
Exemplo n.º 32
0
 public static void SaveTour(Tour tour)
 {
     XmlOperation.TrySerialize(tour, CustomTourPath(tour));
 }
Exemplo n.º 33
0
    public void checkFusionL(ref List <Tour> tourTrouves, int x, int y, int level)     //Cette fusion vérifie s'il y a des tours similaires sur les cases adjacentes à la tour concernée
    {
        int  Row        = place_script.creation_script.ROW;
        int  Col        = place_script.creation_script.COL;
        Tour tourDroite = null;
        Tour tourGauche = null;
        Tour tourHaut   = null;
        Tour tourBas    = null;

        if (x + 1 < Row)
        {
            tourDroite = place_script.creation_script.plateauTour[x + 1, y];            //Correspond à la tour potentiellement présente sur la case à droite de la tour concernée
        }

        if (x - 1 > 0)
        {
            tourGauche = place_script.creation_script.plateauTour[x - 1, y];           //Correspond à la tour potentiellement présente sur la case à gauche de la tour concernée
        }

        if (y - 1 > 0)
        {
            tourHaut = place_script.creation_script.plateauTour[x, y - 1];             //Correspond à la tour potentiellement présente sur la case au dessus de la tour concernée
        }

        if (y + 1 < Col)
        {
            tourBas = place_script.creation_script.plateauTour[x, y + 1];              //Correspond à la tour potentiellement présente sur la case en dessous de la tour concernée
        }


        if (tourDroite && tourDroite.level == level)            //Si il y a une tour dans la case à droite de la tour concernée et qu'elle est de même niveau
        {
            if (tourTrouves.Contains(tourDroite) == false)      //On vérifie que cette tour n'a pas déjà été détectée dans le cadre de ce test de fusion
            {
                tourTrouves.Add(tourDroite);                    //Si ce n'est pas le cas, on l'ajoute à la liste des tours qui ont déjà été détectées pour la fusion
                checkFusionL(ref tourTrouves, x + 1, y, level); //On actualise la liste de tours détectées grâce à REF et on effectue à nouveau le test de fusion à partir de la tour détectée à droite de la tour concernée
            }
        }
        if (tourGauche != null && tourGauche.level == level)    //Si il y a une tour dans la case à gauche de la tour concernée et qu'elle est de même niveau
        {
            if (tourTrouves.Contains(tourGauche) == false)      //On vérifie que cette tour n'a pas déjà été détectée dans le cadre de ce test de fusion
            {
                tourTrouves.Add(tourGauche);                    //Si ce n'est pas le cas, on l'ajoute à la liste des tours qui ont déjà été détectées pour la fusion
                checkFusionL(ref tourTrouves, x - 1, y, level); //On actualise la liste de tours détectées grâce à REF et on effectue à nouveau le test de fusion à partir de la tour détectée à gauche de la tour concernée
            }
        }
        if (tourBas != null && tourBas.level == level)          //Si il y a une tour dans la case en dessous de la tour concernée et qu'elle est de même niveau
        {
            if (tourTrouves.Contains(tourBas) == false)         //On vérifie que cette tour n'a pas déjà été détectée dans le cadre de ce test de fusion
            {
                tourTrouves.Add(tourBas);                       //Si ce n'est pas le cas, on l'ajoute à la liste des tours qui ont déjà été détectées pour la fusion
                checkFusionL(ref tourTrouves, x, y + 1, level); //On actualise la liste de tours détectées grâce à REF et on effectue à nouveau le test de fusion à partir de la tour détectée en dessous de la tour concernée
            }
        }
        if (tourHaut != null && tourHaut.level == level)        //Si il y a une tour dans la case au dessus de la tour concernée et qu'elle est de même niveau
        {
            if (tourTrouves.Contains(tourHaut) == false)        //On vérifie que cette tour n'a pas déjà été détectée dans le cadre de ce test de fusion
            {
                tourTrouves.Add(tourHaut);                      //Si ce n'est pas le cas, on l'ajoute à la liste des tours qui ont déjà été détectées pour la fusion
                checkFusionL(ref tourTrouves, x, y - 1, level); //On actualise la liste de tours détectées grâce à REF et on effectue à nouveau le test de fusion à partir de la tour détectée au dessus de la tour concernée
            }
        }
    }
Exemplo n.º 34
0
 public override int GetTourIndex(Tour tour)
 {
     return(0);
 }
Exemplo n.º 35
0
 public void setTourSelected(bool state)
 {
     Tour.setTourSelected(state);
 }
Exemplo n.º 36
0
        public static void Initialize(ApplicationDbContext context)
        {
            context.Database.EnsureCreated();

            if (context.Tours.Any())
            {
                return;
            }

            // init seed data
            var managers = new Manager[]
            {
                new Manager
                {
                    ManagerId = new Guid("fec0a4d6-5830-4eb8-8024-272bd5d6d2bb"),
                    Name      = "Kevin",
                    CreatedBy = "system",
                    CreatedOn = DateTime.UtcNow
                },
                new Manager
                {
                    ManagerId = new Guid("c3b7f625-c07f-4d7d-9be1-ddff8ff93b4d"),
                    Name      = "Sven",
                    CreatedBy = "system",
                    CreatedOn = DateTime.UtcNow
                }
            };

            foreach (Manager manager in managers)
            {
                context.Managers.Add(manager);
            }
            context.SaveChanges();

            var bands = new Band[]
            {
                new Band
                {
                    BandId    = new Guid("25320c5e-f58a-4b1f-b63a-8ee07a840bdf"),
                    Name      = "Queens of the Stone Age",
                    CreatedBy = "system",
                    CreatedOn = DateTime.UtcNow
                },
                new Band
                {
                    BandId    = new Guid("83b126b9-d7bf-4f50-96dc-860884155f8b"),
                    Name      = "Nick Cave and the Bad Seeds",
                    CreatedBy = "system",
                    CreatedOn = DateTime.UtcNow
                }
            };

            foreach (Band band in bands)
            {
                context.Bands.Add(band);
            }
            context.SaveChanges();

            var tours = new Tour[]
            {
                new Tour
                {
                    TourId           = new Guid("c7ba6add-09c4-45f8-8dd0-eaca221e5d93"),
                    BandId           = new Guid("25320c5e-f58a-4b1f-b63a-8ee07a840bdf"),
                    ManagerId        = new Guid("fec0a4d6-5830-4eb8-8024-272bd5d6d2bb"),
                    Title            = "Villains World Tour",
                    Description      = "The Villains World Tour is a concert tour in support of the band's seventh studio album, Villains.",
                    StartDate        = new DateTimeOffset(2017, 6, 22, 0, 0, 0, new TimeSpan()),
                    EndDate          = new DateTimeOffset(2018, 3, 18, 0, 0, 0, new TimeSpan()),
                    EstimatedProfits = 2500000,
                    CreatedBy        = "system",
                    CreatedOn        = DateTime.UtcNow,
                    Shows            = new Show[]
                    {
                        new Show
                        {
                            Venue     = "The Rapids Theatre",
                            City      = "Niagara Falls",
                            Country   = "United States",
                            Date      = new DateTimeOffset(2017, 6, 22, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Marina de Montebello",
                            City      = "Montebello",
                            Country   = "Canada",
                            Date      = new DateTimeOffset(2017, 6, 24, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Ventura Theatre",
                            City      = "Venture",
                            Country   = "United States",
                            Date      = new DateTimeOffset(2017, 8, 10, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Golden Gate Park",
                            City      = "San Francisco",
                            Country   = "United States",
                            Date      = new DateTimeOffset(2017, 8, 12, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Capitol Theatre",
                            City      = "Port Chester",
                            Country   = "United States",
                            Date      = new DateTimeOffset(2017, 9, 6, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Festival Pier",
                            City      = "Philadelphia",
                            Country   = "United States",
                            Date      = new DateTimeOffset(2017, 9, 7, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Budweiser Stage",
                            City      = "Toronto",
                            Country   = "Canada",
                            Date      = new DateTimeOffset(2017, 9, 9, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        }
                    }
                },
                new Tour
                {
                    TourId           = new Guid("f67ba678-b6e0-4307-afd9-e804c23b3cd3"),
                    BandId           = new Guid("83b126b9-d7bf-4f50-96dc-860884155f8b"),
                    ManagerId        = new Guid("c3b7f625-c07f-4d7d-9be1-ddff8ff93b4d"),
                    Title            = "Skeleton Tree European Tour",
                    Description      = "Nick Cave and The Bad Seeds have announced an 8-week European tour kicking off in the UK at Bournemouth’s International Centre on 24th September. The tour will be the first time European audiences can experience live songs from new album Skeleton Tree alongside other Nick Cave & The Bad Seeds classics.  The touring line up features Nick Cave, Warren Ellis, Martyn Casey, Thomas Wydler, Jim Sclavunos, Conway Savage, George Vjestica and Larry Mullins.",
                    StartDate        = new DateTimeOffset(2017, 9, 24, 0, 0, 0, new TimeSpan()),
                    EndDate          = new DateTimeOffset(2017, 11, 20, 0, 0, 0, new TimeSpan()),
                    EstimatedProfits = 1200000,
                    CreatedBy        = "system",
                    CreatedOn        = DateTime.UtcNow,
                    Shows            = new Show[]
                    {
                        new Show
                        {
                            Venue     = "Bournemouth International Centre",
                            City      = "Bournemouth",
                            Country   = "United Kingdom",
                            Date      = new DateTimeOffset(2017, 9, 24, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Arena",
                            City      = "Manchester",
                            Country   = "United Kingdom",
                            Date      = new DateTimeOffset(2017, 9, 25, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "The SSE Hydro",
                            City      = "Glasgow",
                            Country   = "United Kingdom",
                            Date      = new DateTimeOffset(2017, 9, 27, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Motorpoint Arena",
                            City      = "Nottingham",
                            Country   = "United Kingdom",
                            Date      = new DateTimeOffset(2017, 9, 28, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "The O2",
                            City      = "London",
                            Country   = "United Kingdom",
                            Date      = new DateTimeOffset(2017, 9, 30, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Zénith",
                            City      = "Paris",
                            Country   = "France",
                            Date      = new DateTimeOffset(2017, 10, 3, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Ziggo Dome",
                            City      = "Amsterdam",
                            Country   = "The Netherlands",
                            Date      = new DateTimeOffset(2017, 10, 6, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Jahrhunderthalle",
                            City      = "Frankfurt",
                            Country   = "Germany",
                            Date      = new DateTimeOffset(2017, 10, 7, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Sporthalle",
                            City      = "Hamburg",
                            Country   = "Germany",
                            Date      = new DateTimeOffset(2017, 10, 9, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Rockhal",
                            City      = "Luxembourg",
                            Country   = "Luxembourg",
                            Date      = new DateTimeOffset(2017, 10, 10, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Mitsubishi Electric Halle",
                            City      = "Düsseldorf",
                            Country   = "Germany",
                            Date      = new DateTimeOffset(2017, 10, 10, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        },
                        new Show
                        {
                            Venue     = "Sportpaleis",
                            City      = "Antwerp",
                            Country   = "Belgium",
                            Date      = new DateTimeOffset(2017, 10, 13, 0, 0, 0, new TimeSpan()),
                            CreatedBy = "system",
                            CreatedOn = DateTime.UtcNow
                        }
                    }
                }
            };

            foreach (Tour tour in tours)
            {
                context.Tours.Add(tour);
            }
            context.SaveChanges();
        }
Exemplo n.º 37
0
 public async Task AddTourAsync(Tour tour)
 {
     await _tourRepository.CreateAsync(tour);
 }
        public static void Apply(PotvinEncoding solution, PotvinPDShiftMove move, IVRPProblemInstance problemInstance)
        {
            bool newTour = false;

            if (move.Tour >= solution.Tours.Count)
            {
                solution.Tours.Add(new Tour());
                newTour = true;
            }
            Tour tour = solution.Tours[move.Tour];

            Tour oldTour = solution.Tours.Find(t => t.Stops.Contains(move.City));

            oldTour.Stops.Remove(move.City);

            if (problemInstance is IPickupAndDeliveryProblemInstance)
            {
                IPickupAndDeliveryProblemInstance pdp = problemInstance as IPickupAndDeliveryProblemInstance;

                int  location = pdp.GetPickupDeliveryLocation(move.City);
                Tour oldTour2 = solution.Tours.Find(t => t.Stops.Contains(location));
                oldTour2.Stops.Remove(location);

                solution.InsertPair(tour, move.City, location, problemInstance);
            }
            else
            {
                int place = solution.FindBestInsertionPlace(tour, move.City);
                tour.Stops.Insert(place, move.City);
            }

            if (newTour)
            {
                List <int> vehicles = new List <int>();
                for (int i = move.Tour; i < problemInstance.Vehicles.Value; i++)
                {
                    vehicles.Add(solution.GetVehicleAssignment(i));
                }

                double bestQuality = double.MaxValue;
                int    bestVehicle = -1;

                int originalVehicle = solution.GetVehicleAssignment(move.Tour);
                foreach (int vehicle in vehicles)
                {
                    solution.VehicleAssignment[move.Tour] = vehicle;

                    double quality = problemInstance.EvaluateTour(tour, solution).Quality;
                    if (quality < bestQuality)
                    {
                        bestQuality = quality;
                        bestVehicle = vehicle;
                    }
                }

                solution.VehicleAssignment[move.Tour] = originalVehicle;

                int index = -1;
                for (int i = move.Tour; i < solution.VehicleAssignment.Length; i++)
                {
                    if (solution.VehicleAssignment[i] == bestVehicle)
                    {
                        index = i;
                        break;
                    }
                }
                solution.VehicleAssignment[index]     = originalVehicle;
                solution.VehicleAssignment[move.Tour] = bestVehicle;
            }

            solution.Repair();
        }
Exemplo n.º 39
0
 public TourNode(Tour tour)
 {
     this.Tour = tour;
     this.Text = tour.Name;
 }
 public override int GetHashCode()
 {
     return(Tour.GetHashCode() + City.GetHashCode());
 }
Exemplo n.º 41
0
 /// <summary>Évalue si le déplacement de la reine de la source à la destination est possible</summary>
 /// <param name="liSrc">Indice de la ligne source</param>
 /// <param name="liDest">Indice de la ligne de destination</param>
 /// <param name="colSrc">Indice de la colonne source</param>
 /// <param name="colDest">Indice de la colonne de destination</param>
 /// <returns>Retourne true si le déplacement de la reine est possible</returns>
 /// <remarks>Cette méthode ne tient pas compte des autres pièces possiblement présentes sur l'<see cref="Echiquier"></see></remarks>
 public override bool SiDeplacer(byte liSrc, byte liDest, byte colSrc, byte colDest) => Fou.SiDeplacerFou(liSrc, liDest, colSrc, colDest) || Tour.SiDeplacerTour(liSrc, liDest, colSrc, colDest);
Exemplo n.º 42
0
        /// <summary>
        /// Executes the actual algorithm.
        /// </summary>
        protected override void DoRun()
        {
            // calculate weight matrix.
            if (!_weightMatrixAlgorithm.HasRun)
            { // only run if it has not been run yet.
                _weightMatrixAlgorithm.Run();
            }
            if (!_weightMatrixAlgorithm.HasSucceeded)
            { // algorithm has not succeeded.
                this.ErrorMessage = string.Format("Could not calculate weight matrix: {0}",
                                                  _weightMatrixAlgorithm.ErrorMessage);
                return;
            }

            LocationError    le;
            RouterPointError rpe;

            if (_weightMatrixAlgorithm.TryGetError(_first, out le, out rpe))
            { // if the last location is set and it could not be resolved everything fails.
                if (le != null)
                {
                    this.ErrorMessage = string.Format("Could resolve first location: {0}",
                                                      le);
                }
                else if (rpe != null)
                {
                    this.ErrorMessage = string.Format("Could route to/from first location: {0}",
                                                      rpe);
                }
                else
                {
                    this.ErrorMessage = string.Format("First location was in error list.");
                }
                return;
            }

            // build problem.
            var       first   = _first;
            TSProblem problem = null;

            if (_last.HasValue)
            {     // the last customer was set.
                if (_weightMatrixAlgorithm.TryGetError(_last.Value, out le, out rpe))
                { // if the last location is set and it could not be resolved everything fails.
                    if (le != null)
                    {
                        this.ErrorMessage = string.Format("Could resolve last location: {0}",
                                                          le);
                    }
                    else if (rpe != null)
                    {
                        this.ErrorMessage = string.Format("Could route to/from last location: {0}",
                                                          rpe);
                    }
                    else
                    {
                        this.ErrorMessage = string.Format("Last location was in error list.");
                    }
                    return;
                }

                problem = new TSProblem(_weightMatrixAlgorithm.WeightIndex(first), _weightMatrixAlgorithm.WeightIndex(_last.Value),
                                        _weightMatrixAlgorithm.Weights, _turnPenalty);
            }
            else
            { // the last customer was not set.
                problem = new TSProblem(_weightMatrixAlgorithm.WeightIndex(first), _weightMatrixAlgorithm.Weights, _turnPenalty);
            }

            // execute the solver.
            if (_solver == null)
            {
                _tour = problem.Solve();
            }
            else
            {
                _tour = problem.Solve(_solver);
            }

            this.HasSucceeded = true;
        }
Exemplo n.º 43
0
 public AddTourViewModel(Tour tour)
 {
     Load(tour);
 }
Exemplo n.º 44
0
 public ActionResult DeleteTour(Tour tour)
 {
     db.Tours.Remove(db.Tours.Find(tour.ID_Tour));
     db.SaveChanges();
     return(RedirectToAction("FilteredBrowse"));
 }
Exemplo n.º 45
0
 public async Task AddTour(Tour tour)
 {
     await _context.Tours.AddAsync(tour);
 }
Exemplo n.º 46
0
 public Log AddNewTourLog(Tour tour, Log log)
 {
     return(AddNewTourLog(tour, log.Date, log.Report, log.Distance, log.Duration, log.Rating, log.Steps, log.WeightKG, log.BloodPreassure, log.Feeling, log.Weather));
 }
Exemplo n.º 47
0
        public void Load()
        {
            var country1 = new Country
            {
                Name   = "Egypt",
                Cities = new List <City>()
            };

            var c1city1 = new City
            {
                Name    = "Kom Jombo",
                Country = country1
            };

            var c1city2 = new City
            {
                Name    = "Mol Kombo",
                Country = country1
            };

            country1.Cities.Add(c1city1);
            country1.Cities.Add(c1city2);

            var room1 = new Room
            {
                Type  = "Luxe",
                Price = 1500,
                Seats = 2
            };

            var room2 = new Room
            {
                Type  = "Standard",
                Price = 700,
                Seats = 2
            };

            var room3 = new Room
            {
                Type  = "Medium",
                Price = 1150,
                Seats = 2
            };

            var room4 = new Room
            {
                Type  = "Luxe",
                Price = 2200,
                Seats = 3
            };

            var room5 = new Room
            {
                Type  = "Standard",
                Price = 850,
                Seats = 3
            };

            var room6 = new Room
            {
                Type  = "Medium",
                Price = 1500,
                Seats = 3
            };

            var meal1 = new Meal
            {
                Type  = "HB",
                Price = 200
            };

            var meal2 = new Meal
            {
                Type  = "FB",
                Price = 700
            };

            var meal3 = new Meal
            {
                Type  = "SB",
                Price = 350
            };

            var hotel1 = new Hotel
            {
                City        = c1city1,
                Name        = "Hotel Kom Jombo",
                Rating      = 4,
                SeaDistance = 500,
                Meals       = new List <Meal>(),
                Tours       = new List <Tour>(),
                Rooms       = new List <Room>()
            };

            var hotel2 = new Hotel
            {
                City        = c1city2,
                Name        = "Hotell Mol Kombo",
                Rating      = 5,
                SeaDistance = 400,
                Meals       = new List <Meal>(),
                Tours       = new List <Tour>(),
                Rooms       = new List <Room>()
            };

            hotel1.Rooms.Add(room1);
            hotel1.Rooms.Add(room2);
            hotel1.Rooms.Add(room3);
            hotel1.Rooms.Add(room6);
            hotel1.Rooms.Add(room4);

            hotel2.Rooms.Add(room1);
            hotel2.Rooms.Add(room4);
            hotel2.Rooms.Add(room5);
            hotel2.Rooms.Add(room6);
            hotel2.Rooms.Add(room3);

            hotel1.Meals.Add(meal1);
            hotel1.Meals.Add(meal2);
            hotel1.Meals.Add(meal3);

            hotel2.Meals.Add(meal1);
            hotel2.Meals.Add(meal2);
            hotel2.Meals.Add(meal3);

            var tour1 = new Tour
            {
                Description = "Best tour Egypt ever",
                DateDepart  = new DateTime(2019, 09, 30),
                Duration    = 7,
                Price       = 10000,
                Hotel       = hotel1
            };

            var tour2 = new Tour
            {
                Description = "Second Best tour Egypt ever",
                DateDepart  = new DateTime(2019, 09, 29),
                Duration    = 12,
                Price       = 16075,
                Hotel       = hotel1
            };

            var tour3 = new Tour
            {
                Description = "Third Best tour Egypt ever",
                DateDepart  = new DateTime(2019, 10, 15),
                Duration    = 10,
                Price       = 12560,
                Hotel       = hotel1
            };

            var tour5 = new Tour
            {
                Description = "Good tour Egypt",
                DateDepart  = new DateTime(2019, 09, 5),
                Duration    = 8,
                Price       = 12650,
                Hotel       = hotel2
            };

            var tour6 = new Tour
            {
                Description = "Good tour Egypt second",
                DateDepart  = new DateTime(2019, 10, 20),
                Duration    = 10,
                Price       = 15250,
                Hotel       = hotel2
            };

            var tour4 = new Tour
            {
                Description = "Third Good tour Egypt",
                DateDepart  = new DateTime(2019, 10, 26),
                Duration    = 9,
                Price       = 14520,
                Hotel       = hotel2
            };

            hotel1.Tours.Add(tour1);
            hotel1.Tours.Add(tour2);
            hotel1.Tours.Add(tour3);

            hotel2.Tours.Add(tour4);
            hotel2.Tours.Add(tour5);
            hotel2.Tours.Add(tour6);

            hotels.Add(hotel1);
            hotels.Add(hotel2);
        }
        public static void Apply(AlbaEncoding individual, int tour1Index, int position1, int length1,
                                 int tour2Index, int position2, int length2)
        {
            List <Tour> tours = individual.GetTours();

            Tour tour1      = tours[tour1Index];
            int  tour1Start = -1;

            for (int i = 0; i < individual.Length; i++)
            {
                if (individual[i] == tour1.Stops[0] - 1)
                {
                    tour1Start = i;
                    break;
                }
            }

            Tour tour2      = tours[tour2Index];
            int  tour2Start = -1;

            for (int i = 0; i < individual.Length; i++)
            {
                if (individual[i] == tour2.Stops[0] - 1)
                {
                    tour2Start = i;
                    break;
                }
            }

            AlbaEncoding original = individual.Clone() as AlbaEncoding;
            int          index    = 0;

            int start1 = tour1Start + position1;
            int end1   = start1 + length1;

            int start2 = tour2Start + position2;
            int end2   = start2 + length2;

            for (int i = 0; i < original.Length; i++)
            {
                if (index == start1)
                {
                    if (end2 - start2 == 0)
                    {
                        index = end1;
                    }
                    else
                    {
                        index = start2;
                    }
                }
                else if (index == start2)
                {
                    if (end1 - start1 == 0)
                    {
                        index = end2;
                    }
                    else
                    {
                        index = start1;
                    }
                }
                else if (index == end1)
                {
                    index = end2;
                }
                else if (index == end2)
                {
                    index = end1;
                }

                individual[i] = original[index];

                index++;
            }
        }
Exemplo n.º 49
0
 public TourReport(Tour model, string?imagePath, bool isSummary = false)
 {
     Model     = model;
     ImagePath = imagePath;
     IsSummary = isSummary;
 }
Exemplo n.º 50
0
 public void insertTour(Tour tour)
 {
     DataProvider.Instance.ExecuteVoidQuery("select add_tour( @ten , @price , @info );", new object[] { tour.TourName, tour.TourPrice, tour.TourInfo });
 }
Exemplo n.º 51
0
        public override List <Tour> GetTours()
        {
            List <Tour> result = new List <Tour>();

            int cities = ProblemInstance.Cities.Value;

            //Split permutation into vector P
            int[] P = new int[cities + 1];
            for (int i = 0; i <= cities; i++)
            {
                P[i] = -1;
            }

            double[] V = new double[cities + 1];
            V[0] = 0;
            for (int i = 1; i <= cities; i++)
            {
                V[i] = double.MaxValue;
            }

            for (int i = 1; i <= cities; i++)
            {
                int  j        = i;
                Tour tour     = new Tour();
                bool feasible = true;

                do
                {
                    tour.Stops.Add(this[j - 1] + 1);

                    VRPEvaluation eval =
                        ProblemInstance.EvaluateTour(tour, this);

                    double cost = eval.Quality;
                    feasible = ProblemInstance.Feasible(eval);

                    if (feasible || j == i)
                    {
                        if (V[i - 1] + cost < V[j])
                        {
                            V[j] = V[i - 1] + cost;
                            P[j] = i - 1;
                        }
                        j++;
                    }
                } while (j <= cities && feasible);
            }

            //extract VRP solution from vector P
            int  index  = 0;
            int  index2 = cities;
            Tour trip   = null;

            do
            {
                index = P[index2];
                trip  = new Tour();

                for (int k = index + 1; k <= index2; k++)
                {
                    trip.Stops.Add(this[k - 1] + 1);
                }

                if (trip.Stops.Count > 0)
                {
                    result.Add(trip);
                }

                index2 = index;
            } while (index != 0);

            //if there are too many vehicles - repair
            while (result.Count > ProblemInstance.Vehicles.Value)
            {
                Tour tour = result[result.Count - 1];

                //find predecessor / successor in permutation
                int predecessorIndex = Array.IndexOf(this.array, tour.Stops[0] - 1) - 1;
                if (predecessorIndex >= 0)
                {
                    int predecessor = this[predecessorIndex] + 1;

                    foreach (Tour t in result)
                    {
                        int insertPosition = t.Stops.IndexOf(predecessor) + 1;
                        if (insertPosition != -1)
                        {
                            t.Stops.InsertRange(insertPosition, tour.Stops);
                            break;
                        }
                    }
                }
                else
                {
                    int successorIndex = Array.IndexOf(this.array,
                                                       tour.Stops[tour.Stops.Count - 1] - 1) + 1;
                    int successor = this[successorIndex] + 1;

                    foreach (Tour t in result)
                    {
                        int insertPosition = t.Stops.IndexOf(successor);
                        if (insertPosition != -1)
                        {
                            t.Stops.InsertRange(insertPosition, tour.Stops);
                            break;
                        }
                    }
                }

                result.Remove(tour);
            }

            return(result);
        }
Exemplo n.º 52
0
 public void updateTour(Tour tour)
 {
     DataProvider.Instance.ExecuteVoidQuery("UPDATE tour SET ten_tour = @ten , gia_tour = @price , noi_dung = @info WHERE id_tour = @id ;",
                                            new object[] { tour.TourName, tour.TourPrice, tour.TourInfo, tour.IdTour });
 }
Exemplo n.º 53
0
        public static void writeKML(string filename, Dictionary <int, List <CurrentState> > flightdatas, Action <double> progressBar1, double basealt = 0)
        {
            SharpKml.Dom.AltitudeMode altmode = SharpKml.Dom.AltitudeMode.Absolute;

            Color[] colours =
            {
                Color.Red,    Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo,
                Color.Violet, Color.Pink
            };

            Document kml = new Document();

            AddNamespace(kml, "gx", "http://www.google.com/kml/ext/2.2");

            Style style = new Style();

            style.Id   = "yellowLineGreenPoly";
            style.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4);


            PolygonStyle pstyle = new PolygonStyle();

            pstyle.Color  = new Color32(HexStringToColor("7f00ff00"));
            style.Polygon = pstyle;

            kml.AddStyle(style);

            Style stylet = new Style();

            stylet.Id = "track";
            SharpKml.Dom.IconStyle ico = new SharpKml.Dom.IconStyle();
            LabelStyle             lst = new LabelStyle();

            lst.Scale   = 0;
            stylet.Icon = ico;
            ico.Icon    =
                new IconStyle.IconLink(
                    new Uri("http://earth.google.com/images/kml-icons/track-directional/track-none.png"));
            stylet.Icon.Scale = 0.5;
            stylet.Label      = lst;

            kml.AddStyle(stylet);

            foreach (var flightdatai in flightdatas)
            {
                var sysid      = flightdatai.Key;
                var flightdata = flightdatai.Value;

                Tour tour = new Tour()
                {
                    Name = "First Person View"
                };
                Playlist tourplaylist = new Playlist();

                // create sub folders
                Folder planes = new Folder();
                planes.Name = "Models " + sysid;
                kml.AddFeature(planes);

                Folder points = new Folder();
                points.Name = "Points " + sysid;
                kml.AddFeature(points);

                // coords for line string
                CoordinateCollection coords = new CoordinateCollection();

                int      a          = 1;
                int      c          = -1;
                DateTime lasttime   = DateTime.MaxValue;
                DateTime starttime  = DateTime.MinValue;
                Color    stylecolor = Color.AliceBlue;
                string   mode       = "";
                if (flightdata.Count > 0)
                {
                    mode = flightdata[0].mode;
                }

                foreach (CurrentState cs in flightdata)
                {
                    progressBar1(50 + (int)((float)a / (float)flightdata.Count * 100.0f / 2.0f));

                    if (starttime == DateTime.MinValue)
                    {
                        starttime = cs.datetime;
                        lasttime  = cs.datetime;
                    }

                    if (mode != cs.mode || flightdata.Count == a)
                    {
                        c++;

                        LineString ls = new LineString();
                        ls.AltitudeMode = altmode;
                        ls.Extrude      = true;

                        ls.Coordinates = coords;

                        Placemark pm = new Placemark();

                        pm.Name     = c + " Flight Path " + mode;
                        pm.StyleUrl = new Uri("#yellowLineGreenPoly", UriKind.Relative);
                        pm.Geometry = ls;

                        SharpKml.Dom.TimeSpan ts = new SharpKml.Dom.TimeSpan();
                        ts.Begin = starttime;
                        ts.End   = cs.datetime;

                        pm.Time = ts;

                        // setup for next line
                        mode      = cs.mode;
                        starttime = cs.datetime;

                        stylecolor = colours[c % (colours.Length - 1)];

                        Style style2 = new Style();
                        style2.Line = new LineStyle(new Color32(stylecolor), 4);

                        pm.StyleSelector = style2;

                        kml.AddFeature(pm);

                        coords = new CoordinateCollection();
                    }

                    Vector location = new Vector(cs.lat, cs.lng, cs.altasl);

                    if (basealt != 0)
                    {
                        location.Altitude = cs.alt + basealt;
                        coords.Add(location);
                    }
                    else
                    {
                        coords.Add(location);
                    }

                    SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();
                    tstamp.When = cs.datetime;

                    FlyTo flyto = new FlyTo();

                    flyto.Duration = (cs.datetime - lasttime).TotalMilliseconds / 1000.0;

                    flyto.Mode = FlyToMode.Smooth;
                    SharpKml.Dom.Camera cam = new SharpKml.Dom.Camera();
                    cam.AltitudeMode = altmode;
                    cam.Latitude     = cs.lat;
                    cam.Longitude    = cs.lng;
                    cam.Altitude     = location.Altitude;
                    cam.Heading      = cs.yaw;
                    cam.Roll         = -cs.roll;
                    cam.Tilt         = (90 - (cs.pitch * -1));

                    cam.GXTimePrimitive = tstamp;

                    flyto.View = cam;
                    //if (Math.Abs(flyto.Duration.Value) > 0.1)
                    {
                        tourplaylist.AddTourPrimitive(flyto);
                        lasttime = cs.datetime;
                    }


                    Placemark pmplane = new Placemark();
                    pmplane.Name = "Point " + a;


                    pmplane.Time = tstamp;

                    pmplane.Visibility = false;

                    SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                    loc.Latitude  = cs.lat;
                    loc.Longitude = cs.lng;
                    loc.Altitude  = location.Altitude;

                    if (loc.Altitude < 0)
                    {
                        loc.Altitude = 0.01;
                    }

                    SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                    ori.Heading = cs.yaw;
                    ori.Roll    = -cs.roll;
                    ori.Tilt    = -cs.pitch;

                    SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                    sca.X = 2;
                    sca.Y = 2;
                    sca.Z = 2;

                    Model model = new Model();
                    model.Location     = loc;
                    model.Orientation  = ori;
                    model.AltitudeMode = altmode;
                    model.Scale        = sca;

                    try
                    {
                        Description desc = new Description();
                        desc.Text = @"<![CDATA[
              <table>
                <tr><td>Roll: " + model.Orientation.Roll.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Pitch: " + model.Orientation.Tilt.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Yaw: " + model.Orientation.Heading.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Time: " + cs.datetime.ToString("HH:mm:sszzzzzz") + @" </td></tr>
              </table> ]]>";
                        //            ]]>";

                        pmplane.Description = desc;
                    }
                    catch
                    {
                    }

                    SharpKml.Dom.Link link = new SharpKml.Dom.Link();
                    link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                    model.Link = link;

                    pmplane.Geometry = model;

                    planes.AddFeature(pmplane);

                    ///

                    Placemark pmt = new Placemark();

                    SharpKml.Dom.Point pnt = new SharpKml.Dom.Point();
                    pnt.AltitudeMode = altmode;
                    pnt.Coordinate   = location;

                    pmt.Name = "" + a;

                    pmt.Description = pmplane.Description;

                    pmt.Time = tstamp;

                    pmt.Geometry = pnt;
                    pmt.StyleUrl = new Uri("#track", UriKind.Relative);

                    points.AddFeature(pmt);

                    a++;
                }

                tour.Playlist = tourplaylist;

                kml.AddFeature(tour);
            }

            Serializer serializer = new Serializer();

            serializer.Serialize(kml);


            //Console.WriteLine(serializer.Xml);

            StreamWriter sw = new StreamWriter(filename);

            sw.Write(serializer.Xml);
            sw.Close();

            // create kmz - aka zip file

            FileStream      fs        = File.Open(filename.Replace(Path.GetExtension(filename), ".kmz"), FileMode.Create);
            ZipOutputStream zipStream = new ZipOutputStream(fs);

            zipStream.SetLevel(9);             //0-9, 9 being the highest level of compression
            zipStream.UseZip64 = UseZip64.Off; // older zipfile

            // entry 1
            string entryName = ZipEntry.CleanName(Path.GetFileName(filename));
            // Removes drive from name and fixes slash direction
            ZipEntry newEntry = new ZipEntry(entryName);

            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[] buffer = new byte[4096];
            using (FileStream streamReader = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            File.Delete(filename);

            filename = Settings.GetRunningDirectory() +
                       "block_plane_0.dae";

            // entry 2
            entryName = ZipEntry.CleanName(Path.GetFileName(filename));
            // Removes drive from name and fixes slash direction
            newEntry          = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();


            zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream
            zipStream.Close();
        }
Exemplo n.º 54
0
        public Tour GetByID(int id)
        {
            Tour data = db.Tours.FirstOrDefault(x => x.TourID == id);

            return(data);
        }
Exemplo n.º 55
0
 public static void DeleteTour(Tour tour)
 {
     File.Delete(CustomTourPath(tour));
 }
Exemplo n.º 56
0
        public void Create_Tour_With_Competitions_And_Players()
        {
            var courseconfig = new Courseconfiguration
            {
                CourseMap   = "coursemap",
                CourseName  = "first",
                Description = "my first course"
            };

            courseconfig.AddHole(new Hole {
                Length = 100, Number = 1, Par = 3
            });
            courseconfig.AddHole(new Hole {
                Length = 86, Number = 2, Par = 3
            });
            courseconfig.AddHole(new Hole {
                Length = 149, Number = 3, Par = 4
            });

            var player1 = new Player
            {
                Email     = "*****@*****.**",
                FirstName = "firstname",
                LastName  = "lastname",
                Phone     = "08112233"
            };

            var player2 = new Player
            {
                Email     = "*****@*****.**",
                FirstName = "john",
                LastName  = "doe",
                Phone     = "08334422"
            };

            var competition = new Competition {
                Date = DateTime.UtcNow, Name = "dgt1"
            };

            competition.AddPlayer(new PlayerStatus {
                Player = player1, Status = PlayerCompetitionStatus.Registered
            });
            competition.AddPlayer(new PlayerStatus {
                Player = player2, Status = PlayerCompetitionStatus.Payed
            });

            competition.AddRound(new Round {
                Courseconfig = courseconfig, RoundNumber = 1
            });
            competition.AddRound(new Round {
                Courseconfig = courseconfig, RoundNumber = 2
            });

            var tour = new Tour {
                Year = "2015", Description = "testTour"
            };

            tour.AddCompetition(competition);

            Player dbPlayer1;
            Player dbPlayer2;
            Courseconfiguration dbCourseconfig;
            Tour dbTour;

            using (var session = NHibernateFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var pid1 = session.Save(player1);
                    var pid2 = session.Save(player2);
                    var cid  = session.Save(courseconfig);
                    var tid  = session.Save(tour);

                    dbPlayer1      = session.Get <Player>(pid1);
                    dbPlayer2      = session.Get <Player>(pid2);
                    dbCourseconfig = session.Get <Courseconfiguration>(cid);
                    dbTour         = session.Get <Tour>(tid);

                    session.Delete(dbPlayer1);
                    session.Delete(dbPlayer2);
                    session.Delete(dbCourseconfig);
                    session.Delete(dbTour);

                    transaction.Commit();
                }
            }

            Assert.AreEqual(player1, dbPlayer1);
            Assert.AreEqual(player2, dbPlayer2);
            Assert.AreEqual(courseconfig, dbCourseconfig);
            Assert.AreEqual(tour, dbTour);
        }
Exemplo n.º 57
0
 public static void SaveDefaultTour(Tour tour)
 {
     XmlOperation.TrySerialize(tour, Paths.defaultTourPath);
 }
Exemplo n.º 58
0
#pragma warning restore 1998

#pragma warning disable 1998
        // disable async warning - no RemoveAsync available
        public async Task DeleteTour(Tour tour)
        {
            _context.Tours.Remove(tour);
        }
Exemplo n.º 59
0
#pragma warning disable 1998
        // disable async warning - no code
        public async Task UpdateTour(Tour tour)
        {
            // no code in this implementation
        }
Exemplo n.º 60
0
        public int InsertTour(Tour tour, Tournament tournament)
        {
            string state    = "";
            short  inserted = 0;
            short  skipped  = 0;
            short  error    = 0;

            using (SqlConnection connection = new SqlConnection(_connectionString))
            {
                try
                {
                    Trace.TraceInformation($"Checking tour #{tour.Id} ({tour.QuestionsNum})");
                    if (!Exist(connection, tour))
                    {
                        Trace.TraceInformation($"Inserting tour #{tour.Id}");
                        tour.ImportedAt = DateTime.UtcNow;
                        connection.Insert(tour);
                        state = "Inserted";
                    }
                    else
                    {
                        Trace.TraceInformation($"Tounament #{tour.Id} already exists");
                        state = "Skipped";
                    }
                    int tourId       = tour.Id;
                    int tournamentId = tournament?.Id ?? tour.ParentId;

                    foreach (var question in tour.Questions)
                    {
                        try
                        {
                            //Trace.TraceInformation($"Checking question #{question.Id}");
                            if (!Exist(connection, question))
                            {
                                Trace.Write(".");
                                //Trace.TraceInformation($"Inserting question #{question.Id}");

                                question.ParentId     = tourId;
                                question.TourId       = tourId;
                                question.TournamentId = tournamentId;
                                question.ImportedAt   = DateTime.UtcNow;

                                connection.Insert(question);
                                inserted++;
                            }
                            else
                            {
                                Trace.Write("-");
                                //Trace.TraceInformation($"Question #{question.Id} already exists");
                                skipped++;
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.WriteLine("");
                            Trace.TraceError($"Exception when inserting question #{question.Id}. {ex.Message}", ex);
                            error++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("");
                    Trace.TraceError($"Exception when inserting tour #{tour.Id}. {ex.Message}", ex);
                    state = "Error";
                }
            }

            Trace.WriteLine("");
            Trace.TraceInformation($"Tour #{tour.Id} handled. State: {state}. {inserted} + {skipped} + {error} = {inserted + skipped + error} = {tour.QuestionsNum} ");

            return(tour.Questions.Count);
        }