Esempio n. 1
0
        private void btnGraph_Click(object sender, EventArgs e)
        {
            double cAmount  = double.Parse(txtChangeAmount.Text);
            double maxPrice = double.Parse(txtMaxPrice.Text);
            double minPrice = double.Parse(txtMinPrice.Text);

            if (chbIncludeExtra.Checked && !ExtraFunctions.ValidateExtraConfiguration(txtPeriod.Text, tbExtraPeriod.Text,
                                                                                      cbPeriodType.SelectedIndex, cbExtraPeriodType.SelectedIndex))
            {
                showError(Constancts.ErrorMessagePeriodType);
            }
            double basePrice  = double.Parse(txtBasePrice.Text);
            int    period     = int.Parse(txtPeriod.Text);
            int    periodType = cbPeriodType.SelectedIndex;
            double newPrice   = basePrice;

            SetImport2FirstPeriods(period, basePrice);

            for (int i = period; i < _importDateData.Count; i++)
            {
                newPrice = AlgorithmFunctions.GetNewPrice(newPrice, period, periodType, _exportDateData, _exportSalesData, cAmount, maxPrice, minPrice);
                _exportPriceData.Add(newPrice);
                _exportSalesData.Add(AlgorithmFunctions.CalculateSales(newPrice, _importSalesData.ToArray()[i], double.Parse(txtBasePrice.Text)));
            }

            DateTime[] x  = _importDateData.ToArray();
            int[]      y  = _importSalesData.ToArray();
            int[]      y2 = _exportSalesData.ToArray();

            Grahps grahps = new Grahps(Constancts.CompareTitule, Constancts.Serie1, x, y, Constancts.Serie2, y2);

            grahps.ShowGrahpVaues();
        }
Esempio n. 2
0
 public void XORFunction()
 {
     Assert.IsTrue(AlgorithmFunctions.XOR('1', '1') == '0');
     Assert.IsTrue(AlgorithmFunctions.XOR('1', '0') == '1');
     Assert.IsTrue(AlgorithmFunctions.XOR('0', '1') == '1');
     Assert.IsTrue(AlgorithmFunctions.XOR('0', '0') == '0');
 }
Esempio n. 3
0
        public void KeyTransformantion()
        {
            string key            = "10111110101011100001110001001110000010000100100000100011";
            var    transformedKey = AlgorithmFunctions.KeyTransformation(key, 0, EnumProcessType.ENCRYPTION);

            Assert.IsTrue(transformedKey.Length == 48);
        }
Esempio n. 4
0
        public async Task <IActionResult> Create([Bind("AnalysisName,UserIsNetworkSeed,UserGivenNetworkGeneration,UserGivenNodes,UserGivenTarget,UserGivenDrugTarget,AlgorithmType,GeneticRandomSeed,GeneticMaxIteration,GeneticMaxIterationNoImprovement,GeneticMaxPathLength,GeneticPopulationSize,GeneticElementsRandom,GeneticPercentageRandom,GeneticPercentageElite,GeneticProbabilityMutation,GreedyRandomSeed,GreedyMaxIteration,GreedyMaxIterationNoImprovement,GreedyMaxPathLength,GreedyRepeats,GreedyHeuristics")] AnalysisModel analysisModel)
        {
            ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User);

            analysisModel.User = user;

            // If the model is valid and the user is logged in.
            if (ModelState.IsValid && user != null)
            {
                // If the network is generated successfully.
                if (AlgorithmFunctions.GenerateNetwork(analysisModel))
                {
                    // Save the new analysis to the database.
                    _context.Add(analysisModel);
                    await _context.SaveChangesAsync();

                    // Calling on a Hangfire background task the analysis run.
                    var analysisRun = new AnalysisRun(_context);
                    BackgroundJob.Enqueue(() => analysisRun.RunAnalysis(analysisModel.AnalysisId));

                    // This also seems to be working. The only problem is that it's not implmeneted on a background task.
                    // await AlgorithmFunctions.RunAnalysis(_context, analysisModel);

                    // Return to Dashboard.
                    return(RedirectToAction(nameof(Index)));
                }
                else
                {
                    return(View(analysisModel));
                }
            }
            return(View(analysisModel));
        }
Esempio n. 5
0
        public void CompressionPermutation()
        {
            Assert.IsTrue(Data.CompressionPermutationTable.Length == 48);

            string data = "ENSAR DUMAN";
            //56 to 48
            var res = AlgorithmFunctions.CompressionPermutation(data);
        }
Esempio n. 6
0
        public void CircularLeftShift()
        {
            string data = "ENSAR DUMAN";
            var    res  = AlgorithmFunctions.CircularLeftShift(data, 0, EnumProcessType.ENCRYPTION);

            res = AlgorithmFunctions.CircularLeftShift(res, 0, EnumProcessType.DECRYPTION);
            Assert.IsTrue(res == data);
        }
Esempio n. 7
0
        public void ExpensionPermutation()
        {
            Assert.IsTrue(Data.ExpansionPermutationTable.Length == 48);

            string data = "ENSAR DUMAN";

            //32 to 48
            var res2 = AlgorithmFunctions.ExpentsonPermutation(data);
        }
Esempio n. 8
0
        public void FinalPermutation()
        {
            for (int i = 1; i <= 64; i++)
            {
                Assert.IsTrue(Data.InitialPermutationTable.Contains(i));
            }

            var data   = "0011111111100111000100111101100000101000010110001111111100101100";
            var output = AlgorithmFunctions.FinalPermutation(data);

            Assert.IsTrue(output == "0101110001011100010110101110101101101101110110100011100100011001");
        }
Esempio n. 9
0
        private void btnSingleValue_Click(object sender, EventArgs e)
        {
            double basePrice  = double.Parse(txtBasePrice.Text);
            int    period     = int.Parse(txtPeriod.Text);
            int    periodType = cbPeriodType.SelectedIndex;
            double cAmount    = double.Parse(txtChangeAmount.Text);
            double maxPrice   = double.Parse(txtMaxPrice.Text);
            double minPrice   = double.Parse(txtMinPrice.Text);

            SetImport2FirstPeriods(period, basePrice);

            txtSingleValue.Text = AlgorithmFunctions.GetNewPrice(basePrice, period, periodType, _exportDateData, _exportSalesData, cAmount, maxPrice, minPrice).ToString();
        }
        /// <summary>
        /// The initial testing program of the greedy algorithm.
        /// </summary>
        public static void InitialProgram()
        {
            var randomSeed = new Random().Next();
            var separators = new List <String>()
            {
                ";", "\t", "\n", "\r"
            };
            var rand = new Random(randomSeed);

            var graphType      = "BreastDEF";
            var graphText      = System.IO.File.ReadAllText($@"C:\Users\vpopescu\source\repos\NetControl\NetControl\Networks\{graphType}Graph.txt");
            var targetText     = System.IO.File.ReadAllText($@"C:\Users\vpopescu\source\repos\NetControl\NetControl\Networks\{graphType}Target.txt");
            var drugTargetText = System.IO.File.ReadAllText($@"C:\Users\vpopescu\source\repos\NetControl\NetControl\Networks\DrugTarget.txt");

            var greedyRepeats       = 2;
            var greedyHeuristic     = "A;B;C;D;E;F;G;Z";
            var greedyMaxPathLength = 5;
            var greedyMaxIterations = 1000;
            var greedyMaxIterationsNoImprovement = 100;

            var nodes       = AlgorithmFunctions.GetNodes(graphText, separators);
            var edges       = AlgorithmFunctions.GetEdges(graphText, separators);
            var targets     = AlgorithmFunctions.GetTargetNodes(targetText, nodes, separators);
            var drugTargets = AlgorithmFunctions.GetTargetNodes(drugTargetText, nodes, separators);

            var fullSeparator = ";";
            var halfSeparator = ",";

            // Get the heuristic list from the string.
            var heuristics = AlgorithmGreedyFunctions.GetHeuristic(greedyHeuristic, fullSeparator, halfSeparator);
            // Get all heuristics.
            var allHeuristics = new List <string>();

            foreach (var item in heuristics)
            {
                foreach (var h in item)
                {
                    allHeuristics.Add(h);
                }
            }

            Console.WriteLine($"{nodes.Count} nodes, {edges.Count} edges, {targets.Count} targets, {drugTargets.Count} drug targets.");
            heuristics.ForEach((item) => { item.ForEach((h) => Console.Write($"{h} ")); Console.Write("; "); });
            Console.WriteLine();

            // Set up for the initial iteration.
            var currentIteration = 0;
            var currentIterationNoImprovement = 0;
            var bestResult = targets.Count;

            // Run for as long as we haven't reached the final iteration or the final iteration without improvement.
            while (currentIteration < greedyMaxIterations && currentIterationNoImprovement < greedyMaxIterationsNoImprovement)
            {
                // Display the current iteration.
                // Console.WriteLine($"Now at iteration {currentIteration} / {greedyMaxIterations}, {currentIterationNoImprovement} / {greedyMaxIterationsNoImprovement}");
                // Set up the control path to start from the target nodes.
                var controlPath = new Dictionary <String, List <String> >();
                targets.ForEach((node) => controlPath[node] = new List <String>()
                {
                    node
                });
                var currentRepeat = 0;
                while (currentRepeat < greedyRepeats)
                {
                    var currentTargets    = new List <String>(targets);
                    var currentPathLength = 0;
                    // If it is the first check of the current iteration, we have no kept nodes, so the current targets are simply the targets.
                    // The optimization part for the "repeats" starts here.
                    var keptNodes = AlgorithmGreedyFunctions.GetKeptTargetNodes(controlPath);
                    controlPath    = AlgorithmGreedyFunctions.ResetControlPath(keptNodes, controlPath);
                    currentTargets = currentTargets.Except(keptNodes).ToList();
                    // Run until there are no current targets or we reached the maximum path length.
                    while (currentTargets.Any() && currentPathLength < greedyMaxPathLength)
                    {
                        //var (matchedEdges, unmatched) = ComputeMaximalMatching(nodes, edges, heuristics, controlPath, currentTargets, rand, drugTargets);
                        var unmatched = new List <string>();
                        unmatched.AddRange(currentTargets);
                        var free = new List <string>();
                        free.AddRange(nodes);
                        var matchedEdges = new List <(string, string)>();
                        // If it is the first check of the current iteration, we have no kept nodes, so the left nodes and edges remain unchanged.
                        // Otherwise, we remove from the left nodes the corresponding nodes in the current step in the control paths for the kept nodes.
                        // The optimization part for the "repeat" begins here.
                        foreach (var item in keptNodes)
                        {
                            if (currentPathLength + 1 < controlPath[item].Count)
                            {
                                var leftNode = controlPath[item][currentPathLength + 1];
                                free.Remove(leftNode);
                            }
                        }
                        foreach (var heuristic in heuristics)
                        {
                            var matchings    = new List <(string, string)>();
                            var left         = new List <string>(); left.AddRange(free);
                            var right        = new List <string>(); right.AddRange(unmatched);
                            var currentEdges = new List <(string, string)>();
                            currentEdges = GetSingleHeuristicEdges(left, right, edges, heuristic, controlPath, drugTargets);
                            var mEdges = GetMaximumMatching(left, right, currentEdges, rand);
                            foreach (var mEdge in mEdges)
                            {
                                matchedEdges.Add(mEdge);
                                free.Remove(mEdge.Item1);
                                unmatched.Remove(mEdge.Item2);
                            }
                        }
                        currentTargets = AlgorithmGreedyFunctions.GetMatchedNodes(matchedEdges);
                        // And update the control path.
                        controlPath = AlgorithmGreedyFunctions.UpdateControlPath(matchedEdges, controlPath);

                        currentPathLength++;
                    }
                    currentRepeat++;
                }
                // Display the control path for the current iteration.
                //foreach (var item in controlPath)
                //{
                //    Console.Write($"{item.Key}:\t");
                //    foreach (var node in item.Value)
                //    {
                //        Console.Write($"{node}\t");
                //    }
                //    Console.WriteLine();
                //}
                //Console.WriteLine("----");
                // The optimization part for the "cut to driven" parameter begins here.
                var stop = false;
                while (!stop)
                {
                    stop = true;
                    foreach (var item1 in controlPath)
                    {
                        var controllingNode = item1.Value.Last();
                        foreach (var item2 in controlPath)
                        {
                            var firstIndex = item2.Value.IndexOf(controllingNode);
                            if (firstIndex != -1 && firstIndex != item2.Value.Count - 1)
                            {
                                item2.Value.RemoveRange(firstIndex + 1, item2.Value.Count - firstIndex - 1);
                                stop = false;
                            }
                        }
                    }
                }
                // We compute the result.
                var controllingNodes = AlgorithmGreedyFunctions.GetControllingNodes(controlPath).Keys.ToList();
                var result           = controllingNodes.Count;
                // If the current solution is better than the previously obtained best solution.
                if (result < bestResult)
                {
                    bestResult = result;
                    Console.WriteLine($"{result} nodes in best solution so far, out of which {controllingNodes.Intersect(drugTargets).Count()} drug targets.");
                    controllingNodes.ForEach((node) => Console.Write($"{node} "));
                    Console.WriteLine();
                    currentIterationNoImprovement = 0;
                }
                else
                {
                    currentIterationNoImprovement++;
                }
                currentIteration++;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Runs the genetic algorithm on the given analysis.
        /// </summary>
        /// <param name="analysisModel">The analysis upon which to run the algorithm.</param>
        /// <param name="separators">The separators which are used to split the entries in the database strings.</param>
        /// <returns></returns>
        private async Task RunGeneticAlgorithm(AnalysisModel analysisModel, List <String> separators)
        {
            // Get the initial list of nodes and edges from the generated network.
            var oldNodes         = AlgorithmFunctions.GetNodes(analysisModel.NetworkEdges, separators);
            var oldEdges         = AlgorithmFunctions.GetEdges(analysisModel.NetworkEdges, separators);
            var oldTargets       = AlgorithmFunctions.GetTargetNodes(analysisModel.NetworkTargets, oldNodes, separators);
            var oldTargetIndices = AlgorithmGeneticFunctions.GetTargetIndices(oldNodes, oldTargets);
            var oldA             = AlgorithmGeneticFunctions.GetAdjacencyMatrix(oldNodes, oldEdges);
            var oldPowersA       = AlgorithmGeneticFunctions.GetAdjacencyMatrixPowers(oldA, analysisModel.GeneticMaxPathLength.Value);
            var oldList          = AlgorithmGeneticFunctions.GetList(oldPowersA, oldTargetIndices);

            // Get the trimmed list of nodes and edges.
            var nodes         = AlgorithmGeneticFunctions.GetNewNodes(oldNodes, oldList);
            var edges         = AlgorithmGeneticFunctions.GetNewEdges(oldEdges, nodes);
            var singleNodes   = AlgorithmGeneticFunctions.GetSingleTargets(nodes, oldTargets);
            var A             = AlgorithmGeneticFunctions.GetAdjacencyMatrix(nodes, edges);
            var targets       = AlgorithmGeneticFunctions.GetNewTargets(nodes, oldTargets);
            var drugTargets   = analysisModel.NetworkDrugTargetCount.Value != 0 ? AlgorithmFunctions.GetTargetNodes(analysisModel.NetworkDrugTargets, nodes, separators) : null;
            var targetIndices = AlgorithmGeneticFunctions.GetTargetIndices(nodes, targets);
            var C             = AlgorithmGeneticFunctions.GetTargetMatrix(nodes, targetIndices);
            var powersA       = AlgorithmGeneticFunctions.GetAdjacencyMatrixPowers(A, analysisModel.GeneticMaxPathLength.Value);
            var powers        = AlgorithmGeneticFunctions.GetTargetMatrixPowers(C, powersA);
            var list          = AlgorithmGeneticFunctions.GetList(powersA, targetIndices);

            // Initialization of the first population.
            var rand        = new Random(analysisModel.GeneticRandomSeed.Value);
            var bestFitness = 0.0;
            var p           = new Population(analysisModel.GeneticPopulationSize.Value);

            p.Initialize(powers, list, analysisModel.GeneticElementsRandom.Value, rand);

            // Running for the given number of iterations.
            while (analysisModel.AlgorithmCurrentIteration < analysisModel.GeneticMaxIteration && analysisModel.AlgorithmCurrentIterationNoImprovement < analysisModel.GeneticMaxIterationNoImprovement && !analysisModel.ScheduledToStop.Value)
            {
                // Move on to the next population.
                p = p.nextPopulation(analysisModel.GeneticPercentageElite.Value, analysisModel.GeneticPercentageRandom.Value,
                                     analysisModel.GeneticProbabilityMutation.Value, powers, list, analysisModel.GeneticElementsRandom.Value, rand);
                // Get the best fitness of the current population.
                var fitness = p.getBestFitness();
                // If the fitness is better than the current best one.
                if (bestFitness <= fitness)
                {
                    if (bestFitness < fitness)
                    {
                        // Update the current best fitness.
                        bestFitness = fitness;
                        analysisModel.AlgorithmCurrentIterationNoImprovement = -1;
                    }
                    // Get the best results.
                    var bestChromosomes = p.GetBestChromosomes();
                    var result          = "";
                    foreach (var chromosome in bestChromosomes)
                    {
                        foreach (var gene in chromosome.Genes.Distinct())
                        {
                            result += nodes[gene] + ";";
                        }
                        result += "\n";
                    }
                    analysisModel.NetworkBestResultCount = bestChromosomes.First().Genes.Distinct().Count();
                    analysisModel.NetworkBestResultNodes = result;
                    analysisModel.AlgorithmCurrentIterationNoImprovement++;
                }
                else
                {
                    analysisModel.AlgorithmCurrentIterationNoImprovement++;
                }
                analysisModel.AlgorithmCurrentIteration++;
                analysisModel.Status = $"Analysis ongoing ({analysisModel.AlgorithmCurrentIteration} / {analysisModel.GeneticMaxIteration}, " +
                                       $"{analysisModel.AlgorithmCurrentIterationNoImprovement} / {analysisModel.GeneticMaxIterationNoImprovement}).";
                await _context.SaveChangesAsync();
            }
            analysisModel.Status  = "Completed";
            analysisModel.EndTime = DateTime.Now;
            await _context.SaveChangesAsync();
        }
Esempio n. 12
0
        /// <summary>
        /// Runs the greedy algorithm on the given analysis.
        /// </summary>
        /// <param name="analysisModel">The analysis upon which to run the algorithm.</param>
        /// <param name="separators">The separators which are used to split the entries in the database strings.</param>
        /// <returns></returns>
        private async Task RunGreedyAlgorithm(AnalysisModel analysisModel, List <String> separators)
        {
            // Get the list of nodes and edges from the generated network.
            var nodes       = AlgorithmFunctions.GetNodes(analysisModel.NetworkEdges, separators);
            var edges       = AlgorithmFunctions.GetEdges(analysisModel.NetworkEdges, separators);
            var targets     = AlgorithmFunctions.GetTargetNodes(analysisModel.NetworkTargets, nodes, separators);
            var drugTargets = analysisModel.NetworkDrugTargetCount.Value != 0 ? AlgorithmFunctions.GetTargetNodes(analysisModel.NetworkDrugTargets, nodes, separators) : null;

            // Get the heuristic list from the string.
            var fullSeparator = ";";
            var halfSeparator = ",";
            var heuristics    = AlgorithmGreedyFunctions.GetHeuristic(analysisModel.GreedyHeuristics, fullSeparator, halfSeparator);
            // Get all heuristics.
            var allHeuristics = new List <string>();

            foreach (var item in heuristics)
            {
                foreach (var h in item)
                {
                    allHeuristics.Add(h);
                }
            }

            // Set up for the first iteration.
            var bestResult = targets.Count;
            var rand       = new Random(analysisModel.GreedyRandomSeed.Value);

            // Run for as long as we haven't reached the final iteration or the final iteration without improvement.
            while (analysisModel.AlgorithmCurrentIteration < analysisModel.GreedyMaxIteration && analysisModel.AlgorithmCurrentIterationNoImprovement < analysisModel.GreedyMaxIterationNoImprovement && !analysisModel.ScheduledToStop.Value)
            {
                // Set up the control path to start from the target nodes.
                var controlPath = new Dictionary <String, List <String> >();
                targets.ForEach((node) => controlPath[node] = new List <String>()
                {
                    node
                });
                var currentRepeat = 0;
                while (currentRepeat < analysisModel.GreedyRepeats)
                {
                    var currentTargets    = new List <String>(targets);
                    var currentPathLength = 0;
                    // If it is the first check of the current iteration, we have no kept nodes, so the current targets are simply the targets.
                    // The optimization part for the "repeats" starts here.
                    var keptNodes = AlgorithmGreedyFunctions.GetKeptTargetNodes(controlPath);
                    controlPath    = AlgorithmGreedyFunctions.ResetControlPath(keptNodes, controlPath);
                    currentTargets = currentTargets.Except(keptNodes).ToList();
                    while (currentTargets.Any() && currentPathLength + 1 < analysisModel.GreedyMaxPathLength)
                    {
                        // Compute the current edges ending in the current targets.
                        var heuristicEdges = AlgorithmGreedyFunctions.GetHeuristicEdges(currentTargets, edges, heuristics, allHeuristics, controlPath, drugTargets);
                        // Start building the bipartite graph for the current step.
                        var leftNodes     = heuristicEdges.Select((edge) => edge.Item1).Distinct().ToList();
                        var rightNodes    = new List <String>(currentTargets);
                        var matchingEdges = new List <(String, String)>(heuristicEdges);
                        // If it is the first check of the current iteration, we have no kept nodes, so the left nodes and edges remain unchanged.
                        // Otherwise, we remove from the left nodes the corresponding nodes in the current step in the control paths for the kept nodes.
                        // The optimization part for the "repeat" begins here.
                        foreach (var item in keptNodes)
                        {
                            if (currentPathLength + 1 < controlPath[item].Count)
                            {
                                var leftNode = controlPath[item][currentPathLength + 1];
                                leftNodes.Remove(leftNode);
                                matchingEdges.RemoveAll((edge) => edge.Item1 == leftNode);
                            }
                        }
                        // Compute the maximum matching and the matched left nodes, which will become the new current targets.
                        var matchedEdges        = AlgorithmGreedyFunctions.GetMaximumMatching(leftNodes, rightNodes, matchingEdges, rand);
                        var unmatchedRightNodes = AlgorithmGreedyFunctions.GetUnmatchedNodes(currentTargets, matchedEdges);
                        currentTargets = AlgorithmGreedyFunctions.GetMatchedNodes(matchedEdges);
                        // And update the control path.
                        controlPath = AlgorithmGreedyFunctions.UpdateControlPath(matchedEdges, controlPath);
                        currentPathLength++;
                    }
                    currentRepeat++;
                }
                // The optimization part for the "cut to driven" parameter begins here.
                var stop = false;
                while (!stop)
                {
                    stop = true;
                    foreach (var item1 in controlPath)
                    {
                        var controllingNode = item1.Value.Last();
                        foreach (var item2 in controlPath)
                        {
                            var firstIndex = item2.Value.IndexOf(controllingNode);
                            if (firstIndex != -1 && firstIndex != item2.Value.Count - 1)
                            {
                                item2.Value.RemoveRange(firstIndex, item2.Value.Count - 1 - firstIndex);
                                stop = false;
                            }
                        }
                    }
                }
                // We compute the result.
                var controllingNodes = AlgorithmGreedyFunctions.GetControllingNodes(controlPath).Keys.ToList();
                var result           = controllingNodes.Count;
                // If the current solution is better than the previously obtained best solution.
                if (result < bestResult)
                {
                    bestResult = result;
                    var resultNodes = "";
                    analysisModel.AlgorithmCurrentIterationNoImprovement = 0;
                    analysisModel.NetworkBestResultCount            = result;
                    controllingNodes.ForEach((node) => resultNodes += nodes + ";");
                    analysisModel.NetworkBestResultNodes            = resultNodes;
                }
                else
                {
                    analysisModel.AlgorithmCurrentIterationNoImprovement++;
                }
                analysisModel.AlgorithmCurrentIteration++;
                analysisModel.Status = $"Analysis ongoing ({analysisModel.AlgorithmCurrentIteration} / {analysisModel.GreedyMaxIteration}, " +
                                       $"{analysisModel.AlgorithmCurrentIterationNoImprovement} / {analysisModel.GreedyMaxIterationNoImprovement}).";
                await _context.SaveChangesAsync();
            }
            analysisModel.Status  = "Completed";
            analysisModel.EndTime = DateTime.Now;
            await _context.SaveChangesAsync();
        }