示例#1
0
 private void InitCars(ProblemData problemData)
 {
     for (int i = 0; i < problemData.NumberOfVehicles; ++i)
     {
         problemData.Cars.Add(new Car());
     }
 }
        public List <ExtRouteInfo> BuildRoutePool(List <RouteSet> solutionPool, double overloadFactor, string gamsFolderPath)
        {
            OverloadFactor = 0;
            List <ExtRouteInfo> routePool     = new List <ExtRouteInfo>();
            SingleRouteSPDGAMS  gamsProcedure = new SingleRouteSPDGAMS(ProblemData);
            DirectoryInfo       gamsDir       = Directory.CreateDirectory(gamsFolderPath);
            int i = 0;

            foreach (var solution in solutionPool)
            {
                foreach (var route in solution)
                {
                    if (route.IsEmpty)
                    {
                        continue;
                    }
                    if (ProblemData.IsFeasible(route) && !ExtRouteInfo.IsInPool(routePool, route))
                    {
                        DirectoryInfo gamsIteration = gamsDir.CreateSubdirectory(i.ToString());
                        Route         current       = gamsProcedure.Solve(gamsIteration.FullName, route);
                        routePool.Add(new ExtRouteInfo(current, GetTravelCost(route)));
                    }
                }
            }
            return(routePool);
        }
示例#3
0
        /// <summary>
        /// Default constructor that requires a path to be passed in
        /// </summary>
        /// <param name="path"></param>
        public Creation(string path)
        {
            _universePath = path;
            ShipData      = LoadData <ShipData>(@"Data/shipData.json");
            _worldInfo    = LoadData <WorldInfo>(@"Data/worldTags.json");
            _starData     = LoadData <StarData>(@"Data/starData.json");
            _charData     = LoadData <CharData>(@"Data/characterData.json");
            PoiData       = LoadData <PoiData>(@"Data/pointsOfInterest.json");
            ProblemData   = LoadData <ProblemData>(@"Data/problemData.json");
            // SocietyData = LoadData<SocietyData>(@"Data/societyData.json");
            SocietyData = null;
            AlienData   = LoadData <AlienData>(@"Data/alienData.json");

            MaleFirstNameGeneration = new NameGeneration();
            MaleFirstNameGeneration.GenerateChain(_charData.MaleName);

            FemaleFirstNameGeneration = new NameGeneration();
            FemaleFirstNameGeneration.GenerateChain(_charData.FemaleName);

            StarNameGeneration = new NameGeneration();
            StarNameGeneration.GenerateChain(_starData.Stars);

            PlanetNameGeneration = new NameGeneration();
            PlanetNameGeneration.GenerateChain(_starData.Planets);

            // LastNameGeneration = new NameGeneration();
            // LastNameGeneration.GenerateChain(CharData.LastName);

            CharacterNameGenerations.Add(MaleFirstNameGeneration);
            CharacterNameGenerations.Add(FemaleFirstNameGeneration);
            // CharacterNameGenerations.Add(LastNameGeneration);
        }
        public override bool IsAllowedMovement(TwoInterMove m)
        {
            double delivery = ProblemData.TotalDelivery(m.deRoute) + ProblemData.Clients[m.current[m.orIndex]].Delivery + ProblemData.Clients[m.current[m.orIndex + 1]].Delivery;
            double pickup   = ProblemData.TotalPickup(m.deRoute) + ProblemData.Clients[m.current[m.orIndex]].Pickup + +ProblemData.Clients[m.current[m.orIndex + 1]].Pickup;

            return(Math.Max(delivery, pickup) <= m.deRoute.Vehicle.Capacity);
        }
示例#5
0
        private void menuSettingProblem_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new ProblemSetupDialog(this);

            if (dlg.ShowDialog() != true)
            {
                return;
            }

            EnableSelectMode();

            try
            {
                problemData = dlg.problemData;

                if (dlg.P > countPoint)
                {
                    MessageBox.Show("Не может быть начато. Должен содержать хотя бы одну вершину.", "Ошибка");
                    return;
                }
            }
            catch (GeneticAlgorithmException ex)
            {
                MessageBox.Show(ex.Message, "Ошибка");
                return;
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка");
                return;
            }
        }
        private ProblemData GetProblemData()
        {
            EntryFileParser parser = new EntryFileParser(EntryFilePath);
            ProblemData     data   = parser.Parse();

            return(data);
        }
示例#7
0
        public static double isAnswer(Chromosome chromosome, Cost cost, ProblemData problemData)
        {
            double fitness   = 0;
            int    sumMedian = 0;

            int[][] X = XMultiplicationChromosome(cost.arrayX, chromosome.chromosomeArray);

            for (int i = 0; i < chromosome.SizeChromosome; i++)
            {
                sumMedian += chromosome.chromosomeArray[i];

                for (int j = 0; j < cost.vertexCount; j++)
                {
                    if (cost.costEdgeArray[i][j].EmptyCost)
                    {
                        continue;
                    }

                    fitness += (
                        (cost.costEdgeArray[i][j].roadKm * problemData.RoadCost) * X[i][j]);
                }
                fitness += cost.costVertexArray[i] * chromosome.chromosomeArray[i];
            }


            return(fitness);
        }
示例#8
0
 public override void Setup(IEvolutionState state, IParameter paramBase)
 {
     confMat                = new double[10, 10];
     imageTransformer       = new ImageTransformer(0, 0, "", "");
     NumOfImagesPerCategory = 100;
     SuperpixelSize         = 8;
     NumOfClasses           = 10;
     NumOfFeatures          = 64 * 64 / (SuperpixelSize * SuperpixelSize);
     CategoryDirs           = Directory.EnumerateDirectories(@"F:\Gesty\problem2\grayscale").ToArray();
     currentImage           = new Image <Gray, Byte> [4];
     originalImage          = new Image <Gray, Byte> [4];
     for (int i = 0; i < 4; i++)
     {
         currentImage[i]  = new Image <Gray, Byte>(64, 64);
         originalImage[i] = new Image <Gray, Byte>(64, 64);
     }
     // Parameter = new SVMParameter();
     //Parameter.Type = SVMType.C_SVC;
     //Parameter.Kernel = SVMKernelType.POLY;
     base.Setup(state, paramBase);
     Input = (ProblemData)state.Parameters.GetInstanceForParameterEq(
         paramBase.Push(P_DATA), null, typeof(ProblemData));
     Input.Setup(state, paramBase.Push(P_DATA));
     // imageTransformer.RescaleAndSaveImages();
     // imageList = Directory.GetFiles(@"F:\Gesty\rescaled");
 }
示例#9
0
        public MainWindow()
        {
            InitializeComponent();

            // Create DefaultUser if it doesn't exist
            try
            {
                // Try loading default profile
                currentUserProfile = ProblemData.LoadUserData("DefaultUser" + ".xml");

                // Check loaded profile for version
                if (currentUserProfile.clientVersion != clientVersion)
                {
                    throw new Exception($"Loaded file (ver. {currentUserProfile.clientVersion}) has version mismatch with client (ver. {clientVersion})");
                }
            }
            catch (System.IO.FileNotFoundException)
            {
                // Create new and save
                currentUserProfile = new UserProfile("DefaultUser", clientVersion);
                currentUserProfile.SaveUserData();
            }

            // Greet the user
            HelloUser_TextBlock.Text = HelloUser_TextBlock.Text.Replace("[username]", currentUserProfile.userName);

            // Display the client version
            ClientVersion_TextBlock.Text = ClientVersion_TextBlock.Text.Replace("[version]", clientVersion);
        }
示例#10
0
        public async Task <ActionResult <ProblemMetadata> > Create([FromBody] ProblemData data)
        {
            IProblemProvider res = await _workspace.Problems.Create(data.Metadata);

            await res.SetDescription(data.Description);

            if (data.Samples != null)
            {
                foreach (TestCaseData v in data.Samples)
                {
                    ITestCaseProvider item = await res.Samples.Create(v.Metadata);
                    await UpdateIOData(v, item);
                }
            }

            if (data.Tests != null)
            {
                foreach (TestCaseData v in data.Tests)
                {
                    ITestCaseProvider item = await res.Tests.Create(v.Metadata);
                    await UpdateIOData(v, item);
                }
            }

            return(Created($"problems/{res.Id}", await res.GetMetadata()));
        }
