private static GeneticEllipseMatch PrepareGeneticEllipseMatchAlgorithm(EllipsisMatchFilterConfiguration configuration, ILogger logger) { var geneticEllipseMatch = new GeneticEllipseMatch { BufferWidth = configuration.BufferWidth, EccentricityThreshold = configuration.InvalidEccentricityThreshold, }; var factory = new CollectivePhenotypeFactory <EllipticParameters>(); var individualFactory = new IndividualFactory <CollectiveGenotype <EllipticParameters>, CollectivePhenotype <EllipticParameters>, EllipsisMatchFitness>( factory); var compareCriteria = new SimpleComparison <EllipsisMatchFitness>(EOptimizationMode.Minimize); if (!File.Exists(configuration.GeneticAlgorithmConfigurationFile)) { logger.Fatal("Genetic configuration file does not exist!"); Environment.Exit(0); } var geneticAlgorithmConfigurationContent = File.ReadAllText(configuration.GeneticAlgorithmConfigurationFile); var geneticAlgorithmInfo = JsonConvert.DeserializeObject <DynamicObjectInfo>(geneticAlgorithmConfigurationContent); var geneticAlgorithm = DynamicObjectFactory <GeneticAlgorithm> .Build(geneticAlgorithmInfo); geneticAlgorithm.Population.CompareCriteria = compareCriteria; geneticAlgorithm.Population.IndividualFactory = individualFactory; geneticEllipseMatch.GeneticAlgorithm = geneticAlgorithm; return(geneticEllipseMatch); }
private static GeneticDistributionFilter PrepareGeneticDistributionFilter(GeneticDistributionFilterConfiguration configuration, ILogger logger) { var handler = FunctionBuilder <double> .CreateFunction(configuration.TrunkThreshold); var geneticDistributionFilterParams = new GeneticDistributionFilterParams { DistributionResolution = configuration.DistributionResolution, GetTrunkThreshold = height => handler(new object[] { height }) }; var geneticDistributionFilter = new GeneticDistributionFilter(geneticDistributionFilterParams); var compareCriteria = new SimpleComparison <GeneticDistributionFitness>(EOptimizationMode.Minimize); var factory = new CollectivePhenotypeFactory <ParabolicParameters>(); var individualFactory = new IndividualFactory <CollectiveGenotype <ParabolicParameters>, CollectivePhenotype <ParabolicParameters>, GeneticDistributionFitness> (factory); if (!File.Exists(configuration.GeneticAlgorithmConfigurationFile)) { logger.Fatal("Genetic configuration file does not exist!"); Environment.Exit(0); } var geneticAlgorithmConfigurationContent = File.ReadAllText(configuration.GeneticAlgorithmConfigurationFile); var geneticAlgorithmInfo = JsonConvert.DeserializeObject <DynamicObjectInfo>(geneticAlgorithmConfigurationContent); var geneticAlgorithm = DynamicObjectFactory <GeneticAlgorithm> .Build(geneticAlgorithmInfo); geneticAlgorithm.Population.CompareCriteria = compareCriteria; geneticAlgorithm.Population.IndividualFactory = individualFactory; geneticDistributionFilter.GeneticAlgorithm = geneticAlgorithm; return(geneticDistributionFilter); }
protected override void Context() { _createIndvidualAlgorithm = A.Fake <ICreateIndividualAlgorithm>(); _entityBaseFactory = A.Fake <IObjectBaseFactory>(); _individualModelTask = A.Fake <IIndividualModelTask>(); _speciesRepository = A.Fake <ISpeciesRepository>(); _entityValidator = A.Fake <IEntityValidator>(); _reportGenerator = A.Fake <IReportGenerator>(); _genderRepository = A.Fake <IGenderRepository>(); _moleculeOntogenyVariabilityUpdater = A.Fake <IMoleculeOntogenyVariabilityUpdater>(); _diseaseStateImplementationRepository = A.Fake <IDiseaseStateImplementationFactory>(); sut = new IndividualFactory( _individualModelTask, _entityBaseFactory, _createIndvidualAlgorithm, _speciesRepository, _entityValidator, _reportGenerator, _moleculeOntogenyVariabilityUpdater, _genderRepository, _diseaseStateImplementationRepository ); _age = DomainHelperForSpecs.ConstantParameterWithValue().WithName(CoreConstants.Parameters.AGE); _gestationalAge = DomainHelperForSpecs.ConstantParameterWithValue().WithName(Constants.Parameters.GESTATIONAL_AGE); _height = DomainHelperForSpecs.ConstantParameterWithValue().WithName(CoreConstants.Parameters.HEIGHT); _weight = DomainHelperForSpecs.ConstantParameterWithValue().WithName(CoreConstants.Parameters.WEIGHT); _bmi = DomainHelperForSpecs.ConstantParameterWithValue().WithName(CoreConstants.Parameters.BMI); }
private void UpdateIndividual(int index, short[] child) { var childGenotype = Individuals[index].Genotype.EmptyCopy <CombinatoryGenotype>(); childGenotype.Value = child; var childIndividual = IndividualFactory.CreateFromGenotype(childGenotype); Individuals[index] = CompareCriteria.GetBetter(Individuals[index], childIndividual); }
protected override void Context() { _createIndvidualAlgorithm = A.Fake <ICreateIndividualAlgorithm>(); _entityBaseFactory = A.Fake <IObjectBaseFactory>(); _individualModelTask = A.Fake <IIndividualModelTask>(); _speciesRepository = A.Fake <ISpeciesRepository>(); _entityValidator = A.Fake <IEntityValidator>(); _reportGenerator = A.Fake <IReportGenerator>(); _moleculeOntogenyVariabilityUpdater = A.Fake <IMoleculeOntogenyVariabilityUpdater>(); sut = new IndividualFactory(_individualModelTask, _entityBaseFactory, _createIndvidualAlgorithm, _speciesRepository, _entityValidator, _reportGenerator, _moleculeOntogenyVariabilityUpdater); }
public override void NextGeneration() { var nextGenSize = ResizePolicy.NextGenSize(this); var nextGeneration = new IIndividual[nextGenSize]; for (var i = 0; i < nextGenSize / Crossover.ChildrenCount; i++) { var parentalGenotypes = SelectParentalGenotypes(); var genotypes = Crossover.Cross(parentalGenotypes); for (var j = 0; j < genotypes.Length; j++) { var child = IndividualFactory.CreateFromGenotype(genotypes[j]); Mutation.Mutate(child.Genotype, MutationPolicy, this); if (!IncompatibilityPolicy.IsCompatible(this, child)) { child = IncompatibilityPolicy.GetReplacement(this, child, parentalGenotypes); } nextGeneration[i * Crossover.ChildrenCount + j] = child; } } var childrenCountDifference = nextGenSize % Crossover.ChildrenCount; if (childrenCountDifference > 0) { var parentalGenotypes = SelectParentalGenotypes(); var genotypes = Crossover.Cross(parentalGenotypes); var start = nextGenSize - childrenCountDifference; for (var j = 0; j < childrenCountDifference; j++) { var child = IndividualFactory.CreateFromGenotype(genotypes[j]); Mutation.Mutate(child.Genotype, MutationPolicy, this); if (!IncompatibilityPolicy.IsCompatible(this, child)) { child = IncompatibilityPolicy.GetReplacement(this, child, parentalGenotypes); } nextGeneration[start + j] = child; } } Individuals = nextGeneration; DeprecateData(); UpdatePerGenerationData(); if (Generation % 1000 == 0) { GC.Collect(); } }
/// <summary> /// Метод добавления физ.лица в БД /// </summary> /// <param name="lastName">фамилия</param> /// <param name="firstName">имя</param> /// <param name="middleName">отчество</param> /// <param name="series">серия паспорта</param> /// <param name="number">номер паспорта</param> /// <param name="address">адрес</param> /// <param name="phoneNumber">номер телефона</param> /// <param name="email">эмейл</param> /// <param name="cardName">наименование карты</param> /// <param name="accountType">тип аккаунта</param> /// <returns>признак успешного добавления, сообщение</returns> public static (bool successfully, string message) AddIndividualToDb(string lastName, string firstName, string middleName, string series, string number, string address, string phoneNumber, string email, string cardName, AccountType accountType) { using (AppDbContext context = new AppDbContext()) { var(passport, contact, account) = CreateBaseRequisites(lastName, firstName, middleName, series, number, address, phoneNumber, email, cardName, accountType); //Создание физ.лица var individual = IndividualFactory.CreateIndividual(passport, contact, account); //Проверка на совпадения в реквизитах var(noMatchesFound, message) = SearchForMatchesForAdding.IndividualErrorProcessing(passport, contact); if (noMatchesFound) { context.Clients.Add(individual); context.SaveChanges(); message = "Произведена операция добавления:\n" + $"Клиент: {individual.Passport.FullName.Name}\n" + $"Карта: {individual.Account.Card.CardName}\n" + $"Номер: {individual.Account.Card.CardNumber}\n" + $"Статус: {(individual.Account is RegularAccount ? "Стандарт" : "VIP")}\n" + $"Дата: {DateTime.Now: dd/MM/yyyy HH:mm:ss}\n" + "Отчет: Успешно"; ClientAdded?.Invoke(null, new AddClientEventArgs { LogMessage = message }); } return(noMatchesFound, message); } }
/// <summary> /// Метод заполнения репозитория клиентами /// </summary> /// <param name="dbContext">контекст данных</param> /// <param name="quantity">кол-во клиентов</param> private static void FillRepository(AppDbContext dbContext, int quantity) { Parallel.For(1, quantity + 1, (i) => { lock (locker) { Client client = null; decimal cardBalance = random.Next(1, 10) * 10000; decimal depositBalance = random.Next(1, 10) * 10000; bool capitalization = Convert.ToBoolean(random.Next(2)); //Паспортные данные var passport = PassportFactory.CreatePassport( FullNameFactory.CreateFullName(Gender.Female), SeriesAndNumberFactory.CreateSeriesAndNumber(), $"Адрес_{i}"); //Контактные данные var contact = ContactFactory.CreateContact(PhoneNumberFactory.CreateNumber(), $"Client@Email_{i}.ru"); switch (random.Next(Enum.GetNames(typeof(ClientType)).Length)) { case (int)ClientType.Individual: //Данные аккаунта var card = IndividualsCardFactories[random.Next(IndividualsCardFactories.Length)].CreateCard(cardBalance); var deposit = random.Next(2) == 0 ? new DefaultDepositFactory().CreateDeposit(depositBalance, capitalization, ClientType.Individual) : new NullDeposit(); var individualAccount = AccountFactories[random.Next(AccountFactories.Length)].CreateAccount(card, deposit); //Создание физ. лица client = IndividualFactory.CreateIndividual(passport, contact, individualAccount); break; case (int)ClientType.Entity: //Данные аккаунта card = EntitiesCardFactories[random.Next(EntitiesCardFactories.Length)].CreateCard(cardBalance); deposit = random.Next(2) == 0 ? new DefaultDepositFactory().CreateDeposit(depositBalance, capitalization, ClientType.Entity) : new NullDeposit(); var entityAccount = AccountFactories[random.Next(AccountFactories.Length)].CreateAccount(card, deposit); //Данные компании var company = CompanyFactory.CreateCompany($"Компания_{i}", $"http:\\Company.Website_{i}.ru"); //Создание юр.лица client = EntityFactory.CreateEntity(passport, contact, entityAccount, company); break; default: throw new ArgumentOutOfRangeException(); } ProcessingCountEvent?.Invoke(Count++); dbContext.Add(client); } }); dbContext.SaveChanges(); }