Beispiel #1
0
        public IDNA <T> Anneal(IDNA <T> Initial)
        {
            double   InstanceTempature = GlobalConfiguration.InitialTempature;
            Random   rnd             = new Random((int)DateTime.Now.Ticks);
            IDNA <T> CurrentIterator = Initial.Clone();
            IDNA <T> InstanceBest    = Initial.Clone();

            while (InstanceTempature > 1)
            {
                IDNA <T> Neighbour = CurrentIterator.Clone();
                Neighbour.Mutate(rnd);
                Neighbour.CalculateFitness();

                double probability = AcceptanceProbability(1 / CurrentIterator.GetFitnesss() * 100000, 1 / Neighbour.GetFitnesss() * 100000, InstanceTempature);
                if (Shared.HitChance(rnd, probability))
                {
                    CurrentIterator = Neighbour;
                }

                if (BestFitness.GetFitnesss() < Neighbour.GetFitnesss())
                {
                    InstanceBest = CurrentIterator;
                }

                InstanceTempature *= 1 - GlobalConfiguration.TempatureDecay;
            }

            return(InstanceBest);
        }
Beispiel #2
0
        public void SingleAnneal()
        {
            IDNA <T> CurrentIterator = this.BestFitness.Clone();

            this.BestFitness = this.BestFitness.Clone();
            this.StatusGraph.ClearHistory();
            this.StatusGraph.Average = 0;
            this.Temperature         = GlobalConfiguration.InitialTempature;

            while (this.Temperature > 1)
            {
                IDNA <T> Neighbour = CurrentIterator.Clone();
                Neighbour.Mutate();
                Neighbour.CalculateFitness();

                double probability = AcceptanceProbability(1 / CurrentIterator.GetFitnesss() * 100000, 1 / Neighbour.GetFitnesss() * 100000, this.Temperature);
                if (Shared.HitChance(probability))
                {
                    CurrentIterator = Neighbour;
                }

                if (BestFitness.GetFitnesss() < Neighbour.GetFitnesss())
                {
                    this.BestFitness = CurrentIterator;
                }

                this.StatusGraph.AddToHistory(CurrentIterator.GetFitnesss());
                this.Temperature *= 1 - GlobalConfiguration.TempatureDecay;
            }
        }
Beispiel #3
0
 public static string ToAscii(string domain, bool beStrict = false)
 {
     if (IDNA.Unicode_ToASCII(domain, false, true, true, beStrict, false, beStrict, out string result))
     {
         throw new ValidationErrorException();
     }
     return(result);
 }
Beispiel #4
0
        private IDNA <T>[] PickParents()
        {
            IDNA <T>[] arrParents = new IDNA <T> [2];

            arrParents[0] = this.MyRoulette.Pick();
            arrParents[1] = this.MyRoulette.Pick();

            return(arrParents);
        }
Beispiel #5
0
        public int Search(IDNA dna)
        {
            int result = 0;

            result += dna.Components.CountHorizontalOcurrences(this.SequenceToFind);
            result += dna.Components.CountVerticalOcurrences(this.SequenceToFind);
            result += dna.Components.CountDiagonalOcurrences(this.SequenceToFind);

            return(result);
        }
Beispiel #6
0
        public IEnumerable <IAnalysisResult> Analyze(IDNA dna)
        {
            List <IAnalysisResult> result = new List <IAnalysisResult>();

            foreach (var analysis in this.ConfiguredAnalyses)
            {
                result.Add(analysis.Analyze(dna));
            }

            return(result);
        }
Beispiel #7
0
        public IDNA <CSingleAssignment> CoinCrossover(IDNA <CSingleAssignment> objPartner)
        {
            CTaamAssignment Child = new CTaamAssignment(false);

            for (int i = 0; i < this.Genes.Length; i++)
            {
                CTaamAssignment Selected = Shared.Coin() ? this : objPartner as CTaamAssignment;
                Child[i] = Selected[i].Clone() as CSingleAssignment;
            }

            return(Child);
        }
        public IEnumerable <IAnalysisResult> Analyze(string name, IDNA dna)
        {
            List <IAnalysisResult> result      = new List <IAnalysisResult>();
            IAnalysisSet           analysisSet = this.analysisSets.Where(a => a.Name == name).FirstOrDefault();

            if (analysisSet == null)
            {
                throw new UnknownTypeException();
            }

            return(analysisSet.Analyze(dna));
        }
Beispiel #9
0
        public IDNA CoinCrossover(IDNA objPartner)
        {
            AWorld child   = (AWorld)this.CreateInstance(false);
            AWorld partner = (AWorld)objPartner;

            for (int i = 0; i < partner.Genes.Length; i++)
            {
                child[i] = (ISlim)(Shared.Coin() ? this[i].Clone() : partner[i].Clone());
            }

            child.Mutate();

            return(child);
        }
Beispiel #10
0
        public God(Func <IDNA> PopulationGenerator)
        {
            this.Population      = new List <IDNA>();
            this.GenerationCount = 0;
            this.StatusGraph     = new CStatutsGraph();

            for (int i = 0; i < GlobalConfiguration.PopulationCount; i++)
            {
                IDNA dna = PopulationGenerator();
                dna.Execute();
                this.Population.Add(dna);
            }

            this.AssessPopulation();
        }
Beispiel #11
0
        public IDNA Crossover()
        {
            IDNA child = null;

            IDNA[] arrParents = this.PickParents();

            if (Shared.HitChance(GlobalConfiguration.ParentChance / 100))
            {
                child = Shared.Coin() ? arrParents[0].Revive() : arrParents[1].Revive();
            }
            else
            {
                child = arrParents[0].Crossover(arrParents[1]);
            }

            return(child);
        }
        public async Task <IQuantityAnalysisResult> AnalyzeMutant(IDNA dna)
        {
            List <IAnalysisResult>  analysisResult = new List <IAnalysisResult>(this.Analyze("mutant", dna));
            IQuantityAnalysisResult result         = (IQuantityAnalysisResult)analysisResult[0];

            if (await this.MutantRepository.InsertDNA(dna.StringRepresentation()))
            {
                if (result.Result)
                {
                    await this.StatsRepository.IncrementStat(MutantDnaKey);
                }
                else
                {
                    await this.StatsRepository.IncrementStat(HumanDnaKey);
                }
            }

            return(result);
        }
Beispiel #13
0
        public IDNA Crossover(IDNA partner)
        {
            DNA child    = new DNA(0, this.Target);
            int midpoint = RandomProvider.RND.Next(this.Genes.Count);

            for (int x = 0; x < this.Genes.Count; ++x)
            {
                if (x > midpoint)
                {
                    child.Genes.Insert(x, this.Genes[x]);
                }
                else
                {
                    child.Genes.Insert(x, partner.Genes[x]);
                }
            }

            return(child);
        }
Beispiel #14
0
        private void Merge(List <IDNA> input, int low, int middle, int high)
        {
            int left  = low;
            int right = middle + 1;

            IDNA[] tmp      = new IDNA[(high - low) + 1];
            int    tmpIndex = 0;

            while ((left <= middle) && (right <= high))
            {
                if (input[left].GetFitnesss() < input[right].GetFitnesss())
                {
                    tmp[tmpIndex] = input[left];
                    left          = left + 1;
                }
                else
                {
                    tmp[tmpIndex] = input[right];
                    right         = right + 1;
                }
                tmpIndex = tmpIndex + 1;
            }

            while (left <= middle)
            {
                tmp[tmpIndex] = input[left];
                left          = left + 1;
                tmpIndex      = tmpIndex + 1;
            }

            while (right <= high)
            {
                tmp[tmpIndex] = input[right];
                right         = right + 1;
                tmpIndex      = tmpIndex + 1;
            }

            for (int i = 0; i < tmp.Length; i++)
            {
                input[low + i] = tmp[i];
            }
        }
Beispiel #15
0
        private List <IDNA <T> > ChooseElitist(List <IDNA <T> > Population, int nElitistCount)
        {
            List <IDNA <T> > Elitist = new List <IDNA <T> >();

            if (GlobalConfiguration.ApplyElitist)
            {
                if (GlobalConfiguration.ApplyNaturalSelection)
                {
                    for (int j = 0; j < nElitistCount; j++)
                    {
                        Elitist.Add(Population[Population.Count - 1 - j].Revive());
                    }
                }
                else
                {
                    IDNA <T>[] Elitists = new IDNA <T> [nElitistCount];
                    for (int j = 0; j < nElitistCount; j++)
                    {
                        Elitists[j] = Population[j];
                    }

                    for (int j = nElitistCount; j < Population.Count; j++)
                    {
                        for (int k = 0; k < nElitistCount; k++)
                        {
                            if (Population[j].GetFitnesss() > Elitists[k].GetFitnesss())
                            {
                                Elitists[k] = Population[j];
                                break;
                            }
                        }
                    }

                    for (int j = 0; j < nElitistCount; j++)
                    {
                        Elitist.Add(Elitists[j].Revive());
                    }
                }
            }

            return(Elitist);
        }
        public IAnalysisResult Analyze(IDNA dna)
        {
            if (!dna.IsValid())
            {
                throw new InvalidDNAException();
            }

            int quantity = 0;

            foreach (var quantitySearch in this.QuantitySearchList)
            {
                quantity += quantitySearch.Search(dna);
            }

            bool analysisThresholdTest = quantity <= this.Max && quantity >= this.Min;

            IAnalysisResult result = this.QuantityAnalysisResultFactory.CreateInstance(this.Min, this.Max, analysisThresholdTest);

            return(result);
        }
Beispiel #17
0
        private void AssessPopulation()
        {
            int nChunksCount     = this.Population.Count / GlobalConfiguration.Performances.ThreadBulkSize;
            int nChunksRemainder = this.Population.Count % GlobalConfiguration.Performances.ThreadBulkSize;
            int nRemainder       = nChunksRemainder > 0 ? 1 : 0;

            Task[] Assesments = new Task[nChunksCount + nRemainder];

            for (int i = 0; i < Assesments.Length - nRemainder; i++)
            {
                int q = i;
                Assesments[i] = Task.Factory.StartNew(() => this.PartialAssesment(q * GlobalConfiguration.Performances.ThreadBulkSize, GlobalConfiguration.Performances.ThreadBulkSize), TaskCreationOptions.None);
            }
            if (nRemainder > 0)
            {
                Assesments[Assesments.Length - 1] = Task.Factory.StartNew(() => this.PartialAssesment((Assesments.Length - 1) * GlobalConfiguration.Performances.ThreadBulkSize, nChunksRemainder), TaskCreationOptions.None);
            }

            Task.WaitAll(Assesments);
            int   bestIdx        = 0;
            float BestDNAFitness = -2;
            float TotalFintess   = 0;

            for (int i = 0; i < this.Population.Count; i++)
            {
                IDNA <T> objDNA = this.Population[i];
                TotalFintess += objDNA.GetFitnesss();

                if (objDNA.GetFitnesss() > BestDNAFitness)
                {
                    BestDNAFitness = objDNA.GetFitnesss();
                    bestIdx        = i;
                }
            }

            this.BestFitness    = this.Population[bestIdx].Clone();
            this.AvreageFitness = TotalFintess / GlobalConfiguration.PopulationCount;

            this.StatusGraph.AddToHistory(BestDNAFitness);
            this.StatusGraph.Average = this.AvreageFitness;
        }
        public void Anneal(Func <IDNA> GetSolution, IProgress <IDNA> progress)
        {
            int initialTemp = 1000;

            // Set initial temp
            this.Temperature = initialTemp / 2;
            this.StatusGraph.ClearHistory();

            // Cooling rate
            double coolingRate = 0.0001;

            this.BestFitness = GetSolution();
            this.BestFitness.Execute();
            this.BestFitness.CalculateFitness();
            IDNA CurrentIterator = this.BestFitness.Clone();

            while (this.Temperature > 1)
            {
                IDNA Neighbour = CurrentIterator.Clone();
                Neighbour.Mutate();
                Neighbour.CalculateFitness();

                double probability = AcceptanceProbability(1 / CurrentIterator.GetFitnesss() * (initialTemp * 20), 1 / Neighbour.GetFitnesss() * (initialTemp * 20), this.Temperature);
                if (Shared.HitChance(probability))
                {
                    CurrentIterator = Neighbour;
                }

                if (BestFitness.GetFitnesss() < Neighbour.GetFitnesss())
                {
                    this.BestFitness = CurrentIterator;
                }

                this.StatusGraph.AddToHistory(CurrentIterator.GetFitnesss());
                this.StatusGraph.Average = 0;

                this.Temperature *= 1 - coolingRate;

                progress.Report(this.BestFitness);
            }
        }
        public async Task <HttpResponseMessage> Post([FromBody] MutantRequest request)
        {
            try
            {
                Log.Debug("Request received");
                IDNA dna = this.DNAFactory.CreateInstance(request.Dna);
                IQuantityAnalysisResult result = await this.DNAAnalyzerService.AnalyzeMutant(dna);

                if (result.Result)
                {
                    return(Request.CreateResponse());
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Is not a mutant"));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
Beispiel #20
0
        public IDNA PartialGenomeCrossover(IDNA objPartner)
        {
            AWorld child   = (AWorld)this.CreateInstance(false);
            AWorld partner = (AWorld)objPartner;

            int        nStart             = Shared.Next(this.Genes.Length / 2 + 1);
            int        nEnd               = nStart + Shared.Next(this.Genes.Length / 2);
            List <int> colPassedGenesUIDs = new List <int>();

            for (int i = nStart; i < nEnd; i++)
            {
                child[i] = (ISlim)partner[i].Clone();
                colPassedGenesUIDs.Add(partner[i].UID);
            }

            int nGeneInsertionPos = 0;

            for (int i = 0; i < this.Genes.Length; i++)
            {
                if (nGeneInsertionPos == nStart)
                {
                    nGeneInsertionPos = nEnd;
                }

                if (colPassedGenesUIDs.Contains(this.Genes[i].UID))
                {
                    continue;
                }

                child[nGeneInsertionPos] = (ISlim)this.Genes[i].Clone();
                nGeneInsertionPos++;
            }

            child.Mutate();

            return(child);
        }
Beispiel #21
0
        public IDNA <CSingleAssignment> PartialGenomeCrossover(IDNA <CSingleAssignment> objPartner)
        {
            CTaamAssignment child   = new CTaamAssignment(false);
            CTaamAssignment partner = (CTaamAssignment)objPartner;

            int        nStart             = Shared.Next(this.Genes.Length / 2) + 1;
            int        nEnd               = nStart + Shared.Next(this.Genes.Length / 2);
            List <int> colPassedGenesUIDs = new List <int>();

            for (int i = nStart; i < nEnd; i++)
            {
                child[i] = partner[i].Clone();
                colPassedGenesUIDs.Add(partner[i].UID);
            }

            int nGeneInsertionPos = 0;

            for (int i = 0; i < this.Genes.Length; i++)
            {
                if (nGeneInsertionPos == nStart)
                {
                    nGeneInsertionPos = nEnd;
                }

                if (colPassedGenesUIDs.Contains(this.Genes[i].UID))
                {
                    continue;
                }

                child[nGeneInsertionPos] = this.Genes[i].Clone();
                nGeneInsertionPos++;
            }

            child.Mutate();

            return(child);
        }
Beispiel #22
0
 public abstract IDNA Crossover(IDNA objPartner);
Beispiel #23
0
        public void TestConformance()
        {
            SortedDictionary <long, IDictionary <string, string> > inputData = null;

            try
            {
                inputData = ReadInput.GetInputData();
            }
            catch (EncoderFallbackException e)
            {
                Errln(e.ToString());
                return;
            }
            catch (IOException e)
            {
                Errln(e.ToString());
                return;
            }

            var keyMap = inputData.Keys;

            foreach (var element in keyMap)
            {
                var tempHash = inputData.Get(element);

                //get all attributes from input data
                String passfail  = (String)tempHash.Get("passfail");
                String desc      = (String)tempHash.Get("desc");
                String type      = (String)tempHash.Get("type");
                String namebase  = (String)tempHash.Get("namebase");
                String nameutf8  = (String)tempHash.Get("nameutf8");
                String namezone  = (String)tempHash.Get("namezone");
                String failzone1 = (String)tempHash.Get("failzone1");
                String failzone2 = (String)tempHash.Get("failzone2");

                //they maybe includes <*> style unicode
                namebase = StringReplace(namebase);
                namezone = StringReplace(namezone);

                String result = null;
                bool   failed = false;

                if ("toascii".Equals(tempHash.Get("type")))
                {
                    //get the result
                    try
                    {
                        //by default STD3 rules are not used, but if the description
                        //includes UseSTD3ASCIIRules, we will set it.
                        if (desc.ToLowerInvariant().IndexOf(
                                "UseSTD3ASCIIRules".ToLowerInvariant()) == -1)
                        {
                            result = IDNA.ConvertIDNToASCII(namebase,
                                                            IDNA2003Options.AllowUnassigned).ToString();
                        }
                        else
                        {
                            result = IDNA.ConvertIDNToASCII(namebase,
                                                            IDNA2003Options.UseSTD3Rules).ToString();
                        }
                    }
                    catch (StringPrepParseException e2)
                    {
                        //Errln(e2.getMessage());
                        failed = true;
                    }


                    if ("pass".Equals(passfail))
                    {
                        if (!namezone.Equals(result))
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);
                            Errln("\t pass fail standard is pass, but failed");
                        }
                        else
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);
                            Logln("\tpassed");
                        }
                    }

                    if ("fail".Equals(passfail))
                    {
                        if (failed)
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);
                            Logln("passed");
                        }
                        else
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);
                            Errln("\t pass fail standard is fail, but no exception thrown out");
                        }
                    }
                }
                else if ("tounicode".Equals(tempHash.Get("type")))
                {
                    try
                    {
                        //by default STD3 rules are not used, but if the description
                        //includes UseSTD3ASCIIRules, we will set it.
                        if (desc.ToLowerInvariant().IndexOf(
                                "UseSTD3ASCIIRules".ToLowerInvariant()) == -1)
                        {
                            result = IDNA.ConvertIDNToUnicode(namebase,
                                                              IDNA2003Options.AllowUnassigned).ToString();
                        }
                        else
                        {
                            result = IDNA.ConvertIDNToUnicode(namebase,
                                                              IDNA2003Options.UseSTD3Rules).ToString();
                        }
                    }
                    catch (StringPrepParseException e2)
                    {
                        //Errln(e2.getMessage());
                        failed = true;
                    }
                    if ("pass".Equals(passfail))
                    {
                        if (!namezone.Equals(result))
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);

                            Errln("\t Did not get the expected result. Expected: " + Prettify(namezone) + " Got: " + Prettify(result));
                        }
                        else
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);
                            Logln("\tpassed");
                        }
                    }

                    if ("fail".Equals(passfail))
                    {
                        if (failed || namebase.Equals(result))
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);

                            Logln("\tpassed");
                        }
                        else
                        {
                            PrintInfo(desc, namebase, nameutf8, namezone,
                                      failzone1, failzone2, result, type, passfail);

                            Errln("\t pass fail standard is fail, but no exception thrown out");
                        }
                    }
                }
                else
                {
                    continue;
                }
            }
        }
 protected AlleleBase(IDNA dna)
 {
     this.DNA = dna;
     this.DNA.Parent = this;
 }
Beispiel #25
0
 public abstract IDNA <T> Crossover(IDNA <T> objPartner);
Beispiel #26
0
 public override IDNA <CSingleAssignment> Crossover(IDNA <CSingleAssignment> objPartner)
 {
     return(GlobalConfiguration.PartialGenomCrossover || GlobalConfiguration.SwitchMutation ? this.PartialGenomeCrossover(objPartner) : this.CoinCrossover(objPartner));
 }
Beispiel #27
0
 public override IDNA Crossover(IDNA objPartner)
 {
     return(GlobalConfiguration.PartialGenomCrossover ? this.PartialGenomeCrossover(objPartner) : this.CoinCrossover(objPartner));
 }