Добавил:
Studfiles2
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Программы для выполнения лаб 1 и 2 / KALMAN / SOURCE / SOURCE / FIRSTAPP
.CPP/* Project first
Copyright © 1997 by US. All Rights Reserved.
SUBSYSTEM: first.exe Application
FILE: firstapp.cpp
AUTHOR: US
OVERVIEW
========
Source file for implementation of firstApp (TApplication).
*/
#include <owl\owlpch.h>
#pragma hdrstop
#include <owl\controlg.h>
#include <dir.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <dos.h>
#include <assert.h>
#include <string.h>
#include "firstapp.h"
#include "frstabtd.h" // Definition of about dialog.
#include "tstpfrst.h" // Definition of First Setup dialog.
#include "tstpscnd.h" // Definition of Second Setup dialog.
#include "tstpthra.h" // Definition of Third A Setup dialog.
#include "tstpthrd.h" // Definition of Third A Setup dialog.
#include "bkgndwin.h" // Definition of background window
#include "frstctlb.h" // Definition of control bar
#include "matrix.h" // Definition of vectors and matrices
#include "waitdlg.h" // Definition of wait dialog
#include "draw.h"
#include "tools.h"
#if LOG==1
#define logop(x) x
#else
#define logop(x)
#endif
const char MethodId[4][SetupTitleLength] = {
"Калман",
"КалманСоСтарением",
"РасширенныйКалман",
"АдаптивныйМетод"
};
const char NoiseId[3][SetupTitleLength] = {
"ГауссовскоеРаспределение",
"ПоказательноеРаспределение",
"РавномерноеРаспределение"
};
// Drag / Drop support:
TFileDrop::TFileDrop (char* fileName, TPoint& p, BOOL inClient, TModule* module)
{
char exePath[MAXPATH];
exePath[0] = 0;
FileName = strcpy(new char[strlen(fileName) + 1], fileName);
Point = p;
InClientArea = inClient;
Icon = (WORD)FindExecutable(FileName, ".\\", exePath) <= 32 ? 0 : ::ExtractIcon(*module, exePath, 0);
// Use a question mark if couldn't get the icon from the executable.
//
if ((WORD)Icon <= 1) { // 0=no icons in exe, 1=not an exe
Icon = LoadIcon(0, (WORD)Icon == 1 ? IDI_APPLICATION : IDI_QUESTION);
DefIcon = TRUE;
} else
DefIcon = FALSE;
}
TFileDrop::~TFileDrop ()
{
delete FileName;
if (!DefIcon)
FreeResource(Icon);
}
const char *TFileDrop::WhoAmI ()
{
return FileName;
}
//{{firstApp Implementation}}
//
// Build a response table for all messages/commands handled
// by the application.
//
DEFINE_RESPONSE_TABLE1(firstApp, TApplication)
//{{firstAppRSP_TBL_BEGIN}}
EV_COMMAND(CM_FILENEW, CmFileNew),
EV_COMMAND(CM_FILEOPEN, CmFileOpen),
EV_COMMAND(CM_HELPABOUT, CmHelpAbout),
EV_WM_DROPFILES,
EV_COMMAND(CM_SIMULATE, CmSimulate),
EV_COMMAND(CM_RESIMULATE, CmReSimulate),
EV_COMMAND(CM_FILESAVE, CmFileSave),
EV_COMMAND(CM_FILESAVEAS, CmFileSaveAs),
EV_COMMAND(CM_FILEWRITEDATA, CmWriteData),
EV_COMMAND(CM_FILESAVEBMP, CmWriteImage),
//{{firstAppRSP_TBL_END}}
END_RESPONSE_TABLE;
//
// FrameWindow must be derived to override Paint for Preview and Print.
//
class SDIDecFrame : public TDecoratedFrame {
public:
SDIDecFrame (TWindow *parent, const char far *title, TWindow *clientWnd, BOOL trackMenuSelection = FALSE, TModule *module = 0) :
TDecoratedFrame(parent, title, clientWnd, trackMenuSelection, module)
{ }
~SDIDecFrame ()
{ }
};
//////////////////////////////////////////////////////////
// firstApp
// =====
//
firstApp::firstApp () : TApplication("First Attempt"),
AttemptNum(1)
{
// Common file file flags and filters for Open/Save As dialogs. Filename and directory are
// computed in the member functions CmFileOpen, and CmFileSaveAs.
FileData.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
FileData.SetFilter("Файлы параметров (*.PAR)|*.PAR|Все файлы (*.*)|*.*|");
XFileData.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
XFileData.SetFilter("Файлы протокола(*.PRO)|*.PRO|Все файлы (*.*)|*.*|");
BMPFileData.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
BMPFileData.SetFilter("Изображение bitmap(*.BMP)|*.BMP|Все файлы (*.*)|*.*|");
}
firstApp::~firstApp ()
{
// INSERT>> Your destructor code here.
}
//////////////////////////////////////////////////////////
// firstApp
// =====
// Application intialization.
//
void firstApp::InitMainWindow ()
{
Client = new TBackgroundWindow(0, "");
SDIDecFrame *frame = new SDIDecFrame(0, GetName(), Client, FALSE);
nCmdShow = nCmdShow != SW_SHOWMINIMIZED ? SW_SHOWMAXIMIZED : nCmdShow;
//
// Assign ICON w/ this application.
//
frame->SetIcon(this, IDI_FIRSTAPPLICATION);
//
// Menu associated with window and accelerator table associated with table.
//
frame->AssignMenu(FIRST_MENU);
//
// Associate with the accelerator table.
//
frame->Attr.AccelTable = FIRST_MENU;
//
// Create a control bar
//
TButtonGadget *button;
TFirstControlBar *cb = new TFirstControlBar(frame, TControlBar::Horizontal,
new TGadgetWindowFont(8, FALSE, FALSE)
/*new TFont("MS Sans Serif", 8)AnsiVar*/);
// Create buttons
cb->Insert(*(button = new TButtonGadget(CM_FILENEW, CM_FILENEW)));
button->SetNotchCorners(FALSE);
cb->Insert(*(button = new TButtonGadget(CM_FILEOPEN, CM_FILEOPEN)));
button->SetNotchCorners(FALSE);
cb->Insert(*(button = new TButtonGadget(CM_FILESAVE, CM_FILESAVE)));
button->SetNotchCorners(FALSE);
cb->Insert(*(button = new TButtonGadget(CM_FILEWRITEDATA, CM_FILEWRITEDATA)));
button->SetNotchCorners(FALSE);
cb->Insert(* new TSeparatorGadget(12));
cb->Insert(*(button = new TButtonGadget(CM_SIMULATE, CM_SIMULATE)));
button->SetNotchCorners(FALSE);
cb->Insert(*(button = new TButtonGadget(CM_RESIMULATE, CM_RESIMULATE)));
button->SetNotchCorners(FALSE);
// AttemptNames list
AttemptName = new TComboBox(cb, IDC_ATTEMPTNAME, 170, 3, 200, 100,
CBS_DROPDOWNLIST, SetupTitleLength, 0);
AttemptName->Attr.Style &= ~WS_TABSTOP;
// Graph list
GraphicName = new TComboBox(cb, IDC_GRAPHICNAME, 380, 3, 250, 100,
CBS_DROPDOWNLIST, SetupTitleLength, 0);
GraphicName->Attr.Style &= ~WS_TABSTOP;
frame->Insert(*cb, TDecoratedFrame::Top);
MainWindow = frame;
EnableBWCC();
}
//////////////////////////////////////////////////////////
// firstApp
// ===========
// Menu File New command
void firstApp::CmFileNew ()
{
while (!FirstSetupHistory.Root->Predefined)
FirstSetupHistory.Delete();
while (AttemptName->GetCount())
assert(AttemptName->DeleteString(0) >= 0);
while (GraphicName->GetCount())
assert(GraphicName->DeleteString(0) >= 0);
Client->Invalidate();
}
//////////////////////////////////////////////////////////
// firstApp
// ===========
// Menu File Open command
void firstApp::CmFileOpen ()
{
//
// Display standard Open dialog box to select a file name.
//
*FileData.FileName = 0;
if (Client->CanClose())
if (TFileOpenDialog(MainWindow, FileData).Execute() == IDOK)
OpenFile();
}
void firstApp::OpenFile (const char *fileName)
{
FILE *f;
char buffer[SetupTitleLength+1];
FirstSetup *p;
unsigned i;
if (fileName)
lstrcpy(FileData.FileName, fileName);
if (!(f = fopen(FileData.FileName, "rt")))
{
MainWindow->MessageBox(FileData.FileName, "Ошибка открытия файла", MB_OK|MB_ICONSTOP);
return;
}
while (!feof(f))
{
FirstSetupHistory.Insert();
if (!fgets(buffer, SetupTitleLength, f))
break;
if (buffer[strlen(buffer)-1] != '\n')
{
while (fgetc(f) != '\n' && !feof(f)) ;
if (feof(f))
break;
}
else
buffer[strlen(buffer)-1] = '\0';
if (!*buffer)
break;
p = FirstSetupHistory.Root;
strcpy(p->Title, buffer);
readWord(buffer, SetupTitleLength, f);
for (i = 0; i < 4 && strcmp(buffer, MethodId[i]); i++) ;
if (i < 4)
p->Method = i;
else
goto error;
fscanf(f, "%lf %lf %lf %lf %lf "
"%lu",
&p->m, &p->f, &p->kf, &p->Qf, &p->sigma,
&p->length);
if (feof(f))
goto error;
readWord(buffer, SetupTitleLength, f);
for (i = 0; i < 3 && strcmp(buffer, NoiseId[i]); i++) ;
if (i < 3)
p->VNoise = i;
else
goto error;
fscanf(f, "%lf %lf %lf %lf "
"%lf %lf %lf %lf "
"%lf %lf %lf %lf",
&p->Y, &p->DiffY, &p->TrueY, &p->TrueDiffY,
&p->COV11, &p->COV12, &p->COV21, &p->COV22,
&p->KOld, &p->sm, &p->sf, &p->skf);
if (feof(f))
goto error;
readWord(buffer, SetupTitleLength, f);
for (i = 0; i < 3 && strcmp(buffer, NoiseId[i]); i++) ;
if (i < 3)
p->XI_IntervalRule = i;
else
goto error;
readWord(buffer, SetupTitleLength, f);
for (i = 0; i < 3 && strcmp(buffer, NoiseId[i]); i++) ;
if (i < 3)
p->XI_DurationRule = i;
else
goto error;
readWord(buffer, SetupTitleLength, f);
for (i = 0; i < 3 && strcmp(buffer, NoiseId[i]); i++) ;
if (i < 3)
p->XI_TypeRule = i;
else
goto error;
fscanf(f, "%lf %lf %lf %lf "
"%lf %lf "
"%lf %lf %lf",
&p->XI_Interval_E, &p->XI_Interval_D,
&p->XI_Duration_E, &p->XI_Duration_D,
&p->XI_Type_E, &p->XI_Type_D,
&p->AfM, &p->AfAlpha, &p->AfBeta);
if (feof(f))
goto error;
p->Complete = TRUE;
continue;
error:
MainWindow->MessageBox("Ошибка анализа информации", "Ошибка", MB_OK|MB_ICONINFORMATION);
break;
}
FirstSetupHistory.Delete();
fclose(f);
}
//////////////////////////////////////////////////////////
// firstApp
// ===========
// Menu Help About first.exe command
void firstApp::CmHelpAbout ()
{
//
// Show the modal dialog.
//
firstAboutDlg(MainWindow).Execute();
}
void firstApp::InitInstance ()
{
TApplication::InitInstance();
// Accept files via drag/drop in the frame window.
MainWindow->DragAcceptFiles(TRUE);
}
void firstApp::EvDropFiles (TDropInfo drop)
{
// Number of files dropped.
int totalNumberOfFiles = drop.DragQueryFileCount();
TFileList* files = new TFileList;
for (int i = 0; i < totalNumberOfFiles; i++) {
// Tell DragQueryFile the file interested in (i) and the length of your buffer.
int fileLength = drop.DragQueryFileNameLen(i) + 1;
char *fileName = new char[fileLength];
drop.DragQueryFile(i, fileName, fileLength);
// Getting the file dropped. The location is relative to your client coordinates,
// and will have negative values if dropped in the non client parts of the window.
//
// DragQueryPoint copies that point where the file was dropped and returns whether
// or not the point is in the client area. Regardless of whether or not the file
// is dropped in the client or non-client area of the window, you will still receive
// the file name.
TPoint point;
BOOL inClientArea = drop.DragQueryPoint(point);
files->Add(new TFileDrop(fileName, point, inClientArea, this));
}
// Open the files that were dropped.
AddFiles(files);
// Release the memory allocated for this handle with DragFinish.
drop.DragFinish();
}
void firstApp::AddFiles (TFileList* files)
{
// Open all files dragged in.
TFileListIter fileIter(*files);
while (fileIter) {
lstrcpy(FileData.FileName, fileIter.Current()->WhoAmI());
fileIter++;
}
}
firstApp *App;
int OwlMain (int , char* [])
{
/* firstApp App;
int result;
result = App.Run();
return result; */
return (App = new firstApp())->Run();
}
void firstApp::CmAttNameChange()
{
// ReGenerate();
Simulate();
}
void firstApp::CmGrNameChange()
{
ReRender();
}
void firstApp::CmSimulate ()
{
if (!GraphicName->GetCount())
{
// Add graph names into the list
for (unsigned i = 0; i < MAX_MODE; i++)
GraphicName->AddString(GraphicNames[i]);
GraphicName->SetText(GraphicNames[3]);
}
FirstSetupHistory.Insert();
sprintf(FirstSetupHistory.Root->Title, "Попытка %d", AttemptNum++);
retryFirstSetup:
TSetupFirst(GetMainWindow(), FirstSetupHistory, IDD_SETUP, 0).Execute();
switch (FirstSetupHistory.result)
{
case SetupContinue:
break;
case SetupStopped:
default: FirstSetupHistory.Delete();
break;
}
retrySecondSetup:
if (FirstSetupHistory.result == SetupContinue)
{
TSetupSecond(GetMainWindow(), FirstSetupHistory, IDD_SETUP2, 0).Execute();
switch (FirstSetupHistory.result)
{
case SetupContinue:
break;
case SetupBack: goto retryFirstSetup;
case SetupStopped:
default: FirstSetupHistory.Delete();
break;
}
}
if (FirstSetupHistory.result == SetupContinue)
switch (FirstSetupHistory.Root->Method)
{
case EnhancedKalman:
case KalmanFilter:
AttemptName->AddString(FirstSetupHistory.Root->Title);
AttemptName->SetText(FirstSetupHistory.Root->Title);
Simulate();
break;
// break;
case KalmanVsOld:
{
TSetupThirdA(GetMainWindow(), FirstSetupHistory, IDD_SETUP3A, 0).Execute();
switch (FirstSetupHistory.result)
{
case SetupContinue: AttemptName->AddString(FirstSetupHistory.Root->Title);
AttemptName->SetText(FirstSetupHistory.Root->Title);
Simulate();
break;
case SetupBack: goto retrySecondSetup;
case SetupStopped:
default: FirstSetupHistory.Delete();
break;
}
}
break;
case AdaptiveFilter:
{
TSetupThirdD(GetMainWindow(), FirstSetupHistory, IDD_SETUP3D, 0).Execute();
switch (FirstSetupHistory.result)
{
case SetupContinue: AttemptName->AddString(FirstSetupHistory.Root->Title);
AttemptName->SetText(FirstSetupHistory.Root->Title);
Simulate();
break;
case SetupBack: goto retrySecondSetup;
case SetupStopped:
default: FirstSetupHistory.Delete();
break;
}
}
break;
}
}
////////////////////////////////////////////////////////////////////////
// Some math functions
//
double firstApp::GenerateNoise(NoiseType noise, double dispersion)
{
double param, sigma = sqrt(dispersion);
switch (noise)
{
case EquNoise:
if ((param = sqrt(2*dispersion)) > 32767)
param = 32767;
return param*2*rand()/RAND_MAX - param;
case GaussNoise:
{
double x, y, dens_max = 1/sqrt(2*M_PI)/sigma;
do {
y = dens_max * rand() / double(RAND_MAX);
x = 6*sigma * rand() / double(RAND_MAX) - 3*sigma;
} while (y > dens_max*exp(-sqr(x)/dispersion/2));
return x;
}
case FactNoise:
{
int signum = (rand()+(RAND_MAX/2)) / RAND_MAX;
if (!signum)
signum = -1;
return signum*sigma*log(rand() / double(RAND_MAX));
}
default:
::MessageBox(NULL, "Неопознанный тип распределения помехи измерения", "firstApp::Внутренняя ошибка", MB_OK|MB_ICONSTOP);
return 0;
}
}
void firstApp::Simulate(void)
{
FirstSetup *Params = FirstSetupHistory.Root;
unsigned i;
int percent, oldpercent = -10;
char sTitle[SetupTitleLength];
AttemptName->GetText(sTitle, SetupTitleLength);
while (Params && strcmp(sTitle, Params->Title))
Params = Params->Next;
if (!Params)
return;
unsigned Yh = Params->Method == EnhancedKalman ? 4 : 2;
// Algorithm-dependent matrices
TMatrix FIk(Yh, Yh), FIx(Yh, Yh),
Pk(Yh, Yh),
Qk(Yh, Yh),
Ck(1, 1),
Kk(1, Yh),
I(Yh, Yh),
// vectors
Yk(1, Yh),
Zk(1, 1),
H(Yh, 1),
SqrSigma(1, 1);
// scalars
double s;
// Adaptive filtering data
unsigned afStart = GenerateNoise(Params->XI_IntervalRule,
Params->XI_Interval_D) + Params->XI_Interval_E,
afStop = 0;
int inAdaptiveMode = 0;
TVector Zs(Params->length);
// Analysis results
if (!w_e.resize(Params->length, 2) || !w_y.resize(Params->length, 2)
|| !w_t.resize(Params->length, 2) || !w_k.resize(Params->length, 2)
|| !w_r.resize(Params->length, 2) || !w_w.resize(Params->length)
|| !TrueY.resize(1, Yh))
{
::MessageBox(0, "Мало памяти", "Предупреждение", MB_OK|MB_ICONSTOP);
return;
}
I.zero(); for (i = 0; i < Yh; i++) I[i][i] = 1;
H.zero(); H[0][0] = 1;
Yk[0][0] = Params->Y; Yk[0][1] = Params->DiffY;
TrueY[0][0] = Params->TrueY; TrueY[0][1] = Params->TrueDiffY;
Pk.zero();
Pk[0][0] = Params->COV11; Pk[0][1] = Params->COV12;
Pk[1][0] = Params->COV21; Pk[1][1] = Params->COV22;
FIk.zero();
FIk[0][0] = 0+1; FIk[1][0] = 1;
FIk[0][1] = -Params->kf/Params->m; FIk[1][1] = -Params->f/Params->m+1;
FIx.zero();
FIx[0][0] = 0+1; FIx[1][0] = 1;
FIx[0][1] = -Params->skf/Params->sm; FIx[1][1] = -Params->sf/Params->sm+1;
Qk.zero(); Qk[Yh-1][Yh-1] = Params->Qf / Params->sm / Params->sm;
SqrSigma[0][0] = Params->sigma;
TWaitDialog waitDlg(MainWindow, IDD_WAIT);
waitDlg.Create();
waitDlg.what->SetText("Идёт вычисление...");
logop(FILE *logf = fopen("d:\\first.log", "wt");
assert(logf != NULL);)
switch (Params->Method)
{
case EnhancedKalman:
FIx[2][2] = FIx[3][3] = 1; FIx[2][3] = FIx[3][2] = 0;
Yk[0][2] = FIx[0][1]; Yk[0][3] = FIx[1][1];
Pk[2][2] = sqr(FIx[0][1] - FIk[0][1]);
Pk[3][3] = sqr(FIx[1][1] - FIk[1][1]);
case KalmanFilter:
case AdaptiveFilter:
s = 1;
break;
case KalmanVsOld:
s = Params->KOld;
break;
}
for (i = 0; i < Params->length; i++)
{
if ((percent = int((unsigned long)(i)*100/Params->length)) >= oldpercent + 10)
{
char msg[20];
sprintf(msg, "%d%% завершено", oldpercent = percent);
waitDlg.percent->SetText(msg);
}
logop(fprintf(logf, "Z[%d] = (", i);)
Zk = H * TrueY;
logop(Zk.write(logf);)
logop(fprintf(logf, ")\n");)
Zk[0][0] += (w_w[i] = GenerateNoise(Params->VNoise, Params->sigma));
Zs[i] = sqr(Zk[0][0]);
logop(fprintf(logf, "Y~[%d] = (\n", i);)
if (Params->Method == EnhancedKalman) {
FIx[0][1] = Yk[0][2]; FIx[1][1] = Yk[0][3];
FIx[2][1] = FIx[3][1] = 0; }
Yk = FIx * Yk;
logop(Yk.write(logf);)
logop(fprintf(logf, ")\nP~[%d] = (\n", i);)
if (Params->Method == AdaptiveFilter && i)
{
unsigned k = i - Params->AfM + 1, j;
double Cx = 0;
if (int(k) < 0)
k = 0;
for (j = k; j <= i; j++)
Cx += Zs[j];
Cx /= Params->AfM;
if (inAdaptiveMode)
{
if (Cx / Ck[0][0] < Params->AfAlpha)
{
inAdaptiveMode = 0;
s = 1;
}
}
else
if (Cx / Ck[0][0] > Params->AfBeta)
inAdaptiveMode = 1;
if (inAdaptiveMode)
s = (Cx - (Qk[1][1] + SqrSigma[0][0])) / (H * ~FIx * Pk * FIx * ~H)[0][0];
}
if (Params->Method == EnhancedKalman) {
FIx[2][1] = Yk[0][0]; FIx[3][1] = Yk[0][1]; }
Pk = FIx * Pk * ~FIx * s + Qk;
logop(Pk.write(logf);)
logop(fprintf(logf, ")\nZ~[%d] = (\n", i);)
Zk = Zk - H * Yk;
logop(Zk.write(logf);)
logop(fprintf(logf, ")\nC[%d] = (\n", i);)
Ck = H * Pk * ~H + SqrSigma;
logop(Ck.write(logf);)
logop(fprintf(logf, ")\nK[%d] = (\n", i);)
Kk = Pk * ~H * !Ck;
logop(Kk.write(logf);)
logop(fprintf(logf, ")\nY[%d] = (\n", i);)
Yk = Yk + Kk * Zk;
logop(Yk.write(logf);)
logop(fprintf(logf, ")\nP[%d] = (\n", i);)
Pk = (I - Kk * H) * Pk;
logop(Pk.write(logf);)
logop(fprintf(logf, ")\n");)
Pk[0][1] = Pk[1][0] = (Pk[0][1]+Pk[1][0]) / 2;
w_y[i] = Yk[0];
w_e[i] = Yk[0] - TrueY[0];
w_t[i] = TrueY[0];
w_k[i] = Kk[0];
if (Pk[0][0] < 0 || Pk[1][1] < 0)
{
MainWindow->MessageBox("Попытка вычисления корня от отрицательного числа", "Ошибка", MB_OK|MB_ICONSTOP);
return;
}
w_r[i][0] = sqrt(Pk[0][0]); w_r[i][1] = sqrt(Pk[1][1]);
TrueY = FIk * TrueY;
if (i < afStop)
{
TrueY[0][0] += GenerateNoise(Params->XI_TypeRule,
Params->XI_Type_D) + Params->XI_Type_E;
TrueY[0][1] += GenerateNoise(Params->XI_TypeRule,
Params->XI_Type_D) + Params->XI_Type_E;
}
else
if (i >= afStart)
{
afStop = i + GenerateNoise(Params->XI_DurationRule,
Params->XI_Duration_D) + Params->XI_Duration_E;
afStart = afStop + GenerateNoise(Params->XI_IntervalRule,
Params->XI_Interval_D) + Params->XI_Interval_E;
}
}
logop(fclose(logf);)
waitDlg.CloseWindow();
Params->Complete = TRUE;
ReGenerate();
}
void firstApp::ReGenerate(void)
{
ReRender();
}
void firstApp::ReRender(void)
{
if (!w_ne.resize(w_e.width, 2))
{
::MessageBox(0, "Мало памяти", "Предупреждение", MB_OK|MB_ICONSTOP);
return;
}
w_j.zero();
for (unsigned index = 0; index < 2; index ++)
{
for (unsigned x = 0; x < w_e.width; x++)
{
if (w_r[x][index])
w_ne[x][index] = w_e[x][index] / w_r[x][index];
else
w_ne[x][index] = 0;
w_j[0][index] += sqr(w_e[x][index]);
w_j[1][index] += sqr(w_ne[x][index]);
}
w_j[0][index] /= (double)w_e.width;
w_j[1][index] /= (double)w_e.width;
}
Client->Invalidate(TRUE);
}
void firstApp::CmReSimulate(void)
{
Simulate();
}
void firstApp::CmFileSave ()
{
if (!*FileData.FileName)
CmFileSaveAs();
SaveFile();
}
void firstApp::CmFileSaveAs ()
{
*FileData.FileName = 0;
if (TFileSaveDialog(MainWindow, FileData).Execute() == IDOK)
SaveFile();
}
void firstApp::CmWriteData ()
{
if (TFileSaveDialog(MainWindow, XFileData).Execute() == IDOK)
WriteData();
}
void firstApp::WriteData()
{
FILE *outf;
char msg[80];
unsigned i;
if (!(outf = fopen(XFileData.FileName, "wt")))
{
sprintf(msg, "Невозможно открыть файл '%s': %s",
XFileData.FileName, _sys_errlist[errno]);
MainWindow->MessageBox(msg, "Ошибка", MB_OK|MB_ICONSTOP);
return;
}
TWaitDialog waitDlg(MainWindow, IDD_WAIT);
waitDlg.Create();
waitDlg.what->SetText("Запись...");
fprintf(outf, " Вектор Y: | Вектор оценки Y: | Вектор ошибки оценки Y:\n");
for (i = 0; i < w_y.width-1; i++)
fprintf(outf, " %4u: %8.4lf %8.4lf | %8.4lf %8.4lf | %8.4lf %8.4lf\n",
i, w_t[i][0], w_t[i][1], w_y[i][0], w_y[i][1], w_e[i][0], w_e[i][1]);
waitDlg.CloseWindow();
fclose(outf);
}
void firstApp::CmWriteImage ()
{
if (TFileSaveDialog(MainWindow, BMPFileData).Execute() == IDOK)
{
HDC hdc = GetDC(Client->HWindow);
TDC dc(hdc);
TRect rect;
Client->GetWindowRect(rect);
TMemoryDC mdc(dc);
TBitmap bmp(dc, rect.right-rect.left-1, rect.bottom-rect.top-1);
rect.top = -1;
mdc.SelectObject(bmp);
TBrush brush(TColor::White);
mdc.SelectObject(brush);
mdc.Rectangle(rect);
PaintData(mdc, rect, TRUE);
TDib dib(bmp);
mdc.RestoreBitmap();
mdc.RestoreObjects();
if (!(dib.WriteFile(BMPFileData.FileName)))
Client->MessageBox("Ошибка при записи изображения", "Ошибка", MB_OK|MB_ICONSTOP);
ReleaseDC(Client->HWindow, hdc);
}
}
void firstApp::readWord(char *buffer, unsigned bufferLength, FILE *inf)
{
char ch;
unsigned i;
while (unsigned(ch = fgetc(inf)) < unsigned('А') && !feof(inf)) ;
if (feof(inf))
{
*buffer = '\0';
return;
}
*buffer = ch;
for (i = 1; unsigned(ch = fgetc(inf)) >= unsigned('А') && !feof(inf) && i < bufferLength; i++)
buffer[i] = ch;
buffer[i] = '\0';
}
void firstApp::SaveFile (const char *fileName)
{
FILE *f;
FirstSetup *p;
if (fileName)
lstrcpy(FileData.FileName, fileName);
if (!(f = fopen(FileData.FileName, "wt")))
{
MainWindow->MessageBox(FileData.FileName, "Ошибка открытия файла", MB_OK|MB_ICONSTOP);
return;
}
for (p = FirstSetupHistory.Root; !p->Predefined; p = p->Next)
fprintf(f, "%s\n"
"%s %lf %lf %lf\n"
"%lf %lf\n"
"%lu\n"
"%s\n"
"%lf %lf %lf %lf\n"
"%lf %lf %lf %lf\n"
"%lf %lf %lf %lf\n"
"%s %s %s\n"
"%lf %lf %lf %lf %lf %lf\n"
"%lf %lf %lf\n",
p->Title,
MethodId[p->Method], p->m, p->f, p->kf,
p->Qf, p->sigma,
p->length,
NoiseId[p->VNoise],
p->Y, p->DiffY, p->TrueY, p->TrueDiffY,
p->COV11, p->COV12, p->COV21, p->COV22,
p->KOld, p->sm, p->sf, p->skf,
NoiseId[p->XI_IntervalRule], NoiseId[p->XI_DurationRule], NoiseId[p->XI_TypeRule],
p->XI_Interval_E, p->XI_Interval_D,
p->XI_Duration_E, p->XI_Duration_D,
p->XI_Type_E, p->XI_Type_D,
p->AfM, p->AfAlpha, p->AfBeta);
fclose(f);
}
Соседние файлы в папке SOURCE