diff --git a/Deaf2.0/Deaf2.0/Agent.cpp b/Deaf2.0/Deaf2.0/Agent.cpp index 4a09ba2..ba66bdf 100644 --- a/Deaf2.0/Deaf2.0/Agent.cpp +++ b/Deaf2.0/Deaf2.0/Agent.cpp @@ -21,16 +21,16 @@ Agent::Agent(Agent* father, int fID, Agent* mother, int mID){ this->motherID = mID; std::default_random_engine& generator = Settings::RANDOM_GENERATOR; - std::uniform_int_distribution distribution(0,1); // ERROR - + std::uniform_int_distribution distribution(0,1); // ERROR - генерирует только нули int mAllele = distribution(generator); int fAllele = distribution(generator); - // + // Тут пока без рекомбинации this->mGenome = (mAllele == 0 ? mother->mGenome : mother->fGenome); this->fGenome = (fAllele == 0 ? father->mGenome : father->fGenome); - // : + // Определяем глухоту: только если в обоих аллелях единицы this->isDeaf = (this->mGenome.at(0) + this->fGenome.at(0)) > 1 ? true : false; @@ -42,21 +42,21 @@ Agent::Agent(Agent* father, int fID, Agent* mother, int mID){ this->isDeaf = true; } - // . - // , , - // ( ) - // 2018.11.20 + // Трансмиссия жестового языка. + // Пока решили, что если в семье хоть один глухой, то все его члены автоматически должны владеть им + // (Егор с ОЛ должны решить этот момент) + // 2018.11.20 Заменили на другой алгоритм в процессоре //this->knowsSignLanguage = (father->knowsSignLanguage && father->isDeaf // || mother->knowsSignLanguage && mother->isDeaf); - // ( ) - // : + // Социальная позиция (ДИСКУССИЯ НУЖНА) + // Пока: берём среднее от родителей и на некоторую нормально распределённую величину сдвигаем std::normal_distribution distrN(0,0.1f); float delta = distrN(generator); this->socialPosition = 0.5f*(mother->socialPosition + father->socialPosition) + delta; this->alreadyMarried = false; - // + // Берём из популяции // delta = distribution(generator); // this->bachelority = 0.5f*(mother->bachelority + father->bachelority) + delta; // this->age = 0; diff --git a/Deaf2.0/Deaf2.0/Agent.h b/Deaf2.0/Deaf2.0/Agent.h index 9860ef3..140dd66 100644 --- a/Deaf2.0/Deaf2.0/Agent.h +++ b/Deaf2.0/Deaf2.0/Agent.h @@ -22,7 +22,7 @@ protected: public: Agent(int fGene, int mGene, bool deaf, bool signL, - float socialP); // + float socialP); // Только для инициализации Agent(Agent*,int, Agent*, int); bool deaf() const { return isDeaf;} int getDeafAllelesCount() const { return mGenome.at(0)+fGenome.at(0);} diff --git a/Deaf2.0/Deaf2.0/Processor.cpp b/Deaf2.0/Deaf2.0/Processor.cpp index b7ecafd..09db80a 100644 --- a/Deaf2.0/Deaf2.0/Processor.cpp +++ b/Deaf2.0/Deaf2.0/Processor.cpp @@ -28,12 +28,12 @@ void Processor::run(std::string fileName){ int initPopSizeW = Settings::INIT_POP_SIZE_W; ///float deafAlleleRatio = Settings::DEAF_ALLELE_RATIO; - float birthRateH = Settings::BIRTH_RATE_H; // - float birthRateD = Settings::BIRTH_RATE_D; // + float birthRateH = Settings::BIRTH_RATE_H; // среднее число потомков + float birthRateD = Settings::BIRTH_RATE_D; // среднее число потомков int maxGenerations = Settings::MAX_GENERATIONS; - // + // Подготовка файла выдачи std::cout<<"Initializing output file..\t"; std::ofstream outputFile(Settings::OUTPUT_FILE); outputFile<<"Generation\tTotalPopulation\tMen\tWomen\tDeaf"; @@ -41,10 +41,10 @@ void Processor::run(std::string fileName){ outputFile<<"\tDH marriages\tDH children"; outputFile<<"\tHH marriages\tHH children"; outputFile<<"\tDA frequency\tDA homozygotes frequency"; - // TODO , + // TODO Допишите ещё данные, которые вы хотите чтобы были outputFile< > matrixCurrent; //std::vector > matrixFuture; @@ -54,7 +54,7 @@ void Processor::run(std::string fileName){ std::vector newMen; std::vector newWomen; - // - + // Эмуляция сообщества глухих - образуют замкнутый круг знающих все и вся std::vector deafMen; std::vector deafWomen; std::vector deafNewMen; @@ -65,18 +65,18 @@ void Processor::run(std::string fileName){ //generator.seed(std::time(0)); //RandomDevice::RandomDevice(unsigned long n) : rand_seed(n), engine(n){ } - // + // Создаём мужчин std::cout<<"Creating men..("< distrUI(0.f,1.f); if(distrUI(generator) < Settings::SPONTANEOUS_DEAF) isDeaf = true; @@ -94,14 +94,14 @@ void Processor::run(std::string fileName){ if(isDeaf) deafMen.push_back(a); - } // - + } // Создали мужчин - слышащих гомозигот - // ( ) + // Слышащие гетерозиготы (в них могут быть спонтанные) for(int i = 0; i < heterozygores; i++){ bool isDeaf = false; - int alleleFather = 1; // TODO: + int alleleFather = 1; // TODO: Чуть аккуратнее int alleleMother = 0; - // - + // Спонтанная глухота - только для негенетических std::uniform_real_distribution distrUI(0.f,1.f); if(distrUI(generator) < Settings::SPONTANEOUS_DEAF) isDeaf = true; @@ -119,9 +119,9 @@ void Processor::run(std::string fileName){ if(isDeaf) deafMen.push_back(a); - } // - + } // Создали мужчин - слышащих гетерозигот - // + // Глухие гомозиготы for(int i = 0; i < deafHomozygotes; i++){ bool isDeaf = true; int alleleFather = 1; @@ -141,23 +141,23 @@ void Processor::run(std::string fileName){ if(isDeaf) deafMen.push_back(a); - }// - + }// Создали мужчин - неслышащих гомозигот std::random_shuffle(men.begin(), men.end()); std::random_shuffle(deafMen.begin(), deafMen.end()); - // + // Создали всех мужчин std::cout<<"Done\n"; std::cout<<"Creating women..\t"; - // + // Создаём женщин deafHomozygotes = (int) (initPopSizeW*Settings::DEAF_HOMOZYGOTES); hearHomozygotes = (int) (initPopSizeW*Settings::HEAR_HOMOZYGOTES); heterozygores = initPopSizeW - deafHomozygotes - hearHomozygotes; - // ( ) + // Слышащие гомозиготы (в них могут быть спонтанные) for(int i = 0; i < hearHomozygotes; i++){ bool isDeaf = false; int alleleFather = 0; int alleleMother = 0; - // - + // Спонтанная глухота - только для негенетических std::uniform_real_distribution distrUI(0.f,1.f); if(distrUI(generator) < Settings::SPONTANEOUS_DEAF) isDeaf = true; @@ -175,14 +175,14 @@ void Processor::run(std::string fileName){ if(isDeaf) deafWomen.push_back(a); - } // - + } // Создали женщин - слышащих гомозигот - // ( ) + // Слышащие гетерозиготы (в них могут быть спонтанные) for(int i = 0; i < heterozygores; i++){ bool isDeaf = false; - int alleleFather = 1; // TODO: + int alleleFather = 1; // TODO: Чуть аккуратнее int alleleMother = 0; - // - + // Спонтанная глухота - только для негенетических std::uniform_real_distribution distrUI(0.f,1.f); if(distrUI(generator) < Settings::SPONTANEOUS_DEAF) isDeaf = true; @@ -200,9 +200,9 @@ void Processor::run(std::string fileName){ if(isDeaf) deafWomen.push_back(a); - } // - + } // Создали женщин - слышащих гетерозигот - // + // Глухие гомозиготы for(int i = 0; i < deafHomozygotes; i++){ bool isDeaf = true; int alleleFather = 1; @@ -222,14 +222,14 @@ void Processor::run(std::string fileName){ if(isDeaf) deafWomen.push_back(a); - }// - + }// Создали женщин - неслышащих гомозигот std::random_shuffle(women.begin(), women.end()); std::random_shuffle(deafWomen.begin(), deafWomen.end()); - // + // Создали женщин std::cout<<"Done\n"; std::cout<<"\nMain cycle\n"; - // + // Основной цикл for(int gen = 0; gen < maxGenerations; gen++){ std::cout<<"Generation\t"< + // Эмулятор разреженной матрицы - пара <индекс, оценка> std::cout<<"\tInitializing settledPairs\t"; std::uniform_real_distribution distrUI(0.f,1.f); std::cout<<"."; @@ -258,11 +258,11 @@ void Processor::run(std::string fileName){ int candidatePairs = Settings::CANDIDATE_PAIRS_MEAN + (int)(sign*f*Settings::CANDIDATE_PAIRS_VAR); - // TODO: + // TODO: Несколько топологий краёв int left = i - candidatePairs/2; int right = i + candidatePairs/2; - // HACK: 2018/11/23 + // HACK: 2018/11/23 Для глухих модель Егора if(men.at(i)->deaf() && Settings::DEAF_COMMUNITY_MODEL == 1){ left = 0; right = women.size() - 1; @@ -281,29 +281,29 @@ void Processor::run(std::string fileName){ std::vector > pairs(candidatePairs); for(unsigned int p = 0; p < pairs.size(); p++){ pairs.at(p).first = left; - // - + // Зараз и оценили друг-друга //matrixCurrent.at(i).at(left) pairs.at(p).second = esteem(men.at(i),women.at(left)); left++; } settledPairs.at(i) = pairs; } - // (END) + // (END) Эмулятор разреженной матрицы std::cout<<"Done\n"; - // - // + // Заполняем матрицу взаимных оцениваний + // По всем мужчинам /*for(unsigned int m = 0; m < men.size(); m++){ - // + // По всем женщинам for(unsigned int w = 0; w < women.size(); w++){ if(matrixCurrent.at(m).at(w) >= 0.0f) matrixCurrent.at(m).at(w) = esteem(men.at(m),women.at(w)); } } */ - // + // Заполнили матрицу взаимных оцениваний /* std::cout<<"\tGenerating offsprings\t"; - // , - // + // Формируем окончательные пары, генерируем потомков + // По всем мужчинам std::cout << "MENS" << std::endl; for (auto m = 0; m < settledPairs.size(); ++m) { @@ -319,19 +319,19 @@ void Processor::run(std::string fileName){ for(int m = 0; m < men.size(); m++){ - // + // Ищем наиболее подходящую женщину int bestW = 0; float bestScore = 0.0f; - /* + /* БЫЛО ДО РАЗРЕЖЕННЫХ МАТРИЦ for(int w = 0; w < women.size(); w++){ if(matrixCurrent.at(m).at(w) > bestScore){ bestScore = matrixCurrent.at(m).at(w); bestW = w; } - } // + } // Нашли **/ - // + // С РАЗРЕЖЕННЫМИ for(unsigned int p = 0; p < settledPairs.at(m).size(); p++){ unsigned int w = settledPairs.at(m).at(p).first; @@ -344,12 +344,12 @@ void Processor::run(std::string fileName){ } } - // (END) + // (END) С РАЗРЕЖЕННЫМ if(bestScore <= 0.0f) - continue; // + continue; // Этому мужчине никто не подошёл - // , + // Формируем пару, рожаем детей int* mariage = &marriageHH; int* childrenType = &childrenHH; @@ -387,9 +387,9 @@ void Processor::run(std::string fileName){ (*mariage)++; (*childrenType) += children; - // TODO: - + - std::vector newSibs; // - std::vector deafSibs;// + // TODO: Добавить знание жестового языка если хотя бы один сибс - глухой + знает жестовый язык + std::vector newSibs; // Для учёта распространения жестового языка в одной семье + std::vector deafSibs;// Для подсчёта вновь рождённых глухих for(int i = 0; i < children; i++){ Agent* newAgent = new Agent(men.at(m), m, women.at(bestW), bestW); @@ -397,7 +397,7 @@ void Processor::run(std::string fileName){ if(newAgent->deaf()){ deafSibs.push_back(newAgent); } - // + // Добавляем в общую популяцию std::uniform_int_distribution distrUI(0,1); if(distrUI(generator) == 0){ newMen.push_back(newAgent); @@ -406,8 +406,8 @@ void Processor::run(std::string fileName){ newWomen.push_back(newAgent); } } - // - // 1 - - + // Трансмиссия жестового языка + // Случай 1 - Хотя бы один родитель глухой и кто-то знает жестовый if(men.at(m)->deaf() || women.at(bestW)->deaf()){ if(men.at(m)->knowsSign() || women.at(bestW)->knowsSign()){ for(auto i = 0; i < newSibs.size(); i++){ @@ -416,26 +416,26 @@ void Processor::run(std::string fileName){ } } - // 2 - + // Случай 2 - Хотя бы один сибс глухой else if(deafSibs.size() > 0){ std::uniform_real_distribution distrUF(0.f,1.f); - // ) + // а) Он получает случайный шанс bool sibsKnowSL = false; - // + // Глухие случайно узнают жестовый for(auto i = 0; i < deafSibs.size(); i++){ if(distrUF(generator) <= Settings::SIGN_LANG_DEAF){ deafSibs.at(i)->teachSignLanguage(); sibsKnowSL = true; } } - // + // Слышащие случайно узнают жестовый for(auto i = 0; i < newSibs.size(); i++){ if(!newSibs.at(i)->deaf() && distrUF(generator) <= Settings::SIGN_LANG_HEAR){ newSibs.at(i)->teachSignLanguage(); sibsKnowSL = true; } } - // ) + // б) Если родители или сибсы знают жестовый if(men.at(m)->knowsSign() || women.at(bestW)->knowsSign() || sibsKnowSL){ for(auto i = 0; i < newSibs.size(); i++){ newSibs.at(i)->teachSignLanguage(); @@ -443,7 +443,7 @@ void Processor::run(std::string fileName){ } } - // 3 - + // Случай 3 - Слышащий просто случайно узнаёт жестовый else { std::uniform_real_distribution distrUF(0.f,1.f); for(auto i = 0; i < newSibs.size(); i++){ @@ -452,18 +452,18 @@ void Processor::run(std::string fileName){ } } } - // (END) + // (END) Трансмиссия жестового языка - // + // Делаем эту женщину недоступной для всех остальных women.at(bestW)->alreadyMarried = true; //for(int i = m; i < men.size(); i++){ // matrixCurrent.at(i).at(bestW) = -100.0f; //} - } // + } // Конец генерации потомков std::cout<<"Done\n"; std::cout<<"\tSaving model state\t"; - // + // Сохранить текущее состояние модели int totalP = men.size()+women.size(); outputFile<getFatherID() == woman->getFatherID() || man->getMotherID() == woman->getMotherID()) && woman->getMotherID() != -1){ return -50.f; @@ -597,7 +597,7 @@ void Processor::initSettings(std::string fileName){ boost::to_lower(instr); boost::trim(instr); - // + // Инструкции if(instr == "generations" || instr == "iterations" ){ int iter = Settings::MAX_GENERATIONS; sscanf_s(tokensVector.at(1).c_str(),"%d", &iter); @@ -736,4 +736,4 @@ void Processor::initSettings(std::string fileName){ }*/ } // (END) for(curLine = 0; curLine < script.size(); curLine++) -} \ No newline at end of file +} diff --git a/Deaf2.0/Deaf2.0/Settings.cpp b/Deaf2.0/Deaf2.0/Settings.cpp index ca1bafe..d6c86a0 100644 --- a/Deaf2.0/Deaf2.0/Settings.cpp +++ b/Deaf2.0/Deaf2.0/Settings.cpp @@ -13,8 +13,8 @@ float Settings::DEAF_ALLELE_RATIO = 0.1f; float Settings::DEAF_HOMOZYGOTES = 0.05f; float Settings::HEAR_HOMOZYGOTES = 0.65f; -float Settings::BIRTH_RATE_H = 2.3f; // -float Settings::BIRTH_RATE_D = 2.1f; // +float Settings::BIRTH_RATE_H = 2.3f; // среднее число потомков +float Settings::BIRTH_RATE_D = 2.1f; // среднее число потомков float Settings::BETA_A = 2.0f; float Settings::BETA_B = 5.0f; diff --git a/Deaf2.0/Deaf2.0/Settings.h b/Deaf2.0/Deaf2.0/Settings.h index 489d2db..56e9740 100644 --- a/Deaf2.0/Deaf2.0/Settings.h +++ b/Deaf2.0/Deaf2.0/Settings.h @@ -16,8 +16,8 @@ public: static float DEAF_HOMOZYGOTES; static float HEAR_HOMOZYGOTES; - static float BIRTH_RATE_H; // - static float BIRTH_RATE_D; // + static float BIRTH_RATE_H; // среднее число потомков + static float BIRTH_RATE_D; // среднее число потомков static float BETA_A; static float BETA_B; @@ -37,7 +37,7 @@ public: static std::default_random_engine RANDOM_GENERATOR; - static int DEAF_COMMUNITY_MODEL; // 0 - , 1 - , 2 - + static int DEAF_COMMUNITY_MODEL; // 0 - сообщества глухих нет, 1 - глухие видят всю матрицу, 2 - малая матрица для глухих static std::string OUTPUT_FILE; }; \ No newline at end of file