Ejemplo n.º 1
0
 public EvoStrat(
     OptimizationRun run,
     ICollection <long> driverIds,
     ICollection <long> taskIds,
     ICollection <Entity> entities,
     ICollection <Driver> drivers,
     ICollection <Task> tasks,
     ICollection <RouteLeg> routeLegs,
     ICollection <DriverTaskMultiplier> routeMutipliers,
     bool costOptimization, double distanceCostRatio, double avgLegLength, double maxLegLength,
     double avgLegPenalty, double maxLegPenalty, double demand)
 {
     _run               = run;
     _driverIds         = driverIds.ToList();
     _stopIds           = taskIds.ToList();
     _routeEntities     = entities.ToList();
     _drivers           = drivers.ToList();
     _tasks             = tasks.ToList();
     _routeLegs         = routeLegs.ToList();
     _mutipliers        = routeMutipliers.ToList();
     _costOptimization  = costOptimization;
     _distanceCostRatio = distanceCostRatio;
     _avgLegLength      = avgLegLength;
     _avgLegPenalty     = avgLegPenalty;
     _maxLegLength      = maxLegLength;
     _maxLegPenalty     = maxLegPenalty;
     _demand            = demand;
 }
Ejemplo n.º 2
0
 public EvoStrat(OptimizationRun run, ICollection <RouteDriver> drivers, ICollection <RouteOrder> orders, ICollection <RouteLeg> routeLegs, ICollection <RouteOrderMultiplier> routeMutipliers,
                 bool costOptimization, double distanceCostRatio, double avgLegLength, double maxLegLength, double avgLegPenalty, double maxLegPenalty, double demand, double capacity)
 {
     _run               = run;
     _drivers           = drivers.ToList();
     _orders            = orders.ToList();
     _routeLegs         = routeLegs.ToList();
     _mutipliers        = routeMutipliers.ToList();
     _costOptimization  = costOptimization;
     _distanceCostRatio = distanceCostRatio;
     _avgLegLength      = avgLegLength;
     _avgLegPenalty     = avgLegPenalty;
     _maxLegLength      = maxLegLength;
     _maxLegPenalty     = maxLegPenalty;
     _demand            = demand;
     _capacity          = capacity;
 }
Ejemplo n.º 3
0
        public void StartOptimization()
        {
            _running = true;
            _ready   = true;

            while (_running && _ready)
            {
                OptimizationRun run           = new OptimizationRun();
                RouteResponse   response      = null;
                List <Entity>   routeEntities = new List <Entity> ();
                List <RouteLeg> routeLegs     = new List <RouteLeg>();

                try{
                    // First, let's check to see if there's any jobs to process
                    response = GetNextJobToProcess();


                    if (response != null)
                    {
                        // we've got a job!
                        run.ID = response.routeId;
                        _runID = response.routeId;
                        _ready = false;

                        Console.WriteLine("Set RunID = " + run.ID);

                        List <Int64> driverList = new List <Int64>();
                        List <Int64> stopList   = new List <Int64>();

                        Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Optimization job " + run.ID + " started.");

                        NpgsqlConnection conn = new NpgsqlConnection("Server=hci.cvwcpfnur8ep.us-east-1.rds.amazonaws.com;Port=5432;User Id=hci_user;Password=Nov299pe;Database=route;");
                        conn.Open();

                        try
                        {
                            // Update the driver entities
                            foreach (Driver d in response.drivers)
                            {
                                NpgsqlCommand command = new NpgsqlCommand(
                                    "SELECT * FROM update_entity(" + response.customerId.ToString() + "::bigint, "
                                    + d.name + "::varchar, "
                                    + d.location.latitude.ToString() + "::float8, "
                                    + d.location.longitude.ToString() + "::float8, "
                                    + "2::int2)", conn);

                                command.CommandType = CommandType.Text;

                                Object result = command.ExecuteScalar();

                                // set the driver system id
                                d.id = Convert.ToInt64(result);
                                driverList.Add(Convert.ToInt64(result));

                                // now add the driver to the entity list
                                routeEntities.Add(new Entity {
                                    id     = Convert.ToInt64(result),
                                    geoLat = d.location.latitude,
                                    geoLon = d.location.longitude
                                });
                            }

                            Console.WriteLine("Drivers: " + string.Join <Int64>(",", driverList));

                            // update the stop entities
                            foreach (Task t in response.tasks)
                            {
                                NpgsqlCommand command = new NpgsqlCommand(
                                    "SELECT * FROM update_entity(" + response.customerId.ToString() + "::bigint, "
                                    + t.stop.name + "::varchar, "
                                    + t.stop.location.latitude.ToString() + "::float8, "
                                    + t.stop.location.longitude.ToString() + "::float8, "
                                    + "1::int2)", conn);

                                command.CommandType = CommandType.Text;

                                Object result = command.ExecuteScalar();

                                // set's the id to the stop ID, to lookup during the routeleg calculation
                                t.id = Convert.ToInt64(result);
                                stopList.Add(Convert.ToInt64(result));

                                // now add the stop to the entity list
                                routeEntities.Add(new Entity {
                                    id     = Convert.ToInt64(result),
                                    geoLat = t.stop.location.latitude,
                                    geoLon = t.stop.location.longitude
                                });
                            }

                            Console.WriteLine("Stops: " + string.Join <Int64>(",", stopList));

                            // now get a list of route legs
                            string drivers = string.Join <Int64>(",", driverList);
                            string stops   = string.Join <Int64>(",", stopList);

                            NpgsqlCommand legCommand = new NpgsqlCommand("SELECT * FROM calc_entity_matrix('" + drivers + "','" + stops + "')", conn);


                            NpgsqlDataReader dr = legCommand.ExecuteReader();
                            while (dr.Read())
                            {
                                routeLegs.Add(new RouteLeg {
                                    FromID          = Convert.ToInt32(dr.GetValue(0)),
                                    ToID            = Convert.ToInt32(dr.GetValue(1)),
                                    DrivingDistance = Convert.ToDecimal(dr.GetValue(2)),
                                    DrivingTime     = Convert.ToDecimal(dr.GetValue(3))
                                });
                            }
                        }

                        finally
                        {
                            conn.Close();
                        }

                        // Now calculate the route leg stuff
                        Routing routing = new Routing();


                        ICollection <RouteLeg>             legs           = routing.GetRouteLegs(routeEntities, routeLegs, 1, Routing.CostType.Distance);
                        ICollection <DriverTaskMultiplier> legMultipliers = routing.GetRoutePenalties(response.drivers, response.tasks);

                        int demand = 1;

                        // set the alogorithm manually for demo
                        run.GenerationsToRun  = response.generations;
                        run.Algorithm         = "ES_MDVRPTW_v3.hl";
                        run.CostOptimization  = false;
                        run.DistanceCostRatio = 1.0m;
                        run.AvgLegLength      = 20;
                        run.AvgLegPenalty     = 0;
                        run.MaxLegLength      = 30;
                        run.MaxLegPenalty     = 0;

                        _evoStrat = new EvoStrat(
                            run,
                            driverList,
                            stopList,
                            routeEntities,
                            response.drivers,
                            response.tasks,
                            legs,
                            legMultipliers,
                            run.CostOptimization,
                            Convert.ToDouble(run.DistanceCostRatio),
                            Convert.ToDouble(run.AvgLegLength),
                            Convert.ToDouble(run.MaxLegLength),
                            Convert.ToDouble(run.AvgLegPenalty),
                            Convert.ToDouble(run.MaxLegPenalty),
                            demand);

                        _evoStrat.StatusUpdate += new EventHandler(Routing_StatusUpdate);
                        _evoStrat.StartOptimization();
                    }
                    else
                    {
                        //Stop ();

                        // No jobs, so terminate instance!
                        Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": No job to process...");

                        //Process shutdown = new Process();
                        //shutdown.StartInfo.FileName = "shutdown.sh";
                        //shutdown.Start();


                        Thread.Sleep(_sleepDuration);
                    }
                }
                catch (Exception exc) {
                    // ignore error
                    Thread.Sleep(_sleepDuration);
                    var error = exc;
                }
            }              // loop until it gets a job
        }
Ejemplo n.º 4
0
        public void StartOptimization()
        {
            _running = true;
            _ready   = true;

            while (_running && _ready)
            {
                // first get the next Optimization Run to solve
                //OptimizationRun run = GetNextOptimizationJob();

                OptimizationRun run = null;

                using (JsonServiceClient client = new JsonServiceClient())
                {
                    RouteJobsResponse response = client.Get <RouteJobsResponse>("http://api.datalyticsllc.com/routing/routejobs/-1");
                    if (response.RouteJobs.Count > 0)
                    {
                        run = response.RouteJobs [0];
                    }
                };

                if (run != null)
                {
                    //Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Optimization job " + run.ID + " started.");

                    /*
                     * // get the connection string for the customer who posted the optimization job
                     * ScheduleCustomer customer = centralUnitOfWork.ScheduleCustomerRepository.GetByID(run.CustomerID);
                     *
                     * RoutingUnitOfWork unitOfWork = new RoutingUnitOfWork(customer.ConnectionString);
                     */

                    // we've got a job! don't get the next job off this thread...we're done.
                    _ready = false;
                    Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Optimization job " + run.ID + " started.");

                    /*
                     * // need to dynamically switch to the customer database to get the list of drivers and orders
                     * ICollection<RouteDriver> drivers = unitOfWork.GetRouteDriversWithAvailability(run.Drivers, run.ServiceDate).ToList();
                     * ICollection<RouteOrder> orders = unitOfWork.GetRouteOrders(run.Orders).ToList();
                     *
                     * // get a list of stops from the orders (ie. patients from the visits).  Used for RouteLeg lookup
                     * ICollection<RouteStop> stops = orders.Select(x => new RouteStop()
                     *                                           {
                     *      ID = x.StopID, GeoLat = x.GeoLat, GeoLon = x.GeoLon,
                     *      Address = x.Address, City = x.City, State = x.State, Zip = x.Zip
                     * }).Distinct().ToList();
                     *
                     *
                     * // So we pass the route legs when we call the optimizer, or calculate here?
                     * Routing.Routing routing = new Routing.Routing();
                     *
                     * ICollection<RouteLeg> routeLegs = routing.GetRouteLegs(stops, drivers, run.CustomerID, Routing.Routing.CostType.Distance);
                     *
                     * Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Parsing optimization tags - '" + run.OptimizationTags + "'.");
                     * IEnumerable<OptimizationTag> optimizationTags = OptimizationTagParser.Parse(run.OptimizationTags);
                     *
                     * ICollection<RouteOrderMultiplier> legMultipliers = routing.GetRouteMultipliers(orders, drivers, optimizationTags);
                     *
                     * int demand = run.MaxCapacity > 0 ? 1 : 0;
                     *
                     * _evoStrat = new EvoStrat(
                     *      run,
                     *      drivers,
                     *      orders,
                     *      routeLegs,
                     *      legMultipliers,
                     *      run.CostOptimization,
                     *      Convert.ToDouble(run.DistanceCostRatio),
                     *      Convert.ToDouble(run.AvgLegLength),
                     *      Convert.ToDouble(run.MaxLegLength),
                     *  Convert.ToDouble(run.AvgLegPenalty),
                     *      Convert.ToDouble(run.MaxLegPenalty),
                     *      demand,
                     *      run.MaxCapacity);
                     *
                     * _evoStrat.StatusUpdate += new EventHandler(Routing_StatusUpdate);
                     * _evoStrat.StartOptimization();
                     */
                }
                else
                {
                    Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": No job to process.");
                    Thread.Sleep(_sleepDuration);
                }
            }              // loop until it gets a job
        }
Ejemplo n.º 5
0
        // Thread-safe method to get the next optimization job to run
        private OptimizationRun GetNextOptimizationJob()
        {
            OptimizationRun run = null;

            SqlConnection  conn = new SqlConnection("Data Source=CoordCare.com;Initial Catalog=Optimization;Integrated Security=False;User ID=sa;Password=Nov299pe");
            SqlCommand     cmd;
            SqlDataAdapter sda;
            DataSet        tables = new DataSet();

            conn.Open();

            // get the next
            cmd             = new SqlCommand();
            cmd.Connection  = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "GetNextOptimizationRun";

            tables = new DataSet();

            sda = new SqlDataAdapter(cmd);
            sda.Fill(tables);

            if (tables.Tables[0].Rows.Count == 0)
            {
                conn.Close();
                return(null);
            }
            else
            {
                foreach (DataRow r in tables.Tables[0].Rows)
                {
                    try
                    {
                        run = new OptimizationRun();

                        run.ID                = Convert.ToInt32(r["ID"].ToString());
                        run.CustomerID        = Convert.ToInt32(r["CustomerID"].ToString());
                        run.GenerationsToRun  = Convert.ToInt32(r["GenerationsToRun"].ToString());
                        run.ServiceDate       = Convert.ToDateTime(r["ServiceDate"].ToString());
                        run.Drivers           = r["Drivers"].ToString();
                        run.Orders            = r["Orders"].ToString();
                        run.Algorithm         = r["Algorithm"].ToString();
                        run.Demo              = r["Demo"] == null ? false : Convert.ToInt32(r["Demo"]) == 1;
                        run.OptimizationTags  = r["Tags"].ToString();
                        run.CostOptimization  = Convert.ToBoolean(r["CostOptimization"].ToString());
                        run.DistanceCostRatio = Convert.ToDecimal(r["DistanceCostRatio"].ToString());
                        run.AvgLegLength      = Convert.ToInt32(r["AvgLegLength"].ToString());
                        run.MaxLegLength      = Convert.ToInt32(r["MaxLegLength"].ToString());
                        run.AvgLegPenalty     = Convert.ToDecimal(r["AvgLegPenalty"].ToString());
                        run.MaxLegPenalty     = Convert.ToDecimal(r["MaxLegPenalty"].ToString());
                        run.MaxCapacity       = Convert.ToInt32(r["MaxCapacity"].ToString());
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine("[" + string.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now) + "] Thread " + _threadID + ": Error -- " + exc.ToString());
                    }
                }

                conn.Close();
            }

            return(run);
        }