Inheritance: Customer
 public static void PrintGroup(int group, Individual i, TimetableData ttData)
 {
     System.Diagnostics.Debug.WriteLine("");
     System.Diagnostics.Debug.WriteLine("Group " + group);
     for (int block = 0; block < i.Courses.GetLength(2); block++)
     {
         System.Diagnostics.Debug.Write("Block " + block + ": ");
         for (int day = 0; day < 5; day++)
         {
             int course = i.Groups[group, day, block];
             if (course == -1)
             {
                 for (int j = 0; j < 44; j++)
                 {
                     System.Diagnostics.Debug.Write("-");
                 }
             }
             else
             {
                 string output = ttData.Courses[course].Name + ", " + ttData.Rooms[i.Courses[course, day, block]].Id;
                 System.Diagnostics.Debug.Write(output.PadRight(44, ' '));
             }
             System.Diagnostics.Debug.Write("| ");
         }
         System.Diagnostics.Debug.WriteLine("");
     }
 }
 public Individual CreateChild(Individual parentA, Individual parentB, string geneSet)
 {
     int reversePointA = Random.Next(parentA.Genes.Length);
     int reversePointB = Random.Next(parentA.Genes.Length);
     if (reversePointA == reversePointB)
     {
         reversePointB = Random.Next(parentA.Genes.Length);
         if (reversePointA == reversePointB)
         {
             return parentA;
         }
     }
     int min = Math.Min(reversePointA, reversePointB);
     int max = Math.Max(reversePointA, reversePointB);
     var childGenes = parentA.Genes.ToCharArray();
     for (int i = 0; i <= (max - min) / 2; i++)
     {
         int lowIndex = i + min;
         int highIndex = max - i;
         char temp = childGenes[lowIndex];
         childGenes[lowIndex] = childGenes[highIndex];
         childGenes[highIndex] = temp;
     }
     var child = new Individual
     {
         Genes = new String(childGenes),
         Strategy = this,
         Parent = parentA
     };
     return child;
 }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // ****** Program ******

            // Initialize WorkbookDesigner object
            WorkbookDesigner designer = new WorkbookDesigner();
            // Load the template file
            designer.Workbook = new Workbook(dataDir + "SM_NestedObjects.xlsx");
            // Instantiate the List based on the class
            System.Collections.Generic.ICollection<Individual> list = new System.Collections.Generic.List<Individual>();
            // Create an object for the Individual class
            Individual p1 = new Individual("Damian", 30);
            // Create the relevant Wife class for the Individual
            p1.Wife = new Wife("Dalya", 28);
            // Create another object for the Individual class
            Individual p2 = new Individual("Mack", 31);
            // Create the relevant Wife class for the Individual
            p2.Wife = new Wife("Maaria", 29);
            // Add the objects to the list
            list.Add(p1);
            list.Add(p2);
            // Specify the DataSource
            designer.SetDataSource("Individual", list);
            // Process the markers
            designer.Process(false);
            // Save the Excel file.
            designer.Workbook.Save(dataDir+ "output.xlsx");

        }
    static void Main()
    {
        Individual ivan = new Individual("Ivan");
        Company tech = new Company("Tech OOD");

        MortageAcount firstAcc = new MortageAcount(ivan, 1000, 3);

        MortageAcount mortAcc = new MortageAcount(tech, 20000, 10);

        Console.WriteLine(mortAcc.CalculateInterestAmount(10)); //10 months * 10% / 2 = 10months * 5% from 20 000 = 10 000

        Console.WriteLine(mortAcc.CalculateInterestAmount(24)); //12m * 5% from 20000 and 12m * 10 % from 20000 = 12*1000 + 12*2000 = 36 000

        Console.WriteLine(firstAcc.CalculateInterestAmount(7)); //only 1 month (first 6 are no rate) * 3% from 1000 = 30

        DepositAcount depAcc = new DepositAcount(ivan, 700, 20);

        Console.WriteLine(depAcc.CalculateInterestAmount(99999)); // 0 - amount is 700 which is positive and less than 1000

        LoanAcount loanIndivid = new LoanAcount(ivan, 10000, 10);
        LoanAcount loanCompany = new LoanAcount(tech, 100000, 15);

        Console.WriteLine(loanIndivid.CalculateInterestAmount(3)); // 0 - free 3 months
        Console.WriteLine(loanIndivid.CalculateInterestAmount(4)); // free 3 months --> 1 * 10% from 10000 = 1000

        Console.WriteLine(loanCompany.CalculateInterestAmount(2)); // 0 - free 3 months
        Console.WriteLine(loanCompany.CalculateInterestAmount(4)); // free 2 months --> 2 * 15% from 100000 = 30000
    }
Example #5
0
        public override void evaluate(EvolutionState state,
			                      Individual ind,
			                      int subpopulation,
			                      int threadnum)
        {
            try
            {
                this.state = state;
                this.ind = ((GPIndividual)ind);
                this.subpopulation = subpopulation;
                this.threadnum = threadnum;

                model.problem = this;
                // Signal model to start simulation
                model._signal.Set();
                // Model plays out scene with individual and sets fitness
                _signal.WaitOne();

                Debug.Log("Fitness " + model.fitness + " Result " + model.result
                    + " = " + this.ind.trees [0].child.makeCTree(true, true, true));

                KozaFitness f = ((KozaFitness)ind.fitness);
                f.setStandardizedFitness(state, model.fitness);
                f.hits = 0;
                ind.evaluated = true;
            } catch (Exception e)
            {
                Debug.LogError(e.Message);
                throw new Exception("Error while evaluating: ", e);
            }
        }
Example #6
0
        public void TestIndividualConstructors()
        {
            ListGenotype<FloatGene> genotype1 = new ListGenotype<FloatGene>(new[] {new FloatGene(1)});
            ListGenotype<FloatGene> genotype2 = new ListGenotype<FloatGene>(new[] {new FloatGene(2)});

            Individual<ListGenotype<FloatGene>, int> individual1 =
                new Individual<ListGenotype<FloatGene>, int>(genotype1);
            Individual<ListGenotype<FloatGene>, int> individual2 =
                new Individual<ListGenotype<FloatGene>, int>(genotype2, 30);

            Assert.AreEqual(1, individual1.Genotype.Count);
            Assert.AreEqual(1, individual2.Genotype.Count);

            Assert.False(individual1.HasFitnessAssigned);
            Assert.True(individual2.HasFitnessAssigned);

            int a;
            Assert.Throws<InvalidOperationException>(() => a = individual1.Fitness);
            Assert.AreEqual(30, individual2.Fitness);

            ListGenotype<FloatGene> genotype3 = individual1.Genotype;
            Assert.AreSame(individual1.Genotype, genotype3);

            IList<Individual<ListGenotype<FloatGene>, int>> individuals =
                Individual<ListGenotype<FloatGene>, int>.FromGenotypes(new[] {genotype1, genotype2, genotype3});

            Assert.AreSame(individuals[0].Genotype, genotype1);
            Assert.AreSame(individuals[1].Genotype, genotype2);
            Assert.AreSame(individuals[2].Genotype, genotype3);
        }
Example #7
0
    private static void Main()
    {
        Customer customerOne = new Individual("Radka Piratka");
        Customer customerTwo = new Company("Miumiunali Brothers");

        Account[] accounts =
        {
            new Deposit(customerOne, 7000, 5.5m, 18),
            new Deposit(customerOne, 980, 5.9m, 12),
            new Loan(customerOne, 20000, 7.2m, 2),
            new Loan(customerOne, 2000, 8.5m, 9),
            new Mortgage(customerOne, 14000, 5.4m, 5),
            new Mortgage(customerOne, 5000, 4.8m, 10),
            new Deposit(customerTwo, 10000, 6.0m, 12),
            new Mortgage(customerTwo, 14000, 6.6m, 18),
            new Loan(customerTwo, 15000, 8.9m, 2),
            new Loan(customerTwo, 7000, 7.5m, 12),
        };

        foreach (Account account in accounts)
        {
            Console.WriteLine(account);
        }

        Deposit radkaDeposit = new Deposit(customerOne, 980, 5.9m, 12);
        Deposit miumiuDeposit = new Deposit(customerTwo, 10000, 6.0m, 12);

        Console.WriteLine();
        Console.WriteLine("Current balance: {0}", radkaDeposit.WithdrawMoney(150));
        Console.WriteLine("Current balance: {0}", radkaDeposit.DepositMoney(1500));
        Console.WriteLine("Current balance: {0}", miumiuDeposit.WithdrawMoney(5642));
        Console.WriteLine("Current balance: {0}", miumiuDeposit.DepositMoney(1247));
    }
Example #8
0
        public ActionResult Add(FormCollection form)
        {
            var individualToAdd = new Individual();

            // Deserialize (Include white list!)
            TryUpdateModel(individualToAdd, new string[] { "Name", "DateOfBirth" }, form.ToValueProvider());

            // Validate
            if (String.IsNullOrEmpty(individualToAdd.Name))
                ModelState.AddModelError("Name", "Name is required!");
            if (String.IsNullOrEmpty(individualToAdd.DateOfBirth))
                ModelState.AddModelError("DateOfBirth", "DateOfBirth is required!");

            var error = individualToAdd.ValidateDateOfBirth();
            if (!String.IsNullOrEmpty(error))
                ModelState.AddModelError("DateOfBirth", error);

            // If valid, save Individual to Database
            if (ModelState.IsValid)
            {
                _db.AddToIndividuals(individualToAdd);
                _db.SaveChanges();
                return RedirectToAction("Add");
            }

            // Otherwise, reshow form
            return View(individualToAdd);
        }
    // Use this for initialization
    void Start()
    {
        Debug.Log("Population size: " + populationSize);
        int width = (int)Mathf.Round(Mathf.Sqrt(populationSize));
        int height = (int)Mathf.Round(Mathf.Sqrt(populationSize));

        testing = new ComputeBuffer(10, Marshal.SizeOf(typeof(Individual)));

        Debug.Log("Seed " + DateTime.Now.Millisecond);

        // Fill with random genome, and run first fitness test.
        int kernel = shader.FindKernel("InitializePopulation");
        DebugAux.Assert(kernel >= 0, "Couldn't find kernel: " + "InitializePopulation " + kernel);
        shader.SetBuffer(kernel, "Population", testing);
        shader.SetFloat("seed", DateTime.Now.Millisecond);
        shader.Dispatch(kernel, 32, 32, 1);

        Individual[] tes = new Individual[10];
        testing.GetData(tes);
        for (int i = 0; i < tes.Length; i++)
            Debug.Log(tes[i].genome + " " + tes[i].fitness);

        // Selection..
        /*kernel = shader.FindKernel("AllOnesFitness");
        DebugAux.Assert(kernel >= 0, "Couldn't find kernel: " + "AllOnesFitness " + kernel);
        shader.SetBuffer(kernel, "Population", testing);
        shader.Dispatch(kernel, 32, 32, 1);*/

        testing.Dispose();
    }
        public Individual CreateChild(Individual parentA, Individual parentB, string geneSet)
        {
            const int charsToShift = 1;
            if (parentA.Genes.Length < charsToShift + 1)
            {
                return parentA;
            }
            bool shiftingPairLeft = Random.Next(2) == 1;
            string childGenes;
            int segmentStart = Random.Next(parentA.Genes.Length - charsToShift - 1);
            int segmentLength = Random.Next(charsToShift + 1, parentA.Genes.Length + 1 - segmentStart);
            string childGenesBefore = parentA.Genes.Substring(0, segmentStart);

            if (shiftingPairLeft)
            {
                string shiftedSegment = parentA.Genes.Substring(segmentStart, segmentLength - charsToShift);
                string shiftedPair = parentA.Genes.Substring(segmentStart + segmentLength - charsToShift, charsToShift);
                string childGenesAfter = parentA.Genes.Substring(segmentStart + segmentLength);
                childGenes = childGenesBefore + shiftedPair + shiftedSegment + childGenesAfter;
            }
            else
            {
                string shiftedPair = parentA.Genes.Substring(segmentStart, charsToShift);
                string shiftedSegment = parentA.Genes.Substring(segmentStart + charsToShift, segmentLength - charsToShift);
                string childGenesAfter = parentA.Genes.Substring(segmentStart + segmentLength);
                childGenes = childGenesBefore + shiftedSegment + shiftedPair + childGenesAfter;
            }
            var child = new Individual
            {
                Genes = childGenes,
                Strategy = this,
                Parent = parentA
            };
            return child;
        }
        public Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>> CrossoverFunc(IIndividual<Wrapper<LearningObject>> individualA, IIndividual<Wrapper<LearningObject>> individualB)
        {
            int minlen = Math.Min(individualA.Chromosome.Genes.Count, individualB.Chromosome.Genes.Count);
            Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>> tmpTuple;
            if (minlen > 2)
            {
                var fistChild = CrossIndividuals(individualA, individualB);
                var secondChild = CrossIndividuals(individualB, individualA);
                tmpTuple = new Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>>(fistChild, secondChild);
            }
            else
            {
                IIndividual<Wrapper<LearningObject>> ind1 = new Individual<Wrapper<LearningObject>>();
                foreach (var gene in individualA.Chromosome.Genes)
                {
                    ind1.Chromosome.Genes.Add(new Wrapper<LearningObject>(gene.Used, gene.Value));
                }

                IIndividual<Wrapper<LearningObject>> ind2 = new Individual<Wrapper<LearningObject>>();
                foreach (var gene in individualB.Chromosome.Genes)
                {
                    ind2.Chromosome.Genes.Add(new Wrapper<LearningObject>(gene.Used, gene.Value));
                }

                tmpTuple = new Tuple<IIndividual<Wrapper<LearningObject>>, IIndividual<Wrapper<LearningObject>>>(ind1, ind2);
            }

            return tmpTuple;
        }
