?? genetestview.cpp
字號:
// genetestView.cpp : implementation of the CGenetestView class
//
#include "stdafx.h"
#include "genetest.h"
//#include "Winbase.h"
#include "genetestDoc.h"
#include "genetestView.h"
#include "DlgInputPara.h"
#include <math.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CGenetestView
IMPLEMENT_DYNCREATE(CGenetestView, CScrollView)
BEGIN_MESSAGE_MAP(CGenetestView, CScrollView)
//{{AFX_MSG_MAP(CGenetestView)
ON_COMMAND(ID_GENEParaSet, OnGENEParaSet)
ON_COMMAND(ID_GENE_Begin, OnGENEBegin)
ON_COMMAND(ID_GENE_End, OnGENEEnd)
ON_COMMAND(ID_ShowResult, OnShowResult)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CScrollView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CScrollView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CScrollView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CGenetestView construction/destruction
CGenetestView::CGenetestView()
{
// TODO: add construction code here
m_oldpop = NULL;
m_newpop = NULL;
m_maxfitChrom = NULL;
m_fcrossover = 0.0f;
m_ngenerations = 0;
m_fmutation = 0.0f;
m_npopulationsize = 0;
m_ntarget = 0;
m_nweapon = 0;
m_bInputFlag = FALSE;
m_nOutputY = 0;
m_nmaxpp = -1;
m_nminpp = -1;
m_fWholeMaxFit = 0.0;
m_nTestFlag = 0;
//m_nIndex = -1;
//m_bDrawFlag = FALSE;
//初始化數組
for(int i=0;i<maxTarget;i++)
{
m_Worthiness[i]=0.0;
for(int j=0;j<maxWeapon;j++)
{
m_SuccessArray[i][j]=0.0;
}
}
}
CGenetestView::~CGenetestView()
{
//釋放內存,避免內存泄漏
int nCount = m_WeaponList.GetCount();
int i;
if(nCount != 0)
{
POSITION pos = m_WeaponList.GetHeadPosition();
for(i=0;i<nCount;i++)
{
CWeapon *Oldnode = m_WeaponList.GetAt(pos);
delete Oldnode;
m_WeaponList.GetNext(pos);
}
}
if(m_oldpop!=NULL||m_newpop!=NULL)
{
for(i = 0; i < m_npopulationsize; i++)
{
free(m_oldpop[i].chrom);
free(m_newpop[i].chrom);
}
free(m_oldpop);
free(m_newpop);
}
if(m_maxfitChrom!=NULL)
{
free(m_maxfitChrom);
}
}
BOOL CGenetestView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CScrollView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CGenetestView drawing
void CGenetestView::OnDraw(CDC* pDC)
{
CGenetestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
/*if(m_bDrawFlag==TRUE)
{
//循環輸出遺傳算法各代的染色體的值
int j = 0;
for(int i=0;i<m_OutstrArray.GetSize();i++)
{
pDC->TextOut(0,j,m_OutstrArray.GetAt(m_nIndex));
j += 30;
}
m_bDrawFlag = FALSE;
}*/
}
/////////////////////////////////////////////////////////////////////////////
// CGenetestView printing
BOOL CGenetestView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CGenetestView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CGenetestView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CGenetestView diagnostics
#ifdef _DEBUG
void CGenetestView::AssertValid() const
{
CScrollView::AssertValid();
}
void CGenetestView::Dump(CDumpContext& dc) const
{
CScrollView::Dump(dc);
}
CGenetestDoc* CGenetestView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CGenetestDoc)));
return (CGenetestDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CGenetestView message handlers
/*參數設置菜單響應函數*/
void CGenetestView::OnGENEParaSet()
{
// TODO: Add your command handler code here
CDlgInputPara dlg;
if(dlg.DoModal()==IDOK)
{
m_fcrossover = dlg.m_fcrossover;
m_ngenerations = dlg.m_ngenerations;
m_fmutation = dlg.m_fmutation;
m_npopulationsize = dlg.m_npopulationsize;
m_ntarget = dlg.m_ntarget;
m_nweapon = dlg.m_nweapon;
m_bInputFlag = TRUE;
}
//m_OutstrArray.SetSize((m_npopulationsize+1)*(m_ngenerations+1));
}
void CGenetestView::OnGENEBegin()
{
// TODO: Add your command handler code here
int gen = 0;
CIndividual *temp;
if(m_bInputFlag==FALSE)
{
MessageBox("請先輸入遺傳算法的控制參數!");
return;
}
Initialize();
while(gen < m_ngenerations)
{
gen += 1;
Generation(gen);
Statistics(m_newpop);
temp = m_oldpop;
m_oldpop = m_newpop;
m_newpop = temp;
}
}
void CGenetestView::OnGENEEnd()
{
// TODO: Add your command handler code here
/*InitPheromone();
WritePheromone();
CWinThread *antThread[2];
g_nIndex = 0;
antThread[1] = AfxBeginThread(AntThreadProcTest, this,THREAD_PRIORITY_HIGHEST);
Sleep(1000);//必須進行延時且大于600ms,否則兩個線程的效果相同,因為隨機數是根據時間產生的
antThread[2] = AfxBeginThread(AntThreadProcTest, this,THREAD_PRIORITY_HIGHEST);*/
//設定測試標志
//m_nTestFlag = 1;
//初始化跡,讓跡等于打擊概率
/*int i,j;
for(i=0;i<m_ntarget;i++)
{
for(j=0;j<m_nweapon;j++)
{
m_PheromoneArray[i][j] = m_SuccessArray[i][j];
}
}
WriteLog("螞蟻算法測試,將打擊成功概率賦值給跡:");
//InitAntList();
CString str;
float maxFitness = (float)0.0;
float OldmaxFitness = maxFitness;
float Sub;
for(i = 0; i<m_nRepeat;i++)
{
Sub = maxFitness - OldmaxFitness;
if(i>0&&Sub<0.001)
{
break;
}
else OldmaxFitness = maxFitness;
POSITION pos = g_antList.GetHeadPosition();
str.Format("螞蟻第%d次迭代:",i+1);
WriteLog(str);
WritePheromone();
int nIndex = 1;
while(pos!=NULL)
{
CAllocationAnt *ant = g_antList.GetAt(pos);
ant->SetAllocArray();
ant->ReadTargetLimit();
ant->SearchPath();
ant->m_fFitness = ant->ComputePathLength();
if(ant->m_fFitness > maxFitness)
maxFitness = ant->m_fFitness;
ant->WriteResult();
str.Format("第%d只螞蟻的適應度為:%f",nIndex,ant->m_fFitness);
WriteLog(str);
g_antList.GetNext(pos);
nIndex++;
}
UpdatePheromoneTestUsed();
}
str.Format("最大適應度為:%f",maxFitness);
WriteLog(str);
str += "m_nTestFlag=1 以成功概率為跡無遺傳算法結果的螞蟻算法運行結束!";
MessageBox(str);*/
}
void CGenetestView::Initpop()
{
int i,j,k,lchrom;
lchrom = m_nweapon*m_ntarget;
int n/*c,*/;
char c;
CString str = "初始群體:目標數:";
CString str1;
str1.Format("%d",m_ntarget);
str += str1;
str += "武器數:";
str1.Format("%d",m_nweapon);
str += str1;
CClientDC dc(this);
dc.TextOut(0,m_nOutputY,str);
ReleaseDC(&dc);
WriteLog(str);
m_nOutputY += 30;
//m_nIndex++;
//m_OutstrArray.SetAt(m_nIndex,str);
for(i=0;i<m_npopulationsize;i++)//群體規模
{
for(j=0;j<m_ntarget;j++)//目標數,代表子串的樹木
{
POSITION pos;
pos = m_WeaponList.GetHeadPosition();
for(k=0;k<m_nweapon;k++)//武器數,代表子串的長度
{
int temp = rand();
c = temp%2;
//給武器增加分配標志
if(j==0)//第一個子串,代表對第一個目標的分配情況
{
m_WeaponList.GetAt(pos)->m_bFBBZ = c;
if(c==1)
{
//分配目標號
m_WeaponList.GetAt(pos)->m_nFBMBH = j;
}
// ResetWeaponState(pos,c);
}
else//其他目標的分配情況
{
if(m_WeaponList.GetAt(pos)->m_bFBBZ==1)
{
c = 0;
}
else if(c==1)
{
m_WeaponList.GetAt(pos)->m_bFBBZ = c;
m_WeaponList.GetAt(pos)->m_nFBMBH = j;//分配目標號
}
}
n = j*m_nweapon+k;
m_oldpop[i].chrom[n] = c;//出錯處,原因是未曾分配內存
m_WeaponList.GetNext(pos);
}
}
/*//Objfunc(&(m_oldpop[i]));//計算個體適應度,若用此函數,必須放在ResetWeaponList()之前
//重新初始化武器的狀態,為下一個的個體做準備
if(i!=m_npopulationsize-1)
{
ResetWeaponList();
}*/
OutputResult(m_oldpop[i]);
ObjFunction(&(m_oldpop[i]));
}
}
//系統初始化
void CGenetestView::Initialize()
{
time_t t;
srand((unsigned) time(&t));//設置rand函數所用的啟始種子值,以期每次產生的隨機數序列均不相同。
InitWeaponList();
SetWTAArray();
InitMalloc();
Initpop();
Statistics(m_oldpop);//統計數據
}
//統計函數,計算種群統計數據,這樣統計出來的是當前代(也就是最終是最后一代的染色體代表的數據)
//應改進,是否應該可以統計出所有迭代過程中的最優個體的適應度??
void CGenetestView::Statistics(CIndividual *pop)
{
//CString str;
float max = pop[0].fitness;
m_nmaxpp = 0;
m_nminpp = 0;
float min = pop[0].fitness;
float Sum = 0.0;
for(int i=0;i<m_npopulationsize;i++)
{
Sum += pop[i].fitness;
if(pop[i].fitness > max)
{
max = pop[i].fitness;
m_nmaxpp = i;
}
if(pop[i].fitness < min)
{
min = pop[i].fitness;
m_nminpp = i;
}
//str.Format("%f",pop[i].fitness);
//MessageBox(str);
}
m_fsumfitness = Sum;
m_fmax = max;
m_fmin = min;
m_favg = Sum/m_npopulationsize;
//統計全局(也就是所有代中)最優染色體
if(m_fmax > m_fWholeMaxFit)
{
m_fWholeMaxFit = m_fmax;
for(int l = 0;l<m_ntarget*m_nweapon;l++)
{
m_maxfitChrom[l] = pop[m_nmaxpp].chrom[l];
}
}
}
void CGenetestView::InitWeaponList()
{
int i;
POSITION pos;
pos = m_WeaponList.GetHeadPosition();
for(i=0;i<m_nweapon;i++)
{
CWeapon *node = new CWeapon;
node->m_bFBBZ = FALSE;
node->m_nDYXHL = 0;
node->m_nFBMBH = -1;
node->m_nSJJL = 0;
node->m_strLSDW = "";
node->m_nMaxWeapon = 1; //暫時設為每個目標最多允許分配一個武器
pos = m_WeaponList.InsertAfter(pos,node);
}
}
void CGenetestView::ResetWeaponList()
{
int nCount = m_WeaponList.GetCount();
int i;
POSITION pos;
pos = m_WeaponList.GetHeadPosition();
for(i=0;i<nCount;i++)
{
CWeapon *Oldnode = m_WeaponList.GetAt(pos);
Oldnode->m_bFBBZ = 0;
Oldnode->m_nDYXHL = 0;
Oldnode->m_nFBMBH = -1;
Oldnode->m_nSJJL = 0;
Oldnode->m_strLSDW = "";
m_WeaponList.GetNext(pos);
}
}
//此函數用于更改一個武器的狀體,暫時沒用到
void CGenetestView::ResetWeaponState(POSITION &pos, int c)
{
CWeapon *Oldnode = m_WeaponList.GetAt(pos);
CWeapon *Newnode = new CWeapon;
Newnode->m_bFBBZ = c;
Newnode->m_nDYXHL = 0;
Newnode->m_nFBMBH = 0;
Newnode->m_nSJJL = 0;
Newnode->m_strLSDW = "";
m_WeaponList.SetAt(pos,Newnode);
delete Oldnode;
}
//分配內存
void CGenetestView::InitMalloc()
{
int nbytes;
int j;
/* 分配給當前代和新一代種群內存空間 */
nbytes = m_npopulationsize*sizeof(struct CIndividual);
if((m_oldpop = (struct CIndividual *) malloc(nbytes)) == NULL)
{
MessageBox("內存分配失敗!");
return;
}
if((m_newpop = (struct CIndividual *) malloc(nbytes)) == NULL)
{
MessageBox("內存分配失敗!");
return;
}
/*if((m_p1 = (struct CIndividual *) malloc(sizeof(struct CIndividual))) == NULL)
{
MessageBox("內存分配失敗!");
return;
}*/
/* 分配給染色體內存空間 */
nbytes = m_ntarget*m_nweapon*sizeof(char);
for(j = 0; j < m_npopulationsize; j++)
{
if((m_oldpop[j].chrom = (char*) malloc(nbytes)) == NULL)
{
MessageBox("內存分配失敗!");
return;
}
if((m_newpop[j].chrom = (char*) malloc(nbytes)) == NULL)
{
MessageBox("內存分配失敗!");
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -