Commit 7ba722aa authored by 刘乐's avatar 刘乐

1, 遗传算法计算流程

parent fea0e9bf
...@@ -109,5 +109,5 @@ double FirstOptScheduling::objectiveFunction(float cost, const map<string, doubl ...@@ -109,5 +109,5 @@ double FirstOptScheduling::objectiveFunction(float cost, const map<string, doubl
} }
} }
return 1 / (C1 + cost) * (1 + sum); return 1 / (C1 + cost) * (1 + (double)sum);
} }
\ No newline at end of file
...@@ -237,7 +237,7 @@ Genome GenAlg::bestFitness() ...@@ -237,7 +237,7 @@ Genome GenAlg::bestFitness()
int maxIndex = -1; int maxIndex = -1;
for (int i = 0; i < vecPop.size(); i++) for (int i = 0; i < vecPop.size(); i++)
{ {
if (mBestFitness == vecPop[i].fitness) if (mBestFitness == vecPop[i].fitness)
maxIndex = i; maxIndex = i;
} }
...@@ -253,20 +253,43 @@ double GenAlg::averageFitness() ...@@ -253,20 +253,43 @@ double GenAlg::averageFitness()
return mAverageFitness; return mAverageFitness;
} }
void GenAlg::fitnessfunction(map<string, double>& monitorValues) double GenAlg::fitnessfunction(float cost, map<string, double>& monitorValues)
{ {
// 计算适应 // 计算适应
double objVal = mOptScheduling->objectiveFunction(); double objVal = mOptScheduling->objectiveFunction(cost, monitorValues);
return objVal;
} }
void GenAlg::encoding(map<string, int>& phenotype, vector<char>& chromo) void GenAlg::encoding(map<string, int>& phenotype, vector<char>& chromo)
{ {
map<string, int>::iterator iter = phenotype.begin();
for (; iter != phenotype.end(); iter++)
{
}
} }
void GenAlg::decoding(vector<char>& chromo, map<string, int>& phenotype) void GenAlg::decoding(vector<map<string, int>>& phenotype)
{ {
size_t total = vecPop.size();
for (int i = 0; i < total; i++)
{
Genome genome = vecPop[i];
vector<char> genVec = genome.mBinaryGenVec;
for (int j = 0; j < genVec.size(); j++)
{
phenotype[i].insert(pair<string, char>(mPumpBits[j], genVec[j]));
}
}
}
void GenAlg::decodingSingle(vector<char>& chromo, map<string, int>& phenotype)
{
for (int j = 0; j < chromo.size(); j++)
{
phenotype.insert(pair<string, char>(mPumpBits[j], chromo[j]));
}
} }
void GenAlg::setMaxMonitorVals(const map<string, double>& maxMonitors) void GenAlg::setMaxMonitorVals(const map<string, double>& maxMonitors)
...@@ -277,4 +300,9 @@ void GenAlg::setMaxMonitorVals(const map<string, double>& maxMonitors) ...@@ -277,4 +300,9 @@ void GenAlg::setMaxMonitorVals(const map<string, double>& maxMonitors)
void GenAlg::setMinMonitorsVals(const map<string, double>& minMonitors) void GenAlg::setMinMonitorsVals(const map<string, double>& minMonitors)
{ {
mOptScheduling->setMinMonitorsVals(minMonitors); mOptScheduling->setMinMonitorsVals(minMonitors);
}
void GenAlg::setPumpBit(const vector<string>& pumpBit)
{
mPumpBits = pumpBit;
} }
\ No newline at end of file
...@@ -64,7 +64,7 @@ public: ...@@ -64,7 +64,7 @@ public:
void select(); void select();
// 根据监测点计算值,计算个体自适应度 // 根据监测点计算值,计算个体自适应度
void fitnessfunction(map<string,double>& monitorValues); double fitnessfunction(float cost,map<string,double>& monitorValues);
/** /**
* @brief 编码, 将水泵开关状态编码成二进制状态:0表示管,1表示开 * @brief 编码, 将水泵开关状态编码成二进制状态:0表示管,1表示开
...@@ -76,12 +76,16 @@ public: ...@@ -76,12 +76,16 @@ public:
* @brief 解码, 将二进制状态吗解码成水泵对应的状态 * @brief 解码, 将二进制状态吗解码成水泵对应的状态
* @param * @param
*/ */
void decoding(vector<char>& chromo,map<string,int>& phenotype); void decoding(vector<map<string, int>>& phenotype);
void decodingSingle(vector<char>& chromo, map<string, int>& phenotype);
void setMaxMonitorVals(const map<string, double>& maxMonitors); void setMaxMonitorVals(const map<string, double>& maxMonitors);
void setMinMonitorsVals(const map<string, double>& minMonitors); void setMinMonitorsVals(const map<string, double>& minMonitors);
void setPumpBit(const vector<string>& pumpBit);
private: private:
// 产生[a,b)之间的浮点数 // 产生[a,b)之间的浮点数
double random(int a=0, int b= RAND_MAX); double random(int a=0, int b= RAND_MAX);
...@@ -135,6 +139,9 @@ private: ...@@ -135,6 +139,9 @@ private:
// 右边界 // 右边界
double mRightPoint; double mRightPoint;
// 水泵状态位
vector<string> mPumpBits;
// 优化调度函数 // 优化调度函数
std::unique_ptr<OptScheduling> mOptScheduling; std::unique_ptr<OptScheduling> mOptScheduling;
}; };
#include "GenEngine.h"
GenEngine::GenEngine()
{
}
\ No newline at end of file
#pragma once
/**
¿Í»§¶Ë
*/
class GenEngine
{
public:
explicit GenEngine();
private:
};
#pragma once #pragma once
#include <vector> #include <vector>
class CivOptSchedEngine;
class GenAlg;
/** /**
染色体,实值编码 染色体,实值编码
*/ */
...@@ -8,7 +10,7 @@ class Genome ...@@ -8,7 +10,7 @@ class Genome
{ {
public: public:
friend class GenAlg; friend class GenAlg;
friend class GenEngine; friend class CivOptSchedEngine;
Genome() :fitness(0) {} Genome() :fitness(0) {}
Genome(std::vector <double> vec, double f) : vecGenome(vec), fitness(f) {} //类的带参数初始化参数。 Genome(std::vector <double> vec, double f) : vecGenome(vec), fitness(f) {} //类的带参数初始化参数。
......
...@@ -153,7 +153,6 @@ copy OptScheduling.h $(OutDir)..\include /y</Command> ...@@ -153,7 +153,6 @@ copy OptScheduling.h $(OutDir)..\include /y</Command>
<ItemGroup> <ItemGroup>
<ClInclude Include="FirstOptScheduling.h" /> <ClInclude Include="FirstOptScheduling.h" />
<ClInclude Include="GenAlg.h" /> <ClInclude Include="GenAlg.h" />
<ClInclude Include="GenEngine.h" />
<ClInclude Include="Genome.h" /> <ClInclude Include="Genome.h" />
<ClInclude Include="OptScheduling.h" /> <ClInclude Include="OptScheduling.h" />
<ClInclude Include="pandaAlgorithm.h" /> <ClInclude Include="pandaAlgorithm.h" />
...@@ -162,7 +161,6 @@ copy OptScheduling.h $(OutDir)..\include /y</Command> ...@@ -162,7 +161,6 @@ copy OptScheduling.h $(OutDir)..\include /y</Command>
<ItemGroup> <ItemGroup>
<ClCompile Include="FirstOptScheduling.cpp" /> <ClCompile Include="FirstOptScheduling.cpp" />
<ClCompile Include="GenAlg.cpp" /> <ClCompile Include="GenAlg.cpp" />
<ClCompile Include="GenEngine.cpp" />
<ClCompile Include="OptScheduling.cpp" /> <ClCompile Include="OptScheduling.cpp" />
</ItemGroup> </ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
......
...@@ -27,9 +27,6 @@ ...@@ -27,9 +27,6 @@
<ClInclude Include="GenAlg.h"> <ClInclude Include="GenAlg.h">
<Filter>头文件</Filter> <Filter>头文件</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="GenEngine.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Genome.h"> <ClInclude Include="Genome.h">
<Filter>头文件</Filter> <Filter>头文件</Filter>
</ClInclude> </ClInclude>
...@@ -47,8 +44,5 @@ ...@@ -47,8 +44,5 @@
<ClCompile Include="GenAlg.cpp"> <ClCompile Include="GenAlg.cpp">
<Filter>源文件</Filter> <Filter>源文件</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="GenEngine.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -2,12 +2,16 @@ ...@@ -2,12 +2,16 @@
#include "CivInpConvertor.h" #include "CivInpConvertor.h"
#include "GenAlg.h" #include "GenAlg.h"
#include "FirstOptScheduling.h" #include "FirstOptScheduling.h"
#include "CivPumpHelper.h"
#include "CivSchedulingCompute.h"
#include "Genome.h"
CivOptSchedEngine::CivOptSchedEngine(const string& uri):mUri(uri) CivOptSchedEngine::CivOptSchedEngine(const string& uri):mUri(uri)
{ {
mMutRate = 0.45;
mCrossRate = 0.07;
} }
bool CivOptSchedEngine::optimalScheduling() bool CivOptSchedEngine::optimalScheduling()
...@@ -16,19 +20,126 @@ bool CivOptSchedEngine::optimalScheduling() ...@@ -16,19 +20,126 @@ bool CivOptSchedEngine::optimalScheduling()
CivInpConvertor convertor(mUri); CivInpConvertor convertor(mUri);
string inpFile = convertor.convertBaseInp(); string inpFile = convertor.convertBaseInp();
// // 获取水泵个数,根据水泵个数确定基因编码长度
CivPumpHelper pumpHelper(mUri);
mGenLength = pumpHelper.getPumpNumbers();
// 获取本点号和code的映射
map<string, string> snToCodeMap;
pumpHelper.getMap("本点号", "code", snToCodeMap);
// 获取本点号集合
vector<string> snVec;
pumpHelper.getPumpSn(snVec);
// 开始遗传算法
GenAlg genAlg(GenAlg::BinaryCoding); GenAlg genAlg(GenAlg::BinaryCoding);
// 设置水泵的编码位
genAlg.setPumpBit(snVec);
// 种群初始化 // 种群初始化
popsize = 100; popsize = 100;
genAlg.init(popsize, mMutRate, mCrossRate, mGenLength, 0, 0); genAlg.init(popsize, mMutRate, mCrossRate, mGenLength, 0, 0);
// genAlg.epoch();
// 构造水力计算对象
CivSchedulingCompute schedulingCompute;
vector<string> monitorVec;
for (auto iter = mMonitoring.begin(); iter != mMonitoring.end(); iter++)
{
monitorVec.push_back(iter->first);
}
schedulingCompute.setMonitors(monitorVec);
schedulingCompute.openFile(inpFile);
// 原始管网计算一次水力,保留调度前的水力计算结果
if (!schedulingCompute.calculate())
return false;
// 保存原始管网监测点的模拟值
schedulingCompute.getMonitorsValue(mBforeSchedulingResults);
// 开始迭代计算
int index = 0;
while (index++ < popsize)
{
// 管网平差计算
vector<map<string, int>>monitorsMap;
genAlg.decoding(monitorsMap);
// 计算个体自适度
// 根据个体自适应度进行选择
// 自适应交叉变异
// 产生下一代种群
}
// 获取最好的
Genome genome = genAlg.bestFitness();
vector<char> genVec = genome.mBinaryGenVec;
// 最优水泵组合
genAlg.decodingSingle(genVec, mPumpBestStatus);
// 再做一次水力计算,计算调度后的值
schedulingCompute.updatePumpStatus(mPumpBestStatus);
schedulingCompute.calculate();
// 最有调度值
schedulingCompute.getMonitorsValue(mBforeSchedulingResults);
// 结束计算
schedulingCompute.close();
return true;
} }
void CivOptSchedEngine::schedulingResultToJson(string& json) void CivOptSchedEngine::schedulingResultToJson(string& json)
{ {
// 水泵:组合
json.append("{\"水泵状态\":{");
map<string, int>::iterator iter = mPumpBestStatus.begin();
for (;iter!=mPumpBestStatus.end();iter++)
{
json.append(iter->first + ":" + to_string(iter->second));
json.append(",");
}
json = json.substr(0, json.length() - 1);
json.append("},");
// 调度组合
json.append("\"监测点:[\"");
int total = mBforeSchedulingResults.size();
for (int i = 0; i < total; i++)
{
map<string, double> beforeResult = mBforeSchedulingResults[i];
map<string, double> afterResult = mAfterSchedulingResults[i];
json.append("{");
for (auto iter = beforeResult.begin(); iter != beforeResult.end(); iter++)
{
string monitorName = iter->first;
double beforeMonitorVal = iter->second;
auto afteriter = afterResult.find(monitorName);
if (afteriter == afterResult.end())
continue;
double afterMonitorvVal = afteriter->second;
json.append("\""+monitorName+"\":[");
json.append(to_string(beforeMonitorVal));
json.append(",");
json.append(to_string(afterMonitorvVal));
json.append("],");
}
json = json.substr(0, json.length() - 1);
json.append("},");
}
json.substr(0, json.length() - 1);
json.append("]}");
} }
void CivOptSchedEngine::setMonitor(const map<string, vector<double>>& monitorMap) void CivOptSchedEngine::setMonitor(const map<string, vector<double>>& monitorMap)
......
...@@ -38,11 +38,13 @@ private: ...@@ -38,11 +38,13 @@ private:
// 编码与状态的映射 // 编码与状态的映射
map<int, string> mStatusBit; map<int, string> mStatusBit;
// 调度结果 // 选出的最优组合
vector<map<string, int>> mSchedulingResults; map<string, int> mPumpBestStatus;
// 监测点 // 监测点
map<string, vector<double>> mMonitoring; map<string, vector<double>> mMonitoring;
vector<map<string, double>> mBforeSchedulingResults;
vector<map<string, double>> mAfterSchedulingResults;
// 数据连接地址 // 数据连接地址
string mUri; string mUri;
......
...@@ -14,14 +14,14 @@ void CivReportReader::readEnergy(const string& pumpSn, string& enery) ...@@ -14,14 +14,14 @@ void CivReportReader::readEnergy(const string& pumpSn, string& enery)
bool CivReportReader::open(const string& reportFile) bool CivReportReader::open(const string& reportFile)
{ {
ifstream stream(reportFile.c_str()); ifstream reader(reportFile.c_str());
// жȡ // жȡ
string sLine; string sLine;
while (getline(stream, sLine)) while (getline(reader, sLine))
{ {
} }
stream.close(); reader.close();
} }
...@@ -103,7 +103,7 @@ void CivSchedulingCompute::close() ...@@ -103,7 +103,7 @@ void CivSchedulingCompute::close()
ENclose(); ENclose();
} }
void CivSchedulingCompute::updatePumpStatus(const map<string, char>& pumpStatus) void CivSchedulingCompute::updatePumpStatus(const map<string, int>& pumpStatus)
{ {
mPumpStatus.clear(); mPumpStatus.clear();
mPumpStatus = pumpStatus; mPumpStatus = pumpStatus;
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
#include <string> #include <string>
using namespace std; using namespace std;
/** /**
优化调度计算类 优化调度计算类
*/ */
...@@ -25,7 +24,7 @@ public: ...@@ -25,7 +24,7 @@ public:
void close(); void close();
// 更新水泵开关状态 // 更新水泵开关状态
void updatePumpStatus(const map<string, char>& pumpStatus); void updatePumpStatus(const map<string, int>& pumpStatus);
// 获取监测点计算出的值 // 获取监测点计算出的值
void getMonitorsValue(vector<map<string, double>>& monitorMap); void getMonitorsValue(vector<map<string, double>>& monitorMap);
...@@ -45,7 +44,7 @@ private: ...@@ -45,7 +44,7 @@ private:
int mErrcode = 0; int mErrcode = 0;
// 更新水泵的状态 // 更新水泵的状态
map<string, char> mPumpStatus; map<string, int> mPumpStatus;
// 存储测点的计算值 // 存储测点的计算值
vector<map<string, double>> mMonitorsValue; vector<map<string, double>> mMonitorsValue;
......
...@@ -32,4 +32,46 @@ void CivPumpHelper::getMap(const string& key, const string& val, map<string, str ...@@ -32,4 +32,46 @@ void CivPumpHelper::getMap(const string& key, const string& val, map<string, str
res.insert(pair<string, string>(keyVal, valVal)); res.insert(pair<string, string>(keyVal, valVal));
} }
} }
\ No newline at end of file
int CivPumpHelper::getPumpNumbers()
{
string sql = "select count(id) as cunt from " + mTable;
if (!mConn->execSql(sql))
return 0;
vector<map<string,string>> pumpRes;
if (!mConn->queryResult(pumpRes))
return 0;
if (pumpRes.size() <= 0)
return 0;
map<string, string> pumpMap = pumpRes[0];
map<string, string>::iterator iter = pumpMap.find("cunt");
if (iter == pumpMap.end())
return 0;
string pumpSize = iter->second;
int pumps = atoi(pumpSize.c_str());
return pumps;
}
void CivPumpHelper::getPumpSn(vector<string>& pumpNames)
{
const string sz = "";
vector<map<string, string>> vecMap;
if (!mConn->query(mTable, { sz }, vecMap))
return;
if (vecMap.size() <= 0)
return;
size_t total = vecMap.size();
for (int i = 0; i < total; i++)
{
map<string, string> tempMap = vecMap[i];
string val = tempMap.find(sz)->second;
pumpNames.push_back(val);
}
}
#pragma once #pragma once
#include<string> #include<string>
#include<map> #include<map>
#include<vector>
#include "pandaDbManager.h" #include "pandaDbManager.h"
...@@ -9,7 +10,7 @@ using namespace std; ...@@ -9,7 +10,7 @@ using namespace std;
class CivConnection; class CivConnection;
/** /**
水泵查询接口 水泵查询接口
*/ */
class PANDADBMANAGER_API CivPumpHelper class PANDADBMANAGER_API CivPumpHelper
{ {
...@@ -20,6 +21,11 @@ public: ...@@ -20,6 +21,11 @@ public:
// 获取指定属性字段键值对映射 // 获取指定属性字段键值对映射
void getMap(const string& key, const string& val, map<string, string>& res); void getMap(const string& key, const string& val, map<string, string>& res);
// 获取水泵的个数
int getPumpNumbers();
// 获取水泵的编号
void getPumpSn(vector<string>& pumpNames);
private: private:
CivConnection* mConn = nullptr; CivConnection* mConn = nullptr;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment