Esempio n. 1
0
            /********************************************
            *  individual mate
            *  given the parents, creates a new child chromosome
            *  by taking parts from the parents at random
            *  then returns the child
            ********************************************/
            public individual mate(individual parent2, uint[,,] source, uint[,,] stock, int stockSize)
            {
                int    total   = (int)Pow(Globals.SIZE, 2);
                Random rnd     = new Random();
                Random mutated = new Random();

                int[] child_chrom = new int[total];

                for (int i = 0; i < total; i++)
                {
                    double p = rnd.Next(0, 100) / 100.0;

                    // if probability is less than 0.45
                    // insert gene from parent 1
                    if (p < 0.45)
                    {
                        child_chrom[i] = chromosome[i];
                    }
                    // if probability is less than 0.90
                    // insert gene from parent 2
                    else if (p < 0.90)
                    {
                        child_chrom[i] = parent2.chromosome[i];
                    }
                    // otherwise add a new random gene
                    else
                    {
                        child_chrom[i] = mutated.Next(0, stockSize);
                    }
                }

                individual child = new individual(child_chrom, source, stock);

                return(child);
            }
        public object GetData()
        {
            if (null == savedRecord)
            {
                savedRecord = new individual();
            }
            savedRecord.firstname  = FirstName;
            savedRecord.lastname   = LastName;
            savedRecord.sunshineid = ID;
            savedRecord.phone      = Phone;

            savedRecord.phonenumbers_individual.Clear();
            foreach (var item in flpPhoneNumbers.Controls)
            {
                if (item is PhoneAdd)
                {
                    savedRecord.phonenumbers_individual.Add(new phonenumbers_individual()
                    {
                        ownerID     = savedRecord.id,
                        phonenumber = (item as PhoneAdd).GetText()
                    });
                }
            }

            savedRecord.social_media_individual.Clear();
            foreach (var item in flpSocial.Controls)
            {
                if (item is SocialMediaLink)
                {
                    savedRecord.social_media_individual.Add(new social_media_individual()
                    {
                        sm_ind_id = savedRecord.id,
                        sm_title  = (item as SocialMediaLink).LinkTitle,
                        sm_link   = Encoding.ASCII.GetBytes((item as SocialMediaLink).LinkURL),
                        sm_type   = (item as SocialMediaLink).SMType
                    });
                }
            }

            savedRecord.addresses_individual.Clear();
            if (null != GetPrimaryAddress())
            {
                savedRecord.addresses_individual.Add(GetPrimaryAddress());
            }
            if (null != GetSecondaryAddress())
            {
                savedRecord.addresses_individual.Add(GetSecondaryAddress());
            }


            savedRecord.actions_individual.Clear();
            foreach (var item in actions)
            {
                savedRecord.actions_individual.Add(item);
            }


            savedRecord.financialsupport = GetFinancialSupport();
            return(savedRecord);
        }
Esempio n. 3
0
            static void FindBestIndividual(ref individual[] population, ref individual bestindividual, ref individual currentbest, int generation, ref int[] TempCitySet, ref int[] WorkSet, ref int[] CitySet, int PopSiz_e, double[,] temp)
            {
                int i;

                bestindividual = population[0];

                for (i = 1; i < PopSiz_e; i++)
                {
                    if (population[i].fitness > bestindividual.fitness)
                    {
                        bestindividual = population[i];
                    }
                }

                if (generation == 0)
                {
                    currentbest = bestindividual;
                }
                else
                {
                    if (bestindividual.fitness > currentbest.fitness)
                    {
                        currentbest = bestindividual;
                        OutputTextReport(ref currentbest, ref generation, ref TempCitySet, ref WorkSet, ref CitySet, (int)Math.Sqrt(PopSiz_e), temp);
                    }
                }
            }
Esempio n. 4
0
        //Генетический оператор - арифметический кроссинговер
        public void crossingover(individual p1, individual p2, individual c1, individual c2)
        {
            //лямбда-переменная для кроссинговера
            double ß = random.NextDouble();

            for (int i = 0; i < p1.Genes.Count(); i++)
            {
                c1.Genes[i] = Convert.ToInt32(ß * p1.Genes[i] + (1 - ß) * p2.Genes[i]);
                c2.Genes[i] = Convert.ToInt32(ß * p2.Genes[i] + (1 - ß) * p1.Genes[i]);
            }
        }
Esempio n. 5
0
        public double absolutlifitnessPersent(individual ind, individual model)
        {
            double rgbFitness = 0;

            for (int i = 0; i < ind.Genes.Count(); i++)
            {
                rgbFitness += Math.Pow(ind.Genes[i] - model.Genes[i], 2);
            }
            rgbFitness = Math.Sqrt(rgbFitness);
            return(rgbFitness);
        }
Esempio n. 6
0
        private string test_self()
        {
            individual self = new individual("Self");

            gedcomer gc = new gedcomer();

            gc.root(self);

            string gedcom = gc.ToString();

            return(gedcom);
        }
Esempio n. 7
0
        // Test father
        private string test_father()
        {
            individual self   = new individual("Self");
            individual father = new individual("Father");

            self.relate(kinship.FATHER, father);

            gedcomer gc = new gedcomer();

            gc.root(self);

            string gedcom = gc.ToString();

            return(gedcom);
        }
Esempio n. 8
0
        // @todo Spousal relationship should be drawn
        // Create FAM record
        private string test_spouse()
        {
            individual self   = new individual("Self");
            individual spouse = new individual("Spouse");

            self.relate(kinship.SPOUSE, spouse);

            gedcomer gc = new gedcomer();

            gc.root(self);

            string gedcom = gc.ToString();

            return(gedcom);
        }
Esempio n. 9
0
            public static void m3_Main(double[,] temp, int size)
            {
                int POPSIZE       = (int)Math.Pow(size, 2) + size;
                int CITYCOUNT     = size;
                int CHROMLENGTH   = CITYCOUNT;
                int PopSiz_e      = (int)Math.Pow(size, 2);
                int MaxGeneration = POPSIZE;

                individual bestindividual = new individual();
                individual currentbest    = new individual();

                individual[] population    = new individual[POPSIZE];
                individual[] newpopulation = new individual[POPSIZE];



                bestindividual.chrom = new int[CHROMLENGTH];
                currentbest.chrom    = new int[CHROMLENGTH];
                for (int i = 0; i < POPSIZE; i++)
                {
                    population[i].chrom    = new int[CHROMLENGTH];
                    newpopulation[i].chrom = new int[CHROMLENGTH];
                }

                int[] CitySet     = new int[CITYCOUNT];
                int[] WorkSet     = new int[CITYCOUNT];
                int[] TempCitySet = new int[CITYCOUNT];

                double[,] CityDistance = new double[CITYCOUNT, CITYCOUNT];
                CityDistance           = temp;

                int generation = 0;

                GenerateInitialPopulation(ref CitySet, ref population, PopSiz_e);
                CalculateFitness(ref population, ref TempCitySet, ref CityDistance, ref WorkSet, ref CitySet, PopSiz_e, CITYCOUNT);
                FindBestIndividual(ref population, ref bestindividual, ref currentbest, generation, ref TempCitySet, ref WorkSet, ref CitySet, PopSiz_e, temp);
                OutputTextReport(ref currentbest, ref generation, ref TempCitySet, ref WorkSet, ref CitySet, CHROMLENGTH, temp);

                while (generation < MaxGeneration)
                {
                    generation++;
                    GenerateNextPopulation(ref population, ref newpopulation, PopSiz_e, POPSIZE);
                    CalculateFitness(ref population, ref TempCitySet, ref CityDistance, ref WorkSet, ref CitySet, PopSiz_e, CITYCOUNT);
                    FindBestIndividual(ref population, ref bestindividual, ref currentbest, generation, ref TempCitySet, ref WorkSet, ref CitySet, PopSiz_e, temp);
                }
            }
Esempio n. 10
0
        //отбор при помощи турнинрой селекции с турниром (размер турнира в переменной)
        public void choice(population parent, population selectionparent)
        {
            Random     rand = new Random();
            population parentForSelection = new population();

            for (int i = 0; i < numberOfIndividuals / 2; i++)
            {
                int    theBest       = 0;
                double theBestresult = 50000;
                for (int j = 0; j < sizeTourney; j++)
                {
                    int in1 = rand.Next(0, numberOfIndividuals);
                    if (absolutlifitnessPersent(parent.Population[in1], model) < theBestresult)
                    {
                        theBestresult = absolutlifitnessPersent(parent.Population[in1], model);
                        theBest       = in1;
                    }
                }
                parentForSelection.Population.Add(parent.Population[theBest]);
                selectionparent.Population.Add(parent.Population[theBest]);
            }
            parent.Population.Clear();
            individual child1;
            individual child2;

            while (parent.Population.Count < numberOfIndividuals)
            {
                int i = rand.Next(0, numberOfIndividuals / 2);
                int j = rand.Next(0, numberOfIndividuals / 2);
                if (p > rand.NextDouble())
                {
                    crossingover(parentForSelection.Population[i], parentForSelection.Population[j], child1 = new individual(), child2 = new individual());
                }
                else
                {
                    child1       = new individual();
                    child2       = new individual();
                    child1.Genes = parentForSelection.Population[i].Genes;
                    child2.Genes = parentForSelection.Population[j].Genes;
                }
                parent.Population.Add(child1);
                parent.Population.Add(child2);
            }
        }
Esempio n. 11
0
            static void OutputTextReport(ref individual currentbest, ref int generation, ref int[] TempCitySet, ref int[] WorkSet, ref int[] CitySet, int CHROMLENGTH, double[,] temp)
            {
                int i, j;


                TextWriter   str     = Console.Out;
                StreamWriter fileOut = new StreamWriter(new FileStream("graph_opt.txt",
                                                                       FileMode.Create,
                                                                       FileAccess.Write));

                Console.SetOut(fileOut);

                for (i = 0; i < CHROMLENGTH; i++)
                {
                    for (j = 0; j < CHROMLENGTH; j++)
                    {
                        Console.Write("{0:N}  ", temp[i, j]);
                    }

                    Console.WriteLine();
                }

                Console.SetOut(str);

                DecodeChromosome(ref currentbest.chrom, ref TempCitySet, ref WorkSet, ref CitySet, CHROMLENGTH);
                Console.SetOut(fileOut);
                Console.Write("\nНайкраще значення = {0:N}  при шляху ==>>  ", currentbest.value);

                for (i = 0; i < CHROMLENGTH; i++)
                {
                    Console.Write("<{0}>", TempCitySet[i]);
                }
                Console.WriteLine("\n");

                fileOut.Close();
                Console.SetOut(str);
            }
Esempio n. 12
0
        public void NewIndividual()
        {
            if (Repository.HasChanges())
            {
                var result = MessageBox.Show($"You have unsaved changes, save first?", $"Save?", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                case MessageBoxResult.Cancel:
                    return;

                case MessageBoxResult.Yes:
                    Save();
                    break;

                case MessageBoxResult.No:
                    Repository.CancelChanges();
                    break;

                default:
                    break;
                }
            }
            ReportsVM = null;
            NewIndividualVisibility   = Visibility.Collapsed;
            NewOrganizationVisibility = Visibility.Collapsed;
            ContentView = _container.GetInstance <IndividualDetailViewModel>();
            individual i = new individual();

            (ContentView as IndividualDetailViewModel).Entity = new ModelLibrary.Models.ReturnedEntity()
            {
                Entity = i
            };
            var ida = _container.GetInstance <IndividualDataAccess>();

            ida.Add(i);
            ActivateItem(ContentView);
        }
Esempio n. 13
0
            /********************************************
            *  individual - copy constructor
            *  copys a given individual
            ********************************************/
            public individual(individual copy)
            {
                int total = (int)Pow(Globals.SIZE, 2);

                chromosome    = new int[total];
                uint[,,] temp = new uint[total, 5, 3];
                fitness       = new uint[total, 5];
                wholeIMGscore = new double[total];

                for (int i = 0; i < total; i++)
                {
                    chromosome[i] = copy.chromosome[i];

                    wholeIMGscore[i] = copy.wholeIMGscore[i];
                }
                chromscore = copy.chromscore;
                for (int i = 0; i < total; i++)
                {
                    for (int k = 0; k < 5; k++)
                    {
                        fitness[i, k] = copy.fitness[i, k];
                    }
                }
            }
Esempio n. 14
0
        private void button_win_Click(object sender, EventArgs e)
        {
            //данные с формы
            numberOfIndividuals = Convert.ToInt32(PopulationNumber.Text);
            sizeTourney         = Convert.ToInt32(textBox_sizeTourney.Text);

            //храним родителей, родителей для селекции и потомство
            parents             = new population();
            parentsForSelection = new population();
            children            = new population();

            Random rnd = new Random();

            //Эталонная особь
            model.Genes = new int[] { 96, 96, 159 };
            //Генерация начальной популяции
            population FirstPopulation = new population();

            for (int i = 0; i < numberOfIndividuals; i++)
            {
                individual curentIndividuals = new individual();
                curentIndividuals.Genes = new int[] { rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256) };
                FirstPopulation.Population.Add(curentIndividuals);
            }
            bool individualIsfind = false;
            int  iter             = 0;

            listBox_number.Items.Clear();
            while (!individualIsfind)
            {
                double theBestreslt = 50000;
                for (int i = 0; i < FirstPopulation.Population.Count; i++)
                {
                    double rez = absolutlifitnessPersent(FirstPopulation.Population[i], model);
                    if (rez < theBestreslt)
                    {
                        theBestreslt = rez;
                    }
                    if (absolutlifitnessPersent(FirstPopulation.Population[i], model) == 0)
                    {
                        individualIsfind = true;
                        int number = i;
                        break;
                    }
                }
                rezult.Add(theBestreslt);
                if (!individualIsfind)
                {
                    iter++;
                    foreach (var item in FirstPopulation.Population)
                    {
                        parents.Population.Add(item);
                    }
                    listBox_number.Items.Add(iter);
                    choice(FirstPopulation, parentsForSelection);
                    foreach (var item in FirstPopulation.Population)
                    {
                        children.Population.Add(item);
                    }


                    Mutation(FirstPopulation);
                }
            }
            Form2 graph = new Form2(rezult, iter);

            graph.Show();
        }
Esempio n. 15
0
            public Generation NextGen(CNF_Instance cnf)
            {
                Generation newGen = new Generation(this.variable_count);

                newGen.gen_count   = this.gen_count + 1;
                newGen.total_flips = this.total_flips;
                this.Get_fitness(cnf);
                this.population.Sort((x, y) => y.fitness.CompareTo(x.fitness));
                List <individual> selected = new List <individual>(10);
                Random            r        = new Random();

                //add elites
                for (int i = 0; i < 2; i++)
                {
                    newGen.population.Add(this.population[i]);
                    selected.Add(this.population[i]);
                }

                //select 8
                double[] cdf = new double[10];
                for (int i = 0; i < 10; i++)
                {
                    cdf[i] = this.population[i].prob;
                    if (i != 0)
                    {
                        cdf[i] += cdf[i - 1];
                    }
                }

                for (int i = 0; i < 8; i++)
                {
                    double selector = r.NextDouble();
                    int    j        = 0;
                    for (j = 0; j < 10; j++)
                    {
                        if (selector <= cdf[j])
                        {
                            break;
                        }
                    }
                    selected.Add(this.population[j]);
                }

                //crossover

                for (int i = 2; i < 10; i += 2)
                {
                    string     father   = selected[i].bits;
                    string     mother   = selected[i + 1].bits;
                    individual son      = new individual();
                    individual daughter = new individual();
                    for (int j = 0; j < variable_count; j++)
                    {
                        if (r.NextDouble() < 0.5)
                        {
                            son.bits      = string.Concat(son.bits, father[j]);
                            daughter.bits = string.Concat(son.bits, mother[j]);
                        }
                        else
                        {
                            daughter.bits = string.Concat(son.bits, father[j]);
                            son.bits      = string.Concat(son.bits, mother[j]);
                        }
                    }
                    newGen.population.Add(son);
                    newGen.population.Add(daughter);
                }


                //mutation
                for (int i = 2; i < 10; i++)
                {
                    string cur = newGen.population[i].bits;
                    char[] tmp = cur.ToCharArray();
                    if (r.NextDouble() < 0.9)
                    {
                        for (int j = 0; j < this.variable_count; j++)
                        {
                            if (r.NextDouble() < 0.5)
                            {
                                tmp[j] = Flip(tmp[j]);
                                newGen.total_flips++;
                            }
                        }
                        newGen.population[i].bits = new string(tmp);
                    }
                }
                //flip heuristic
                for (int i = 2; i < 10; i++)
                {
                    string cur = newGen.population[i].bits;
                    char[] tmp = cur.ToArray();
                    int[]  flip_order = RandomSequence(variable_count);
                    double old_fitness = 0, new_fitness = 0;
                    do
                    {
                        for (int j = 0; j < variable_count; j++)
                        {
                            old_fitness = Get_single_fitness(new string(tmp), cnf);
                            int index = flip_order[j];
                            tmp[index] = Flip(tmp[index]);
                            newGen.total_flips++;
                            new_fitness = Get_single_fitness(new string(tmp), cnf);
                            if (new_fitness < old_fitness)
                            {
                                tmp[index] = Flip(tmp[index]);
                                newGen.total_flips--;
                            }
                        }
                        if (new_fitness == 1)
                        {
                            break;
                        }
                    } while (old_fitness < new_fitness);
                    newGen.population[i].bits = new string(tmp);
                }


                return(newGen);
            }
Esempio n. 16
0
 //Save button
 private void toolStripButton2_Click(object sender, EventArgs e)
 {
     if (tabControl.SelectedTab is RecordViewTabPage)
     {
         byte   saveID = (tabControl.SelectedTab as RecordViewTabPage).ID;
         object r      = (tabControl.SelectedTab as RecordViewTabPage).GetContactFromData();
         if (r is individual)
         {
             //Replace with UpdateIndividualRecord
             individual c = (individual)r;
             try
             {
                 individual record = Entities.individuals.First(a => a.id == c.id);
                 record.firstname            = c.firstname;
                 record.lastname             = c.lastname;
                 record.addresses_individual = c.addresses_individual;
                 record.phone = c.phone;
                 record.phonenumbers_individual = c.phonenumbers_individual;
                 record.financialsupport        = c.financialsupport;
                 record.actions_individual      = c.actions_individual;
                 record.social_media_individual = c.social_media_individual;
                 record.sunshineid = c.sunshineid;
                 record.source     = c.source;
             }
             catch (InvalidOperationException)
             {
                 Entities.individuals.Add(c);
             }
             finally
             {
                 Entities.SaveChanges();
                 tsslMainForm.Text = $"{c.ToString()} has been saved.";
             }
         }
         else
         {
             //Replace with UpdateOrgRecord
             organization o = (organization)r;
             try
             {
                 organization record = Entities.organizations.First(a => a.orgid == o.orgid);
                 record.name = o.name;
                 record.addresses_organization    = o.addresses_organization;
                 record.phonenumbers_organization = o.phonenumbers_organization;
                 record.phone                     = o.phone;
                 record.financialsupport          = o.financialsupport;
                 record.actions_organization      = o.actions_organization;
                 record.social_media_organization = o.social_media_organization;
                 record.orgsunshineid             = o.orgsunshineid;
             }
             catch (InvalidOperationException)
             {
                 Entities.organizations.Add(o);
             }
             finally
             {
                 Entities.SaveChanges();
                 tsslMainForm.Text = $"{o.name} has been saved.";
             }
         }
     }
 }
Esempio n. 17
0
        public void SetData()
        {
            workingRecord = JsonConvert.DeserializeObject <individual>(JsonConvert.SerializeObject(savedRecord,
                                                                                                   new JsonSerializerSettings {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));


            if (this.InvokeRequired)
            {
                this.Invoke(new EventHandler(delegate { SetData(); }));
            }
            else
            {
                FirstName = savedRecord.firstname;
                LastName  = savedRecord.lastname;
                Phone     = savedRecord.phone;
                ID        = savedRecord.sunshineid;
                if (null != savedRecord.phonenumbers_individual)
                {
                    foreach (var item in savedRecord.phonenumbers_individual)
                    {
                        PhoneAdd pa = new PhoneAdd();
                        pa.SetText(item.phonenumber);
                        flpPhoneNumbers.Controls.Add(pa);
                    }
                }

                SetFinancialSupport(savedRecord.financialsupport);
                if (null != savedRecord.actions_individual)
                {
                    ICollection <actions_individual> items = new List <actions_individual>();
                    foreach (var item in savedRecord.actions_individual)
                    {
                        //items.Add(item);
                    }
                    InitializeActionList(items);
                }

                foreach (var x in savedRecord.addresses_individual)
                {
                    if ((bool)x.primary)
                    {
                        StreetPrimary          = x.streetAddress;
                        CityPrimary            = x.city;
                        cmbState.SelectedIndex = cmbState.FindStringExact(x.state);
                        cmbState.SelectedItem  = cmbState.SelectedIndex;
                        ZipPrimary             = x.zip;
                    }
                    else
                    {
                        StreetSecondary         = x.streetAddress;
                        CitySecondary           = x.city;
                        cmbState2.SelectedIndex = cmbState2.FindStringExact(x.state);
                        ZipSecondary            = x.zip;
                    }
                }

                foreach (var item in savedRecord.social_media_individual)
                {
                    flpSocial.Controls.Add(
                        new SocialMediaLink(item.sm_title, Encoding.ASCII.GetString(item.sm_link))
                    {
                        SMType = item.sm_type
                    });
                }
            }
        }
Esempio n. 18
0
        private string test_family()
        {
            individual self          = new individual("Self You");
            individual grandfather   = new individual("Grand Father");
            individual grandmother   = new individual("Grand Mother");
            individual gotra         = new individual("Gotra");
            individual father        = new individual("Father");
            individual mother        = new individual("Mother");
            individual spouse        = new individual("Spouse");
            individual child1        = new individual("Son #1");
            individual child2        = new individual("Daughter");
            individual child3        = new individual("Unmarried");
            individual daughterinlaw = new individual("Daugher In-Law");
            individual grandson      = new individual("Grand Son");

            self.birth("1980");
            father.birth("1955");
            mother.birth("1960");
            spouse.birth("1984");
            child1.birth("1987");
            child2.birth("1990");

            grandfather.marry(grandmother); // or the revese way should be too possible.
            grandfather.death("2004");
            grandmother.death("2006");

            // generation #2
            daughterinlaw.birth("1995");
            child1.marry(daughterinlaw);

            // generation #3
            grandson.birth("1999");

            self.male();
            child1.male();
            child2.female();

            self.alias("Alias 2");

            mother.marry(father);
            father.note("Seniorly respected");
            father.note("Social worker");
            father.register_event("2010", "Migrate", "City 1");
            father.register_event("2011", "Teaching", "City 2");

            mother.birth("1960");
            mother.death("2001");

            father.relate(kinship.FATHER, grandfather);
            father.relate(kinship.CHILD, self);
            grandfather.relate(kinship.FATHER, gotra);
            child1.relate(kinship.CHILD, grandson);

            // just: values change
            self.relate(kinship.SELF, self);

            // assignment of a new individual defined separately
            //self.relate(kinship.FATHER, father);
            self.relate(kinship.MOTHER, mother);
            //self.relate(kinship.SPOUSE, spouse);
            self.marry(spouse);
            self.relate(kinship.CHILD, child1);
            self.relate(kinship.CHILD, child2);
            self.relate(kinship.CHILD, child3);

            gedcomer gc = new gedcomer();

            gc.root(self);
            // self // case 1
            // grandfather // case 2
            // grandson // case 3
            // mother // case 4

            string gedcom = gc.ToString();

            return(gedcom);
        }
Esempio n. 19
0
        /********************************************
        *   generate
        *   inputs - source, stock, sourceVal, stockVal
        *   outputs - new image to showmosaic picture box
        *   This function uses the genetic algorithm try and piece
        *   together the source image with all the stock photos.
        *   The best generation is brought to the top with
        *   a simple bubble sort.
        ********************************************/
        public void generate(Bitmap[] source, Bitmap[] stock, uint[,,] sourceVal, uint[,,] stockVal)
        {
            // MessageBox.Show("In Generate");
            int mySize      = Globals.SIZE;        // amount of source images per row
            int totalimages = (int)Pow(mySize, 2); // amount of source images
            int popSize     = Globals.population;  // population size
            int TotalGens   = Globals.Generations; // total amount of generations
            int stockSize   = stock.Length;        // stock images size

            progressBar1.Minimum = 0;
            progressBar1.Maximum = TotalGens;


            Bitmap[] BestInGen = new Bitmap[totalimages];         // gets the best person in population
            int[,] populationLoc = new int[popSize, totalimages]; // holds the values of stock

            Random rnd        = new Random();
            int    currentGen = 0;

            int[] sourcegnome = new int[totalimages];
            for (int i = 0; i < totalimages; i++)
            {
                sourcegnome[i] = i;
            }
            individual mySource = new individual(sourceVal);

            // initializes the population array with random stock images
            for (int i = 0; i < popSize; i++)
            {
                for (int j = 0; j < totalimages; j++)
                {
                    int myNum = rnd.Next(0, stockSize);
                    populationLoc[i, j] = myNum;
                }
            }

            // SourceDom(domCol); // gets the dominant color on source images
            // List<individual> myPop = new List<individual>();
            individual[] myPop = new individual[popSize];
            bool         found = false;

            int[] gnome = new int[totalimages];
            for (int i = 0; i < popSize; i++)
            {
                for (int k = 0; k < totalimages; k++)
                {
                    gnome[k] = populationLoc[i, k];
                }

                myPop[i] = (new individual(gnome, sourceVal, stockVal));
            }
            int elite = Globals.elitism;
            int weak  = 100 - elite;

            while (!found && currentGen < TotalGens)
            {
                // sort
                sort();
                if (Globals.Generations <= 500)
                {
                    if (currentGen % 10 == 0)
                    {
                        for (int i = 0; i < totalimages; i++)
                        {
                            BestInGen[i] = stock[myPop[0].chromosome[i]];
                        }
                        DisplayIMG(BestInGen);
                    }
                }
                else
                {
                    if (currentGen % 100 == 0)
                    {
                        for (int i = 0; i < totalimages; i++)
                        {
                            BestInGen[i] = stock[myPop[0].chromosome[i]];
                        }
                        DisplayIMG(BestInGen);
                    }
                }
                progressBar1.Value = currentGen;
                progressBar1.Refresh();
                if (myPop[0].chromscore <= 100)
                {
                    progressBar1.Value = TotalGens;
                    found = true;
                    break;
                }
                List <individual> nextGen = new List <individual>();
                // elitism, variable of user choice of population goes to the next generation
                int s = (elite * popSize) / 100;
                for (int i = 0; i < s; i++)
                {
                    nextGen.Add(new individual(myPop[i]));
                }
                // rest of the population will mate
                // produces offspring from the best 20
                // For those 20 are the fittest, the rest "die"
                s = (weak * popSize) / 100;
                for (int i = 0; i < s; i++)
                {
                    int        r       = rnd.Next(0, 20);
                    individual parent1 = new individual(myPop[r]);
                    r = rnd.Next(0, 20);
                    individual parent2 = new individual(myPop[r]);
                    individual child   = parent1.mate(parent2, sourceVal, stockVal, stockSize);
                    nextGen.Add(new individual(child));
                }
                //nextGen.CopyTo(myPop,totalimages);
                nextGen.CopyTo(myPop);

                currentGen++;
            }
            progressBar1.Value = TotalGens;
            progressBar1.Refresh();

            // Bubble sort
            void sort()
            {
                for (int i = 0; i < popSize - 1; i++)
                {
                    for (int j = 0; j < popSize - i - 1; j++)
                    {
                        if (myPop[j].chromscore > myPop[j + 1].chromscore)
                        {
                            swap(j, j + 1);
                        }
                    }
                }
                return;
            }

            // swaps two individuals
            void swap(int who, int what)
            {
                individual temp = new individual(myPop[who]);

                myPop[who]  = myPop[what];
                myPop[what] = temp;
            }
        }
Esempio n. 20
0
        public string generateIdebJson(DbConnection conn, string resultid, int dbTimeout)
        {
            string    result   = "";
            DataTable dtheader = conn.GetDataTable("select * from slik_ideb where resultid = @1", new object[] { resultid }, dbTimeout);
            DataTable dtpokok  = conn.GetDataTable("select * from slik_ideb_datapokokdebitur where resultid = @1", new object[] { resultid }, dbTimeout);
            DataTable dtkredit = conn.GetDataTable("select * from slik_ideb_kredit where resultid = @1", new object[] { resultid }, dbTimeout);

            if (dtheader.Rows.Count > 0)
            {
                if (dtheader.Rows[0]["isCompany"].ToString() == "0")
                {
                    header             header             = BindData <header>(dtheader, 0);
                    individual         individu           = BindData <individual>(dtheader, 0);
                    parameterPencarian searchParam        = BindData <parameterPencarian>(dtheader, 0);
                    ringkasanFasilitas ringkasanfasilitas = BindData <ringkasanFasilitas>(dtheader, 0);
                    //datapokok
                    List <dataPokokDebitur> datapokoks = new List <dataPokokDebitur>();
                    for (int i = 0; i < dtpokok.Rows.Count; i++)
                    {
                        dataPokokDebitur datapokok = BindData <dataPokokDebitur>(dtpokok, i);
                        datapokoks.Add(datapokok);
                    }
                    //kredit
                    List <kreditPembiayan> kredits = new List <kreditPembiayan>();
                    for (int i = 0; i < dtkredit.Rows.Count; i++)
                    {
                        kreditPembiayan kredit      = BindData <kreditPembiayan>(dtkredit, i);
                        string          fasilitasid = dtkredit.Rows[i]["fasilitasid"].ToString();
                        DataTable       dtagunan    = conn.GetDataTable("select * from slik_ideb_agunan where resultid = @1 and fasilitasid = @2", new object[] { resultid, fasilitasid }, dbTimeout);
                        //agunan
                        List <agunan> agunans = new List <agunan>();
                        for (int x = 0; x < dtagunan.Rows.Count; x++)
                        {
                            agunan agunan = BindData <agunan>(dtagunan, x);
                            agunans.Add(agunan);
                        }

                        kredit.agunan = agunans.ToArray();
                        List <penjamin> penjamins = new List <penjamin>();
                        kredit.penjamin = penjamins.ToArray();
                        kredits.Add(kredit);
                    }

                    individu.dataPokokDebitur   = datapokoks.ToArray();
                    individu.parameterPencarian = searchParam;
                    individu.ringkasanFasilitas = ringkasanfasilitas;
                    fasilitas fasilitas = new fasilitas();
                    fasilitas.kreditPembiayan = kredits.ToArray();
                    individu.fasilitas        = fasilitas;

                    idebIndividu ideb = new idebIndividu();
                    ideb.header     = header;
                    ideb.individual = individu;
                    result          = JsonConvert.SerializeObject(ideb);
                }
                else
                {
                    header     header     = BindData <header>(dtheader, 0);
                    perusahaan perusahaan = BindData <perusahaan>(dtheader, 0);
                    parameterPencarianPerusahaan searchParam        = BindData <parameterPencarianPerusahaan>(dtheader, 0);
                    ringkasanFasilitas           ringkasanfasilitas = BindData <ringkasanFasilitas>(dtheader, 0);
                    //datapokok
                    List <dataPokokDebiturPerusahaan> datapokoks = new List <dataPokokDebiturPerusahaan>();
                    for (int i = 0; i < dtpokok.Rows.Count; i++)
                    {
                        dataPokokDebiturPerusahaan datapokok = BindData <dataPokokDebiturPerusahaan>(dtpokok, i);
                        datapokoks.Add(datapokok);
                    }
                    //kredit
                    List <kreditPembiayan> kredits = new List <kreditPembiayan>();
                    for (int i = 0; i < dtkredit.Rows.Count; i++)
                    {
                        kreditPembiayan kredit      = BindData <kreditPembiayan>(dtkredit, i);
                        string          fasilitasid = dtkredit.Rows[i]["fasilitasid"].ToString();
                        DataTable       dtagunan    = conn.GetDataTable("select * from slik_ideb_agunan where resultid = @1 and fasilitasid = @2", new object[] { resultid, fasilitasid }, dbTimeout);
                        //agunan
                        List <agunan> agunans = new List <agunan>();
                        for (int x = 0; x < dtagunan.Rows.Count; x++)
                        {
                            agunan agunan = BindData <agunan>(dtagunan, x);
                            agunans.Add(agunan);
                        }

                        kredit.agunan = agunans.ToArray();
                        List <penjamin> penjamins = new List <penjamin>();
                        kredit.penjamin = penjamins.ToArray();
                        kredits.Add(kredit);
                    }

                    perusahaan.dataPokokDebitur   = datapokoks.ToArray();
                    perusahaan.parameterPencarian = searchParam;
                    perusahaan.ringkasanFasilitas = ringkasanfasilitas;
                    fasilitas fasilitas = new fasilitas();
                    fasilitas.kreditPembiayan = kredits.ToArray();
                    perusahaan.fasilitas      = fasilitas;

                    idebPerusahaan ideb = new idebPerusahaan();
                    ideb.header     = header;
                    ideb.perusahaan = perusahaan;
                    result          = JsonConvert.SerializeObject(ideb);
                }
            }

            return(result);
        }
 public void Add(individual individual)
 {
     da.Add <individual>(individual);
 }