Example #12
0
        private void cmdCreatClientWithAssociation_Click(object sender, EventArgs e)
        {
            // create client
            var i1 = new Individual()
            {
                LastName = "Smith"
            };
            _gateway.Save(i1);
            var client = _gateway.ConvertContactToClient(i1, "034757", CssContext.Instance.Host.EmployeeId);

            // create contact
            var i2 = new Individual()
            {
                LastName = "Jones"
            };
            _gateway.Save(i2);

            //create relationship
            var r = new Relationship() {
                Contact1 = i1,
                Contact2 = i2,
                RelationshipId = 1 // spouse - from relationship table
            };
            _gateway.Save(r);

            CssContext.Instance.Host.OpenContact(i1.ContactId);
        }
 public Individual CreateChild(Individual parentA, Individual parentB, string geneSet)
 {
     return new Individual
     {
         Genes = GenerateSequence(geneSet),
         Strategy = this
     };
 }
 public override double calculateFitness(Individual ind)
 {
     if (ind.gens.Count < 3)
     {
         throw new Exception("Genanzahl im Individuum  kleiner 3. (" + ind.gens.Count + ")");
     }
     return solveSystem(ind);
 }
 private static IEnumerable<Individual> GetAncestors(Individual bestIndividual)
 {
     while (bestIndividual != null)
     {
         yield return bestIndividual;
         bestIndividual = bestIndividual.Parent;
     }
 }
 public void ICrossoverStrategy_PerformCrossover_ThrowOnCrossoverBetweenSameIndividual()
 {
     var parent1 = new Individual(ValidGraph, ValidProblem);
     Assert.Throws<AlgorithmException>(() =>
     {
         Strategy.PerformCrossover(parent1, parent1);
     });
 }
 public int ComputeSchedulingTime(Individual ind)
 {
     int[] biases = new int[MachinesCount];
     for (int i = 0; i < JobsCount; i++)
     {
         biases[ind.Chromosome[i]] += jobs[i];
     }
     return biases.Max();
 }
Example #18
0
        protected override void DoSm(Individual parent1)
        {
            throw new NotImplementedException();
            //    //needs a refactor...
            //    //

            //    double max = functions.GetMin();
            //    double min = functions.GetMax();

            //    Individual child1 = new Individual();
            //    Individual child2 = new Individual();

            //    Random rand = new Random();
            //    for (int j = 0; j < functions.GetDecisionVariablesCount(); j++)
            //    {
            //        double c;
            //        double r = rand.NextDouble();

            //        if (r <= 0.5)
            //        {
            //            c = Math.Pow((2 * r), (1 / (mu + 1)));
            //        }
            //        else
            //        {
            //            c = Math.Pow(1 / (2 * r), 1 / (mu + 1));
            //        }
            //        child1.DecisionVariables.Add(0.5 * (((1 + c) * parent1.DecisionVariables[j]) + (1 - c) * parent2.DecisionVariables[j]));
            //        child2.DecisionVariables.Add(0.5 * (((1 - c) * parent1.DecisionVariables[j]) + (1 + c) * parent2.DecisionVariables[j]));
            //        if (child1.DecisionVariables[j] > max)
            //        {
            //            child1.DecisionVariables[j] = max;
            //        }
            //        else
            //        {
            //            if (child1.DecisionVariables[j] < min)
            //            {
            //                child1.DecisionVariables[j] = min;
            //            }
            //        }
            //        if (child2.DecisionVariables[j] > max)
            //        {
            //            child2.DecisionVariables[j] = max;
            //        }
            //        else
            //        {
            //            if (child2.DecisionVariables[j] < min)
            //            {
            //                child2.DecisionVariables[j] = min;
            //            }
            //        }
            //    }
            //    functions.EvaluateObjective(child1);
            //    functions.EvaluateObjective(child2);
            //    List<Solution> newBees = new List<Solution>();
            //    newBees.Add(child1);
            //    newBees.Add(child2);
        }
 public double ComputeFitness(Individual ind)
 {
     int[] biases = new int[MachinesCount];
     for (int i = 0; i < JobsCount; i++)
     {
         biases[ind.Chromosome[i]] += jobs[i];
     }
     return jobsSum - biases.Max() + 1; //force positive value
 }
 public static Community Subscribe(this Community community, Individual individual)
 {
     community
         .Subscribe(() => individual)
         .Subscribe(() => individual.Companies)
         .Subscribe(() => individual.Games)
         ;
     return community;
 }
 public void ICrossoverStrategy_PerformCrossover_ThrowsOnProbleMismatch()
 {
     var parent1 = new Individual(ValidGraph, ValidProblem);
     var parent2 = new Individual(ValidGraph, ProblemProvider.ProvideSubstitute());
     Assert.Throws<AlgorithmException>(() =>
     {
         Strategy.PerformCrossover(parent1, parent2);
     });
 }
 public void ICrossoverStrategy_PerformCrossover_ThrowOnLengthMismatch()
 {
     var parent1 = new Individual(ValidGraph, ValidProblem);
     ValidGraph.AddNode("Yet another node");
     var parent2 = new Individual(ValidGraph, ValidProblem);
     Assert.Throws<AlgorithmException>(() =>
     {
         Strategy.PerformCrossover(parent1, parent2);
     });
 }
        public void EvaluateObjective(Individual i)
        {
            //value for each function// cause we do this... and not otherwise... lalla.. alive daft punk
            i.ObjectiveValue.Clear();

            foreach (ObjectiveFunction f in functions)
            {
                i.ObjectiveValue.Add(f.Evaluate(i.DecisionVariables));
            }
        }
 public void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
   // Use vars.yourVariable to access variables in the variable store i.e. yourVariable
   // Write or update results given the range of vectors and resulting qualities
   // Uncomment the following lines if you want to retrieve the best individual
   // Maximization:
   // var bestIndex = qualities.Select((v, i) => Tuple.Create(i, v)).OrderByDescending(x => x.Item2).First().Item1;
   // Minimization:
   // var bestIndex = qualities.Select((v, i) => Tuple.Create(i, v)).OrderBy(x => x.Item2).First().Item1;
   // var best = individuals[bestIndex];
 }
        public void ICrossoverStrategy_PerformCrossover_ValidCrossover()
        {
            var parent1 = new Individual(ValidGraph, ValidProblem);
            var parent2 = new Individual(ValidGraph, ValidProblem);
            var offspring = Strategy.PerformCrossover(parent1, parent2);

            //Only reference check can be performaed here as parents having same genotype
            // will end up having exactly same offspring, thus comparison would eventually fail
            Assert.False(offspring.Equals(parent1));
            Assert.False(offspring.Equals(parent2));
        }
        public HttpResponseMessage DeleteIndividual(Individual individual)
        {
            _individualService.Delete(individual);

            var response = new
            {
                id = individual.Id
            };

            return Request.CreateResponse(HttpStatusCode.OK, response);
        }
Example #27
0
    static void Main(string[] args)
    {
        //A bank holds different types of accounts for its customers: deposit accounts, loan
        //accounts and mortgage accounts. Customers could be individuals or companies.
        //All accounts have customer, balance and interest rate (monthly based). Deposit accounts
        //are allowed to deposit and with draw money. Loan and mortgage accounts can only deposit money.
        //All accounts can calculate their interest amount for a given period (in months). In the
        //common case its is calculated as follows: number_of_months * interest_rate.
        //Loan accounts have no interest for the first 3 months if are held by individuals and for the
        //first 2 months if are held by a company.
        //Deposit accounts have no interest if their balance is positive and less than 1000.
        //Mortgage accounts have ½ interest for the first 12 months for companies and no interest for the
        //first 6 months for individuals.
        //Your task is to write a program to model the bank system by classes and interfaces. You should
        //identify the classes, interfaces, base classes and abstract actions and implement the calculation
        //of the interest functionality through overridden methods.

        //Make two customers - one company and one individual
        Company kaBar = new Company("KaBar");
        Individual peter = new Individual("Peter Petrov");

        //Make deposite account for individual and company and test the account functionalities
        DepositAccount peterDepositAcount = new DepositAccount(peter, 500m, 0.05m);
        DepositAccount kaBarDepositAcount = new DepositAccount(kaBar, 500m, 0.05m);
        peterDepositAcount.Draw(200m);
        Console.WriteLine(peterDepositAcount.Balance);
        peterDepositAcount.AddDeposit(200);
        Console.WriteLine(peterDepositAcount.Balance);

        Console.WriteLine("The {0} of the {1}-{2} have interest amount for next six mounths: {3} "
            , peterDepositAcount.GetType(), peterDepositAcount.Customer.GetType(), peterDepositAcount.Customer.Name, peterDepositAcount.InterestAmountForPeriod(6));
        Console.WriteLine("The {0} of the {1}-{2} have interest amount for next six mounths: {3} "
            , kaBarDepositAcount.GetType(), kaBarDepositAcount.Customer.GetType(), kaBarDepositAcount.Customer.Name, kaBarDepositAcount.InterestAmountForPeriod(6));
        Console.WriteLine("--------------------------------------------------------------------");

        //Make loan account for individual and company and test the account functionalities
        LoanAccount peterLoanAccount = new LoanAccount(peter, 500m, 0.05m);
        Console.WriteLine("The {0} of the {1}-{2} have interest amount for next six mounths: {3} "
            , peterLoanAccount.GetType(), peterLoanAccount.Customer.GetType(), peterLoanAccount.Customer.Name, peterLoanAccount.InterestAmountForPeriod(6));

        LoanAccount kaBarLoanAccount = new LoanAccount(kaBar, 500m, 0.05m);
        Console.WriteLine("The {0} of the {1}-{2} have interest amount for next six mounths: {3} "
            , kaBarLoanAccount.GetType(), kaBarLoanAccount.Customer.GetType(), kaBarLoanAccount.Customer.Name, kaBarLoanAccount.InterestAmountForPeriod(6));
        Console.WriteLine("--------------------------------------------------------------------");

        //Make Mortage account for individual and company and test the account functionalities
        MortageAccount peterMortageAccount = new MortageAccount(peter, 500m, 0.05m);
        Console.WriteLine("The {0} of the {1}-{2} have interest amount for next two years: {3} "
            , peterMortageAccount.GetType(), peterMortageAccount.Customer.GetType(), peterMortageAccount.Customer.Name, peterMortageAccount.InterestAmountForPeriod(24));
        MortageAccount kaBarMortageAccount = new MortageAccount(kaBar, 500m, 0.05m);
        Console.WriteLine("The {0} of the {1}-{2} have interest amount for next two years: {3} "
            , kaBarMortageAccount.GetType(), kaBarMortageAccount.Customer.GetType(), kaBarMortageAccount.Customer.Name, kaBarMortageAccount.InterestAmountForPeriod(24));
    }
 public Individual CreateChild(Individual parentA, Individual parentB, string geneSet)
 {
     var parentGenes = parentA.Genes.ToCharArray();
     int location = Random.Next(0, parentGenes.Length);
     parentGenes[location] = geneSet[Random.Next(0, geneSet.Length)];
     return new Individual
     {
         Genes = new String(parentGenes),
         Strategy = this,
         Parent = parentA
     };
 }
 private Individual Crossover(Individual parentA, Individual parentB, string geneSet)
 {
     int crossOverPoint = _random.Next(parentA.Genes.Length);
     var childGenes = parentA.Genes.ToCharArray();
     var parentBGenes = parentB.Genes.ToCharArray();
     childGenes[crossOverPoint] = parentBGenes[crossOverPoint];
     var child = new Individual
         {
             Genes = new String(childGenes)
         };
     return child;
 }
        protected override IPredicate BuildPredicate(XPathNavigator predicateElement, bool inHead, bool resolveImmediatly)
        {
            IPredicate predicate;
            var        predicateName  = predicateElement.Name;
            var        predicateValue = predicateElement.Value;

            switch (predicateName)
            {
            // --------- IND predicates --------
            case "ind":
                if (predicateValue.ToLower().StartsWith("expr:"))
                {
                    if (inHead)
                    {
                        if (resolveImmediatly)
                        {
                            predicate = new Individual(Compilation.Evaluate(predicateValue));
                        }
                        else
                        {
                            predicate = new Formula(Formula.FormulaResolutionType.NxBRE,
                                                    Binder,
                                                    predicateValue);
                        }
                    }
                    else
                    {
                        predicate = new Function(Function.FunctionResolutionType.Binder,
                                                 predicateValue,
                                                 new ExpressionEvaluator(predicateValue),
                                                 Empty,
                                                 Empty);
                    }
                }
                else if (predicateValue.ToLower().StartsWith("nxbre:"))
                {
                    // NxBRE functions must follow this pattern: NxBRE:Function(uniqueargument)
                    ObjectPair operatorCall = Parameter.ParseOperatorCall(predicateValue);
                    predicate = new Function(Function.FunctionResolutionType.NxBRE,
                                             predicateValue,
                                             null,
                                             (string)operatorCall.First,
                                             (string)operatorCall.Second);
                }
                else if (Binder == null)
                {
                    predicate = new Individual(predicateValue);
                }
                else if ((inHead) && (predicateValue.ToLower().StartsWith("binder:")))
                {
                    predicate = new Formula(Formula.FormulaResolutionType.Binder,
                                            Binder,
                                            predicateValue);
                }
                else if ((inHead) && (predicateValue.EndsWith("()")))
                {
                    predicate = new Formula(Formula.FormulaResolutionType.Binder,
                                            Binder,
                                            predicateValue);
                }
                else
                {
                    predicate = Binder.AnalyzeIndividualPredicate(new Individual(predicateValue));
                }

                break;

            // --------- VAR predicates --------
            case "var":
                predicate = new Variable(predicateValue);
                break;

            // --------- UNKNOWN predicates --------
            default:
                throw new BREException("Unsupported predicate type: " + predicateName);
            }

            return(predicate);
        }
Example #31
0
        protected void InitRace(Individual individual)
        {
            race = game.CreateRace(0);

            FillWeightsWithGenom(((PilotC)race.Teams[0].PodRacers[0].Pilot).nn, individual.Genom);
        }
Example #32
0
 private void updateLiverExpressions(Individual individual)
 {
     individual.AllMolecules().Each(updateLiverMoleculeExpression);
 }
Example #33
0
 private IContainer liverIn(Individual individual)
 {
     return(individual.Organism.Container(CoreConstants.Organ.Liver));
 }
Example #34
0
 public void Single_HasOne(int input) => Assert.Single(Individual.Enumerable(input), input);
Example #35
0
 private static void mutateIndividual(Individual indi)
 {
     alterPieces(indi);
     addPieces(indi);
 }
Example #36
0
 public MainViewModel(Community community, Individual individual)
 {
     _community  = community;
     _individual = individual;
 }
Example #37
0
 public abstract void Crossover(Individual partner, float probability, int pontos);
Example #38
0
 public void Visit(Individual individual)
 {
     convertIndividual(individual);
 }
Example #39
0
 private void verifyIndividual(Individual individual)
 {
     verifyPlasmaProteinOntogenyFactor(individual.Organism);
     individual.AllDefinedMolecules().Each(verifyOntogenyInMolecule);
 }
Example #40
0
 public static void EvaluateIndividual(Individual ind, double value = 1.0)
 {
     ind.SendForEvaluation();
     ind.SetProperty("solution", value);
     ind.SetSolution("solution");
 }
        protected override Tuple <Individual, Individual> PerformCrossover(Individual parent1, Individual parent2)
        {
            var left  = random.Next(parent1.Weights.Length);
            var right = random.Next(parent1.Weights.Length);

            return(PerformPMXCrossover(parent1, parent2, left, right));
        }
        protected override void Context()
        {
            _vssCalculator               = A.Fake <IVSSCalculator>();
            _parameterFactory            = A.Fake <IParameterFactory>();
            _protocolMapper              = A.Fake <IProtocolToSchemaItemsMapper>();
            _protocolFactory             = A.Fake <IProtocolFactory>();
            _globalPKAnalysisRunner      = A.Fake <IGlobalPKAnalysisRunner>();
            _pkCalculationOptionsFactory = A.Fake <IPKCalculationOptionsFactory>();
            _pkAnalysisTask              = A.Fake <IPKAnalysesTask>();
            _interactionTask             = A.Fake <IInteractionTask>();
            _cloner = A.Fake <ICloner>();
            sut     = new GlobalPKAnalysisTask(_parameterFactory, _protocolMapper, _protocolFactory, _globalPKAnalysisRunner,
                                               _pkAnalysisTask, _pkCalculationOptionsFactory, _vssCalculator, _interactionTask, _cloner);

            var baseGrid = new BaseGrid("time", A.Fake <IDimension>());

            _peripheralVenousBloodPlasma = CalculationColumnFor(baseGrid, CoreConstants.Organ.PERIPHERAL_VENOUS_BLOOD, CoreConstants.Observer.PLASMA_PERIPHERAL_VENOUS_BLOOD, CoreConstants.Observer.PLASMA_PERIPHERAL_VENOUS_BLOOD, _compoundName);
            _venousBloodPlasma           = CalculationColumnFor(baseGrid, CoreConstants.Organ.VENOUS_BLOOD, CoreConstants.Compartment.PLASMA, CoreConstants.Observer.CONCENTRATION_IN_CONTAINER, _compoundName);

            _individual = A.Fake <Individual>();
            _species    = new Species();
            A.CallTo(() => _individual.Species).Returns(_species);

            _compound           = new Compound().WithName(_compoundName);
            _compoundProperties = new CompoundProperties {
                Compound = _compound
            };
            _protocol = new SimpleProtocol();
            _compoundProperties.ProtocolProperties.Protocol = _protocol;

            _simulation = new IndividualSimulation {
                Properties = new SimulationProperties()
            };

            _simulation.Properties.AddCompoundProperties(_compoundProperties);
            _simulation.AddUsedBuildingBlock(new UsedBuildingBlock("CompId", PKSimBuildingBlockType.Compound)
            {
                BuildingBlock = _compound
            });
            _simulation.AddUsedBuildingBlock(new UsedBuildingBlock("IndividualId", PKSimBuildingBlockType.Individual)
            {
                BuildingBlock = _individual
            });
            _simulation.DataRepository = new DataRepository {
                _venousBloodPlasma, _peripheralVenousBloodPlasma
            };
            _simulation.SimulationSettings = new SimulationSettings();
            _simulation.OutputSchema       = new OutputSchema();
            _simulation.OutputSchema.AddInterval(new OutputInterval {
                DomainHelperForSpecs.ConstantParameterWithValue(100).WithName(Constants.Parameters.END_TIME)
            });
            _simulation.Model = new OSPSuite.Core.Domain.Model {
                Root = new Container()
            };
            _eventGroup   = new EventGroup();
            _application1 = new Container().WithName("App1").WithContainerType(ContainerType.Application);
            _application1.Add(new MoleculeAmount().WithName(_compoundName));
            _application1.Add(DomainHelperForSpecs.ConstantParameterWithValue(10).WithName(Constants.Parameters.START_TIME));
            _application2 = new Container().WithName("App2").WithContainerType(ContainerType.Application);
            _application2.Add(DomainHelperForSpecs.ConstantParameterWithValue(10).WithName(Constants.Parameters.START_TIME));
            _application2.Add(new MoleculeAmount().WithName(_compoundName));
            _simulation.Model.Root.Add(_eventGroup);
            _eventGroup.Add(_application1);
            _venousBloodPK = new PKValues();
            _venousBloodPK.AddValue(Constants.PKParameters.Vss, 10);
            _venousBloodPK.AddValue(Constants.PKParameters.Vd, 11);
            _venousBloodPK.AddValue(Constants.PKParameters.CL, 12);

            _venousBloodPK.AddValue(Constants.PKParameters.AUC_inf, 13);
            _venousBloodPK.AddValue(Constants.PKParameters.AUC_inf_tD1_norm, 14);

            _peripheralVenousBloodPK = new PKValues();
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.Vss, 21);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.Vd, 22);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.CL, 23);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.AUC_inf, 24);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.AUC_inf_tD1_norm, 25);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.C_max, 26);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.C_max_tDLast_tDEnd, 27);


            A.CallTo(() => _pkAnalysisTask.CalculatePK(_venousBloodPlasma, A <PKCalculationOptions> ._)).Returns(_venousBloodPK);
            A.CallTo(() => _pkAnalysisTask.CalculatePK(_peripheralVenousBloodPlasma, A <PKCalculationOptions> ._)).Returns(_peripheralVenousBloodPK);
            A.CallTo(() => _parameterFactory.CreateFor(A <string> ._, A <double> ._, A <string> ._, PKSimBuildingBlockType.Simulation))
            .ReturnsLazily(s => new PKSimParameter().WithName((string)s.Arguments[0])
                           .WithDimension(A.Fake <IDimension>())
                           .WithFormula(new ConstantFormula((double)s.Arguments[1])));
        }
Example #43
0
        public IEnumerable <ParameterScaling> AllParameterScalingsFrom(Individual originIndividual, Individual targetIndividual)
        {
            //only show parameter for scaling that are visble parameters
            var allTargetParameters = _containerTask.CacheAllChildren <IParameter>(targetIndividual);

            //default individul based on origin indivudal (used to retrieve default value)
            var allOriginParameters = _containerTask.CacheAllChildrenSatisfying <IParameter>(originIndividual, scalingAllowedFor);

            //return parameter scaling for all parameters existing in the source and target compartment
            return(from originParameter in allOriginParameters.KeyValues
                   let targetParameter = allTargetParameters[originParameter.Key]
                                         where scalingRequiredFor(originParameter.Value, targetParameter)
                                         select parameterScalingFor(originParameter.Value, targetParameter));
        }
Example #44
0
 public Fitness Fitness(MaxTimeProblem problem, Individual <MaxTimeSolution, MaxTimeProblem, Fitness> individual)
 {
     return(this.Fitness(problem, individual, false));
 }
Example #45
0
        public void ReturnEvaluatedIndividual(Individual ind)
        {
            ind.ID = _individualsEvaluatedTotal;
            _individualsEvaluatedTotal++;

            if (_bestIndividual == null || _bestIndividual.Fitness < ind.Fitness)
            {
                _bestIndividual = ind;
            }

            if (ind.Generation != _generation)
            {
                return;
            }

            // Note that we don't use overflow individuals in adaptation calculations.
            _individualsEvaluated++;
            _population.Add(ind);
            if (_population.Count >= _params.PopulationSize)
            {
                // Rank solutions
                var parents = _population.OrderByDescending(o => o.Fitness)
                              .Take(_params.NumParents).ToList();
                Console.WriteLine(parents[0].Fitness);

                // Recombination of the new mean
                LA.Vector <double> oldMean = _mean;
                _mean = LA.Vector <double> .Build.Dense(_numParams);

                for (int i = 0; i < _params.NumParents; i++)
                {
                    _mean += DenseVector.OfArray(parents[i].ParamVector) * _weights[i];
                }

                // Update the evolution path
                LA.Vector <double> y = _mean - oldMean;
                LA.Vector <double> z = _C.Invsqrt * y;
                _ps = (1.0 - _cs) * _ps + (Math.Sqrt(_cs * (2.0 - _cs) * _mueff) / _mutationPower) * z;
                double left = _ps.DotProduct(_ps) / _numParams
                              / (1.0 - Math.Pow(1.0 - _cs, 2 * _individualsEvaluated / _params.PopulationSize));
                double right = 2.0 + 4.0 / (_numParams + 1.0);
                double hsig  = left < right ? 1 : 0;
                _pc = (1.0 - _cc) * _pc + hsig * Math.Sqrt(_cc * (2.0 - _cc) * _mueff) * y;

                // Covariance matrix update
                double c1a = _c1 * (1.0 - (1.0 - hsig * hsig) * _cc * (2.0 - _cc));
                _C.C *= (1.0 - c1a - _cmu);
                _C.C += _c1 * _pc.OuterProduct(_pc);
                for (int i = 0; i < _params.NumParents; i++)
                {
                    LA.Vector <double> dv = DenseVector.OfArray(parents[i].ParamVector) - oldMean;
                    _C.C += _weights[i] * _cmu *dv.OuterProduct(dv) / (_mutationPower * _mutationPower);
                }

                if (CheckStop(parents))
                {
                    Reset();
                }
                _C.UpdateEigensystem();

                // Update sigma
                double cn          = _cs / _damps;
                double sumSquarePs = _ps.DotProduct(_ps);
                _mutationPower *= Math.Exp(Math.Min(1, cn * (sumSquarePs / _numParams - 1) / 2));

                _generation++;
                _individualsDispatched = 0;
                _population.Clear();
            }
        }
Example #46
0
 // Sexual reproduction
 public abstract Individual Reproduce(Individual other);
 public Task Save(Individual individual)
 {
     return(Save(individual, individual.Id));
 }
 public void AddToProjectBasedOn(Individual individual)
 {
     AddToProject <ICreateRandomPopulationPresenter>(x => x.CreatePopulation(individual));
 }
 public Task DeleteIndividualGroupings(Individual individual)
 {
     return(Database.Table <IndividualGroupings>().Where(ig => ig.IndividualId == individual.Id).ToListAsync());
 }
Example #50
0
 public void Visit(Individual individual)
 {
     convertIndividual(individual);
     _converted = true;
 }
 public Task <List <IndividualGroupings> > GetAllIndividualGroupingsForIndividual(Individual individual)
 {
     return(Database.Table <IndividualGroupings>().Where(individualGrouping => individualGrouping.IndividualId == individual.Id).ToListAsync());
 }
Example #52
0
        private void updateIsLiverZonatedValue(Individual individual)
        {
            var liver = liverIn(individual);

            liver.Parameter(CoreConstants.Parameters.IS_LIVER_ZONATED).Value = 0;
        }
 public async Task Delete(Individual individual)
 {
     await Delete <Individual>(individual);
     await DeleteIndividualGroupings(individual);
 }
Example #54
0
        private void SearchTask(CancellationToken cancellationToken)
        {
            Population population;

            population = new Population();

            for (int individualIndex = 0; individualIndex < 100; individualIndex++)
            {
                population.Individuals.Add(new Individual(17 + 17 * 32 + 32 + 32 * 32 + 32 + 32 * 32 + 32 + 32 * 13 + 13));
            }

            if (bestNn != null)
            {
                FillGenomWithWeights(population.Individuals[0].Genom, bestNn);
            }

            RaceResult result;
            double     score = 0;

            int    generationsCount = 0;
            double maxScore         = -1;

            while (true)
            {
                generationsCount++;

                foreach (var individual in population.Individuals)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    InitRace(individual);

                    result = race.ExecuteRace();

                    score = CalculateScoreForPodRacer(race.PodRacers[0]);

                    individual.Fitness = score;

                    if (maxScore < score)
                    {
                        maxScore = score;
                        UpdateSearchData(maxScore, generationsCount, population.AverageFitness(), race.RaceState.Round);
                        NeuralNetwork.Storage.WriteNeuralNetworkToFile(((PilotC)(race.PodRacers[0].Pilot)).nn, @"c:\temp\scored14.bin");
                    }
                }

                UpdateSearchData(generationsCount);

                if (!cancellationToken.IsCancellationRequested)
                {
                    population.Breed();
                }
                else
                {
                    break;
                }
            }

            bestNn = NeuralNetwork.Storage.ReadNeuralNetworkFromFile(@"c:\temp\scored14.bin");

            Individual bestIndividual;

            bestIndividual = new Individual(17 + 17 * 32 + 32 + 32 * 32 + 32 + 32 * 32 + 32 + 32 * 13 + 13);

            FillGenomWithWeights(bestIndividual.Genom, bestNn);

            InitRace(bestIndividual);
        }
Example #55
0
 public DataError(int errorType, Individual ind, string description)
     : this(errorType, Fact.FactError.ERROR, ind, description)
 {
 }
 protected override void Context()
 {
     _individual = A.Fake <Individual>();
     _representationInfoRepository = A.Fake <IRepresentationInfoRepository>();
     sut = new MoleculeToQueryExpressionSettingsMapper(_representationInfoRepository);
 }
Example #57
0
 public Fitness Fitness(MaxTimeProblem problem, Individual <MaxTimeSolution, MaxTimeProblem, Fitness> individual, bool validate)
 {
     return(this.Fitness(problem, individual.Genomes));
 }
Example #58
0
 void DgReportSheet_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
 {
     if (e.RowIndex >= 0)
     {
         FamilyTree ft = FamilyTree.Instance;
         if (e.ColumnIndex >= startColumnIndex && e.ColumnIndex <= endColumnIndex)
         {
             DataGridViewCell cell = dgReportSheet.Rows[e.RowIndex].Cells[e.ColumnIndex];
             int value             = (int)cell.Value;
             if (value >= 1 && value <= 7) // allows any type of record to search census
             {
                 IDisplayColourCensus person = (IDisplayColourCensus)dgReportSheet.Rows[e.RowIndex].DataBoundItem;
                 int censusYear;
                 if (_country.Equals(Countries.UNITED_STATES))
                 {
                     censusYear = (1790 + (e.ColumnIndex - startColumnIndex) * 10);
                 }
                 else if (_country.Equals(Countries.CANADA))
                 {
                     if (e.ColumnIndex <= dgReportSheet.Columns["Can1901"].Index)
                     {
                         censusYear = (1851 + (e.ColumnIndex - startColumnIndex) * 10);
                     }
                     else
                     {
                         censusYear = (1901 + (e.ColumnIndex - dgReportSheet.Columns["Can1901"].Index) * 5);
                     }
                 }
                 else if (_country.Equals(Countries.IRELAND))
                 {
                     censusYear = (1901 + (e.ColumnIndex - startColumnIndex) * 10);
                 }
                 else
                 {
                     if (e.ColumnIndex == C1939.Index)
                     {
                         censusYear = 1939;
                     }
                     else
                     {
                         censusYear = (1841 + (e.ColumnIndex - startColumnIndex) * 10);
                     }
                 }
                 string censusCountry = person.BestLocation(new FactDate(censusYear.ToString())).CensusCountry;
                 if (censusYear == 1939 &&
                     !cbCensusSearchProvider.SelectedItem.Equals("Find My Past") &&
                     !cbCensusSearchProvider.SelectedItem.Equals("Ancestry"))
                 {
                     MessageBox.Show($"Unable to search the 1939 National Register on {cbCensusSearchProvider.SelectedItem}.", "FTAnalyzer");
                 }
                 else
                 {
                     try
                     {
                         ft.SearchCensus(censusCountry, censusYear, ft.GetIndividual(person.IndividualID), cbCensusSearchProvider.SelectedIndex, cbRegion.Text);
                     }
                     catch (CensusSearchException ex)
                     {
                         MessageBox.Show(ex.Message);
                     }
                 }
             }
         }
         else if (e.ColumnIndex >= 0)
         {
             string     indID    = (string)dgReportSheet.CurrentRow.Cells["IndividualID"].Value;
             Individual ind      = ft.GetIndividual(indID);
             Facts      factForm = new Facts(ind);
             factForm.Show();
         }
     }
 }
        public Tuple <Individual, Individual> PerformPMXCrossover(Individual parent1, Individual parent2, int left, int right)
        {
            var numberOfGenes = parent1.Weights.Length;

            CommonFunctions.SwapIfNotInOrder(ref left, ref right);

            var offspring1 = GetOffspring(left, right, parent1, parent2);
            var offspring2 = GetOffspring(left, right, parent2, parent1);

            return(new Tuple <Individual, Individual>(offspring1, offspring2));
        }
Example #60
-1
        public static void Main()
        {
            Bank bank = new Bank("SoftUni Bank");
            var e = bank.Accounts;
            foreach (var account in e)
            {
                Console.WriteLine(account);
            }

            try
            {
                Individual clientOne = new Individual("Pencho Pitankata", "Neyde", "1212121230");
                Company clientTwo = new Company("SoftUni", "Hadji Dimitar", "831251119", true);
                DepositAccount depositOne = new DepositAccount(clientOne, 5, 10000);
                DepositAccount depositTwo = new DepositAccount(clientOne, 2, 100, new DateTime(2000, 01, 01));
                DepositAccount depositThree = new DepositAccount(clientOne, 2, 10000, new DateTime(2008, 01, 01));
                LoanAccount loanOne = new LoanAccount(clientOne, 14, 10000, new DateTime(2003, 01, 01));
                LoanAccount loanTwo = new LoanAccount(clientTwo, 14, 10000, new DateTime(2003, 01, 01));
                MortgageAccount mortgageOne = new MortgageAccount(clientOne, 7, 100000, new DateTime(2013, 08, 01));
                MortgageAccount mortgageTwo = new MortgageAccount(clientTwo, 7, 100000, new DateTime(2014, 08, 01));
                Console.WriteLine("Deposit Account 1 Interest: {0:F2}", depositOne.Interest());
                Console.WriteLine("Deposit Account 2 Interest: {0:F2}", depositTwo.Interest());
                Console.WriteLine("Deposit Account 3 Interest: {0:F2}", depositThree.Interest());
                Console.WriteLine("Loan Account Individual Interest: {0:F2}", loanOne.Interest());
                Console.WriteLine("Loan Account Company Interest: {0:F2}", loanTwo.Interest());
                Console.WriteLine("Mortgage Account Interest: {0:F2}", mortgageOne.Interest());
                Console.WriteLine("Mortgage Account Interest: {0:F2}", mortgageTwo.Interest());
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message + "\n" + ex.StackTrace);
            }
        }