示例#11
0
        private IRegressionSolution CreateLinearRegressionSolution()
        {
            if (Content == null)
            {
                throw new InvalidOperationException();
            }
            double rmse, cvRmsError;
            var    problemData = (IRegressionProblemData)ProblemData.Clone();

            if (!problemData.TrainingIndices.Any())
            {
                return(null);                              // don't create an LR model if the problem does not have a training set (e.g. loaded into an existing model)
            }
            //clear checked inputVariables
            foreach (var inputVariable in problemData.InputVariables.CheckedItems)
            {
                problemData.InputVariables.SetItemCheckedState(inputVariable.Value, false);
            }

            //check inputVariables used in the symbolic regression model
            var usedVariables =
                Content.Model.SymbolicExpressionTree.IterateNodesPostfix().OfType <VariableTreeNode>().Select(
                    node => node.VariableName).Distinct();

            foreach (var variable in usedVariables)
            {
                problemData.InputVariables.SetItemCheckedState(
                    problemData.InputVariables.First(x => x.Value == variable), true);
            }

            var solution = LinearRegression.CreateLinearRegressionSolution(problemData, out rmse, out cvRmsError);

            solution.Name = "Baseline (linear subset)";
            return(solution);
        }
示例#12
0
        protected Route ParseGamsSolution(string routePath, int[] mapping, Route currentRoute)
        {
            //TODO!!!!! Verificar q exista el fichero, si no existe es q gams no pudo encontrar solucion para alguna ruta
            Route        newRoute = new Route(currentRoute.Vehicle);
            Regex        routeExp = new Regex(@"(?<ci>C\d+)\S+(?<cj>C\d+)\S+(?<v>\d\.d+)");
            StreamReader reader   = new StreamReader(Path.Combine(routePath, "tspspdsolution.dat"));
            double       cost     = double.Parse(reader.ReadLine().Trim());

            if (cost == 0)
            {
                Console.WriteLine("weak feasible {0} strong feasible {1}", ProblemData.IsFeasible(currentRoute), ((VRPSimultaneousPickupDelivery)ProblemData).IsStrongFeasible(currentRoute));
                return(currentRoute);
            }
            Dictionary <int, int> routeInfo = GetRouteInfo(reader);
            int lastCLient = 0;
            int newClient  = routeInfo[lastCLient];

            while (newClient != 0)
            {
                newRoute.Add(mapping[newClient]);
                lastCLient = newClient;
                newClient  = routeInfo[lastCLient];
            }
            return(newRoute);
        }
示例#13
0
    private void maxValueInCollection(Problem ProblemType, Text textToChange)
    {
        if (Player.playerProgressData.ContainsKey(ProblemType))
        {
            ProblemData problemData = Player.playerProgressData[ProblemType];

            if (problemData.levels.Count > 0)
            {
                int maxLevel = 1;

                foreach (var entry in problemData.levels)
                {
                    if (entry.Value != true)
                    {
                        break;
                    }

                    maxLevel = entry.Key;
                }

                textToChange.text  = LEVEL_TEXT + maxLevel;
                textToChange.color = Color.black;
            }
        }
    }
示例#14
0
 public override bool IsAllowedMovement(TwoOneInterSwap m)
 {
     return(ProblemData.StrongReplaceOverload(m.current, m.orIndex, 2, new List <int> {
         m.deRoute[m.deIndex]
     }) <= epsilon &&
            ProblemData.StrongReplaceOverload(m.deRoute, m.deIndex, 1, m.current.GetRange(m.orIndex, 2)) <= epsilon);
 }
        private List <Journey> CalculateJourneys(ProblemData data)
        {
            JourneyPlanner planner  = new JourneyPlanner(data);
            var            journeys = planner.Plan();

            return(journeys);
        }
        private IRegressionSolution CreateLinearRegressionSolution()
        {
            if (Content == null)
            {
                throw new InvalidOperationException();
            }
            double rmse, cvRmsError;
            var    problemData = (IRegressionProblemData)ProblemData.Clone();

            if (!problemData.TrainingIndices.Any())
            {
                return(null);                              // don't create an LR model if the problem does not have a training set (e.g. loaded into an existing model)
            }
            var usedVariables = Content.Model.VariablesUsedForPrediction;

            var usedDoubleVariables = usedVariables
                                      .Where(name => problemData.Dataset.VariableHasType <double>(name))
                                      .Distinct();

            var usedFactorVariables = usedVariables
                                      .Where(name => problemData.Dataset.VariableHasType <string>(name))
                                      .Distinct();

            // gkronber: for binary factors we actually produce a binary variable in the new dataset
            // but only if the variable is not used as a full factor anyway (LR creates binary columns anyway)
            var usedBinaryFactors =
                Content.Model.SymbolicExpressionTree.IterateNodesPostfix().OfType <BinaryFactorVariableTreeNode>()
                .Where(node => !usedFactorVariables.Contains(node.VariableName))
                .Select(node => Tuple.Create(node.VariableValue, node.VariableValue));

            // create a new problem and dataset
            var variableNames =
                usedDoubleVariables
                .Concat(usedFactorVariables)
                .Concat(usedBinaryFactors.Select(t => t.Item1 + "=" + t.Item2))
                .Concat(new string[] { problemData.TargetVariable })
                .ToArray();
            var variableValues =
                usedDoubleVariables.Select(name => (IList)problemData.Dataset.GetDoubleValues(name).ToList())
                .Concat(usedFactorVariables.Select(name => problemData.Dataset.GetStringValues(name).ToList()))
                .Concat(
                    // create binary variable
                    usedBinaryFactors.Select(t => problemData.Dataset.GetReadOnlyStringValues(t.Item1).Select(val => val == t.Item2 ? 1.0 : 0.0).ToList())
                    )
                .Concat(new[] { problemData.Dataset.GetDoubleValues(problemData.TargetVariable).ToList() });

            var newDs          = new Dataset(variableNames, variableValues);
            var newProblemData = new RegressionProblemData(newDs, variableNames.Take(variableNames.Length - 1), variableNames.Last());

            newProblemData.TrainingPartition.Start = problemData.TrainingPartition.Start;
            newProblemData.TrainingPartition.End   = problemData.TrainingPartition.End;
            newProblemData.TestPartition.Start     = problemData.TestPartition.Start;
            newProblemData.TestPartition.End       = problemData.TestPartition.End;

            var solution = LinearRegression.CreateLinearRegressionSolution(newProblemData, out rmse, out cvRmsError);

            solution.Name = "Baseline (linear subset)";
            return(solution);
        }
示例#17
0
 public Problem(string filename)
 {
     this.name = Path.GetFileNameWithoutExtension(filename);
     using (StreamReader r = new StreamReader(filename))
     {
         this.data = JsonConvert.DeserializeObject <ProblemData>(r.ReadToEnd());
     }
 }
        public MatrixRoadDialog(Window owner, Cost cost, ProblemData problemData, MainGraph graph)
        {
            Owner = owner;
            InitializeComponent();


            DataContext = new Content(Matrix, cost, problemData, graph);
        }
        protected double MaxDemandAfterReplace(Route current, List <int> oldRange, List <int> newRange)
        {
            double pickup    = ProblemData.TotalPickup(current) - oldRange.Sum(c => ProblemData.Clients[c].Pickup) + newRange.Sum(c => ProblemData.Clients[c].Pickup);
            double delivery  = ProblemData.TotalDelivery(current) - oldRange.Sum(c => ProblemData.Clients[c].Delivery) + newRange.Sum(c => ProblemData.Clients[c].Delivery);
            double maxDemand = Math.Max(pickup, delivery);

            return(maxDemand);
        }
        public void Solve()
        {
            ProblemData    data     = GetProblemData();
            List <Journey> journeys = CalculateJourneys(data);

            DisplayResults(data, journeys);

            GenerateOutputFile(journeys);
        }
 private void Start()
 {
     audioSource       = GetComponent <AudioSource>();
     data              = GameState.problemGenerator.GetProblem();
     correctChoice     = Random.Range(1, 3);
     questionText.text = data.Question;
     answer1Text.text  = correctChoice == 1 ? data.Correct : data.Wrong;
     answer2Text.text  = correctChoice == 1 ? data.Wrong : data.Correct;
 }
示例#22
0
        public double AlphaWeakFeasibility(Route current)
        {
            double maxDemand = Math.Max(ProblemData.TotalPickup(current), ProblemData.TotalDelivery(current));

            if (maxDemand <= current.Vehicle.Capacity)
            {
                return(0);
            }
            return((maxDemand - current.Vehicle.Capacity) / current.Vehicle.Capacity);
        }
示例#23
0
        public override bool IsAllowedMovement(InterMove m)
        {
            double maxDemand = Math.Max(ProblemData.TotalPickup(m.deRoute) + ProblemData.Clients[m.current[m.orIndex]].Pickup, ProblemData.TotalDelivery(m.deRoute) + ProblemData.Clients[m.current[m.orIndex]].Delivery);

            if (maxDemand <= m.deRoute.Vehicle.Capacity)
            {
                return(true);
            }
            return((maxDemand - m.deRoute.Vehicle.Capacity) / m.deRoute.Vehicle.Capacity < WeakThreshold);
        }
示例#24
0
 public void Serialize(ProblemData problemData)
 {
     using (FileCreator fc = new FileCreator(_outputPath))
     {
         foreach (var car in problemData.CarsWhichCanTMoveAnymore)
         {
             WriteCarLine(fc, car);
         }
     }
 }
示例#25
0
 public override bool IsAllowedMovement(InterSwap m)
 {
     if (m.deRoute.IsEmpty)
     {
         return(Math.Max(ProblemData.Clients[m.current[m.orIndex]].Delivery, ProblemData.Clients[m.current[m.orIndex]].Pickup) <= m.deRoute.Vehicle.Capacity);
     }
     return(ProblemData.StrongReplaceOverload(m.deRoute, m.deIndex, 1, new List <int> {
         m.current[m.orIndex]
     }) <= epsilon);
 }
示例#26
0
        public ActionResult UpdateProblem(int id, [FromBody] ProblemData problemData)
        {
            var problem = DbContext.Problems.FirstOrDefault(g => g.IdProblem == id);

            problem.Link        = problemData.ProblemLink;
            problem.Dificultate = problemData.ProblemDifficulty;

            DbContext.SaveChanges();

            return(Ok("Problem information changed"));
        }
        private void DisplayResults(ProblemData data, List <Journey> journeys)
        {
            int totalPoints = data.Streets.Where(_ => _.WasVisited).Sum(_ => _.Distance);

            Console.WriteLine(totalPoints + " points !");

            foreach (var journey in journeys)
            {
                Console.WriteLine($"Voiture {journey.CarId} : {journey.Steps.Count()} étapes en {journey.TotalSeconds} secondes");
            }
        }
示例#28
0
        private void ParseFirstLine(ProblemData problemData, Parser parser)
        {
            var firstLineInts = parser.GetIntsOfLine();

            problemData.NumberOfRows     = firstLineInts[0];
            problemData.NumberOfColumns  = firstLineInts[1];
            problemData.NumberOfVehicles = firstLineInts[2];
            problemData.NumberOfRides    = firstLineInts[3];
            problemData.PerRideBonus     = firstLineInts[4];
            problemData.NumberOfSteps    = firstLineInts[5];
        }
示例#29
0
        protected double AlphaWeakFeasibilityAfterReplace(Route current, List <int> oldRange, List <int> newRange)
        {
            double pickup    = ProblemData.TotalPickup(current) - oldRange.Sum(c => ProblemData.Clients[c].Pickup) + newRange.Sum(c => ProblemData.Clients[c].Pickup);
            double delivery  = ProblemData.TotalDelivery(current) - oldRange.Sum(c => ProblemData.Clients[c].Delivery) + newRange.Sum(c => ProblemData.Clients[c].Delivery);
            double maxDemand = Math.Max(pickup, delivery);

            if (maxDemand <= current.Vehicle.Capacity)
            {
                return(0);
            }
            return((maxDemand - current.Vehicle.Capacity) / current.Vehicle.Capacity);
        }
示例#30
0
        // This gets executed by the ProblemLoadingWorker
        private void ProblemLoadingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int loadAm = (int)(e.Argument);

            // For each problem
            foreach (int i in Enumerable.Range(0, loadAm))
            {
                // Load using ProblemData function
                ProblemData.LoadNext(1);
                // Report progress (updates loading bar)
                (sender as BackgroundWorker).ReportProgress(i * 100 / loadAm);
            }
        }