text stringlengths 14 6.51M |
|---|
unit frPreProcessor;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is frPreProcessor.pas.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ preprocessor symbols }
uses
Classes, Controls, Forms,
StdCtrls, JvMemo,
{ local}frmBaseSettingsFrame, JvExStdCtrls;
type
TfPreProcessor = class(TfrSettingsFrame)
mSymbols: TJvMemo;
cbEnable: TCheckBox;
lblSymbols: TLabel;
mOptions: TJvMemo;
lblCompilerOptions: TLabel;
procedure FrameResize(Sender: TObject);
private
public
constructor Create(AOwner: TComponent); override;
procedure Read; override;
procedure Write; override;
end;
implementation
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
uses JcfHelp, JcfSettings;
constructor TfPreProcessor.Create(AOwner: TComponent);
begin
inherited;
fiHelpContext := HELP_CLARIFY;
end;
procedure TfPreProcessor.Read;
begin
inherited;
with JcfFormatSettings.PreProcessor do
begin
cbEnable.Checked := Enabled;
mSymbols.Lines.Assign(DefinedSymbols);
mOptions.Lines.Assign(DefinedOptions);
end;
end;
procedure TfPreProcessor.Write;
begin
inherited;
with JcfFormatSettings.PreProcessor do
begin
Enabled := cbEnable.Checked;
DefinedSymbols.Assign(mSymbols.Lines);
DefinedOptions.Assign(mOptions.Lines);
end;
end;
procedure TfPreProcessor.FrameResize(Sender: TObject);
var
liClientHeight: integer;
begin
liClientHeight := ClientHeight -
(cbEnable.Top + cbEnable.Height +
lblCompilerOptions.Height + lblSymbols.Height +
(GUI_PAD * 3));
mSymbols.Height := (liClientHeight div 2);
mSymbols.Left := 0;
mSymbols.Width := ClientWidth;
lblCompilerOptions.Top := mSymbols.Top + mSymbols.Height + GUI_PAD;
mOptions.Top := lblCompilerOptions.Top + lblCompilerOptions.Height + GUI_PAD;
mOptions.Height := ClientHeight - mOptions.Top;
mOptions.Left := 0;
mOptions.Width := ClientWidth;
end;
end.
|
unit uObjectCombo;
interface
uses Buttons, Classes, SysUtils, Graphics, uMyTypes, Math;
type
TComboObject = class(TObject)
private
objID: integer; // ID
objPoloha: TMyPoint; // pouziva sa len vtedy, ak nie je combo polohovane vzhladom na nejaky svoj komponent
objPolohaObject: integer; // identifikator objektu, ktory urcuje polohu comba (ak je polohovane od svojho stredu, je tento parameter = -1)
objVelkost: TMyPoint;
objName: string;
objRotation: double;
published
constructor Create;
property ID: integer read objID write objID;
property Poloha: TMyPoint read objPoloha write objPoloha;
property X: double read objPoloha.X write objPoloha.X;
property Y: double read objPoloha.Y write objPoloha.Y;
property PolohaObject: integer read objPolohaObject write objPolohaObject;
property Velkost: TMyPoint read objVelkost write objVelkost;
property Name: string read objName write objName;
property Rotation: double read objRotation write objRotation;
procedure SaveToFile(filename: string);
procedure MoveFeaturesBy(offset: TMyPoint);
end;
implementation
uses uMain, uObjectFeature, uConfig, uObjectFeaturePolyLine;
{ ============================= TComboObject ================================= }
constructor TComboObject.Create;
begin
inherited Create;
objID := -1;
objPoloha := MyPoint(-1,-1);
objPolohaObject := -1;
objName := '';
objRotation := 0;
end;
procedure TComboObject.SaveToFile(filename: string);
var
pisar: TStreamWriter;
i, v: integer;
tempStr: string;
vertex: TMyPoint;
begin
// najprv povodny subor zmazeme, aby sa v nom nedrzali stare vymazane objekty
if FileExists(filename) then begin
DeleteFile(filename+'.bak');
RenameFile(filename, filename+'.bak');
end;
pisar := TStreamWriter.Create(filename, false, TEncoding.UTF8);
try
// zapiseme hlavicku
pisar.WriteLine('{>header}');
pisar.WriteLine('filetype=quickpanel:combo');
pisar.WriteLine('filever=' + IntToStr((cfg_swVersion1*10000)+(cfg_swVersion2*100)+cfg_swVersion3));
pisar.WriteLine('name='+StringReplace( ExtractFileName(FileName), '.combo', '', [] ));
pisar.WriteLine('units=mm');
pisar.WriteLine('sizex=' + FloatToStr(RoundTo(objVelkost.X , -4)));
pisar.WriteLine('sizey=' + FloatToStr(RoundTo(objVelkost.Y , -4)));
pisar.WriteLine('insertpointx='+ FloatToStr(RoundTo(objPoloha.X , -4)));
pisar.WriteLine('insertpointy='+ FloatToStr(RoundTo(objPoloha.Y , -4)));
pisar.WriteLine('structfeatures=type,posx,posy,size1,size2,size3,size4,size5,depth,param1,param2,param3,param4,param5,vertexarray'); // MUSIA byt oddelene ciarkami LoadFromFile sa na nich spolieha
pisar.WriteLine('{/header}');
// ficre - prejdeme objekty a vyselectovane ulozime
pisar.WriteLine('{>features}');
for i:=0 to _PNL.Features.Count-1 do
if (Assigned( _PNL.Features[i] )) AND (_PNL.Features[i].Selected) then begin
pisar.WriteLine( IntToStr(_PNL.Features[i].Typ) );
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].X - objPoloha.X , -4)) ); // poloha jednotlivych featurov bude ulozena vzhladom na stred comba
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].Y - objPoloha.Y , -4)) );
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].Rozmer1 , -4)) );
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].Rozmer2 , -4)) );
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].Rozmer3 , -4)) );
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].Rozmer4 , -4)) );
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].Rozmer5 , -4)) );
pisar.WriteLine( FloatToStr(RoundTo(_PNL.Features[i].Hlbka1 , -4)) );
pisar.WriteLine( _PNL.Features[i].Param1 );
pisar.WriteLine( _PNL.Features[i].Param2 );
pisar.WriteLine( _PNL.Features[i].Param3 );
pisar.WriteLine( _PNL.Features[i].Param4 );
pisar.WriteLine( _PNL.Features[i].Param5 );
// zapisanie vertexov polylineu
if (_PNL.Features[i].Typ <> ftPolyLineGrav) then
pisar.WriteLine('')
else begin
tempStr := '';
for v := 0 to (_PNL.Features[i] as TFeaturePolyLineObject).VertexCount-1 do begin
vertex := (_PNL.Features[i] as TFeaturePolyLineObject).GetVertex(v);
tempStr := tempStr + FormatFloat('0.0###',vertex.X)+','+FormatFloat('0.0###',vertex.Y)+separChar;
end;
tempStr := Copy(tempStr, 0, Length(tempStr)-1 ); // odstranime posledny separchar
pisar.WriteLine(tempStr);
end;
end;
pisar.WriteLine('{/features}');
finally
pisar.Free;
end;
// ak vsetko prebehlo OK, mozeme zmazat zalozny subor
if FileExists(filename+'.bak') then DeleteFile(filename+'.bak');
end;
procedure TComboObject.MoveFeaturesBy(offset: TMyPoint);
var
poleObjektov: TPoleIntegerov;
i: integer;
begin
// ciselna poloha comba sa nezmeni, len sa v ramci neho posunu jeho komponenty
_PNL.GetComboFeatures(poleObjektov, objID);
for i := 0 to High(poleObjektov) do begin
_PNL.CreateUndoStep('MOD','FEA',poleObjektov[i]);
_PNL.GetFeatureByID(poleObjektov[i]).X := _PNL.GetFeatureByID(poleObjektov[i]).X + offset.X;
_PNL.GetFeatureByID(poleObjektov[i]).Y := _PNL.GetFeatureByID(poleObjektov[i]).Y + offset.Y;
end;
end;
end.
|
unit Warning;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is Warning, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses SwitchableVisitor, ConvertTypes;
type
TWarning = class(TSwitchableVisitor)
private
fOnWarning: TStatusMessageProc;
protected
procedure SendWarning(const pcNode: TObject; const psMessage: string);
public
constructor Create; override;
function IsIncludedInSettings: boolean; override;
property OnWarning: TStatusMessageProc Read fOnWarning Write fOnWarning;
end;
implementation
uses ParseTreeNode, SourceToken, TokenUtils, FormatFlags, JcfSettings;
constructor TWarning.Create;
begin
inherited;
FormatFlags := FormatFlags + [eWarning];
end;
function TWarning.IsIncludedInSettings: boolean;
begin
// included if warnings are turned on
Result := JcfFormatSettings.Clarify.Warnings;
end;
procedure TWarning.SendWarning(const pcNode: TObject; const psMessage: string);
var
lsMessage, lsProc: string;
lcToken: TSourceToken;
begin
{ don't bother with the rest }
if not Assigned(fOnWarning) then
exit;
lsMessage := psMessage;
if (pcNode is TSourceToken) then
begin
lcToken := TSourceToken(pcNode);
end
else if (pcNode is TParseTreeNode) then
begin
// use first token under this node for pos
lcToken := TParseTreeNode(pcNode).FirstSolidLeaf as TSourceToken;
end
else
lcToken := nil;
if lcToken <> nil then
begin
lsMessage := lsMessage + ' near ' + lcToken.Describe;
lsProc := GetProcedureName(lcToken, True, False);
if lsProc <> '' then
lsMessage := lsMessage + ' in ' + GetBlockType(lcToken) + ' ' + lsProc;
end;
fOnWarning('', lsMessage, mtCodeWarning, lcToken.YPosition, lcToken.XPosition);
end;
end.
|
unit ParametricTableForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, RootForm, GridFrame,
ComponentsParentView, ParametricTableView, NotifyEvents, ComponentsBaseView;
{$WARN UNIT_PLATFORM OFF}
type
TfrmParametricTable = class(TfrmRoot)
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDeactivate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FBeforeClose: TNotifyEventsEx;
FCategoryPath: string;
FOnActivate: TNotifyEventsEx;
FOnDeactivate: TNotifyEventsEx;
FViewParametricTable: TViewParametricTable;
procedure SetCategoryPath(const Value: string);
procedure UpdateCaption;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property BeforeClose: TNotifyEventsEx read FBeforeClose;
property CategoryPath: string read FCategoryPath write SetCategoryPath;
property ViewParametricTable: TViewParametricTable read FViewParametricTable;
property OnDeactivate: TNotifyEventsEx read FOnDeactivate;
property OnActivate: TNotifyEventsEx read FOnActivate;
{ Public declarations }
end;
var
frmParametricTable: TfrmParametricTable;
implementation
{$R *.dfm}
uses Vcl.FileCtrl;
constructor TfrmParametricTable.Create(AOwner: TComponent);
begin
inherited;
FViewParametricTable := TViewParametricTable.Create(Self);
FViewParametricTable.Parent := Self;
FViewParametricTable.Align := alClient;
FBeforeClose := TNotifyEventsEx.Create(Self);
FOnActivate := TNotifyEventsEx.Create(Self);
FOnDeactivate := TNotifyEventsEx.Create(Self);
end;
destructor TfrmParametricTable.Destroy;
begin
FreeAndNil(FBeforeClose);
FreeAndNil(FOnActivate);
FreeAndNil(FOnDeactivate);
inherited;
end;
procedure TfrmParametricTable.FormActivate(Sender: TObject);
begin
inherited;
FOnActivate.CallEventHandlers(Self);
end;
procedure TfrmParametricTable.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FBeforeClose.CallEventHandlers(Self);
Action := caFree;
frmParametricTable := nil;
end;
procedure TfrmParametricTable.FormDeactivate(Sender: TObject);
begin
inherited;
FOnDeactivate.CallEventHandlers(Self);
end;
procedure TfrmParametricTable.FormResize(Sender: TObject);
begin
inherited;
UpdateCaption;
end;
procedure TfrmParametricTable.FormShow(Sender: TObject);
begin
inherited;
UpdateCaption;
end;
procedure TfrmParametricTable.SetCategoryPath(const Value: string);
begin
if CategoryPath = Value then
Exit;
FCategoryPath := Value;
UpdateCaption;
end;
procedure TfrmParametricTable.UpdateCaption;
var
S: string;
begin
if not CategoryPath.IsEmpty then
begin
S := MinimizeName(CategoryPath, Canvas, Width - 120);
S := S.Trim(['\']).Replace('\', '-');
Caption := S;
end
end;
end.
|
unit fShowParseTree;
{
AFS 2002
A form to show a unit's parse tree
mainly for debugiing purposes when the parse goes wrong
}
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is fShowParseTree, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
{ delphi }
{$ifndef fpc}
Windows, ShellAPI,
{$endif}
SysUtils, Classes, Controls, Forms,
ComCtrls, ExtCtrls, StdCtrls,
{ local }
ParseTreeNode;
type
TfrmShowParseTree = class(TForm)
StatusBar1: TStatusBar;
pnlTop: TPanel;
lblTreeCount: TLabel;
lblTreeDepth: TLabel;
pnlBottom: TPanel;
lblCurrent: TLabel;
lblDepth: TLabel;
lblTotalNodeCount: TLabel;
lblImmediateChildCount: TLabel;
cbShowWhiteSpace: TCheckBox;
pcPages: TPageControl;
tsTokens: TTabSheet;
tsTree: TTabSheet;
tvParseTree: TTreeView;
lvTokens: TListView;
procedure tvParseTreeChange(Sender: TObject; Node: TTreeNode);
procedure cbShowWhiteSpaceClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lvTokensClick(Sender: TObject);
procedure lvTokensSelectItem(Sender: TObject; Item: TListItem;
Selected: boolean);
procedure lvTokensDblClick(Sender: TObject);
procedure tvParseTreeDblClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
private
fcRootNode: TParseTreeNode;
procedure ShowTreeNodeDetails(const pcNode: TParseTreeNode);
public
property RootNode: TParseTreeNode Read fcRootNode Write fcRootNode;
procedure DisplayTree;
end;
procedure ShowParseTree(const pcRoot: TParseTreeNode);
implementation
{$ifndef FPC}
{$R *.dfm}
{$endif}
uses
SourceToken, Tokens, JcfHelp, JcfFontSetFunctions
{$ifdef fpc}, LResources{$endif};
procedure ShowParseTree(const pcRoot: TParseTreeNode);
var
lfParseTree: TfrmShowParseTree;
begin
Assert(pcRoot <> nil);
lfParseTree := TfrmShowParseTree.Create(Application);
try
lfParseTree.RootNode := pcRoot;
lfParseTree.DisplayTree;
lfParseTree.ShowModal;
finally
lfParseTree.Free;
end;
end;
procedure TfrmShowParseTree.DisplayTree;
procedure ShowTokensInList(const pcData: TParseTreeNode);
var
lcNewItem: TListItem;
lcToken: TSourceToken;
liLoop: integer;
lsDesc: string;
begin
{ exclude this one as white space }
if (not cbShowWhiteSpace.Checked) and (not pcData.HasChildren) and
(pcData is TSourceToken) and (TSourceToken(pcData).TokenType in
NotSolidTokens) then
exit;
{ list tokens }
if (pcData is TSourceToken) then
begin
lcToken := TSourceToken(pcData);
lcNewItem := lvTokens.Items.Add;
lcNewItem.Caption := IntToStr(lvTokens.Items.Count);
lsDesc := TokenTypeToString(lcToken.TokenType);
lcNewItem.SubItems.Add(lsDesc);
lcNewItem.SubItems.Add(lcToken.SourceCode);
lcNewItem.Data := pcData;
end;
// attach the children
for liLoop := 0 to pcData.ChildNodeCount - 1 do
ShowTokensInList(pcData.ChildNodes[liLoop]);
end;
procedure MakeNodeChildren(const pcGUIParent: TTreeNode; const pcData: TParseTreeNode);
var
lcNewItem: TTreeNode;
liLoop: integer;
begin
{ exclude this one as white space }
if (not cbShowWhiteSpace.Checked) and (not pcData.HasChildren) and
(pcData is TSourceToken) and (TSourceToken(pcData).TokenType in
NotSolidTokens) then
exit;
lcNewItem := tvParseTree.Items.AddChild(pcGUIParent, pcData.Describe);
lcNewItem.Data := pcData;
// attach the children
for liLoop := 0 to pcData.ChildNodeCount - 1 do
MakeNodeChildren(lcNewItem, pcData.ChildNodes[liLoop]);
end;
begin
lblTreeCount.Caption := 'Tree has ' + IntToStr(fcRootNode.RecursiveChildCount) +
' nodes';
lblTreeDepth.Caption := 'Tree has max depth of ' + IntToStr(fcRootNode.MaxDepth);
lvTokens.Items.BeginUpdate;
try
lvTokens.Items.Clear;
ShowTokensInList(fcRootNode);
finally
lvTokens.Items.EndUpdate;
end;
tvParseTree.Items.BeginUpdate;
try
tvParseTree.Items.Clear;
MakeNodeChildren(nil, fcRootNode);
tvParseTree.FullExpand;
finally
tvParseTree.Items.EndUpdate;
end;
end;
procedure TfrmShowParseTree.tvParseTreeChange(Sender: TObject; Node: TTreeNode);
begin
if Node = nil then
ShowTreeNodeDetails(nil)
else
ShowTreeNodeDetails(Node.Data);
end;
procedure TfrmShowParseTree.ShowTreeNodeDetails(const pcNode: TParseTreeNode);
begin
if pcNode = nil then
begin
lblCurrent.Caption := 'Current: none';
lblDepth.Caption := 'Depth: -';
lblImmediateChildCount.Caption := 'Immediate child count: -';
lblTotalNodeCount.Caption := 'Total node count: -';
end
else
begin
lblCurrent.Caption := 'Current: ' + pcNode.Describe;
lblDepth.Caption := 'Level: ' + IntToStr(pcNode.Level);
lblImmediateChildCount.Caption :=
'Immediate child count: ' + IntToStr(pcNode.ChildNodeCount);
lblTotalNodeCount.Caption :=
'Total node count: ' + IntToStr(pcNode.RecursiveChildCount);
end;
end;
procedure TfrmShowParseTree.cbShowWhiteSpaceClick(Sender: TObject);
begin
// ShowWhiteSpace setting has changed. Redisplay
DisplayTree;
end;
procedure TfrmShowParseTree.FormShow(Sender: TObject);
begin
pcPages.ActivePage := tsTree;
end;
procedure TfrmShowParseTree.lvTokensClick(Sender: TObject);
begin
if lvTokens.Selected = nil then
ShowTreeNodeDetails(nil)
else
ShowTreeNodeDetails(lvTokens.Selected.Data);
end;
procedure TfrmShowParseTree.lvTokensSelectItem(Sender: TObject;
Item: TListItem; Selected: boolean);
begin
if lvTokens.Selected = nil then
ShowTreeNodeDetails(nil)
else
ShowTreeNodeDetails(lvTokens.Selected.Data);
end;
procedure TfrmShowParseTree.lvTokensDblClick(Sender: TObject);
var
lpNode: pointer;
liLoop: integer;
lcItem: TTreeNode;
begin
// try to select the same node in the tree
if lvTokens.Selected = nil then
exit;
lpNode := lvTokens.Selected.Data;
if lpNode = nil then
exit;
for liLoop := 0 to tvParseTree.Items.Count - 1 do
begin
lcItem := tvParseTree.Items[liLoop];
if lcItem.Data = lpNode then
begin
lcItem.Selected := True;
pcPages.ActivePage := tsTree;
break;
end;
end;
end;
procedure TfrmShowParseTree.tvParseTreeDblClick(Sender: TObject);
var
lpNode: pointer;
liLoop: integer;
lcItem: TListItem;
begin
// try to select the same node in the list
if tvParseTree.Selected = nil then
exit;
lpNode := tvParseTree.Selected.Data;
if lpNode = nil then
exit;
for liLoop := 0 to lvTokens.Items.Count - 1 do
begin
lcItem := lvTokens.Items[liLoop];
if lcItem.Data = lpNode then
begin
lcItem.Selected := True;
lcItem.Focused := True;
lcItem.MakeVisible(False);
pcPages.ActivePage := tsTokens;
break;
end;
end;
end;
procedure TfrmShowParseTree.FormCreate(Sender: TObject);
begin
SetObjectFontToSystemFont(Self);
end;
procedure TfrmShowParseTree.FormKeyUp(Sender: TObject; var Key: word;
Shift: TShiftState);
begin
{$ifndef fpc}
if Key = VK_F1 then
try
Application.HelpContext(HELP_MAIN);
except
if FileExists(Application.HelpFile) then
ShellExecute(Handle, 'open', PChar(Application.HelpFile), nil, nil, SW_SHOWNORMAL);
end;
{$endif}
end;
initialization
{$ifdef fpc}
{$I fShowParseTree.lrs}
{$endif}
end.
|
unit UBackUp;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
DADump,
UniDump,
cxGraphics,
cxControls,
cxLookAndFeels,
cxLookAndFeelPainters,
cxStyles,
dxSkinsCore,
dxSkinscxPCPainter,
cxCustomData,
cxFilter,
cxData,
cxDataStorage,
cxEdit,
cxNavigator,
Data.DB,
cxDBData,
cxCheckBox,
Vcl.StdCtrls,
Vcl.Mask,
cxGridCustomTableView,
cxGridTableView,
cxGridDBTableView,
MemDS,
DBAccess,
Uni,
cxGridLevel,
cxClasses,
cxGridCustomView,
cxGrid,
dxSkinDevExpressStyle,
dxSkinXmas2008Blue;
type
TBackUp = class(TForm)
dump1: TUniDump;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
QueryBalance: TUniQuery;
dsBalance: TDataSource;
cxGrid1DBTableView1name: TcxGridDBColumn;
cxGrid1DBTableView1q: TcxGridDBColumn;
MaskEdit1: TMaskEdit;
procedure dump1BackupProgress(Sender: TObject; ObjectName: string;
ObjectNum, ObjectCount, Percent: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
BackUp: TBackUp;
implementation
{$R *.dfm}
uses
UDataModule1;
procedure TBackUp.dump1BackupProgress(Sender: TObject; ObjectName: string;
ObjectNum, ObjectCount, Percent: Integer);
begin
Caption := ObjectName + ' [' + IntToStr(Percent) + ' %]';
Application.ProcessMessages;
end;
end.
|
{ ******************************************************* }
{ }
{ Implements a TToolbar descendant that has a Menu to }
{ make IDE like Toolbar menus very easy. This works }
{ only in Delphi 4.0 }
{ }
{ Copyright (c) 1995,98 Inprise Corporation }
{ }
{ ******************************************************* }
unit MenuBar;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ToolWin, ComCtrls, Menus;
type
TMenuBar = class(TToolBar)
private
FMenu: TMainMenu;
procedure SetMenu(const Value: TMainMenu);
protected
{ protected declarations }
public
constructor Create(AOwner: TComponent); override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
published
property EdgeBorders default [];
property Menu: TMainMenu read FMenu write SetMenu;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TMenuBar]);
end;
{ TMenuBar }
constructor TMenuBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Flat := True;
ShowCaptions := True;
EdgeBorders := [];
ControlStyle := [csCaptureMouse, csClickEvents, csDoubleClicks, csMenuEvents, csSetCaption];
end;
procedure TMenuBar.GetChildren(Proc: TGetChildProc; Root: TComponent);
begin
end;
procedure TMenuBar.SetMenu(const Value: TMainMenu);
var
i: Integer;
Button: TToolButton;
begin
if FMenu = Value then
exit;
if Assigned(FMenu) then
for i := ButtonCount - 1 downto 0 do
Buttons[i].Free;
FMenu := Value;
if not Assigned(FMenu) then
exit;
for i := ButtonCount to FMenu.Items.Count - 1 do begin
Button := TToolButton.Create(Self);
try
Button.AutoSize := True;
Button.Grouped := True;
Button.Parent := Self;
Buttons[i].MenuItem := FMenu.Items[i];
except
Button.Free;
raise;
end;
end;
{ Copy attributes from each menu item }
for i := 0 to FMenu.Items.Count - 1 do
Buttons[i].MenuItem := FMenu.Items[i];
end;
end.
|
unit ComakerSearch;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseSearch, Data.DB, Vcl.StdCtrls,
Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel;
type
TfrmComakerSearch = class(TfrmBaseSearch)
private
{ Private declarations }
public
{ Public declarations }
protected
procedure SearchList; override;
procedure SetReturn; override;
procedure Add; override;
procedure Cancel; override;
end;
var
frmComakerSearch: TfrmComakerSearch;
implementation
{$R *.dfm}
uses
LoanData, Comaker, ComakerDetail;
procedure TfrmComakerSearch.SearchList;
var
filter: string;
begin
inherited;
if Trim(edSearchKey.Text) <> '' then
filter := 'name like ''*' + edSearchKey.Text + '*'''
else
filter := '';
grSearch.DataSource.DataSet.Filter := filter;
end;
procedure TfrmComakerSearch.SetReturn;
begin
with grSearch.DataSource.DataSet do
begin
cm.ID := (FieldByName('entity_id').AsString);
cm.Name := FieldByName('name').AsString;
cm.ComakeredLoans := FieldByName('comakered_loans').AsInteger;
end;
end;
procedure TfrmComakerSearch.Add;
begin
with TfrmComakerDetail.Create(self), grSearch.DataSource.DataSet do
begin
cm.Add;
ShowModal;
if ModalResult = mrOK then
begin
// refresh the grid
DisableControls;
Close;
Open;
EnableControls;
end;
end;
end;
procedure TfrmComakerSearch.Cancel;
begin
end;
end.
|
{ ******************************************************************************
*
* AV Catcher
*
* Description
* Log the Access violation to a log file and allow the user to copy
* the information into an email if needed.
*
*
*
*
* ****************************************************************************** }
unit AVCatcher;
interface
uses
Winapi.Windows, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
SHFolder, ShellAPI, Vcl.StdCtrls, Vcl.ExtCtrls,
ComObj, UExceptHook, Vcl.ImgList, Vcl.Imaging.pngimage, Data.Bind.EngExt, Vcl.Bind.DBEngExt, System.Rtti,
System.Bindings.Outputs, Data.Bind.Components, Vcl.Bind.Editors,
System.ImageList;
type
TAppExcept = class(TForm)
ImageList1: TImageList;
pnlBottom: TPanel;
btnLogFile: TButton;
btnLogEMail: TButton;
pnlTop: TPanel;
imgAV: TImage;
lblAVHeading: TLabel;
lblAVText: TLabel;
PnlDetailsMsg: TPanel;
lblDeatailTxt1: TLabel;
lblDeatailTxt2: TLabel;
pnlDetails: TPanel;
LogDetails: TMemo;
btnClose: TButton;
pnlBtns: TGridPanel;
btnCustom: TButton;
BindingsList1: TBindingsList;
BindExpression1: TBindExpression;
procedure lblDeatailTxt1Click(Sender: TObject);
procedure LogDetailsChange(Sender: TObject);
procedure FormCreate(Sender: TObject); // Shows the details panel
private
Function CalcWidthResize(): Integer;
public
end;
TAppException = procedure(Sender: TObject; E: Exception) of object;
IExceptionInterface = interface(IInterface)
['{72A771EF-0DDF-4D73-8F4E-FDEB86683F1E}']
function GetLogFileName(): String;
function GetDaysToPurge(): Integer;
procedure SetDaysToPurge(aValue: Integer);
function GetEmailTo(): TStringList;
procedure SetEmailTo(aValue: TStringList);
function GetEnabled(): Boolean;
procedure SetEnabled(aValue: Boolean);
function GetAppException(): TAppException;
procedure SetAppException(aValue: TAppException);
function GetAfterAppException(): TAppException;
procedure SetAfterAppException(aValue: TAppException);
function GetCustomMethod(): TNotifyEvent;
procedure SetCustomMethod(aValue: TNotifyEvent);
function GetTerminateApp(): Boolean;
procedure SetTerminateApp(aValue: Boolean);
function GetVisible(): Boolean;
procedure SetVisible(aValue: Boolean);
Procedure SetCustomBtn(aValue: string);
Property AVLogFile: String read GetLogFileName;
property DaysToPurge: Integer read GetDaysToPurge write SetDaysToPurge;
Property EmailTo: TStringList read GetEmailTo write SetEmailTo;
property Enabled: Boolean read GetEnabled write SetEnabled;
property OnAppException: TAppException read GetAppException
write SetAppException;
property OnAfterAppException: TAppException read GetAfterAppException
write SetAfterAppException;
property OnCustomMethod: TNotifyEvent read GetCustomMethod
write SetCustomMethod;
Property TerminateApp: Boolean read GetTerminateApp write SetTerminateApp;
Property Visible: Boolean read GetVisible write SetVisible;
Property CustomButtonCaption: string write SetCustomBtn;
end;
TExceptionLogger = class(TInterfacedObject, IExceptionInterface)
private
fAppException: TAppException;
fAfterAppException: TAppException;
fCustomAction: TNotifyEvent;
fAV_LogFileName: string; // Log file for the AV info
fCustomBtnCap: String;
fEmailTo: TStringList;
fEnabled: Boolean;
fExceptionForm: TAppExcept;
fDaysToPurge: Integer;
fVisible: Boolean;
fTerminateApp: Boolean;
procedure AppException(Sender: TObject; E: Exception);
// Inital way to call code
procedure CatchException(Sender: TObject; E: Exception);
// Creates blank email with log information in body
procedure EmailError(LogMessage: String);
// Sets up the log file for the AppData folder
function GetLogFileName(): String;
function GetDaysToPurge(): Integer;
procedure SetDaysToPurge(aValue: Integer);
function GetEmailTo(): TStringList;
procedure SetEmailTo(aValue: TStringList);
function GetEnabled(): Boolean;
procedure SetEnabled(aValue: Boolean);
function GetAppException(): TAppException;
procedure SetAppException(aValue: TAppException);
function GetAfterAppException(): TAppException;
procedure SetAfterAppException(aValue: TAppException);
function GetCustomMethod(): TNotifyEvent;
procedure SetCustomMethod(aValue: TNotifyEvent);
function GetTerminateApp(): Boolean;
procedure SetTerminateApp(aValue: Boolean);
function GetVisible(): Boolean;
procedure SetVisible(aValue: Boolean);
Procedure SetCustomBtn(aValue: string);
// function LeftPad(S: string; ch: char; Len: Integer): string;
// Writes error to log file (creates new files if needed)
procedure LogError(LogMessage: string);
function RightPad(S: string; ch: char; Len: Integer): string;
// Purges log files based on DaysToPurge const
Function ThePurge(): String;
public
constructor Create();
destructor Destroy(); override;
Property CustomButtonCaption: string write SetCustomBtn;
Property AVLogFile: String read GetLogFileName write fAV_LogFileName;
end;
function ExceptionLog: IExceptionInterface;
var
fExceptionLog: IExceptionInterface;
implementation
{$R *.dfm}
function ExceptionLog: IExceptionInterface;
begin
fExceptionLog.QueryInterface(IExceptionInterface, Result);
end;
{$REGION' CRC'}
const
{ copied from ORFn - table for calculating CRC values }
CRC32_TABLE: array[0..255] of DWORD =
($0, $77073096, $EE0E612C, $990951BA, $76DC419, $706AF48F, $E963A535, $9E6495A3,
$EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988, $9B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91,
$1DB71064, $6AB020F2, $F3B97148, $84BE41DE, $1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7,
$136C9856, $646BA8C0, $FD62F97A, $8A65C9EC, $14015C4F, $63066CD9, $FA0F3D63, $8D080DF5,
$3B6E20C8, $4C69105E, $D56041E4, $A2677172, $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B,
$35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59,
$26D930AC, $51DE003A, $C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F,
$2802B89E, $5F058808, $C60CD9B2, $B10BE924, $2F6F7C87, $58684C11, $C1611DAB, $B6662D3D,
$76DC4190, $1DB7106, $98D220BC, $EFD5102A, $71B18589, $6B6B51F, $9FBFE4A5, $E8B8D433,
$7807C9A2, $F00F934, $9609A88E, $E10E9818, $7F6A0DBB, $86D3D2D, $91646C97, $E6635C01,
$6B6B51F4, $1C6C6162, $856530D8, $F262004E, $6C0695ED, $1B01A57B, $8208F4C1, $F50FC457,
$65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65,
$4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2, $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB,
$4369E96A, $346ED9FC, $AD678846, $DA60B8D0, $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9,
$5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525, $206F85B3, $B966D409, $CE61E49F,
$5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD,
$EDB88320, $9ABFB3B6, $3B6E20C, $74B1D29A, $EAD54739, $9DD277AF, $4DB2615, $73DC1683,
$E3630B12, $94643B84, $D6D6A3E, $7A6A5AA8, $E40ECF0B, $9309FF9D, $A00AE27, $7D079EB1,
$F00F9344, $8708A3D2, $1E01F268, $6906C2FE, $F762575D, $806567CB, $196C3671, $6E6B06E7,
$FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC, $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5,
$D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B,
$D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79,
$CB61B38C, $BC66831A, $256FD2A0, $5268E236, $CC0C7795, $BB0B4703, $220216B9, $5505262F,
$C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04, $C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D,
$9B64C2B0, $EC63F226, $756AA39C, $26D930A, $9C0906A9, $EB0E363F, $72076785, $5005713,
$95BF4A82, $E2B87A14, $7BB12BAE, $CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7, $BDBDF21,
$86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777,
$88085AE6, $FF0F6A70, $66063BCA, $11010B5C, $8F659EFF, $F862AE69, $616BFFD3, $166CCF45,
$A00AE278, $D70DD2EE, $4E048354, $3903B3C2, $A7672661, $D06016F7, $4969474D, $3E6E77DB,
$AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9,
$BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605, $CDD70693, $54DE5729, $23D967BF,
$B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94, $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D);
{ returns a cyclic redundancy check for a string }
function UpdateCrc32(Value: DWORD; var Buffer: array of Byte; Count: Integer): DWORD;
var
i: integer;
begin
Result:=Value;
for i := 0 to Pred(Count) do
Result := ((Result shr 8) and $00FFFFFF) xor
CRC32_TABLE[(Result xor Buffer[i]) and $000000FF];
end;
function CRCForFile(AFileName: string): DWORD;
const
BUF_SIZE = 16383;
type
TBuffer = array[0..BUF_SIZE] of Byte;
var
Buffer: Pointer;
AHandle, BytesRead: Integer;
begin
Result:=$FFFFFFFF;
GetMem(Buffer, BUF_SIZE);
AHandle := FileOpen(AFileName, fmShareDenyWrite);
repeat
BytesRead := FileRead(AHandle, Buffer^, BUF_SIZE);
Result := UpdateCrc32(Result, TBuffer(Buffer^), BytesRead);
until BytesRead <> BUF_SIZE;
FileClose(AHandle);
FreeMem(Buffer);
Result := not Result;
end;
{$ENDREGION}
{$REGION' TExceptionLogger'}
// ==============================================================================
// DaysToPurge defines how long a log file can exist on the system. If/when a
// new exception happens all files older than the purge days will be deleted.
// ==============================================================================
constructor TExceptionLogger.Create();
begin
inherited;
fDaysToPurge := 60;
fEnabled := True;
fEmailTo := TStringList.Create;
fVisible := true;
fTerminateApp := false;
Application.OnException := AppException;
end;
destructor TExceptionLogger.Destroy();
begin
FreeAndNil(fEmailTo);
inherited;
end;
procedure TExceptionLogger.AppException(Sender: TObject; E: Exception);
begin
if Assigned(fAppException) then
fAppException(Sender, E);
if fEnabled then
CatchException(Sender, E)
else
Application.ShowException(E);
if assigned(fAfterAppException) and fEnabled then
fAfterAppException(Sender, E);
if fTerminateApp and (not Application.Terminated) then
Application.Terminate;
end;
procedure TExceptionLogger.CatchException(Sender: TObject; E: Exception);
// Inital way to call code
var
ErrLogString: TStringList;
function GetAppVersionStr: string;
var
Exe: string;
Size, Handle: DWORD;
Buffer: TBytes;
FixedPtr: PVSFixedFileInfo;
begin
Exe := ParamStr(0);
Size := GetFileVersionInfoSize(PChar(Exe), Handle);
if Size = 0 then
RaiseLastOSError;
SetLength(Buffer, Size);
if not GetFileVersionInfo(PChar(Exe), Handle, Size, Buffer) then
RaiseLastOSError;
if not VerQueryValue(Buffer, '\', Pointer(FixedPtr), Size) then
RaiseLastOSError;
Result := Format('%d.%d.%d.%d', [LongRec(FixedPtr.dwFileVersionMS).Hi,
// major
LongRec(FixedPtr.dwFileVersionMS).Lo, // minor
LongRec(FixedPtr.dwFileVersionLS).Hi, // release
LongRec(FixedPtr.dwFileVersionLS).Lo]) // build
end;
procedure GatherStackInfo(var OutList: TStringList);
begin
if not Assigned(OutList) then
exit;
OutList.Add(StringOfChar(' ', 15) + 'Application Information');
OutList.Add(RightPad('', '=', 50));
OutList.Add(RightPad('Name', ' ', 10) + ': ' +
ExtractFileName(Application.ExeName));
OutList.Add(RightPad('Version', ' ', 10) + ': ' + GetAppVersionStr);
OutList.Add(RightPad('CRC', ' ', 10) + ': ' +IntToHex(CRCForFile(Application.ExeName), 8));
OutList.Add('');
OutList.Add(StringOfChar(' ', 15) + 'Exception Information');
OutList.Add(RightPad('', '=', 50));
OutList.Add(RightPad('Date/Time', ' ', 10) + ': ' +
FormatDateTime('mm/dd/yyyy hh:mm:ss', now()));
OutList.Add(RightPad('Unit', ' ', 10) + ': ' + E.UnitName);
OutList.Add(RightPad('Class', ' ', 10) + ': ' + E.ClassName);
OutList.Add(RightPad('Message', ' ', 10) + ': ' + E.Message);
if E.ToString <> E.Message then
OutList.Add(RightPad('Text', ' ', 10) + ': ' + E.ToString);
OutList.Add('');
OutList.Add(StringOfChar(' ', 15) + 'Exception Trace');
OutList.Add(RightPad('', '=', 50));
OutList.Add(E.StackTrace);
// OutList.Add('');
// OutList.Add('');
end;
begin
try
ErrLogString := TStringList.Create();
try
GatherStackInfo(ErrLogString);
if fVisible then
begin
if not Application.Terminated then
begin
fExceptionForm := TAppExcept.Create(Application);
try
if fEmailTo.Count = 0 then
fExceptionForm.pnlBtns.ColumnCollection[2].Value := 0
else
fExceptionForm.pnlBtns.ColumnCollection[2].Value := 25;
if Assigned(fCustomAction) then
begin
fExceptionForm.pnlBtns.ColumnCollection[3].Value := 25;
fExceptionForm.btnCustom.Caption := fCustomBtnCap;
fExceptionForm.btnCustom.OnClick := fCustomAction;
end else
fExceptionForm.pnlBtns.ColumnCollection[3].Value := 0;
fExceptionForm.lblAVText.Caption := E.Message;
fExceptionForm.LogDetails.Lines.Clear;
fExceptionForm.LogDetails.Lines.text := ErrLogString.text;
fExceptionForm.ShowModal;
Screen.Cursor := crHourGlass;
try
LogError(ErrLogString.text);
// Log to email
if fExceptionForm.ModalResult = mrNo then
begin
EmailError(ErrLogString.text);
end;
finally
Screen.Cursor := crDefault;
end;
finally
fExceptionForm.Free;
end;
end else
LogError(ErrLogString.text);
end else
LogError(ErrLogString.text);
finally
ErrLogString.Free;
end;
except
// swallow
end;
end;
function TExceptionLogger.GetLogFileName(): String;
Var
OurLogFile, LocalOnly, AppDir, AppName: string;
// Finds the users special directory
function LocalAppDataPath: string;
const
SHGFP_TYPE_CURRENT = 0;
var
path: array [0 .. MAX_PATH] of char;
begin
SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, SHGFP_TYPE_CURRENT, @path[0]);
Result := StrPas(path);
end;
begin
if Trim(fAV_LogFileName) <> '' then
Result := fAV_LogFileName
else
begin
OurLogFile := LocalAppDataPath;
if (Copy(OurLogFile, Length(OurLogFile), 1) <> '\') then
OurLogFile := OurLogFile + '\';
LocalOnly := OurLogFile;
// Now set the application level
OurLogFile := OurLogFile + ExtractFileName(Application.ExeName);
if (Copy(OurLogFile, Length(OurLogFile), 1) <> '\') then
OurLogFile := OurLogFile + '\';
AppDir := OurLogFile;
// try to create or use base direcrtory
if not DirectoryExists(AppDir) then
if not ForceDirectories(AppDir) then
OurLogFile := LocalOnly;
// Get the application name
AppName := ExtractFileName(Application.ExeName);
AppName := Copy(AppName, 0, Pos('.', AppName) - 1);
OurLogFile := OurLogFile + AppName + '_' + IntToStr(GetCurrentProcessID) +
'_' + FormatDateTime('mm_dd_yy_hh_mm', now) + '_LOG.TXT';
fAV_LogFileName := OurLogFile;
Result := OurLogFile;
end;
end;
function TExceptionLogger.GetDaysToPurge(): Integer;
begin
Result := fDaysToPurge;
end;
procedure TExceptionLogger.SetDaysToPurge(aValue: Integer);
begin
fDaysToPurge := aValue;
end;
function TExceptionLogger.GetEmailTo(): TStringList;
begin
Result := fEmailTo;
end;
procedure TExceptionLogger.SetEmailTo(aValue: TStringList);
begin
fEmailTo := aValue;
end;
function TExceptionLogger.GetEnabled(): Boolean;
begin
Result := fEnabled;
end;
procedure TExceptionLogger.SetEnabled(aValue: Boolean);
begin
fEnabled := aValue;
end;
function TExceptionLogger.GetAppException(): TAppException;
begin
Result := fAppException;
end;
procedure TExceptionLogger.SetAppException(aValue: TAppException);
begin
fAppException := aValue;
end;
function TExceptionLogger.GetAfterAppException(): TAppException;
begin
Result := fAfterAppException;
end;
procedure TExceptionLogger.SetAfterAppException(aValue: TAppException);
begin
fAfterAppException := aValue;
end;
function TExceptionLogger.GetCustomMethod(): TNotifyEvent;
begin
Result := fCustomAction;
end;
procedure TExceptionLogger.SetCustomMethod(aValue: TNotifyEvent);
begin
fCustomAction := aValue;
end;
function TExceptionLogger.GetTerminateApp(): Boolean;
begin
Result := fTerminateApp;
end;
procedure TExceptionLogger.SetTerminateApp(aValue: Boolean);
begin
fTerminateApp := aValue;
end;
function TExceptionLogger.GetVisible(): Boolean;
begin
Result := fVisible;
end;
procedure TExceptionLogger.SetVisible(aValue: Boolean);
begin
fVisible := aValue;
end;
Procedure TExceptionLogger.SetCustomBtn(aValue: string);
begin
fCustomBtnCap := aValue;
end;
Function TExceptionLogger.ThePurge(): String;
const
aFileMask = '*_LOG.txt';
var
searchResult: TSearchRec;
iDelCnt, iErrorCnt, iFile: Integer;
dtFileDate, dtNow: TDateTime;
sFilePath: string;
begin
// Init variables
iDelCnt := 0;
iErrorCnt := 0;
dtNow := Date;
sFilePath := ExtractFilePath(AVLogFile);
// Loop through dir looking for the files
iFile := FindFirst(sFilePath + aFileMask, faAnyFile, searchResult);
while iFile = 0 do
begin
// Make sure we are on a file and not a directory
if (searchResult.Name <> '.') and (searchResult.Name <> '..') and
((searchResult.Attr and faDirectory) <> faDirectory) then
begin
// Check the date of the file
dtFileDate := searchResult.TimeStamp;
if trunc(dtNow - dtFileDate) + 1 > fDaysToPurge then
begin
// Try to delete and update the count as needed
if not DeleteFile(sFilePath + searchResult.Name) then
Inc(iErrorCnt)
else
Inc(iDelCnt);
end;
end;
// Grab the next file
iFile := FindNext(searchResult);
end;
// Free up memory allocation
FindClose(searchResult);
// If any files were purged or errored then add this to the return message
if (iErrorCnt > 0) or (iDelCnt > 0) then
begin
Result := (StringOfChar(' ', 15) + 'Log Purge Information');
Result := Result + #13#10 + (RightPad('', '=', 50));
Result := Result + #13#10 + (RightPad('Days:', ' ', 10) + ': ' +
IntToStr(fDaysToPurge));
Result := Result + #13#10 + (RightPad('Purged', ' ', 10) + ': ' +
IntToStr(iDelCnt));
Result := Result + #13#10 + (RightPad('NA', ' ', 10) + ': ' +
IntToStr(iErrorCnt));
Result := Result + #13#10 + #13#10;
end
else
Result := '';
end;
procedure TExceptionLogger.LogError(LogMessage: string);
var
myFile: TextFile;
begin
// Clean the old dir on first run
if Trim(fAV_LogFileName) = '' then
LogMessage := ThePurge + LogMessage;
// Asign our file
AssignFile(myFile, AVLogFile);
if FileExists(AVLogFile) then
Append(myFile)
else
ReWrite(myFile);
// Write this final line
WriteLn(myFile, LogMessage);
CloseFile(myFile);
// Old code that would open file explorer to the log directory
{ if MessageDlg('Error logged, do you wish to navigate to the file?',
mtInformation, [mbYes, mbNo], -1) = mrYes then
ShellExecute(0, nil, 'explorer.exe', PChar('/select,' + CPRS_LogFileName),
nil, SW_SHOWNORMAL); }
end;
Procedure TExceptionLogger.EmailError(LogMessage: string);
const
CannedBdy =
'An access violation has occurred. Log file as follows (also attached to the email)';
var
EmailUsrs, TmpStr: string;
function EncodeURIComponent(const ASrc: string): string;
const
HexMap: string = '0123456789ABCDEF';
function IsSafeChar(ch: Byte): Boolean;
begin
if (ch >= 48) and (ch <= 57) then
Result := True // 0-9
else if (ch >= 65) and (ch <= 90) then
Result := True // A-Z
else if (ch >= 97) and (ch <= 122) then
Result := True // a-z
else if (ch = 33) then
Result := True // !
else if (ch >= 39) and (ch <= 42) then
Result := True // '()*
else if (ch >= 45) and (ch <= 46) then
Result := True // -.
else if (ch = 95) then
Result := True // _
else if (ch = 126) then
Result := True // ~
else
Result := False;
end;
var
I, J: Integer;
Bytes: TBytes;
begin
Result := '';
Bytes := TEncoding.UTF8.GetBytes(ASrc);
I := 0;
J := Low(Result);
SetLength(Result, Length(Bytes) * 3); // space to %xx encode every byte
while I < Length(Bytes) do
begin
if IsSafeChar(Bytes[I]) then
begin
Result[J] := char(Bytes[I]);
Inc(J);
end
else
begin
Result[J] := '%';
Result[J + 1] := HexMap[(Bytes[I] shr 4) + Low(ASrc)];
Result[J + 2] := HexMap[(Bytes[I] and 15) + Low(ASrc)];
Inc(J, 3);
end;
Inc(I);
end;
SetLength(Result, J - Low(ASrc));
end;
procedure SendMail(Subject, Body, RecvAddress, Attachs: string);
const
olMailItem = 0;
var
Outlook: OLEVariant;
MailItem: Variant;
MailInspector: Variant;
stringlist: TStringList;
begin
try
Outlook := GetActiveOleObject('Outlook.Application');
except
Outlook := CreateOleObject('Outlook.Application');
end;
stringlist := TStringList.Create;
try
MailItem := Outlook.CreateItem(olMailItem);
MailItem.Subject := Subject;
MailItem.Recipients.Add(RecvAddress);
MailItem.Attachments.Add(Attachs);
stringlist := TStringList.Create;
stringlist.Add(Body);
MailItem.Body := stringlist.text;
MailInspector := MailItem.GetInspector;
MailInspector.display(false); // true means modal
finally
Outlook := Unassigned;
stringlist.Free;
end;
end;
begin
// Need to figure out the ole object method
// fEmailTo.Delimiter := ';';
EmailUsrs := '';
for TmpStr in fEmailTo do
begin
if (EmailUsrs <> '') then
EmailUsrs := EmailUsrs + '; ';
EmailUsrs := EmailUsrs + TmpStr;
end;
SendMail('Error logged in ' + ExtractFileName(Application.ExeName),
CannedBdy + #13#10 + #13#10 + LogMessage, EmailUsrs, AVLogFile);
end;
function TExceptionLogger.RightPad(S: string; ch: char; Len: Integer): string;
var
RestLen: Integer;
begin
Result := S;
RestLen := Len - Length(S);
if RestLen < 1 then
exit;
Result := S + StringOfChar(ch, RestLen);
end;
{
function TExceptionLogger.LeftPad(S: string; ch: char; Len: Integer): string;
var
RestLen: Integer;
begin
Result := S;
RestLen := Len - Length(S);
if RestLen < 1 then
Exit;
Result := StringOfChar(ch, RestLen) + S;
end;
}
{$ENDREGION}
{$REGION 'TAppExcept'}
procedure TAppExcept.FormCreate(Sender: TObject);
begin
SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_APPWINDOW);
end;
procedure TAppExcept.lblDeatailTxt1Click(Sender: TObject);
var
NewWidth: Integer;
begin
Self.AutoSize := false;
try
NewWidth := CalcWidthResize;
//Ensure that the width and height dont go past the screen
if screen.DesktopWidth > (self.Width + NewWidth) then
Self.Width := self.Width + NewWidth;
if screen.DesktopHeight < (Self.Height) then
Self.Height := screen.DesktopHeight;
finally
Self.AutoSize := true;
end;
pnlDetails.Visible := True;
end;
procedure TAppExcept.LogDetailsChange(Sender: TObject);
begin
BindingsList1.Notify(Sender, '');
end;
Function TAppExcept.CalcWidthResize(): Integer;
var
DC: HDC;
CacheFont : HFont;
I, LineCharCnt, LongLineIDX: Integer;
LngLineText: String;
TextSize: TSize;
begin
DC := GetDC(Logdetails.Handle);
try
CacheFont := SelectObject(DC, Logdetails.Font.Handle);
try
LngLineText := '';
LongLineIDX := -1;
LineCharCnt := 0;
LngLineText := '';
for I := 0 to Logdetails.Lines.Count - 0 do
begin
if Length(LogDetails.Lines[i]) > LineCharCnt then
begin
LineCharCnt := Length(LogDetails.Lines[i]);
LongLineIDX := I;
end;
end;
LngLineText := LogDetails.Lines[LongLineIDX];
GetTextExtentPoint32(DC, PChar(LngLineText), Length(LngLineText), TextSize);
Result := TextSize.cx - (self.Width) + 100;
finally
SelectObject(DC, CacheFont);
end;
finally
ReleaseDC(Logdetails.Handle, DC);
end;
end;
{$ENDREGION 'Private'}
INITIALIZATION
TExceptionLogger.Create.GetInterface(IExceptionInterface, fExceptionLog);
StartExceptionStackMonitoring;
finalization
StopExceptionStackMonitoring;
end.
|
////////////////////////////////////////////////////////////////////////////////
// //
// File : MainFrm.pas //
// Date : 05-03-2009 //
// Threads and GUI DEMO by Jens Borrisholt //
// //
////////////////////////////////////////////////////////////////////////////////
{
Synchronizing Threads and GUI in Delphi application
http://delphi.about.com/od/kbthread/a/thread-gui.htm
}
unit MainU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ExtCtrls;
type
TButton = class(StdCtrls.TButton)
OwnedThread: TThread;
ProgressBar: TProgressBar;
end;
TMyThread = class(TThread)
private
FCounter: Integer;
FCountTo: Integer;
FProgressBar: TProgressBar;
FOwnerButton: TButton;
procedure DoProgress;
procedure SetCountTo(const Value: Integer);
procedure SetProgressBar(const Value: TProgressBar);
procedure SetOwnerButton(const Value: TButton);
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean);
property CountTo: Integer read FCountTo write SetCountTo;
property ProgressBar: TProgressBar read FProgressBar write SetProgressBar;
property OwnerButton: TButton read FOwnerButton write SetOwnerButton;
end;
TMainForm = class(TForm)
Button1: TButton;
ProgressBar1: TProgressBar;
Button2: TButton;
ProgressBar2: TProgressBar;
Button3: TButton;
ProgressBar3: TProgressBar;
Button4: TButton;
ProgressBar4: TProgressBar;
Button5: TButton;
ProgressBar5: TProgressBar;
procedure Button1Click(Sender: TObject);
private
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
{ TMyThread }
constructor TMyThread.Create(CreateSuspended: Boolean);
begin
inherited;
FCounter := 0;
FCountTo := MAXINT;
end;
procedure TMyThread.DoProgress;
var
PctDone: Extended;
begin
PctDone := (FCounter / FCountTo);
FProgressBar.Position := Round(FProgressBar.Step * PctDone);
FOwnerButton.Caption := FormatFloat('0.00 %', PctDone * 100);
end;
procedure TMyThread.Execute;
const
Interval = 1000000;
begin
FreeOnTerminate := True;
FProgressBar.Max := FCountTo div Interval;
FProgressBar.Step := FProgressBar.Max;
while FCounter < FCountTo do
begin
if FCounter mod Interval = 0 then
Synchronize(DoProgress);
Inc(FCounter);
end;
FOwnerButton.Caption := 'Start';
FOwnerButton.OwnedThread := nil;
FProgressBar.Position := FProgressBar.Max;
end;
procedure TMyThread.SetCountTo(const Value: Integer);
begin
FCountTo := Value;
end;
procedure TMyThread.SetOwnerButton(const Value: TButton);
begin
FOwnerButton := Value;
end;
procedure TMyThread.SetProgressBar(const Value: TProgressBar);
begin
FProgressBar := Value;
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
aButton: TButton;
aThread: TMyThread;
aProgressBar: TProgressBar;
begin
aButton := TButton(Sender);
if not Assigned(aButton.OwnedThread) then
begin
aThread := TMyThread.Create(True);
aButton.OwnedThread := aThread;
aProgressBar := TProgressBar(
FindComponent(
StringReplace(
aButton.Name, 'Button', 'ProgressBar', []
)
)
);
aThread.ProgressBar := aProgressBar;
aThread.OwnerButton := aButton;
aThread.Resume;
aButton.Caption := 'Pause';
end
else
begin
if aButton.OwnedThread.Suspended then
aButton.OwnedThread.Resume
else
aButton.OwnedThread.Suspend;
aButton.Caption := 'Run';
end;
end;
end.
|
unit ncPRBaseClasses;
{
ResourceString: Dario 13/03/13
}
interface
uses
ExtCtrls, SysUtils, Classes, Controls, Forms, Graphics, StdCtrls, messages;
const
kNaoImprimir = 'N Ã O I M P R I M I R';
//kPrintThumbsPanel = $00737373;
kPrintThumbsPanelColor = clBtnFace;
kCarregando = 'Carregando...';
kThumbSelectedColor = clNavy;
kPrintBmpsPanelColor = $009E9E9E;
kBmpSelectedColor = clNavy;
kScrollPage = 36;
kMaxMsgRetry = 20;
kMsgRetrySleep = 5;
kMaxReadRetries = 2;
kFirstReadTimeout = 15000;
kReadInterval = 250;
kStartLoadAtOnce = 4;
kResamplerCN = 'TNearestResampler';
THMSG_Load = WM_USER + 11;
THMSG_LoadBMP = WM_USER + 30;
THMSG_SetThumbCount = WM_USER + 40;
THMSG_SetThumbSizes = WM_USER + 41;
THMSG_ThumbLoad = WM_USER + 43;
THMSG_Repaginar = WM_USER + 50;
type
TCanvasHack = class ( TGraphicControl )
public
property Canvas;
end;
TImageR = class ( TImage )
protected
procedure Paint; override;
procedure ReloadBitmap;
function ShadowBmp: graphics.TBitmap;
function DontPrintBmp: graphics.TBitmap;
function NaoImprimir: Boolean;
end;
TLabel2 = class(TLabel)
protected
function getPageNum: integer;
public
property PageNum : integer read getPageNum;
constructor Create(AOwner: TComponent); override;
end;
TPanel = class(ExtCtrls.TPanel)
public
property Canvas;
end;
TImagemPanel = class(TPanel)
private
fImg : TImage;
fSelected : boolean;
fPageNum : integer;
procedure CreateImg;
procedure DestroyImg;
procedure RefreshLB;
function GetCorFundo: TColor; virtual; abstract;
function GetNaoImprimir: boolean;
procedure SetPageNum(const Value: Integer);
protected
procedure SetSelected(value: boolean); virtual;
procedure Paint; override;
function DontPrintBmp: graphics.TBitmap;
function ShadowBmp: graphics.TBitmap;
procedure wmReloadImg(var Message: TMessage); message wm_user + 1;
public
lb : TLabel2;
property PageNum: Integer
read FPageNum write SetPageNum;
property NaoImprimir : boolean read GetNaoImprimir;
property Selected : boolean read fSelected write SetSelected;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetSelectedCustom(Value: Boolean; aScroll: Boolean);
procedure Reload;
procedure Load(aBmp: graphics.TBitmap);
procedure Unload;
end;
TPagePanel = class(TImagemPanel)
private
function GetCorFundo: TColor; override;
end;
TThumbPanel = class(TImagemPanel)
private
function GetCorFundo: TColor; override;
protected
procedure SetSelected(value: boolean); override;
end;
TThumbPanelList = class(TList)
protected
function Get(Index: Integer): TThumbPanel;
procedure Put(Index: Integer; Item: TThumbPanel);
public
procedure Clear; override;
property Items[Index: Integer]: TThumbPanel read Get write Put; default;
destructor Destroy; override;
end;
TPagePanelList = class(TList)
protected
function Get(Index: Integer): TPagePanel;
procedure Put(Index: Integer; Item: TPagePanel);
public
procedure Clear; override;
property Items[Index: Integer]: TPagePanel read Get write Put; default;
destructor Destroy; override;
end;
implementation
uses
jpeg,
Windows,
madGraphics,
ncPRImagesScrollBox,
ncPRPagesScrollBox,
{$IFNDEF NOLOG}
uLogs,
{$ENDIF}
ncPRThumbsScrollBox;
// START resource string wizard section
resourcestring
SCarregando = ' - Carregando';
// END resource string wizard section
{ TPagePanel }
function TPagePanel.GetCorFundo: TColor;
begin
Result := kPrintBmpsPanelColor;
end;
{ TImagemPanel }
constructor TImagemPanel.Create(AOwner: TComponent);
begin
inherited;
fSelected := False;
fImg := nil;
lb := TLabel2.create(Self);
lb.Top := 0;
lb.Left := kBmpBorderWidth;
lb.AlignWithMargins := True;
lb.Margins.Left := kBmpBorderWidth;
lb.Margins.Top := kBmpBorderWidth;
lb.Margins.Right := kBmpBorderWidth;
lb.Margins.Bottom := kBmpBorderWidth;
lb.font.color := clNavy;
lb.font.name := 'Verdana'; // do not localize
lb.font.size := 18;
lb.font.Style := [fsBold];
lb.Parent := Self;
end;
procedure TImagemPanel.CreateImg;
begin
if fImg=nil then begin
fImg := TImageR.create(Self);
fImg.Tag := Tag;
fImg.Stretch := True;
fImg.Proportional := True;
fImg.Parent := Self;
fImg.AlignWithMargins := True;
fImg.Margins.Left := kBmpBorderWidth;
fImg.Margins.Top := kBmpBorderWidth;
fImg.Margins.Right := kBmpBorderWidth;
fImg.Margins.Bottom := kBmpBorderWidth;
fImg.Align := alClient;
fImg.OnClick := OnClick;
fImg.OnDblClick := OnDblClick;
fImg.Cursor := crHandPoint;
lb.BringToFront;
end;
RefreshLB;
end;
destructor TImagemPanel.Destroy;
begin
DestroyImg;
lb.Free;
inherited;
end;
procedure TImagemPanel.DestroyImg;
begin
if Assigned(FImg) then begin
try FImg.Free; except end;
FImg := nil;
end;
RefreshLB;
end;
function TImagemPanel.DontPrintBmp: graphics.TBitmap;
begin
Result := TImagesScrollBox(Parent).DontPrintBmp;
end;
function TImagemPanel.GetNaoImprimir: boolean;
begin
if Parent=nil then
Result := False else
Result := TImagesScrollBox(Parent).NaoImprimir(PageNum);
end;
procedure TImagemPanel.Load(aBmp: graphics.TBitmap);
begin
CreateImg;
FImg.Picture.Bitmap := aBmp;
Invalidate;
end;
procedure TImagemPanel.Paint;
var
SaveMode: TCopyMode;
DestRect : TRect;
begin
inherited;
if NaoImprimir and (not Assigned(FImg)) then begin
SaveMode := Canvas.CopyMode;
try
DestRect := GetClientRect;
Canvas.CopyMode := cmSrcAnd;
Canvas.StretchDraw(DestRect, ShadowBmp);
Canvas.CopyMode := cmMergeCopy;
Canvas.StretchDraw(DestRect, DontPrintBmp);
finally
Canvas.CopyMode := SaveMode;
end;
end;
end;
procedure TImagemPanel.RefreshLB;
begin
if FImg=nil then begin
lb.Align := alClient;
lb.Caption := IntToStr(FPageNum) + SCarregando;
lb.Transparent := False;
lb.Color := $00EEEEEE;
lb.Font.Color := clGray;
lb.Top := kBmpLabelPos;
lb.Left := kBmpLabelPos;
end else begin
lb.Font.Color := clNavy;
lb.Align := alNone;
lb.Caption := IntToStr(FPageNum);
lb.Transparent := True;
end;
end;
procedure TImagemPanel.Reload;
begin
Invalidate;
end;
procedure TImagemPanel.wmReloadImg(var Message: TMessage);
begin
try
gLog.Log(Self, [lcTrace], 'ReloadImg - 1'); // do not localize
if FImg<>nil then begin
gLog.Log(Self, [lcTrace], 'ReloadImg - 2'); // do not localize
FImg.Picture.Assign(graphics.TBitmap(Message.WParam));
FImg.Invalidate;
end;
except
end;
try graphics.TBitmap(Message.WParam).Free; except end;
end;
procedure TImagemPanel.Unload;
begin
DestroyImg;
GLog.Log(self,[lcTrace], 'Unload '+inttostr(PageNum)); // do not localize
end;
procedure TImagemPanel.SetPageNum(const Value: Integer);
begin
FPageNum := Value;
Tag := Value;
if Assigned(FImg) then FImg.Tag := Value;
RefreshLB;
end;
procedure TImagemPanel.SetSelected(value: boolean);
begin
SetSelectedCustom(Value, True);
end;
procedure TImagemPanel.SetSelectedCustom(Value, aScroll: Boolean);
begin
if value<>fSelected then begin
fSelected := value;
if (fSelected) then begin
color := kThumbSelectedColor;
if aScroll and (Parent<>nil) then begin
TScrollBox(Parent).ScrollInView(self);
TScrollBox(Parent).ScrollInView(lb);
end;
end else
color := GetCorFundo;
end;
end;
function TImagemPanel.ShadowBmp: graphics.TBitmap;
begin
Result := TImagesScrollBox(Parent).ShadowBmp;
end;
{ TThumbPanel }
function TThumbPanel.GetCorFundo: TColor;
begin
Result := kPrintThumbsPanelColor;
end;
procedure TThumbPanel.SetSelected(value: boolean);
begin
if value<>fSelected then begin
inherited;
if (fSelected) and (Parent<>nil) then
TScrollBox(Parent).ScrollInView(lb);
end;
end;
{ TLabel2 }
constructor TLabel2.Create(AOwner: TComponent);
begin
inherited;
Height := kLabelHeight;
end;
function TLabel2.getPageNum: integer;
begin
result := TImagemPanel(owner).PageNum;
end;
{ TThumbPanelList }
destructor TThumbPanelList.Destroy;
begin
Clear;
inherited;
end;
procedure TThumbPanelList.Clear;
var
i : integer;
begin
for i:=count-1 downto 0 do
Get(i).free;
count := 0;
end;
function TThumbPanelList.Get(Index: Integer): TThumbPanel;
begin
result := inherited Get(Index);
end;
procedure TThumbPanelList.Put(Index: Integer; Item: TThumbPanel);
begin
inherited Put(Index, Item);
end;
{ TPagePanelList }
procedure TPagePanelList.Clear;
var
i : integer;
begin
for i:=count-1 downto 0 do
Get(i).free;
count := 0;
end;
destructor TPagePanelList.Destroy;
begin
Clear;
inherited;
end;
function TPagePanelList.Get(Index: Integer): TPagePanel;
begin
result := inherited Get(Index);
end;
procedure TPagePanelList.Put(Index: Integer; Item: TPagePanel);
begin
inherited Put(Index, Item);
end;
{ TImageR }
function TImageR.DontPrintBmp: graphics.TBitmap;
begin
Result := TImagemPanel(Parent).DontPrintBmp;
end;
function TImageR.NaoImprimir: Boolean;
begin
Result := TImagemPanel(Parent).NaoImprimir;
end;
type
TThreadReload = Class ( TThread )
private
FArq : String;
FHWND : HWND;
FWidth : Integer;
FHeight : Integer;
protected
procedure Execute; override;
public
constructor Create(aArq: String; aHWND: HWND; aWidth, aHeight: Integer);
end;
TThreadStretch = Class ( TThread )
private
FBmp : graphics.TBitmap;
FHWND : HWND;
FWidth : Integer;
FHeight : Integer;
protected
procedure Execute; override;
public
constructor Create(aBmp: graphics.TBitmap; aHWND: HWND; aWidth, aHeight: Integer);
end;
procedure TImageR.Paint;
var
SaveMode: TCopyMode;
begin
if Width <> Picture.Width then begin
if Width > Picture.Width then begin
gLog.Log(Self, [lcTrace], 'Paint - Need Reload'); // do not localize
TThreadReload.Create(TPagesScrollBox(Parent.Parent).PageFileName(Tag), Parent.Handle, Width, Height);
end else begin
// TThreadStretch.Create(Picture.Bitmap, Parent.Handle, Width, Height);
gLog.Log(Self, [lcTrace], 'Paint - StretchBitmap'); // do not localize
StretchBitmap(Picture.Bitmap, nil, Width, Height, sqVeryHigh);
gLog.Log(Self, [lcTrace], 'Paint - StretchBitmap - Done'); // do not localize
end;
end;
inherited;
gLog.Log(Self, [lcTrace], 'Paint - 1'); // do not localize
if NaoImprimir then begin
SaveMode := TCanvasHack(Self).Canvas.CopyMode;
try
TCanvasHack(Self).Canvas.CopyMode := cmSrcAnd;
TCanvasHack(Self).Canvas.StretchDraw(DestRect, ShadowBmp);
TCanvasHack(Self).Canvas.CopyMode := cmMergeCopy;
TCanvasHack(Self).Canvas.StretchDraw(DestRect, DontPrintBmp);
finally
TCanvasHack(Self).Canvas.CopyMode := SaveMode;
end;
end;
end;
procedure TImageR.ReloadBitmap;
begin
gLog.Log(Self, [lcTrace], 'ReloadBitmap - Tag: ' + IntToStr(Tag)); // do not localize
TPagesScrollBox(Parent.Parent).Requisitar(Tag, Tag, True);
end;
function TImageR.ShadowBmp: graphics.TBitmap;
begin
Result := TImagemPanel(Parent).ShadowBmp;
end;
{ TThreadReload }
constructor TThreadReload.Create(aArq: String; aHWND : HWND; aWidth, aHeight: Integer);
begin
FArq := aArq;
FHWND := aHWND;
FWidth := aWidth;
FHeight := aHeight;
inherited Create(True);
FreeOnTerminate := True;
Priority := tpLowest;
Resume;
end;
procedure TThreadReload.Execute;
var
j : TjpegImage;
b : graphics.TBitmap;
begin
try
gLog.Log(Self, [lcTrace], 'Execute - FArq: '+FArq); // do not localize
J := TjpegImage.Create;
b := graphics.TBitmap.Create;
try
J.LoadFromFile(FArq);
B.Assign(J);
StretchBitmap(B, nil, FWidth, FHeight, sqVeryHigh);
PostMessage(FHWND, wm_user+1, WParam(B), 0);
except
b.free;
end;
J.Free;
except
end;
end;
{ TThreadStretch }
constructor TThreadStretch.Create(aBmp: graphics.TBitmap; aHWND: HWND; aWidth,
aHeight: Integer);
begin
FBmp := graphics.TBitmap.Create;
FBmp.Assign(aBmp);
FHWND := aHWND;
FWidth := aWidth;
FHeight := aHeight;
inherited Create(True);
Priority := tpLowest;
FreeOnTerminate := True;
Resume;
end;
procedure TThreadStretch.Execute;
begin
try
StretchBitmap(FBmp, nil, FWidth, FHeight, sqVeryHigh);
PostMessage(FHWND, wm_user+1, WParam(FBmp), 0);
except
end;
end;
end.
|
unit GrievanceUtilitys;
interface
uses DB, DBTables, Tabs, Classes, Dialogs, SysUtils, Windows, PASTypes, RPBase,
RPDBUtil, RPDefine;
Procedure SetPetitionerNameAndAddress(MainTable : TTable;
LawyerCodeTable : TTable;
LawyerCode : String);
Procedure SetAttorneyNameAndAddress(MainTable : TTable;
LawyerCodeTable : TTable;
LawyerCode : String);
Function DetermineGrievanceYear : String;
Procedure DetermineGrantedValues( GrievanceResultsTable : TTable;
var GrantedLandValue : LongInt;
var GrantedTotalValue : LongInt;
var GrantedExemptionAmount : LongInt;
var GrantedExemptionPercent : Double;
var GrantedExemptionCode : String);
Procedure MoveGrantedValuesToMainParcel(OrigGrantedLandValue : LongInt;
OrigGrantedTotalValue : LongInt;
OrigGrantedExemptionAmount : LongInt;
OrigGrantedExemptionPercent : Double;
OrigGrantedExemptionCode : String;
NewGrantedLandValue : LongInt;
NewGrantedTotalValue : LongInt;
NewGrantedExemptionAmount : LongInt;
NewGrantedExemptionPercent : Double;
NewGrantedExemptionCode : String;
GrievanceProcessingType : Integer;
SwisSBLKey : String;
GrievanceYear : String;
ParcelTabSet : TTabSet;
TabTypeList : TStringList;
GrievanceNumber : Integer;
ResultNumber : Integer;
Disposition : String;
DecisionDate : String;
UpdatedInBulkJob : Boolean;
ShowMessage : Boolean;
AutomaticallyMoveWhollyExemptsToRS8 : Boolean;
FreezeAssessment : Boolean;
var NowWhollyExempt : Boolean;
var Updated : Boolean;
var ErrorMessage : String;
var LandValueChange : Comp;
var TotalValueChange : Comp;
var CountyTaxableChange : Comp;
var TownTaxableChange : Comp;
var SchoolTaxableChange : Comp;
var VillageTaxableChange : Comp);
Function GetGrievanceStatus( GrievanceTable : TTable;
GrievanceExemptionsAskedTable : TTable;
GrievanceResultsTable : TTable;
GrievanceDispositionCodeTable : TTable;
GrievanceYear : String;
SwisSBLKey : String;
ShortDescription : Boolean;
var StatusStr : String) : Integer;
Function GetGrievanceNumberToDisplay(GrievanceTable : TTable) : String;
Function GetCert_Or_SmallClaimStatus( Table : TTable;
var StatusCode : Integer) : String;
Function CopyGrievanceToCert_Or_SmallClaim(IndexNumber : LongInt;
GrievanceNumber : Integer;
CurrentYear : String;
PriorYear : String;
SwisSBLKey : String;
LawyerCode : String;
NumberOfParcels : Integer;
GrievanceTable,
DestinationTable,
LawyerCodeTable,
ParcelTable,
CurrentAssessmentTable,
PriorAssessmentTable,
SwisCodeTable,
PriorSwisCodeTable,
CurrentExemptionsTable,
DestinationExemptionsTable,
CurrentSpecialDistrictsTable,
DestinationSpecialDistrictsTable,
CurrentSalesTable,
DestinationSalesTable,
GrievanceExemptionsAskedTable,
DestinationExemptionsAskedTable,
GrievanceResultsTable,
GrievanceDispositionCodeTable : TTable;
Source : Char {(C)ert or (S)mall claim}) : Boolean;
Function IsGrievance_SmallClaims_CertiorariScreen(ScreenName : String) : Boolean;
Function UserCanViewGrievance_SmallClaims_CertiorariInformation(ScreenName : String) : Boolean;
Procedure InitGrievanceTotalsRecord(var TotalsRec : GrievanceTotalsRecord);
Procedure UpdateSmallClaims_Certiorari_TotalsRecord(var TotalsRec : GrievanceTotalsRecord;
Status : Integer);
Procedure UpdateGrievanceTotalsRecord(var TotalsRec : GrievanceTotalsRecord;
Status : Integer);
Procedure PrintGrievanceTotals(Sender : TObject;
TotalsRec : GrievanceTotalsRecord);
Function ParcelHasOpenCertiorari(tbCertiorari : TTable;
sSwisSBLKey : String) : Boolean;
implementation
uses
Types, Utilitys, PASUtils, GlblCnst, GlblVars, WinUtils,
UtilRTot, UtilEXSD, UtilPRCL, DataAccessUnit;
{===============================================================}
Procedure SetPetitionerNameAndAddress(MainTable : TTable;
LawyerCodeTable : TTable;
LawyerCode : String);
begin
If FindKeyOld(LawyerCodeTable, ['Code'], [LawyerCode])
then
begin
MainTable.FieldByName('PetitName1').Text := LawyerCodeTable.FieldByName('Name1').Text;
MainTable.FieldByName('PetitName2').Text := LawyerCodeTable.FieldByName('Name2').Text;
MainTable.FieldByName('PetitAddress1').Text := LawyerCodeTable.FieldByName('Address1').Text;
MainTable.FieldByName('PetitAddress2').Text := LawyerCodeTable.FieldByName('Address2').Text;
MainTable.FieldByName('PetitStreet').Text := LawyerCodeTable.FieldByName('Street').Text;
MainTable.FieldByName('PetitCity').Text := LawyerCodeTable.FieldByName('City').Text;
MainTable.FieldByName('PetitState').Text := LawyerCodeTable.FieldByName('State').Text;
MainTable.FieldByName('PetitZip').Text := LawyerCodeTable.FieldByName('Zip').Text;
MainTable.FieldByName('PetitZipPlus4').Text := LawyerCodeTable.FieldByName('ZipPlus4').Text;
MainTable.FieldByName('PetitPhoneNumber').Text := LawyerCodeTable.FieldByName('PhoneNumber').Text;
try
MainTable.FieldByName('PetitFaxNumber').Text := LawyerCodeTable.FieldByName('FaxNumber').Text;
MainTable.FieldByName('PetitAttorneyName').Text := LawyerCodeTable.FieldByName('AttorneyName').Text;
MainTable.FieldByName('PetitEmail').Text := LawyerCodeTable.FieldByName('Email').Text;
except
end;
end
else MessageDlg('Error finding lawyer code ' + LawyerCode + '.', mtError, [mbOK], 0);
end; {SetPetitionerNameAndAddress}
{===============================================================}
Procedure SetAttorneyNameAndAddress(MainTable : TTable;
LawyerCodeTable : TTable;
LawyerCode : String);
begin
If FindKeyOld(LawyerCodeTable, ['Code'], [LawyerCode])
then
begin
MainTable.FieldByName('AttyName1').Text := LawyerCodeTable.FieldByName('Name1').Text;
MainTable.FieldByName('AttyName2').Text := LawyerCodeTable.FieldByName('Name2').Text;
MainTable.FieldByName('AttyAddress1').Text := LawyerCodeTable.FieldByName('Address1').Text;
MainTable.FieldByName('AttyAddress2').Text := LawyerCodeTable.FieldByName('Address2').Text;
MainTable.FieldByName('AttyStreet').Text := LawyerCodeTable.FieldByName('Street').Text;
MainTable.FieldByName('AttyCity').Text := LawyerCodeTable.FieldByName('City').Text;
MainTable.FieldByName('AttyState').Text := LawyerCodeTable.FieldByName('State').Text;
MainTable.FieldByName('AttyZip').Text := LawyerCodeTable.FieldByName('Zip').Text;
MainTable.FieldByName('AttyZipPlus4').Text := LawyerCodeTable.FieldByName('ZipPlus4').Text;
MainTable.FieldByName('AttyPhoneNumber').Text := LawyerCodeTable.FieldByName('PhoneNumber').Text;
try
MainTable.FieldByName('AttyFaxNumber').Text := LawyerCodeTable.FieldByName('FaxNumber').Text;
MainTable.FieldByName('AttyAttorneyName').Text := LawyerCodeTable.FieldByName('AttorneyName').Text;
MainTable.FieldByName('AttyEmail').Text := LawyerCodeTable.FieldByName('Email').Text;
except
end;
end
else MessageDlg('Error finding lawyer code ' + LawyerCode + '.', mtError, [mbOK], 0);
end; {SetPetitionerNameAndAddress}
{===================================================================}
{=================== GRIEVANCE ===================================}
{===================================================================}
Function DetermineGrievanceYear : String;
begin
If GlblIsWestchesterCounty
then Result := GlblNextYear
else Result := GlblThisYear;
end; {DetermineGrievanceYear}
{==================================================================}
Procedure DetermineGrantedValues( GrievanceResultsTable : TTable;
var GrantedLandValue : LongInt;
var GrantedTotalValue : LongInt;
var GrantedExemptionAmount : LongInt;
var GrantedExemptionPercent : Double;
var GrantedExemptionCode : String);
begin
GrantedLandValue := 0;
GrantedTotalValue := 0;
GrantedExemptionAmount := 0;
GrantedExemptionPercent := 0;
GrantedExemptionCode := '';
with GrievanceResultsTable do
begin
GrantedLandValue := FieldByName('LandValue').AsInteger;
GrantedTotalValue := FieldByName('TotalValue').AsInteger;
GrantedExemptionAmount := FieldByName('ExAmount').AsInteger;
GrantedExemptionCode := FieldByName('ExGranted').Text;
GrantedExemptionPercent := FieldByName('ExPercent').AsFloat;
end; {with GrievanceResultsTable do}
end; {DetermineGrantedValues}
{==================================================================}
Procedure MoveGrantedValuesToMainParcel(OrigGrantedLandValue : LongInt;
OrigGrantedTotalValue : LongInt;
OrigGrantedExemptionAmount : LongInt;
OrigGrantedExemptionPercent : Double;
OrigGrantedExemptionCode : String;
NewGrantedLandValue : LongInt;
NewGrantedTotalValue : LongInt;
NewGrantedExemptionAmount : LongInt;
NewGrantedExemptionPercent : Double;
NewGrantedExemptionCode : String;
GrievanceProcessingType : Integer;
SwisSBLKey : String;
GrievanceYear : String;
ParcelTabSet : TTabSet;
TabTypeList : TStringList;
GrievanceNumber : Integer;
ResultNumber : Integer;
Disposition : String;
DecisionDate : String;
UpdatedInBulkJob : Boolean;
ShowMessage : Boolean;
AutomaticallyMoveWhollyExemptsToRS8 : Boolean;
FreezeAssessment : Boolean;
var NowWhollyExempt : Boolean;
var Updated : Boolean;
var ErrorMessage : String;
var LandValueChange : Comp;
var TotalValueChange : Comp;
var CountyTaxableChange : Comp;
var TownTaxableChange : Comp;
var SchoolTaxableChange : Comp;
var VillageTaxableChange : Comp);
{Move the values to the main assessment (amd/or) exemption table, update the
roll totals, add a record to the main audit table, add records to the assessor's
trial balance audit tables, and add a record to the grievance audit table.}
var
Quit, FoundExemption,
SplitParcel, AlreadyRollSection8 : Boolean;
Difference,
OrigLandAssessedVal, OrigTotalAssessedVal,
OrigPhysicalQtyInc, OrigPhysicalQtyDec,
OrigEqualizationInc, OrigEqualizationDec,
NewLandAssessedVal, NewTotalAssessedVal,
NewPhysicalQtyInc, NewPhysicalQtyDec,
NewEqualizationInc, NewEqualizationDec : Comp; {Based on the assessment table.}
AssessmentTable, ExemptionTable,
ExemptionCodeTable, ClassTable,
ParcelTable, SwisCodeTable,
AuditAVChangeTable, AuditEXChangeTable,
AuditGrievanceTable : TTable;
SBLRec : SBLRecord;
AuditEXChangeList : TList;
EXAmounts, OrigEXAmounts, NewEXAmounts : ExemptionTotalsArrayType;
CurrentTime : TDateTime;
PriorAssessmentDate, ResultString,
PropertyClass, OriginalRollSection : String;
BasicSTARAmount, EnhancedSTARAmount,
OrigCountyTaxableValue, OrigTownTaxableValue,
OrigSchoolTaxableValue, OrigVillageTaxableValue : Comp;
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts : TStringList;
begin
CurrentTime := Now;
NowWhollyExempt := False;
AlreadyRollSection8 := False;
FoundExemption := False;
Difference := 0;
Updated := True;
ErrorMessage := '';
LandValueChange := 0;
TotalValueChange := 0;
CountyTaxableChange := 0;
TownTaxableChange := 0;
SchoolTaxableChange := 0;
VillageTaxableChange := 0;
AuditEXChangeList := TList.Create;
ParcelTable := TTable.Create(nil);
AssessmentTable := TTable.Create(nil);
ExemptionTable := TTable.Create(nil);
AuditAVChangeTable := TTable.Create(nil);
AuditEXChangeTable := TTable.Create(nil);
AuditGrievanceTable := TTable.Create(nil);
OpenTableForProcessingType(AssessmentTable, AssessmentTableName,
GrievanceProcessingType, Quit);
AssessmentTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY';
FindKeyOld(AssessmentTable, ['TaxRollYr', 'SwisSBLKey'],
[GrievanceYear, SwisSBLKey]);
OpenTableForProcessingType(ExemptionTable,
ExemptionsTableName,
GrievanceProcessingType, Quit);
ExemptionTable.IndexName := 'BYYEAR_SWISSBLKEY_EXCODE';
OpenTableForProcessingType(ParcelTable, ParcelTableName,
GrievanceProcessingType, Quit);
OpenTableForProcessingType(AuditAVChangeTable, 'AuditAVChangeTbl',
GrievanceProcessingType, Quit);
OpenTableForProcessingType(AuditEXChangeTable, 'AuditEXChangeTbl',
GrievanceProcessingType, Quit);
OpenTableForProcessingType(AuditGrievanceTable, 'gauditgrantedvalues',
GrievanceProcessingType, Quit);
{Now recalculate the exemptions.}
ExemptionCodeTable := FindTableInDataModuleForProcessingType(DataModuleExemptionCodeTableName,
GrievanceProcessingType);
SwisCodeTable := FindTableInDataModuleForProcessingType(DataModuleSwisCodeTableName,
GrievanceProcessingType);
ClassTable := FindTableInDataModuleForProcessingType(DataModuleClassTableName,
GrievanceProcessingType);
ParcelTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY';
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section', 'Subsection',
'Block', 'Lot', 'Sublot', 'Suffix'],
[GrievanceYear, SwisCode, Section, SubSection,
Block, Lot, Sublot, Suffix]);
OriginalRollSection := ParcelTable.FieldByName('RollSection').Text;
PropertyClass := ParcelTable.FieldByName('PropertyClassCode').Text;
FindKeyOld(ClassTable, ['TaxRollYr', 'SwisSBLKey'],
[GrievanceYear, SwisSBLKey]);
with AssessmentTable do
begin
OrigLandAssessedVal := FieldByName('LandAssessedVal').AsInteger;
OrigTotalAssessedVal := FieldByName('TotalAssessedVal').AsInteger;
OrigPhysicalQtyInc := FieldByName('PhysicalQtyIncrease').AsInteger;
OrigPhysicalQtyDec := FieldByName('PhysicalQtyDecrease').AsInteger;
OrigEqualizationInc := FieldByName('IncreaseForEqual').AsInteger;
OrigEqualizationDec := FieldByName('DecreaseForEqual').AsInteger;
end; {with AssessmentTable do}
OrigCountyTaxableValue := OrigTotalAssessedVal - OrigEXAmounts[EXCounty];
OrigTownTaxableValue := OrigTotalAssessedVal - OrigEXAmounts[EXTown];
OrigSchoolTaxableValue := OrigTotalAssessedVal - OrigEXAmounts[EXSchool];
OrigVillageTaxableValue := OrigTotalAssessedVal - OrigEXAmounts[EXVillage];
NewLandAssessedVal := OrigLandAssessedVal;
NewTotalAssessedVal := OrigTotalAssessedVal;
{Make them update it manually if this is a split parcel.}
SplitParcel := (ParcelTable.FieldByName('HomesteadCode').Text = 'S');
If SplitParcel
then
begin
Updated := False;
ErrorMessage := 'The AV was not updated because it is a split parcel.';
If ShowMessage
then MessageDlg(ErrorMessage + #13 +
'Please determine and enter the homestead and non-homestead amounts manually.', mtWarning, [mbOK], 0);
end {If SplitParcel}
else
begin
{First get all the values before the changes.}
AdjustRollTotalsForParcel_New(GrievanceYear, GrievanceProcessingType,
SwisSBLKey, OrigEXAmounts,
['S', 'C', 'E', 'D'], 'D');
GetAuditEXList(SwisSBLKey, GrievanceYear, ExemptionTable, AuditEXChangeList);
InsertAuditEXChanges(SwisSBLKey, GrievanceYear, AuditEXChangeList,
AuditEXChangeTable, 'B');
{Now make the change in assessment and\or exemption.}
If ((NewGrantedTotalValue > 0) and {Don't do it if they didn't change AV.}
((NewGrantedLandValue <> OrigLandAssessedVal) or
(NewGrantedTotalValue <> OrigTotalAssessedVal)))
then
begin
with AssessmentTable do
try
Difference := NewGrantedTotalValue - OrigTotalAssessedVal;
Edit;
If (Difference > 0)
then FieldByName('IncreaseForEqual').AsFloat := FieldByName('IncreaseForEqual').AsFloat +
Difference
else FieldByName('DecreaseForEqual').AsFloat := FieldByName('DecreaseForEqual').AsFloat +
-1 * Difference;
{FXX06022002-1: If they do not fill in a land value on the grievance,
assume that the land value stays the same.}
{FXX08132007-1(2.11.3.1)[D968]: If the total value is reduced on vacant land,
reduce the land value, too.}
If _Compare(NewGrantedLandValue, 0, coEqual)
then
begin
If ParcelIsNonImprovedVacantLand(PropertyClass)
then
begin
FieldByName('LandAssessedVal').AsInteger := NewGrantedTotalValue;
NewGrantedLandValue := NewGrantedTotalValue;
end
else NewGrantedLandValue := FieldByName('LandAssessedVal').AsInteger;
end
else FieldByName('LandAssessedVal').AsInteger := NewGrantedLandValue;
FieldByName('TotalAssessedVal').AsInteger := NewGrantedTotalValue;
{FXX04232009-11(4.20.1.1)[D161]: Do not let the total value become less than the
land value. Also, give warning.}
If _Compare(FieldByName('TotalAssessedVal').AsInteger, FieldByName('LandAssessedVal').AsInteger, coLessThan)
then
begin
FieldByName('LandAssessedVal').AsInteger := FieldByName('TotalAssessedVal').AsInteger;
MessageDlg('The total assessed value is now less than the land value.' + #13 +
'The land value has been adjusted to be the same as the total value.' + #13 +
'Please review the land value.', mtError, [mbOK], 0);
end; {If _Compare(FieldByName('TotalAssessedVal').AsInteger ...}
PriorAssessmentDate := FieldByName('AssessmentDate').Text;
FieldByName('AssessmentDate').AsDateTime := Date;
{FXX05182012-1[PAS-359](2.28.4.25): Allow freeze to be an option.}
If FreezeAssessment
then FieldByName('DateFrozen').AsDateTime := AddOneYear(Date);
Post;
LandValueChange := NewGrantedLandValue - OrigLandAssessedVal;
TotalValueChange := NewGrantedTotalValue - OrigTotalAssessedVal;
except
SystemSupport(010, AssessmentTable, 'Error updating assessment table for parcel ' + SwisSBLKey + '.',
'PASUTILS', GlblErrorDlgBox);
end;
If (NewGrantedLandValue <> OrigLandAssessedVal)
then AddToTraceFile(SwisSBLKey,
'Assessment', 'Land Assessed Val',
FormatFloat(CurrencyDisplayNoDollarSign,
OrigLandAssessedVal),
FormatFloat(CurrencyDisplayNoDollarSign,
NewGrantedLandValue),
CurrentTime, AssessmentTable);
AddToTraceFile(SwisSBLKey,
'Assessment', 'Total Assessed Val',
FormatFloat(CurrencyDisplayNoDollarSign,
OrigTotalAssessedVal),
FormatFloat(CurrencyDisplayNoDollarSign,
NewGrantedTotalValue),
CurrentTime, AssessmentTable);
AddToTraceFile(SwisSBLKey,
'Assessment', 'AssessmentDate',
PriorAssessmentDate,
DateToStr(Date),
CurrentTime, AssessmentTable);
AddToTraceFile(SwisSBLKey,
'Assessment', 'Date Frozen Until',
'',
AssessmentTable.FieldByName('DateFrozen').Text,
CurrentTime, AssessmentTable);
If (Difference > 0)
then AddToTraceFile(SwisSBLKey,
'Assessment', 'Increase For Equal',
FormatFloat(CurrencyDisplayNoDollarSign,
OrigEqualizationDec),
FormatFloat(CurrencyDisplayNoDollarSign,
AssessmentTable.FieldByName('DecreaseForEqual').AsFloat),
CurrentTime, AssessmentTable)
else AddToTraceFile(SwisSBLKey,
'Assessment', 'Decrease For Equal',
FormatFloat(CurrencyDisplayNoDollarSign,
OrigEqualizationDec),
FormatFloat(CurrencyDisplayNoDollarSign,
AssessmentTable.FieldByName('DecreaseForEqual').AsFloat),
CurrentTime, AssessmentTable);
end; {If ((NewGrantedLandValue <> OrigLandAssessedVal) or ...}
{Add the granted exemption if there is one.}
If ((Deblank(NewGrantedExemptionCode) <> '') and
(Deblank(OrigGrantedExemptionCode) = ''))
then
begin
{FXX06072002-1: If the exemption already exists, make them
update it manually.}
If (ParcelTable.FieldByName('RollSection').Text = '8')
then
begin
AlreadyRollSection8 := True;
Updated := False;
ErrorMessage := 'Exemption ' + NewGrantedExemptionCode +
' was not added because the parcel is already RS 8.';
If ShowMessage
then MessageDlg(ErrorMessage + #13 +
'Please investigate.', mtWarning, [mbOK], 0);
end; {If (ParcelTable.FieldByName('RollSection').Text = '8')}
If not AlreadyRollSection8
then
begin
ExemptionTable.CancelRange;
FoundExemption := FindKeyOld(ExemptionTable,
['TaxRollYr', 'SwisSBLKey','ExemptionCode'],
[GrievanceYear, SwisSBLKey, NewGrantedExemptionCode]);
If FoundExemption
then
begin
Updated := False;
ErrorMessage := 'The exemption ' + NewGrantedExemptionCode + ' was not updated because it already exists.';
If ShowMessage
then MessageDlg(ErrorMessage + #13 +
'Please update it manually.', mtWarning, [mbOK], 0);
end
else
begin
with ExemptionTable do
try
Insert;
FieldByName('TaxRollYr').Text := GrievanceYear;
FieldByName('SwisSBLKey').Text := SwisSBLKey;
FieldByName('ExemptionCode').Text := NewGrantedExemptionCode;
FieldByName('Amount').AsFloat := NewGrantedExemptionAmount;
FieldByName('Percent').AsFloat := NewGrantedExemptionPercent;
FieldByName('InitialDate').AsDateTime := Date;
Post;
except
SystemSupport(011, ExemptionTable,
'Error inserting exemption code ' + NewGrantedExemptionCode + '.',
'PASUTILS', GlblErrorDlgBox);
end;
If ((ParcelTabset <> nil) and
(ParcelTabset.Tabs.IndexOf(ExemptionsTabName) = -1))
then AddExemptionTab(ExemptionTable, ParcelTabset,
GrievanceProcessingType, 0,
TabTypeList, GrievanceYear,
SwisSBLKey);
AddToTraceFile(SwisSBLKey,
'Exemption', 'Exempt Code',
'', NewGrantedExemptionCode,
Now, ExemptionTable);
end; {else of If FoundExemption}
end; {If not AlreadyRollSection8}
{If the parcel was not updated due to an existing EX or already in RS 8,
we must add the totals back in since they were already taken out.}
If not Updated
then AdjustRollTotalsForParcel_New(GrievanceYear, GrievanceProcessingType,
SwisSBLKey, NewEXAmounts,
['S', 'C', 'E', 'D'], 'A');
end; {If ((Deblank(NewGrantedExemptionCode) <> '') and ...}
end; {else of If SplitParcel}
If Updated
then
begin
RecalculateExemptionsForParcel(ExemptionCodeTable,
ExemptionTable,
AssessmentTable,
ClassTable,
SwisCodeTable,
ParcelTable,
GrievanceYear, SwisSBLKey, nil,
0, 0, False);
{If it is now wholly exempt, offer to move the parcel to roll section 8.}
ExemptionCodes := TStringList.Create;
ExemptionHomesteadCodes := TStringList.Create;
ResidentialTypes := TStringList.Create;
CountyExemptionAmounts := TStringList.Create;
TownExemptionAmounts := TStringList.Create;
SchoolExemptionAmounts := TStringList.Create;
VillageExemptionAmounts := TStringList.Create;
EXAmounts := TotalExemptionsForParcel(GrievanceYear, SwisSBLKey,
ExemptionTable,
ExemptionCodeTable,
ParcelTable.FieldByName('HomesteadCode').Text,
'A',
ExemptionCodes,
ExemptionHomesteadCodes,
ResidentialTypes,
CountyExemptionAmounts,
TownExemptionAmounts,
SchoolExemptionAmounts,
VillageExemptionAmounts,
BasicSTARAmount, EnhancedSTARAmount);
If ((Roundoff(AssessmentTable.FieldByName('TotalAssessedVal').AsFloat, 0) =
Roundoff(EXAmounts[EXTown], 0)) and
(OriginalRollSection <> '8'))
then NowWhollyExempt := True;
ExemptionCodes.Free;
ExemptionHomesteadCodes.Free;
ResidentialTypes.Free;
CountyExemptionAmounts.Free;
TownExemptionAmounts.Free;
SchoolExemptionAmounts.Free;
VillageExemptionAmounts.Free;
If (NowWhollyExempt and
((ShowMessage and
(MessageDlg('The granted exemption has now made the parcel wholly exempt.' + #13 +
'Do you want to move the parcel to roll section 8?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)) or
((not ShowMessage) and
AutomaticallyMoveWhollyExemptsToRS8)))
then
begin
with ParcelTable do
try
Edit;
FieldByName('RollSection').Text := '8';
Post;
except
SystemSupport(960, ParcelTable, 'Error moving parcel to roll section 8.',
'PASUTILS', GlblErrorDlgBox);
end;
AddToTraceFile(SwisSBLKey,
'Base Information', 'RollSection',
OriginalRollSection,
'8', CurrentTime, ParcelTable);
end {If NowWhollyExempt}
else NowWhollyExempt := False;
{Adjust the roll totals for the new values.}
AdjustRollTotalsForParcel_New(GrievanceYear, GrievanceProcessingType,
SwisSBLKey, NewEXAmounts,
['S', 'C', 'E', 'D'], 'A');
If ((NewGrantedTotalValue > 0) and {Don't do it if they didn't change AV.}
((NewGrantedLandValue <> OrigLandAssessedVal) or
(NewGrantedTotalValue <> OrigTotalAssessedVal)))
then
begin
with AssessmentTable do
begin
NewLandAssessedVal := FieldByName('LandAssessedVal').AsInteger;
NewTotalAssessedVal := FieldByName('TotalAssessedVal').AsInteger;
NewPhysicalQtyInc := FieldByName('PhysicalQtyIncrease').AsInteger;
NewPhysicalQtyDec := FieldByName('PhysicalQtyDecrease').AsInteger;
NewEqualizationInc := FieldByName('IncreaseForEqual').AsInteger;
NewEqualizationDec := FieldByName('DecreaseForEqual').AsInteger;
end; {with AssessmentTable do}
InsertAuditAVChangeRec(AuditAVChangeTable,
SwisSBLKey,
GrievanceYear,
OrigLandAssessedVal,
OrigTotalAssessedVal,
OrigPhysicalQtyInc,
OrigPhysicalQtyDec,
OrigEqualizationInc,
OrigEqualizationDec,
OrigEXAmounts,
NewLandAssessedVal,
NewTotalAssessedVal,
NewPhysicalQtyInc,
NewPhysicalQtyDec,
NewEqualizationInc,
NewEqualizationDec,
NewEXAmounts);
end; {If ((NewGrantedTotalValue > 0) and ...}
(* If ((Deblank(NewGrantedExemptionCode) <> '') and
(Deblank(OrigGrantedExemptionCode) = ''))
then
begin *)
ClearTList(AuditEXChangeList, SizeOf(AuditEXRecord));
GetAuditEXList(SwisSBLKey, GrievanceYear, ExemptionTable, AuditEXChangeList);
InsertAuditEXChanges(SwisSBLKey, GrievanceYear, AuditEXChangeList,
AuditEXChangeTable, 'A');
(* end; {If ((Deblank(NewGrantedExemptionCode) <> '') and ...} *)
with AuditGrievanceTable do
try
Insert;
FieldByName('TaxRollYr').Text := GrievanceYear;
FieldByName('GrievanceNumber').AsInteger := GrievanceNumber;
FieldByName('ResultNumber').AsInteger := ResultNumber;
FieldByName('SwisSBLKey').Text := SwisSBLKey;
FieldByName('Date').AsDateTime := Date;
FieldByName('Time').AsDateTime := Now;
FieldByName('User').Text := GlblUserName;
FieldByName('Disposition').Text := Disposition;
FieldByName('DecisionDate').Text := DecisionDate;
FieldByName('OrigGrantedLandVal').AsInteger := OrigGrantedLandValue;
FieldByName('OrigGrantedLandVal').AsInteger := OrigGrantedLandValue;
FieldByName('OrigGrantedEXCode').Text := OrigGrantedExemptionCode;
FieldByName('OrigGrantedEXPercent').AsFloat := OrigGrantedExemptionPercent;
FieldByName('OrigGrantedEXAmt').AsInteger := OrigGrantedExemptionAmount;
FieldByName('NewGrantedLandVal').AsInteger := NewGrantedLandValue;
FieldByName('NewGrantedTotalVal').AsInteger := NewGrantedTotalValue;
FieldByName('NewGrantedEXCode').Text := NewGrantedExemptionCode;
FieldByName('NewGrantedEXPercent').AsFloat := NewGrantedExemptionPercent;
FieldByName('NewGrantedEXAmt').AsInteger := NewGrantedExemptionAmount;
FieldByName('UpdatedInBulkJob').AsBoolean := UpdatedInBulkJob;
Post;
except
SystemSupport(012, AuditGrievanceTable,
'Error inserting into audit grievance table.',
'PASUTILS', GlblErrorDlgBox);
end;
{Update the changed flags on the parcel.}
MarkRecChanged(ParcelTable, 'PASUTILS');
SetExtractFlags(SwisSBLKey);
ParcelTable.Close;
AssessmentTable.Close;
ExemptionTable.Close;
AuditAVChangeTable.Close;
AuditEXChangeTable.Close;
AuditGrievanceTable.Close;
ParcelTable.Free;
AssessmentTable.Free;
ExemptionTable.Free;
AuditAVChangeTable.Free;
AuditEXChangeTable.Free;
AuditGrievanceTable.Free;
FreeTList(AuditEXChangeList, SizeOf(AuditEXRecord));
If ShowMessage
then
begin
ResultString := '';
If ((OrigLandAssessedVal <> NewGrantedLandValue) and
(NewGrantedLandValue <> 0))
then ResultString := #13 + 'Land value reduced from ' +
FormatFloat(CurrencyDisplayNoDollarSign,
OrigLandAssessedVal) +
' to ' +
FormatFloat(IntegerDisplay,
NewGrantedLandValue) +
'.';
If ((OrigTotalAssessedVal <> NewGrantedTotalValue) and
(NewGrantedTotalValue <> 0))
then
begin
If ((OrigLandAssessedVal = 0) and
(NewGrantedLandValue = 0))
then ResultString := #13 + 'The land value remained unchanged.';
ResultString := ResultString + #13 +
'Total value reduced from ' +
FormatFloat(CurrencyDisplayNoDollarSign,
OrigTotalAssessedVal) +
' to ' +
FormatFloat(IntegerDisplay,
NewGrantedTotalValue) +
'.';
end; {If (OrigTotalAssessedVal <> NewGrantedTotalValue)}
If (OrigGrantedExemptionCode <> NewGrantedExemptionCode)
then ResultString := #13 + ResultString +
'Exemption ' + NewGrantedExemptionCode +
' was added.';
If not FoundExemption
then MessageDlg('The following actions were taken: ' +
ResultString, mtInformation, [mbOK], 0);
end; {If ShowMessage}
CountyTaxableChange := (NewTotalAssessedVal - NewEXAmounts[EXCounty]) -
(OrigTotalAssessedVal - OrigEXAmounts[EXCounty]);
TownTaxableChange := (NewTotalAssessedVal - NewEXAmounts[EXTown]) -
(OrigTotalAssessedVal - OrigEXAmounts[EXTown]);
SchoolTaxableChange := (NewTotalAssessedVal - NewEXAmounts[EXSchool]) -
(OrigTotalAssessedVal - OrigEXAmounts[EXSchool]);
VillageTaxableChange := (NewTotalAssessedVal - NewEXAmounts[EXVillage]) -
(OrigTotalAssessedVal - OrigEXAmounts[EXVillage]);
end; {If Updated}
end; {MoveGrantedValuesToMainParcel}
{==============================================================}
Procedure AddToGrievanceStatusString(var StatusStr : String;
TempStr : String);
begin
If (Deblank(StatusStr) <> '')
then StatusStr := StatusStr + ', ';
StatusStr := StatusStr + TempStr;
end; {AddToGrievanceStatusString}
{==============================================================}
Function GetGrievanceStatus( GrievanceTable : TTable;
GrievanceExemptionsAskedTable : TTable;
GrievanceResultsTable : TTable;
GrievanceDispositionCodeTable : TTable;
GrievanceYear : String;
SwisSBLKey : String;
ShortDescription : Boolean;
var StatusStr : String) : Integer;
var
Done, FirstTimeThrough : Boolean;
GrievanceNumber, NumComplaints,
NumNotApproved, NumApproved, NumDismissed : LongInt;
(*NumDenied, *) NumWithdrawn : LongInt;
begin
StatusStr := '';
GrievanceNumber := GrievanceTable.FieldByName('GrievanceNumber').AsInteger;
{First figure out how many grievance items there are.}
NumComplaints := 0;
If (Roundoff(GrievanceTable.FieldByName('PetitTotalValue').AsFloat, 0) > 0)
then NumComplaints := NumComplaints + 1;
NumComplaints := NumComplaints +
NumRecordsInRange(GrievanceExemptionsAskedTable,
['SwisSBLKey', 'TaxRollYr', 'GrievanceNumber', 'ExemptionCode'],
[SwisSBLKey, GrievanceYear, IntToStr(GrievanceNumber), ' '],
[SwisSBLKey, GrievanceYear, IntToStr(GrievanceNumber), '99999']);
{Now figure out how many results there are.}
SetRangeOld(GrievanceResultsTable,
['TaxRollYr', 'SwisSBLKey', 'GrievanceNumber', 'ResultNumber'],
[GrievanceYear, SwisSBLKey, IntToStr(GrievanceNumber), '0'],
[GrievanceYear, SwisSBLKey, IntToStr(GrievanceNumber), '9999']);
GrievanceResultsTable.First;
NumNotApproved := 0;
NumApproved := 0;
(*NumDenied := 0;*)
NumDismissed := 0;
NumWithdrawn := 0;
Done := False;
FirstTimeThrough := True;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else GrievanceResultsTable.Next;
If GrievanceResultsTable.EOF
then Done := True;
If ((not Done) and
FindKeyOld(GrievanceDispositionCodeTable, ['Code'],
[GrievanceResultsTable.FieldByName('Disposition').Text]))
then
begin
(*Approved := (GrievanceDispositionCodeTable.FieldByName('ResultType').AsInteger = gtApproved); *)
{FXX10232002-1: If it is dismissed, the status should say dismissed.}
If (Pos('AV', GrievanceResultsTable.FieldByName('ComplaintReason').Text) > 0)
then
begin
{FXX03122003-1(2.06q): If there is no asking value, but there is a disposition
code, then count it as a complaint.}
If ((Roundoff(GrievanceTable.FieldByName('PetitTotalValue').AsFloat, 0) = 0) and
(NumComplaints = 0))
then NumComplaints := NumComplaints + 1;
case GrievanceDispositionCodeTable.FieldByName('ResultType').AsInteger of
gtApproved : AddToGrievanceStatusString(StatusStr,
'AV ' +
FormatFloat(CurrencyDisplayNoDollarSign,
GrievanceResultsTable.FieldByName('TotalValue').AsFloat) +
' granted');
gtDenied : AddToGrievanceStatusString(StatusStr,
'AV denied');
gtDismissed : AddToGrievanceStatusString(StatusStr,
'AV dismissed');
gtWithdrawn : AddToGrievanceStatusString(StatusStr,
'AV withdrawn');
end; {case GrievanceDispositionCodeTable...}
end
else
begin
case GrievanceDispositionCodeTable.FieldByName('ResultType').AsInteger of
gtApproved : AddToGrievanceStatusString(StatusStr,
'EX ' +
GrievanceResultsTable.FieldByName('EXGranted').Text +
' granted');
gtDenied : AddToGrievanceStatusString(StatusStr,
'EX denied');
gtDismissed : AddToGrievanceStatusString(StatusStr,
'EX dismissed');
gtWithdrawn : AddToGrievanceStatusString(StatusStr,
'EX withdrawn');
end; {case GrievanceDispositionCodeTable...}
end; {If (Pos('AV', GrievanceResults.FieldByName('ComplaintReason').Text) > -1)}
case GrievanceDispositionCodeTable.FieldByName('ResultType').AsInteger of
gtApproved : NumApproved := NumApproved + 1;
gtDenied : begin
NumNotApproved := NumNotApproved + 1;
(*NumDenied := NumDenied + 1; *)
end;
gtDismissed : begin
NumNotApproved := NumNotApproved + 1;
NumDismissed := NumDismissed + 1;
end;
gtWithdrawn : begin
NumNotApproved := NumNotApproved + 1;
NumWithdrawn := NumWithdrawn + 1;
end;
end; {case GrievanceDispositionCodeTable.FieldByName('ResultType').AsInteger of}
end; {If ((not Done) and ...}
until Done;
{Now compare the two to find the status.}
If ShortDescription
then StatusStr := 'OPEN';
Result := gsOpen;
If (((NumApproved + NumNotApproved) > 0) and
((NumApproved + NumNotApproved) < NumComplaints))
then
begin
If ShortDescription
then StatusStr := 'MIXED';
Result := gsMixed;
end;
If (((NumApproved + NumNotApproved) = NumComplaints) and
(NumApproved > 0) and
(NumNotApproved > 0))
then
begin
If ShortDescription
then StatusStr := 'CLOSED';
Result := gsClosed;
end;
If (((NumApproved + NumNotApproved) = NumComplaints) and
(NumApproved = NumComplaints))
then
begin
If ShortDescription
then StatusStr := 'APPROVED';
Result := gsApproved;
end;
If (((NumApproved + NumNotApproved) = NumComplaints) and
(NumNotApproved = NumComplaints))
then
If (NumDismissed = NumComplaints)
then
begin
If ShortDescription
then StatusStr := 'DISMISSED';
Result := gsDismissed;
end
else
begin
If ShortDescription
then StatusStr := 'DENIED';
Result := gsDenied;
end; {else of If (NumDismissed = NumComplaints)}
If _Compare(NumWithdrawn, 0, coGreaterThan)
then
begin
If ShortDescription
then StatusStr := 'WITHDRAWN';
Result := gsWithdrawn;
end;
If _Compare((NumApproved + NumNotApproved), 0, coEqual)
then
begin
StatusStr := 'OPEN';
Result := gsOpen;
end;
end; {GetGrievanceStatus}
{=============================================================}
Function GetGrievanceNumberToDisplay(GrievanceTable : TTable) : String;
var
TempStr : String;
begin
{CHG07192002-2: Add No Hearing flag.}
TempStr := '';
try
If GrievanceTable.FieldByName('NoHearing').AsBoolean
then TempStr := 'NH';
except
end;
Result := IntToStr(GrievanceTable.FieldByName('GrievanceNumber').AsInteger) +
TempStr;
end; {GetGrievanceNumberToDisplay}
{===========================================================}
{================= CERTIORARI ============================}
{===========================================================}
Function GetCert_Or_SmallClaimStatus( Table : TTable;
var StatusCode : Integer) : String;
begin
with Table do
begin
Result := 'Open';
StatusCode := csOpen;
If ((FieldByName('GrantedTotalValue').AsInteger > 0) or
_Compare(FieldByName('Disposition').Text, 'COURT ORDER', coEqual))
then
begin
StatusCode := csApproved;
Result := 'AV ' +
FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('GrantedTotalValue').AsFloat) +
' granted';
end; {If (FieldByName('GrantedTotalValue').AsInteger > 0)}
If (Deblank(FieldByName('GrantedEXCode').Text) <> '')
then
begin
StatusCode := csApproved;
Result := 'EX ' + FieldByName('GrantedEXCode').Text +
' granted';
end; {If (Deblank(FieldByName('GrantedEXCode').Text) <> '')}
If (FieldByName('Disposition').Text = 'DISCONTINUED')
then
begin
StatusCode := csDiscontinued;
Result := 'Discontinued ' + FieldByName('DispositionDate').Text;
end;
If _Compare(FieldByName('Disposition').Text, 'WITHDRAWN', coEqual)
then
begin
StatusCode := csWithdrawn;
Result := 'Withdrawn ' + FieldByName('DispositionDate').Text;
end;
If (FieldByName('Disposition').Text = 'DENIED')
then
begin
StatusCode := csDenied;
Result := 'Denied ' + FieldByName('DispositionDate').Text;
end;
If (FieldByName('Disposition').Text = 'DISMISSED')
then
begin
StatusCode := csDenied;
Result := 'Dismissed ' + FieldByName('DispositionDate').Text;
end;
If _Compare(FieldByName('Disposition').Text, 'DEN-NO GRV', coEqual)
then
begin
StatusCode := csDenied;
Result := 'Denied - no grievance';
end;
end; {with CertiorariTable do}
end; {GetCertiorariStatus}
{===============================================================}
Function CopyGrievanceToCert_Or_SmallClaim(IndexNumber : LongInt;
GrievanceNumber : Integer;
CurrentYear : String;
PriorYear : String;
SwisSBLKey : String;
LawyerCode : String;
NumberOfParcels : Integer;
GrievanceTable,
DestinationTable,
LawyerCodeTable,
ParcelTable,
CurrentAssessmentTable,
PriorAssessmentTable,
SwisCodeTable,
PriorSwisCodeTable,
CurrentExemptionsTable,
DestinationExemptionsTable,
CurrentSpecialDistrictsTable,
DestinationSpecialDistrictsTable,
CurrentSalesTable,
DestinationSalesTable,
GrievanceExemptionsAskedTable,
DestinationExemptionsAskedTable,
GrievanceResultsTable,
GrievanceDispositionCodeTable : TTable;
Source : Char {(C)ert or (S)mall claim}) : Boolean;
var
PriorAssessmentFound : Boolean;
StatusStr, TempIndexNumberFieldName : String;
begin
case Source of
'C' : TempIndexNumberFieldName := 'CertiorariNumber';
'S' : TempIndexNumberFieldName := 'IndexNumber';
end;
Result := True;
FindKeyOld(SwisCodeTable, ['SwisCode'], [Copy(SwisSBLKey, 1, 6)]);
FindKeyOld(CurrentAssessmentTable, ['TaxRollYr', 'SwisSBLKey'],
[CurrentYear, SwisSBLKey]);
PriorAssessmentFound := FindKeyOld(PriorAssessmentTable,
['TaxRollYr', 'SwisSBLKey'],
[PriorYear, SwisSBLKey]);
SetRangeOld(CurrentExemptionsTable, ['TaxRollYr', 'SwisSBLKey'],
[CurrentYear, SwisSBLKey], [CurrentYear, SwisSBLKey]);
SetRangeOld(CurrentSpecialDistrictsTable, ['TaxRollYr', 'SwisSBLKey'],
[CurrentYear, SwisSBLKey], [CurrentYear, SwisSBLKey]);
SetRangeOld(CurrentSalesTable, ['SwisSBLKey', 'SaleNumber'],
[SwisSBLKey, '0'], [SwisSBLKey, '9999']);
SetRangeOld(GrievanceExemptionsAskedTable,
['TaxRollYr', 'SwisSBLKey', 'GrievanceNumber', 'ExemptionCode'],
[CurrentYear, SwisSBLKey, IntToStr(GrievanceNumber), '00000'],
[CurrentYear, SwisSBLKey, IntToStr(GrievanceNumber), '9999']);
with DestinationTable do
try
Append;
FieldByName('TaxRollYr').Text := CurrentYear;
FieldByName(TempIndexNumberFieldName).AsInteger := IndexNumber;
FieldByName('SwisSBLKey').Text := SwisSBLKey;
FieldByName('CurrentName1').Text := GrievanceTable.FieldByName('CurrentName1').Text;
FieldByName('CurrentName2').Text := GrievanceTable.FieldByName('CurrentName2').Text;
FieldByName('CurrentAddress1').Text := GrievanceTable.FieldByName('CurrentAddress1').Text;
FieldByName('CurrentAddress2').Text := GrievanceTable.FieldByName('CurrentAddress2').Text;
FieldByName('CurrentStreet').Text := GrievanceTable.FieldByName('CurrentStreet').Text;
FieldByName('CurrentCity').Text := GrievanceTable.FieldByName('CurrentCity').Text;
FieldByName('CurrentState').Text := GrievanceTable.FieldByName('CurrentState').Text;
FieldByName('CurrentZip').Text := GrievanceTable.FieldByName('CurrentZip').Text;
FieldByName('CurrentZipPlus4').Text := GrievanceTable.FieldByName('CurrentZipPlus4').Text;
FieldByName('LawyerCode').Text := LawyerCode;
If ((Deblank(LawyerCode) = '') or
GlblGrievanceSeperateRepresentativeInfo)
then
begin
{They are representing themselves.}
FieldByName('PetitName1').Text := GrievanceTable.FieldByName('PetitName1').Text;
FieldByName('PetitName2').Text := GrievanceTable.FieldByName('PetitName2').Text;
FieldByName('PetitAddress1').Text := GrievanceTable.FieldByName('PetitAddress1').Text;
FieldByName('PetitAddress2').Text := GrievanceTable.FieldByName('PetitAddress2').Text;
FieldByName('PetitStreet').Text := GrievanceTable.FieldByName('PetitStreet').Text;
FieldByName('PetitCity').Text := GrievanceTable.FieldByName('PetitCity').Text;
FieldByName('PetitState').Text := GrievanceTable.FieldByName('PetitState').Text;
FieldByName('PetitZip').Text := GrievanceTable.FieldByName('PetitZip').Text;
FieldByName('PetitZipPlus4').Text := GrievanceTable.FieldByName('PetitZipPlus4').Text;
end
else SetPetitionerNameAndAddress(DestinationTable, LawyerCodeTable, LawyerCode);
FieldByName('PropertyClassCode').Text := GrievanceTable.FieldByName('PropertyClassCode').Text;
FieldByName('OwnershipCode').Text := GrievanceTable.FieldByName('OwnershipCode').Text;
FieldByName('ResidentialPercent').AsFloat := GrievanceTable.FieldByName('ResidentialPercent').AsFloat;
FieldByName('RollSection').Text := GrievanceTable.FieldByName('RollSection').Text;
FieldByName('HomesteadCode').Text := GrievanceTable.FieldByName('HomesteadCode').Text;
FieldByName('LegalAddr').Text := GrievanceTable.FieldByName('LegalAddr').Text;
FieldByName('LegalAddrNo').Text := GrievanceTable.FieldByName('LegalAddrNo').Text;
FieldByName('LegalAddrInt').AsInteger := GrievanceTable.FieldByName('LegalAddrInt').AsInteger;
FieldByName('CurrentLandValue').AsInteger := CurrentAssessmentTable.FieldByName('LandAssessedVal').AsInteger;
FieldByName('CurrentTotalValue').AsInteger := CurrentAssessmentTable.FieldByName('TotalAssessedVal').AsInteger;
FieldByName('CurrentFullMarketVal').AsInteger := Round(ComputeFullValue(CurrentAssessmentTable.FieldByName('TotalAssessedVal').AsInteger,
SwisCodeTable,
GrievanceTable.FieldByName('PropertyClassCode').Text,
GrievanceTable.FieldByName('OwnershipCode').Text,
False));
If PriorAssessmentFound
then
begin
FindKeyOld(PriorSwisCodeTable, ['TaxRollYr', 'SwisCode'],
[PriorYear, Copy(SwisSBLKey, 1, 6)]);
FieldByName('PriorLandValue').AsInteger := PriorAssessmentTable.FieldByName('LandAssessedVal').AsInteger;
FieldByName('PriorTotalValue').AsInteger := PriorAssessmentTable.FieldByName('TotalAssessedVal').AsInteger;
try
FieldByName('PriorFullMarketVal').AsInteger := Round(ComputeFullValue(PriorAssessmentTable.FieldByName('TotalAssessedVal').AsInteger,
PriorSwisCodeTable,
GrievanceTable.FieldByName('PropertyClassCode').Text,
GrievanceTable.FieldByName('OwnershipCode').Text,
False));
except
end;
end; {If PriorAssessmentFound}
FieldByName('CurrentEqRate').AsFloat := SwisCodeTable.FieldByName('EqualizationRate').AsFloat;
FieldByName('CurrentUniformPercent').AsFloat := SwisCodeTable.FieldByName('UniformPercentValue').AsFloat;
FieldByName('CurrentRAR').AsFloat := SwisCodeTable.FieldByName('ResAssmntRatio').AsFloat;
FieldByName('SchoolCode').Text := ParcelTable.FieldByName('SchoolCode').Text;
FieldByName('OldParcelID').Text := ParcelTable.FieldByName('RemapOldSBL').Text;
FieldByName('NumberOfParcels').AsInteger := NumberOfParcels;
FieldByName('PetitLandValue').AsInteger := GrievanceTable.FieldByName('PetitLandValue').AsInteger;
FieldByName('PetitTotalValue').AsInteger := GrievanceTable.FieldByName('PetitTotalValue').AsInteger;
FieldByname('PetitFullMarketVal').AsInteger := Round(ComputeFullValue(FieldByName('PetitTotalValue').AsInteger,
SwisCodeTable,
FieldByName('PropertyClassCode').Text,
FieldByName('OwnershipCode').Text,
False));
FieldByName('PetitReason').Text := GrievanceTable.FieldByName('PetitReason').Text;
TMemoField(FieldByName('PetitSubReason')).Value := TMemoField(GrievanceTable.FieldByName('PetitSubReason')).Value;
FieldByName('PetitSubReasonCode').Text := GrievanceTable.FieldByName('PetitSubReasonCode').Text;
GetGrievanceStatus(GrievanceTable, GrievanceExemptionsAskedTable,
GrievanceResultsTable, GrievanceDispositionCodeTable,
GrievanceTable.FieldByName('TaxRollYr').Text, SwisSBLKey,
False, StatusStr);
FieldByName('GrievanceDecision').Text := StatusStr;
{CHG07262004-1(2.08): Option to have attorney information seperate.}
If GlblGrievanceSeperateRepresentativeInfo
then
try
FieldByName('AttyName1').Text := GrievanceTable.FieldByName('AttyName1').Text;
FieldByName('AttyName2').Text := GrievanceTable.FieldByName('AttyName2').Text;
FieldByName('AttyAddress1').Text := GrievanceTable.FieldByName('AttyAddress1').Text;
FieldByName('AttyAddress2').Text := GrievanceTable.FieldByName('AttyAddress2').Text;
FieldByName('AttyStreet').Text := GrievanceTable.FieldByName('AttyStreet').Text;
FieldByName('AttyCity').Text := GrievanceTable.FieldByName('AttyCity').Text;
FieldByName('AttyState').Text := GrievanceTable.FieldByName('AttyState').Text;
FieldByName('AttyZip').Text := GrievanceTable.FieldByName('AttyZip').Text;
FieldByName('AttyZipPlus4').Text := GrievanceTable.FieldByName('AttyZipPlus4').Text;
FieldByName('AttyPhoneNumber').Text := GrievanceTable.FieldByName('AttyPhoneNumber').Text;
except
end;
Post;
except
Result := False;
Cancel;
(*SystemSupport(002, DestinationTable,
'Error adding index # ' + IntToStr(IndexNumber) +
' to parcel ' + SwisSBLKey + '.',
'GrievanceUtilitys', GlblErrorDlgBox); *)
end;
If Result
then
begin
CopyTableRange(CurrentExemptionsTable, DestinationExemptionsTable,
'TaxRollYr', [TempIndexNumberFieldName], [IntToStr(IndexNumber)]);
CopyTableRange(CurrentSpecialDistrictsTable, DestinationSpecialDistrictsTable,
'TaxRollYr', [TempIndexNumberFieldName], [IntToStr(IndexNumber)]);
CopyTableRange(CurrentSalesTable, DestinationSalesTable,
'SwisSBLKey', [TempIndexNumberFieldName], [IntToStr(IndexNumber)]);
CopyTableRange(GrievanceExemptionsAskedTable, DestinationExemptionsAskedTable,
'SwisSBLKey', [TempIndexNumberFieldName], [IntToStr(IndexNumber)]);
end;
end; {CopyGrievanceToCert_Or_SmallClaim}
{========================================================================================}
Function IsGrievance_SmallClaims_CertiorariScreen(ScreenName : String) : Boolean;
{CHG02152004-1(2.07l): Add grievance, small claims and cert info. to search report.}
begin
Result := ((ScreenName = GrievanceScreenName) or
(ScreenName = SmallClaimsScreenName) or
(ScreenName = SmallClaimsAppraisalsScreenName) or
(ScreenName = SmallClaimsCalendarScreenName) or
(ScreenName = SmallClaimsNotesScreenName) or
(ScreenName = CertiorariScreenName) or
(ScreenName = CertiorariAppraisalsScreenName) or
(ScreenName = CertiorariCalendarScreenName) or
(ScreenName = CertiorariNotesScreenName));
end; {IsGrievance_SmallClaims_CertiorariScreen}
{========================================================================================}
Function UserCanViewGrievance_SmallClaims_CertiorariInformation(ScreenName : String) : Boolean;
{CHG02152004-1(2.07l): Add grievance, small claims and cert info. to search report.}
begin
Result := True;
If ((not GlblCanSeeCertiorari) and
((ScreenName = CertiorariScreenName) or
(ScreenName = CertiorariAppraisalsScreenName) or
(ScreenName = CertiorariCalendarScreenName) or
(ScreenName = CertiorariNotesScreenName)))
then Result := False;
If (Result and
(not GlblCanSeeCertNotes) and
(ScreenName = CertiorariNotesScreenName))
then Result := False;
If (Result and
(not GlblCanSeeCertAppraisals) and
(ScreenName = CertiorariAppraisalsScreenName))
then Result := False;
end; {UserCanViewGrievance_SmallClaims_CertiorariInformation}
{====================================================================}
Procedure InitGrievanceTotalsRecord(var TotalsRec : GrievanceTotalsRecord);
begin
with TotalsRec do
begin
TotalCount := 0;
_Open := 0;
_Closed := 0;
_Approved := 0;
_Denied := 0;
_Dismissed := 0;
_Withdrawn := 0;
end; {with TotalsRec do}
end; {InitGrievanceTotalsRecord}
{====================================================================}
Procedure UpdateSmallClaims_Certiorari_TotalsRecord(var TotalsRec : GrievanceTotalsRecord;
Status : Integer);
begin
Inc(TotalsRec.TotalCount);
If _Compare(Status, csOpen, coEqual)
then Inc(TotalsRec._Open);
If _Compare(Status,
[csApproved, csDenied, csWithdrawn, csDismissed], coEqual)
then Inc(TotalsRec._Closed);
If _Compare(Status, csApproved, coEqual)
then Inc(TotalsRec._Approved);
If _Compare(Status, csDenied, coEqual)
then Inc(TotalsRec._Denied);
If _Compare(Status, csWithdrawn, coEqual)
then Inc(TotalsRec._Withdrawn);
If _Compare(Status, csDismissed, coEqual)
then Inc(TotalsRec._Dismissed);
end; {UpdateSmallClaims_Certiorari_TotalsRecord}
{====================================================================}
Procedure UpdateGrievanceTotalsRecord(var TotalsRec : GrievanceTotalsRecord;
Status : Integer);
begin
Inc(TotalsRec.TotalCount);
If _Compare(Status, [gsOpen, gsMixed], coEqual)
then Inc(TotalsRec._Open);
If _Compare(Status,
[gsClosed, gsApproved, gsDenied, gsDismissed], coEqual)
then Inc(TotalsRec._Closed);
If _Compare(Status, gsApproved, coEqual)
then Inc(TotalsRec._Approved);
If _Compare(Status, gsDenied, coEqual)
then Inc(TotalsRec._Denied);
If _Compare(Status, gsWithdrawn, coEqual)
then Inc(TotalsRec._Withdrawn);
If _Compare(Status, gsDismissed, coEqual)
then Inc(TotalsRec._Dismissed);
end; {UpdateGrievanceTotalsRecord}
{====================================================================}
Procedure PrintGrievanceTotals(Sender : TObject;
TotalsRec : GrievanceTotalsRecord);
begin
with Sender as TBaseReport, TotalsRec do
begin
If (LinesLeft < 10)
then NewPage;
Println('');
ClearTabs;
SetTab(0.3, pjCenter, 1.7, 5, BoxLineAll, 25);
SetTab(2.0, pjCenter, 0.5, 5, BoxLineAll, 25);
Bold := True;
Println(#9 + 'Category' +
#9 + 'Count');
ClearTabs;
SetTab(0.3, pjLeft, 1.7, 5, BoxLineAll, 0);
SetTab(2.0, pjRight, 0.5, 5, BoxLineAll, 0);
Bold := False;
Bold := True;
Println(#9 + 'Total:' +
#9 + IntToStr(TotalCount));
Bold := False;
Println(#9 + ' Open:' +
#9 + IntToStr(_Open));
Println(#9 + ' Closed:' +
#9 + '');
Println(#9 + ' Approved:' +
#9 + IntToStr(_Approved));
Println(#9 + ' Denied:' +
#9 + IntToStr(_Denied));
Println(#9 + ' Dismissed:' +
#9 + IntToStr(_Dismissed));
Println(#9 + ' Withdrawn:' +
#9 + IntToStr(_Withdrawn));
end; {with Sender as TBaseReport, TotalsRec do}
end; {PrintGrievanceTotals}
{============================================================================}
Function ParcelHasOpenCertiorari(tbCertiorari : TTable;
sSwisSBLKey : String) : Boolean;
begin
Result := False;
_SetRange(tbCertiorari, [sSwisSBLKey], [], '', [loSameEndingRange]);
with tbCertiorari do
begin
First;
while (not EOF) do
begin
If _Compare(FieldByName('Disposition').AsString, coBlank)
then Result := True;
Next;
end; {while (not EOF) do}
end; {with tbCertiorari do}
end; {ParcelHasOpenCertiorari}
end. |
unit ClientListIntf;
interface
type
TClientFilterType = (cftAll,cftActive,cftRecent);
type
IClientFilter = interface(IInterface)
['{8EB2DE06-03CF-4BCE-B0A2-A75BA96D902D}']
procedure FilterList(const filterType: TClientFilterType;
const nonClients: boolean = false);
end;
implementation
end.
|
unit gfx_pcd;
{***********************************************************************
Unit gfx_pcd.PAS v1.2 0801
(c) by Andreas Moser, amoser@amoser.de,
Delphi version : Delphi 3 / 4
gfx_pcd is part of the gfx_library collection
You may use this sourcecode for your freewareproducts.
You may modify this source-code for your own use.
You may recompile this source-code for your own use.
All functions, procedures and classes may NOT be used in commercial
products without the permission of the author. For parts of this library
not written by me, you have to ask for permission by their
respective authors.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser amoser@amoser.de
********************************************************************************}
interface
uses SysUtils,
classes,
Windows,
JPEG,
Graphics,
io_files,
gfx_errors,
gfx_basedef;
// -----------------------------------------------------------------------------
//
// PCD classes
//
// -----------------------------------------------------------------------------
type
TPCDBitmap = class(TBitmap)
public
procedure LoadFromStream(Stream: TStream);override;
end;
Type
TPCDFile = class(TObject)
FBitmap :TBitmap;
public
constructor Create;
destructor Destroy;override;
procedure LoadFromFile(filename: String);
procedure LoadFromStream(Stream: TStream);
property Bitmap:TBitmap read FBitmap write FBitmap;
end;
// -----------------------------------------------------------------------------
//
// vars
//
// -----------------------------------------------------------------------------
var PCDSize: Integer;
implementation
//***********************************************************
//
// TPCDFile
//
//***********************************************************
// -----------------------------------------------------------------------------
//
// Create
//
// -----------------------------------------------------------------------------
constructor TPCDFile.Create;
begin
FBitmap:=TBitmap.Create;
PCDSize:=3;
end;
// -----------------------------------------------------------------------------
//
// Destroy
//
// -----------------------------------------------------------------------------
destructor TPCDFile.Destroy;
begin
FBitmap.Free;
inherited;
end;
// -----------------------------------------------------------------------------
//
// LoadFromFile
//
// -----------------------------------------------------------------------------
procedure TPCDFile.LoadFromFile(filename: String);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Stream.LoadFromFile(Filename);
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// LoadFromStream
//
// -----------------------------------------------------------------------------
procedure TPCDFile.LoadFromStream(Stream: TStream);
Var y,x:word;
Y1,Y2,CbCr:TBytearray;
ycbcr1,ycbcr2:TYCbCrTriple;
FirstRGB, SecondRGB:TRGBTriple;
b:integer;
Row,w,h,OriginH,OriginW:Integer;
TargetRow:pRGBArray;
DataByte:Byte;
Vertical:Boolean;
Begin
w:=0;
h:=0;
Stream.Position:=0;;
Stream.Seek(72,soFromBeginning);
Stream.Read(DataByte,1);
if DataByte And 63<>8 then Vertical:=True else vertical := False;
Case PCDsize Of
1: Begin
W:=192;
H:=128;
Stream.Seek($2000,soFromBeginning);
End;
2: Begin
W:=384;
H:=256;
Stream.Seek($B800,soFromBeginning);
End;
3: Begin
W:=768;
H:=512;
Stream.Seek($30000,soFromBeginning);
End;
End;
OriginH:=h;
OriginW:=w;
if Vertical then //change the dimensions of the Bitmap, cause the image is
begin // stored in vertical direction
b:=w;
w:=h;
h:=b;
end;
FBitmap.PixelFormat:=pf24Bit;
FBitmap.Width:=w;
FBitmap.Height:=h;
Row:=0;
For y:=0 To (originH div 2) -1 Do
Begin
Stream.Read(Y1,OriginW);
Stream.Read(Y2,OriginW);
Stream.Read(CbCr,OriginW);
For x:=0 To OriginW-1 Do
Begin
with ycbcr1 do
begin
ycbcrY:= Y1[x];
ycbcrCB:= CbCr[x Div 2];
ycbcrCR:= CbCr[(OriginW Div 2)+(x Div 2)];
end;
with ycbcr2 do
begin
ycbcrY:= Y2[x];
ycbcrCB:= CbCr[x Div 2];
ycbcrCR:= CbCr[(OriginW Div 2)+(x Div 2)];
end;
YCbCrToRGB(ycbcr1,FirstRGB);
YCbCrToRGB(ycbcr2,SecondRGB);
if not Vertical then
begin
TargetRow:=FBitmap.ScanLine[Row];
TargetRow[x]:=FirstRGB;
TargetRow:=FBitmap.ScanLine[Row+1];
TargetRow[x]:=SecondRGB;
end else
begin
TargetRow:=FBitmap.ScanLine[ORiginW-x-1];
TargetRow[Row]:=FirstRGB;
TargetRow:=FBitmap.ScanLine[originW-x-1];
TargetRow[Row+1]:=SecondRGB;
end;
End;
Inc(Row,2);
End;
End;
// -----------------------------------------------------------------------------
//
// LoadFromStream
//
// -----------------------------------------------------------------------------
procedure TPCDBitmap.LoadFromStream(Stream: TStream);
var
aPCD: TPCDFile;
aStream: TMemoryStream;
begin
aPCD := TPCDFile.Create;
try
aPCD.LoadFromStream(Stream);
aStream := TMemoryStream.Create;
try
PCDSize:=1;
aPCD.Bitmap.SaveToStream(aStream);
aStream.Position:=0;
inherited LoadFromStream(aStream);
finally
aStream.Free;
end;
finally
aPCD.Free;
end;
end;
initialization
PCDSize:=3;
TPicture.RegisterFileFormat('PCD','PCD-Format', TPCDBitmap);
finalization
TPicture.UnRegisterGraphicClass(TPCDBitmap);
end.
|
unit ClientMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Corba, Account_I, Account_C;
type
TForm1 = class(TForm)
btnBalance: TButton;
Label1: TLabel;
btnGetYearOpened: TButton;
btnSetYearOpened: TButton;
Label2: TLabel;
Edit1: TEdit;
chkToaster: TCheckBox;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure btnBalanceClick(Sender: TObject);
procedure btnGetYearOpenedClick(Sender: TObject);
procedure btnSetYearOpenedClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
acct : Account;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
acct := TAccountHelper.bind;
end;
procedure TForm1.btnBalanceClick(Sender: TObject);
begin
Label1.Caption := 'Balance = ' + FormatFloat('$#,##0.00', acct.balance);
end;
procedure TForm1.btnGetYearOpenedClick(Sender: TObject);
begin
Label2.Caption := 'Year Opened = ' + IntToStr(acct.YearOpened);
end;
procedure TForm1.btnSetYearOpenedClick(Sender: TObject);
begin
if Edit1.Text <> '' then //no check to ensure numbers!!
begin
Acct.YearOpened := StrToInt(Edit1.Text);
btnGetYearOpenedClick(Self);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
chkToaster.checked := acct.GotToaster;
end;
end.
|
unit UnRelatorio;
interface
uses Windows, SysUtils, Messages, Classes, Graphics, Controls,
StdCtrls, ExtCtrls, Forms, RLReport, DB,
{ helsonsant }
Util, DataUtil, UnModelo, Relatorios, QRCtrls, QuickRpt;
type
TRelatorio = class(TRLReport, IReport)
DetailBand1: TQRBand;
PageFooterBand1: TQRBand;
PageHeaderBand1: TQRBand;
SummaryBand1: TQRBand;
QRLabel1: TQRLabel;
QRLabel2: TQRLabel;
lblNumeroDePagina: TQRLabel;
lblTitulo: TQRLabel;
lblSubtitulo: TQRLabel;
QRImage1: TQRImage;
QRLabel3: TQRLabel;
procedure lblNumeroDePaginaPrint(sender: TObject; var Value: String);
private
FModelo: TModelo;
FTotalDePaginas: Integer;
public
function Dados(const Dados: TDataSet): IReport;
function Modelo(const Modelo: TModelo): IReport;
function ObterRelatorio: TRLReport;
function Subtitulo(const Subtitulo: string): IReport;
function Titulo(const Titulo: string): IReport;
function TotalDePaginas(const TotalDePaginas: Integer): IReport;
end;
var
Relatorio: TRelatorio;
implementation
{$R *.DFM}
{ TRelatorio }
function TRelatorio.Dados(const Dados: TDataSet): IReport;
var
_i: Integer;
begin
Self.DataSet := Dados;
for _i := 0 to Self.ComponentCount-1 do
if Self.Components[_i].Tag > 0 then
TQRDBText(Self.Components[_i]).DataSet := Self.DataSet;
end;
function TRelatorio.Modelo(const Modelo: TModelo): IReport;
begin
Self.FModelo := Modelo;
Result := Self;
end;
function TRelatorio.ObterRelatorio: TRLReport;
begin
Result := Self;
end;
function TRelatorio.Subtitulo(const Subtitulo: string): IReport;
begin
Self.lblSubtitulo.Caption := Subtitulo;
Result := Self;
end;
function TRelatorio.Titulo(const Titulo: string): IReport;
begin
Self.lblTitulo.Caption := Titulo;
Result := Self;
end;
function TRelatorio.TotalDePaginas(const TotalDePaginas: Integer): IReport;
begin
Self.FTotalDePaginas := TotalDePaginas;
Result := Self;
end;
procedure TRelatorio.lblNumeroDePaginaPrint(sender: TObject; var Value: String);
begin
Value := IntToStr(Self.PageNumber) + '/' + IntToStr(Self.FTotalDePaginas);
end;
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeDBEdit;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$ENDIF}
DB, TeEngine, TeeSourceEdit, TeCanvas;
type
TBaseDBChartEditor = class(TBaseSourceEditor)
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure FillSourceDatasets;
procedure FillSources;
protected
Function DataSet:TDataSet;
Procedure FillFields(const Combos:Array of TComboBox);
Function IsValid(AComponent:TComponent):Boolean; override;
public
{ Public declarations }
end;
TTeeSeriesDBSource=class(TTeeSeriesSource)
public
class Function Available(AChart:TCustomAxisPanel):Boolean; override;
class function HasNew: Boolean; override;
end;
var OnGetDesignerNames : TOnGetDesignerNamesEvent=nil;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses DBChart, Chart, TeeConst;
procedure TBaseDBChartEditor.FillSourceDatasets;
begin
CBSources.Items.Clear;
FillSources;
end;
Function TBaseDBChartEditor.IsValid(AComponent:TComponent):Boolean;
begin
result:=AComponent is TDataSet;
end;
procedure TBaseDBChartEditor.FillSources;
Procedure FillSourcesForm(ARoot:TComponent);
var t : Integer; { 5.01 }
begin
if Assigned(ARoot) and
(ARoot<>Self) and
(ARoot<>Self.Owner.Owner) then
With ARoot do
for t:=0 to ComponentCount-1 do
AddComponentDataSource(Components[t],CBSources.Items,True);
end;
var t : Integer;
begin
if Assigned(TheSeries) then
begin
if (csDesigning in TheSeries.ComponentState) and
Assigned(OnGetDesignerNames) then
OnGetDesignerNames(AddComponentDataSource,TheSeries,CBSources.Items,
True)
else
begin
With Screen do
begin
for t:=0 to DataModuleCount-1 do FillSourcesForm(DataModules[t]);
for t:=0 to FormCount-1 do FillSourcesForm(Forms[t]); { 5.01 }
end;
if Assigned(TheSeries.ParentChart) then
begin
FillSourcesForm(TheSeries.ParentChart); { 5.01 }
FillSourcesForm(TheSeries.ParentChart.Owner); { 5.01 }
end;
end;
end;
end;
procedure TBaseDBChartEditor.FormShow(Sender: TObject);
begin
inherited;
LLabel.Caption:=TeeMsg_AskDataSet;
FillSourceDatasets;
if Assigned(TheSeries) and Assigned(TheSeries.DataSource) then
With CBSources do
ItemIndex:=Items.IndexOfObject(TheSeries.DataSource);
end;
function TBaseDBChartEditor.DataSet: TDataSet;
begin
With CBSources do
if ItemIndex=-1 then result:=nil
else result:=TDataSet(Items.Objects[ItemIndex]);
end;
Procedure TBaseDBChartEditor.FillFields(const Combos:Array of TComboBox);
Procedure AddField(Const tmpSt:String; tmpType:TFieldType);
var t : Integer;
begin
Case TeeFieldType(tmpType) of
tftNumber,
tftDateTime,
tftText : begin
for t:=Low(Combos) to High(Combos) do
Combos[t].Items.Add(tmpSt);
end;
end;
end;
Var t : Integer;
Begin
for t:=Low(Combos) to High(Combos) do
Combos[t].Clear;
if DataSet<>nil then
With DataSet do
if FieldCount>0 then
for t:=0 to FieldCount-1 do
AddField(Fields[t].FieldName,Fields[t].DataType)
else
begin
FieldDefs.Update;
for t:=0 to FieldDefs.Count-1 do
AddField(FieldDefs[t].Name,FieldDefs[t].DataType);
end;
end;
{ TTeeSeriesDBSource }
class function TTeeSeriesDBSource.Available(AChart: TCustomAxisPanel):Boolean;
begin
result:=AChart is TCustomDBChart;
end;
class function TTeeSeriesDBSource.HasNew: Boolean;
begin
result:=True;
end;
initialization
finalization
OnGetDesignerNames:=nil;
end.
|
{
@abstract(Essa classe é uma classe final)
}
unit URetangulo;
interface
uses
UFormaGeometrica
, Graphics
, Controls
;
type
TRetangulo = class(TFormaGeometrica)
private
FBase: Integer;
FAltura: Integer;
public
constructor Create(const coCor: TColor);
function CalculaArea: Double; override;
function SolicitaParametros: Boolean; override;
procedure Desenha(const ciX: Integer; const ciY: Integer;
const coParent: TWinControl); override;
property ALTURA: Integer read FAltura;
property BASE: Integer read FBase;
end;
implementation
uses
Dialogs
, SysUtils
, ExtCtrls
;
{ TRetangulo }
constructor TRetangulo.Create(const coCor: TColor);
begin
Inherited Create(tfgRetangulo, coCor);
FShape.Shape := stRectangle;
end;
function TRetangulo.CalculaArea: Double;
begin
Result := FBase * FAltura;
end;
procedure TRetangulo.Desenha(const ciX, ciY: Integer;
const coParent: TWinControl);
begin
inherited;
FShape.Width := FBase;
FShape.Height := FAltura;
end;
function TRetangulo.SolicitaParametros: Boolean;
begin
FBase := StrToIntDef(InputBox('Informe', 'Base do Retangulo', ''), -1);
FAltura := StrToIntDef(InputBox('Informe', 'Altura do Retangulo', ''), -1);
Result := (FBase > -1) and (FAltura > -1);
end;
end.
|
{$IFDEF SOLID}
unit Stat;
interface
function SERVICE(ServiceNumber: Longint; Buffer: Pointer): Longint;
implementation
{$ELSE}
library Stat;
{$ENDIF}
{$IFDEF VIRTUALPASCAL}
uses Types, Consts_, Log, Video, Wizard, Misc, Language, Config, Semaphor,
Plugins, Dos;
{$IFNDEF SOLID}
{$Dynamic MAIN.LIB}
{$ENDIF}
{$ENDIF}
{$IFDEF DPMI}
uses
{$IFDEF SOLID}
Plugins, Semaphor, Language, Misc, Config, Video,
{$ELSE}
Decl,
{$ENDIF}
Wizard, Consts_, Dos, Macroz, Types;
{$ENDIF}
const
statVersion = $00010200;
_baseVersion: array[1..4] of char = 'Vera';
statCollect: boolean = False;
var
baseVersion: longint absolute _baseVersion;
type
TItem = record
messages: longint;
size: longint;
end;
PStatItem = ^TStatItem;
TStatItem = object(TObject)
public
name: PString;
addr: TAddress;
msgs: longint;
size: longint;
constructor Init(AName: String; AAddr: TAddress; AMsgs, ASize: Longint);
constructor Load(var S: TStream);
procedure Store(var S: TStream);
destructor Done; virtual;
end;
PStatCollection = ^TStatCollection;
TStatCollection = object(TCollection)
public
procedure Ins(Name: String; Addr: TAddress; Size: Longint);
procedure Load(var S: TStream);
procedure Store(var S: TStream);
end;
PData = ^TData;
TData = object(TObject)
public
_subject: PStatCollection;
_from: PStatCollection;
_to: PStatCollection;
_day: array[1..31] of TItem;
_dow: array[1..7] of TItem;
_hour: array[0..23] of TItem;
_total: TItem;
_area: PString;
_base: PString;
_output: PString;
_start: TDate;
_end: TDate;
_block: PStrings;
constructor Init(Area, Base, Output: String; pStart, pEnd: TDate);
procedure Load(var S: TStream);
procedure Store(var S: TStream);
destructor Done; virtual;
end;
var
Datas: PCollection;
{$i scan.inc}
{$i common.inc}
constructor TStatItem.Init;
begin
inherited Init;
Name:=NewStr(AName);
Addr:=AAddr;
Msgs:=AMsgs;
Size:=ASize;
end;
constructor TStatItem.Load;
begin
Name:=NewStr(S.ReadStr);
S.Read(Addr, SizeOf(Addr));
S.Read(Msgs, SizeOf(Msgs));
S.Read(Size, SizeOf(Size));
end;
procedure TStatItem.Store;
begin
S.WriteStr(GetPString(Name));
S.Write(Addr, SizeOf(Addr));
S.Write(Msgs, SizeOf(Msgs));
S.Write(Size, SizeOf(Size));
end;
destructor TStatItem.Done;
begin
DisposeStr(Name);
inherited Done;
end;
constructor TData.Init;
begin
inherited Init;
_Area:=NewStr(Area);
_Base:=NewStr(Base);
_Output:=NewStr(Output);
_Subject:=New(PStatCollection, Init);
_From:=New(PStatCollection, Init);
_To:=New(PStatCollection, Init);
_Start:=pStart;
_End:=pEnd;
FillChar(_day, SizeOf(_day), 0);
FillChar(_dow, SizeOf(_dow), 0);
FillChar(_hour, SizeOf(_hour), 0);
FillChar(_total, SizeOf(_total), 0);
end;
procedure TData.Load;
begin
_Subject^.Load(S);
_From^.Load(S);
_To^.Load(S);
S.Read(_day, SizeOf(_day));
S.Read(_dow, SizeOf(_dow));
S.Read(_hour, SizeOf(_hour));
S.Read(_total, SizeOf(_total));
end;
procedure TData.Store;
begin
_Subject^.Store(S);
_From^.Store(S);
_To^.Store(S);
S.Write(_day, SizeOf(_day));
S.Write(_dow, SizeOf(_dow));
S.Write(_hour, SizeOf(_hour));
S.Write(_total, SizeOf(_total));
end;
destructor TData.Done;
begin
Dispose(_Subject, Done);
Dispose(_From, Done);
Dispose(_To, Done);
DisposeStr(_Area);
DisposeStr(_Base);
DisposeStr(_Output);
inherited Done;
end;
procedure TStatCollection.Load(var S: TStream);
var
K, C: Longint;
begin
S.Read(C, SizeOf(C));
for K:=1 to C do
Insert(New(PStatItem, Load(S)));
end;
procedure TStatCollection.Store(var S: TStream);
var
K: Longint;
begin
S.Write(Count, SizeOf(Count));
for K:=1 to Count do
PStatItem(At(K))^.Store(S);
end;
procedure TStatCollection.Ins;
var
K: Longint;
I: PStatItem;
S1: String;
begin
I:=Nil;
S1:=StUpcase(Name);
for K:=1 to Count do
if StUpcase(GetPString(PStatItem(At(K))^.Name))=S1 then
begin
Inc(PStatItem(At(K))^.Msgs);
Inc(PStatItem(At(K))^.Size, Size);
Exit;
end;
I:=New(PStatItem, Init(Name, Addr, 1, Size));
Insert(I);
end;
procedure LoadBlock(Name: String);
var
B: PStrings;
D: PData;
Area, Database, Output, Period, KeyWord: String;
pStart: TDate;
pEnd: TDate;
S: TBufStream;
ID: Longint;
begin
B:=bSearch(Name);
if B=Nil then
begin
lngBegin;
lngPush(Name);
lngPrint('Main', 'stat.unknown.block');
lngEnd;
sSetExitNow;
Exit;
end;
Area:=Trim(iGetParam(B, 'Area'));
Database:=Trim(iGetParam(B, 'Database'));
Output:=Trim(iGetParam(B, 'Statistics'));
Period:=Trim(iGetParam(B, 'Period'));
if Area='' then KeyWord:='Area' else
if Database='' then KeyWord:='Database' else
if Output='' then KeyWord:='Statistics' else
if Period='' then KeyWord:='Period' else KeyWord:='';
if KeyWord<>'' then
begin
lngBegin;
lngPush(KeyWord);
lngPrint('Main', 'stat.bad.keyword');
lngEnd;
sSetExitNow;
Exit;
end;
ParseDate(ExtractWord(1, Period, [' ']), pStart);
ParseDate(ExtractWord(2, Period, [' ']), pEnd);
if (not ValidDate(pStart)) or (not ValidDate(pEnd)) then
begin
lngBegin;
lngPush(Period);
lngPrint('Main', 'stat.bad.period');
lngEnd;
sSetExitNow;
Exit;
end;
Database:=FExpand(Database);
D:=New(PData, Init(Area, Database, Output, pStart, pEnd));
D^._block:=B;
Datas^.Insert(D);
mCreate(JustPathName(Database));
S.Init(Database, stOpenRead, 2048);
if S.Status<>stOk then
begin
lngBegin;
lngPush(Database);
lngPrint('Main', 'stat.db.created');
lngEnd;
S.Done;
Exit;
end;
S.Read(ID, SizeOf(ID));
if ID=baseVersion then
D^.Load(S)
else
begin
lngBegin;
lngPush(Database);
lngPrint('Main', 'stat.db.id');
lngEnd;
S.Done;
Exit;
end;
S.Done;
lngBegin;
lngPush(Database);
lngPrint('Main', 'stat.db.loaded');
lngEnd;
end;
procedure SaveData(D: PData);
var
S: TBufStream;
FName: String;
begin
FName:=GetPString(D^._Base);
S.Init(FName, stCreate, 2048);
if S.Status<>stOk then
begin
lngBegin;
lngPush(FName);
lngPrint('Main', 'stat.db.error.creating');
lngEnd;
S.Done;
sSetExitNow;
Exit;
end;
S.Write(baseVersion, SizeOf(baseVersion));
D^.Store(S);
S.Done;
lngBegin;
lngPush(FName);
lngPrint('Main', 'stat.db.saved');
lngEnd;
end;
procedure Startup;
var
Blocks: PStrings;
K: Longint;
begin
Datas:=New(PCollection, Init);
cmCreateStrings(Blocks);
cProcessList('Stat.Define', Blocks);
for K:=1 to cmCount(Blocks) do
LoadBlock(GetPString(cmAt(Blocks, K)));
cmDisposeObject(Blocks);
statCollect:=cGetBoolParam('Stat.Collect');
end;
procedure Shutdown;
var
K: Longint;
begin
for K:=1 to Datas^.Count do
SaveData(Datas^.At(K));
Dispose(Datas, Done);
end;
procedure Statify(D: PData; Msg: PMessage);
var
Day, Month, Year, Hour, Min, Sec, Dow: XWord;
procedure Update(var I: TItem);
begin
Inc(I.Messages);
Inc(I.Size, Msg^.iSize);
end;
begin
ParsePktDateTime(Msg^.iDate, Day, Month, Year, Hour, Min, Sec, Dow);
if (Day<1) or (Day>31) or (Month<1) or (Month>12) or (Hour<0) or (Hour>23) or (Min<0) or (Min>59) or
(Dow<0) or (Dow>6) then
begin
lngBegin;
lngPush(Msg^.iDate);
lngPrint('Main', 'stat.timestamp');
lngEnd;
Exit;
end;
if not InDate(D^._Start, D^._End, Day, Month, Year) then Exit;
if Dow=0 then Dow:=7;
D^._subject^.Ins(uCleanupSubj(Msg^.iSubj), Msg^.iFromAddress, Msg^.iSize);
D^._from^.Ins(Msg^.iFrom, Msg^.iFromAddress, Msg^.iSize);
D^._to^.Ins(Msg^.iTo, Msg^.iToAddress, Msg^.iSize);
Update(D^._day[Day]);
Update(D^._dow[Dow]);
Update(D^._hour[Hour]);
Update(D^._total);
end;
procedure Scan(Msg: PMessage);
var
K: Longint;
D: PData;
begin
for K:=1 to Datas^.Count do
begin
D:=Datas^.At(K);
if mCheckWildCard(Msg^.iArea, D^._area^) then
Statify(D, Msg);
end;
end;
var
Macros: Pointer;
Data: PData;
Cache: PStrings;
F: Text;
procedure ReInitMacros;
begin
umDestroyMacros(Macros);
Macros:=umCreateMacros;
umAddMacro(Macros, '@echo', GetPString(Data^._Area));
umAddMacro(Macros, '@startdate', Date2Str(Data^._Start));
umAddMacro(Macros, '@enddate', Date2Str(Data^._End));
umAddMacro(Macros, '@totalmessages', Long2Str(Data^._Total.Messages));
umAddMacro(Macros, '@totalsize', Long2Str(Data^._Total.Size));
if Data^._Total.Messages=0 then
umAddMacro(Macros, '@averagesize', '0')
else
umAddMacro(Macros, '@averagesize', Long2Str(Round(Data^._Total.Size/(Data^._Total.Messages+1))));
end;
procedure WriteLine(S: String);
begin
{$i-}
InOutRes:=0;
WriteLn(F, S);
InOutRes:=0;
end;
procedure ProcessStrings(Key: String);
var
List: PStrings;
K: Longint;
S: String;
begin
cmCreateStrings(List);
iProcessList(Data^._block, Key, List);
for K:=1 to cmCount(List) do
begin
S:=umProcessMacro(Macros, GetPString(cmAt(List, K)));
if not umEmptyLine(Macros) then WriteLine(S);
end;
cmDisposeObject(List);
end;
procedure CacheStrings(Key: String);
begin
cmFreeAll(Cache);
iProcessList(Data^._block, Key, Cache);
end;
procedure ProcessCachedStrings;
var
S: String;
K: Longint;
begin
for K:=1 to cmCount(Cache) do
begin
S:=umProcessMacro(Macros, GetPString(cmAt(Cache, K)));
if not umEmptyLine(Macros) then WriteLine(S);
end;
end;
function GetNumValue(Key: String): longint;
var
K: Longint;
begin
K:=iGetNumParam(Data^._block, Key);
if K=0 then K:=16383;
GetNumValue:=K;
end;
procedure AddMacro(ID, Data: String);
begin
umAddMacro(Macros, ID, Data);
end;
function SortHandler_Msgs(C: PCollection; Key1, Key2: Longint): Longint; Far;
var
I1, I2: PStatItem;
R: Longint;
begin
I1:=C^.At(Key1);
I2:=C^.At(Key2);
if (I1=Nil) and (I2<>Nil) then R:=1 else
if (I1<>Nil) and (I2=Nil) then R:=-1 else
if (I1=Nil) and (I2=Nil) then R:=0 else
if I1^.Msgs>I2^.Msgs then R:=-1 else
if I1^.Msgs<I2^.Msgs then R:=1 else
if I1^.Size>I2^.Size then R:=-1 else
if I1^.Size<I2^.Size then R:=1 else
if GetPString(I1^.Name)<GetPString(I2^.Name) then R:=-1 else
if GetPString(I1^.Name)>GetPString(I2^.Name) then R:=1 else
R:=0;
SortHandler_Msgs:=R;
end;
function SortHandler_Size(C: PCollection; Key1, Key2: Longint): Longint; Far;
var
I1, I2: PStatItem;
R: Longint;
begin
I1:=C^.At(Key1);
I2:=C^.At(Key2);
if (I1=Nil) and (I2<>Nil) then R:=1 else
if (I1<>Nil) and (I2=Nil) then R:=-1 else
if (I1=Nil) and (I2=Nil) then R:=0 else
if I1^.Size>I2^.Size then R:=-1 else
if I1^.Size<I2^.Size then R:=1 else
if I1^.Msgs>I2^.Msgs then R:=-1 else
if I1^.Msgs<I2^.Msgs then R:=1 else
if GetPString(I1^.Name)<GetPString(I2^.Name) then R:=-1 else
if GetPString(I1^.Name)>GetPString(I2^.Name) then R:=1 else
R:=0;
SortHandler_Size:=R;
end;
procedure Build(D: PData);
function Init: boolean;
var
S: String;
begin
Macros:=umCreateMacros;
Data:=D;
cmCreateStrings(Cache);
S:=FExpand(Trim(iGetParam(D^._block, 'Statistics')));
mCreate(JustPathName(S));
{$i-}
InOutRes:=0;
Assign(F, S);
Rewrite(F);
if InOutRes<>0 then
begin
lngBegin;
lngPush(S);
lngPrint('Main', 'stat.error.creating');
lngEnd;
Init:=False;
Exit;
end;
Init:=True;
end;
procedure Header;
begin
ReInitMacros; ProcessStrings('Header');
end;
procedure Overall;
begin
ReInitMacros; ProcessStrings('Overall');
end;
procedure SendersMsgs;
var
K: Longint;
S: PStatItem;
begin
ReInitMacros; ProcessStrings('Senders.Msgs.Header');
Data^._From^.Sort(SortHandler_Msgs);
CacheStrings('Senders.Msgs.Center');
ReInitMacros;
for K:=1 to GetNumValue('Senders.Msgs.Count') do
begin
S:=Data^._From^.At(K);
if S=Nil then Break;
AddMacro('@no', Long2Str(K));
AddMacro('@name', GetPString(S^.Name));
AddMacro('@address', Address2Str(S^.Addr));
AddMacro('@msgs', Long2Str(S^.Msgs));
AddMacro('@size', Long2Str(S^.Size));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Senders.Msgs.Footer');
end;
procedure SendersSize;
var
K: Longint;
S: PStatItem;
begin
ReInitMacros; ProcessStrings('Senders.Size.Header');
Data^._From^.Sort(SortHandler_Size);
CacheStrings('Senders.Size.Center');
ReInitMacros;
for K:=1 to GetNumValue('Senders.Size.Count') do
begin
S:=Data^._From^.At(K);
if S=Nil then Break;
AddMacro('@no', Long2Str(K));
AddMacro('@name', GetPString(S^.Name));
AddMacro('@address', Address2Str(S^.Addr));
AddMacro('@msgs', Long2Str(S^.Msgs));
AddMacro('@size', Long2Str(S^.Size));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Senders.Size.Footer');
end;
procedure ReceiversMsgs;
var
K: Longint;
S: PStatItem;
begin
ReInitMacros; ProcessStrings('Receivers.Msgs.Header');
Data^._To^.Sort(SortHandler_Msgs);
CacheStrings('Receivers.Msgs.Center');
ReInitMacros;
for K:=1 to GetNumValue('Receivers.Msgs.Count') do
begin
S:=Data^._To^.At(K);
if S=Nil then Break;
AddMacro('@no', Long2Str(K));
AddMacro('@name', GetPString(S^.Name));
AddMacro('@address', Address2Str(S^.Addr));
AddMacro('@msgs', Long2Str(S^.Msgs));
AddMacro('@size', Long2Str(S^.Size));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Receivers.Msgs.Footer');
end;
procedure ReceiversSize;
var
K: Longint;
S: PStatItem;
begin
ReInitMacros; ProcessStrings('Receivers.Size.Header');
Data^._To^.Sort(SortHandler_Size);
CacheStrings('Receivers.Size.Center');
ReInitMacros;
for K:=1 to GetNumValue('Receivers.Size.Count') do
begin
S:=Data^._To^.At(K);
if S=Nil then Break;
AddMacro('@no', Long2Str(K));
AddMacro('@name', GetPString(S^.Name));
AddMacro('@address', Address2Str(S^.Addr));
AddMacro('@msgs', Long2Str(S^.Msgs));
AddMacro('@size', Long2Str(S^.Size));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Receivers.Size.Footer');
end;
procedure SubjsMsgs;
var
K: Longint;
S: PStatItem;
begin
ReInitMacros; ProcessStrings('Subjs.Msgs.Header');
Data^._Subject^.Sort(SortHandler_Msgs);
CacheStrings('Subjs.Msgs.Center');
ReInitMacros;
for K:=1 to GetNumValue('Subjs.Msgs.Count') do
begin
S:=Data^._Subject^.At(K);
if S=Nil then Break;
AddMacro('@no', Long2Str(K));
AddMacro('@subj', GetPString(S^.Name));
AddMacro('@msgs', Long2Str(S^.Msgs));
AddMacro('@size', Long2Str(S^.Size));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Subjs.Msgs.Footer');
end;
procedure SubjsSize;
var
K: Longint;
S: PStatItem;
begin
ReInitMacros; ProcessStrings('Subjs.Size.Header');
Data^._Subject^.Sort(SortHandler_Size);
CacheStrings('Subjs.Size.Center');
ReInitMacros;
for K:=1 to GetNumValue('Subjs.Size.Count') do
begin
S:=Data^._Subject^.At(K);
if S=Nil then Break;
AddMacro('@no', Long2Str(K));
AddMacro('@subj', GetPString(S^.Name));
AddMacro('@msgs', Long2Str(S^.Msgs));
AddMacro('@size', Long2Str(S^.Size));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Subjs.Size.Footer');
end;
procedure DowMsgs;
var
K, M: Longint;
begin
ReInitMacros;
AddMacro('@size', Long2Str(D^._total.size));
AddMacro('@msgs', Long2Str(D^._total.messages));
M:=0;
for K:=1 to 7 do
if D^._dow[K].size > M then M:=D^._dow[K].size;
AddMacro('@maxsize', Long2Str(M));
M:=0;
for K:=1 to 7 do
if D^._dow[K].messages > M then M:=D^._dow[K].messages;
AddMacro('@maxmsgs', Long2Str(M));
for K:=1 to 7 do
begin
AddMacro('@d'+Long2Str(K)+'msgs', Long2Str(D^._dow[K].messages));
AddMacro('@d'+Long2Str(K)+'size', Long2Str(D^._dow[K].size));
end;
ProcessStrings('Dow.Msgs');
end;
procedure DowSize;
var
K, M: Longint;
begin
ReInitMacros;
AddMacro('@size', Long2Str(D^._total.size));
AddMacro('@msgs', Long2Str(D^._total.messages));
M:=0;
for K:=1 to 7 do
if D^._dow[K].size > M then M:=D^._dow[K].size;
AddMacro('@maxsize', Long2Str(M));
M:=0;
for K:=1 to 7 do
if D^._dow[K].messages > M then M:=D^._dow[K].messages;
AddMacro('@maxmsgs', Long2Str(M));
for K:=1 to 7 do
begin
AddMacro('@d'+Long2Str(K)+'msgs', Long2Str(D^._dow[K].messages));
AddMacro('@d'+Long2Str(K)+'size', Long2Str(D^._dow[K].size));
end;
ProcessStrings('Dow.Size');
end;
procedure DayMsgs;
var
I: ^TItem;
K, M: Longint;
begin
ReInitMacros; ProcessStrings('Day.Msgs.Header');
ReInitMacros; CacheStrings('Day.Msgs.Center');
M:=0;
for K:=1 to 31 do
if D^._day[K].size > M then M:=D^._day[K].size;
AddMacro('@maxsize', Long2Str(M));
M:=0;
for K:=1 to 31 do
if D^._day[K].messages > M then M:=D^._day[K].messages;
AddMacro('@maxmsgs', Long2Str(M));
for K:=1 to 31 do
begin
I:=@D^._day[K];
AddMacro('@msgs', Long2Str(D^._total.Messages));
AddMacro('@size', Long2Str(D^._total.Size));
AddMacro('@daymsgs', Long2Str(I^.Messages));
AddMacro('@daysize', Long2Str(I^.Size));
AddMacro('@day', Long2Str(K));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Day.Msgs.Footer');
end;
procedure DaySize;
var
I: ^TItem;
K, M: Longint;
begin
ReInitMacros; ProcessStrings('Day.Size.Header');
ReInitMacros; CacheStrings('Day.Size.Center');
M:=0;
for K:=1 to 31 do
if D^._day[K].size > M then M:=D^._day[K].size;
AddMacro('@maxsize', Long2Str(M));
M:=0;
for K:=1 to 31 do
if D^._day[K].messages > M then M:=D^._day[K].messages;
AddMacro('@maxmsgs', Long2Str(M));
for K:=1 to 31 do
begin
I:=@D^._day[K];
AddMacro('@msgs', Long2Str(D^._total.Messages));
AddMacro('@size', Long2Str(D^._total.Size));
AddMacro('@daymsgs', Long2Str(I^.Messages));
AddMacro('@daysize', Long2Str(I^.Size));
AddMacro('@day', Long2Str(K));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Day.Size.Footer');
end;
procedure HourMsgs;
var
I: ^TItem;
K, M: Longint;
begin
ReInitMacros; ProcessStrings('Hour.Msgs.Header');
ReInitMacros; CacheStrings('Hour.Msgs.Center');
M:=0;
for K:=0 to 23 do
if D^._hour[K].size > M then M:=D^._hour[K].size;
AddMacro('@maxsize', Long2Str(M));
M:=0;
for K:=0 to 23 do
if D^._hour[K].messages > M then M:=D^._hour[K].messages;
AddMacro('@maxmsgs', Long2Str(M));
for K:=0 to 23 do
begin
I:=@D^._hour[K];
AddMacro('@msgs', Long2Str(D^._total.Messages));
AddMacro('@size', Long2Str(D^._total.Size));
AddMacro('@hourmsgs', Long2Str(I^.Messages));
AddMacro('@hoursize', Long2Str(I^.Size));
AddMacro('@hour', Long2Str(K));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Hour.Msgs.Footer');
end;
procedure HourSize;
var
I: ^TItem;
K, M: Longint;
begin
ReInitMacros; ProcessStrings('Hour.Size.Header');
ReInitMacros; CacheStrings('Hour.Size.Center');
M:=0;
for K:=0 to 23 do
if D^._hour[K].size > M then M:=D^._hour[K].size;
AddMacro('@maxsize', Long2Str(M));
M:=0;
for K:=0 to 23 do
if D^._hour[K].messages > M then M:=D^._hour[K].messages;
AddMacro('@maxmsgs', Long2Str(M));
for K:=0 to 23 do
begin
I:=@D^._hour[K];
AddMacro('@msgs', Long2Str(D^._total.Messages));
AddMacro('@size', Long2Str(D^._total.Size));
AddMacro('@hourmsgs', Long2Str(I^.Messages));
AddMacro('@hoursize', Long2Str(I^.Size));
AddMacro('@hour', Long2Str(K));
ProcessCachedStrings;
end;
ReInitMacros; ProcessStrings('Hour.Size.Footer');
end;
procedure Footer;
begin
ReInitMacros; ProcessStrings('Footer');
end;
procedure Done;
begin
umDestroyMacros(Macros);
cmDisposeObject(Cache);
Close(F);
end;
var
S: String;
K: Byte;
begin
if D=Nil then Exit;
if not Init then Exit;
S:=Trim(StUpcase(iGetParam(D^._block, 'Order')));
lngBegin;
lngPush(GetPString(D^._area));
lngPrint('Main', 'stat.start');
lngEnd;
for K:=1 to Length(S) do
begin
case S[K] of
'1': Header;
'2': Overall;
'3': SendersMsgs;
'4': SendersSize;
'5': ReceiversMsgs;
'6': ReceiversSize;
'7': SubjsMsgs;
'8': SubjsSize;
'9': DowMsgs;
'A': DowSize;
'B': DayMsgs;
'C': DaySize;
'D': HourMsgs;
'E': HourSize;
'F': Footer;
else
lngBegin;
lngPush(S[K]);
lngPrint('Main', 'stat.dot.error');
lngEnd;
continue;
end;
lngBegin;
lngPush(S[K]);
lngPrint('Main', 'stat.dot');
lngEnd;
end;
lngPrint('Main', 'stat.end');
Done;
end;
procedure Start;
var
K: Longint;
begin
if sExitNow then Exit;
if not cGetBoolParam('Stat.Make') then EXit;
for K:=1 to Datas^.Count do
begin
mCheckBreak;
if sExitNow then Break;
Build(Datas^.At(K));
end;
end;
function SERVICE(ServiceNumber: Longint; Buffer: Pointer): Longint; {$IFNDEF SOLID}export;{$ENDIF}
begin
Service:=srYes;
case ServiceNumber of
snAfterStartup:
begin
mCheckPlugin('STAT', 'USER');
end;
snStartup: Startup;
snShutdown: Shutdown;
snStart: Start;
snQueryName: sSetSemaphore('Kernel.Plugins.Info.Name','STATISTIX');
snQueryAuthor: sSetSemaphore('Kernel.Plugins.Info.Author','sergey korowkin');
snQueryVersion: Service:=statVersion;
snQueryReqVer: Service:=kernelVersion;
snsMessage:
if statCollect then Scan(Buffer);
snsAreYouScanner: Service:=snrIamScanner;
else
Service:=srNotSupported;
end;
end;
{$IFNDEF SOLID}
exports
SERVICE;
begin
{$ENDIF}
end.
|
unit ClipboardUnit;
interface
uses
System.Classes;
type
TClb = class(TObject)
private
class var Instance: TClb;
// TODO: GetRows
// function GetRows: TStringList;
public
function ConcatRows: string;
function GetRowsAsArray: TArray<String>;
class function NewInstance: TObject; override;
end;
implementation
uses Vcl.Clipbrd, Winapi.Windows, System.SysUtils, System.Contnrs, StrHelper;
var
SingletonList: TObjectList;
function TClb.ConcatRows: string;
begin
Result := StrHelper.DeleteDouble(Clipboard.AsText.Trim.Replace(#13, ' ')
.Replace(#10, ' '), ' ');
end;
function TClb.GetRowsAsArray: TArray<String>;
var
i: Integer;
S: string;
begin
S := Clipboard.AsText.Trim;
// Разбиваем текст на строки
Result := S.Split([#13]);
for i := Low(Result) to High(Result) do
begin
Result[i] := Result[i].Trim([#13, #10, ' ']);
end;
end;
class function TClb.NewInstance: TObject;
begin
if not Assigned(Instance) then
begin
Instance := TClb(inherited NewInstance);
SingletonList.Add(Instance);
end;
Result := Instance;
end;
initialization
SingletonList := TObjectList.Create(True);
finalization
FreeAndNil(SingletonList);
end.
|
unit FileLib;
{ FileLib v1.5 (c) by sergey korowkin, 1998. }
interface
uses
Types, Wizard, Video, Log;
type
PItem = ^TItem;
TItem = record
Id: Byte;
Offset: Longint;
Size: Longint;
Name: String[118];
end;
PIndex = ^TIndex;
TIndex = object(TCollection)
procedure FreeItem(Item: Pointer); virtual;
end;
PLibrary = ^TLibrary;
TLibrary = object(TObject)
public
DataLink: PBufStream;
Index: PIndex;
Debugging: Boolean;
Error: Boolean;
ErrorString: String;
constructor Init(const DataName: String);
destructor Done; virtual;
procedure Debug(const S: String); virtual;
procedure DoError(const S: String);
procedure Prepare;
procedure LoadIndex;
procedure StoreIndex; virtual;
procedure AddResource(const Name: String; S: PStream; const Size: Longint);
procedure AddResourceFromMemory(const Name: String; Data: Pointer; const Size: Longint);
function QueryResource(Name: String): PItem;
procedure KillResource(const Name: String);
function GetResourceSize(const Name: String): Longint;
procedure GetResource(const Name: String; S: PStream);
procedure GetResourceToMemory(const Name: String; Data: Pointer);
procedure Pack(Temp: PStream);
procedure Reset;
end;
const
MaxResources = 4096;
IndexSize = MaxResources * SizeOf(TItem);
ridResource = 1;
implementation
procedure TIndex.FreeItem(Item: Pointer);
begin
if Item <> Nil then
Dispose(PItem(Item));
end;
{* TLibrary *}
constructor TLibrary.Init;
begin
inherited Init;
Debugging:=False;
Error:=False;
Debug('TLibrary.Init()');
Debug('Creating indexcollection');
Index:=New(PIndex, Init);
Debug('Using ' + DataName + ' as resourcefile');
DataLink:=New(PBufStream, Init(DataName, stOpen, 2048));
if DataLink^.Status <> stOk then
begin
Debug('Cannot open resourcefile (stOpen) - rc#' + Long2Str(DataLink^.Status));
Dispose(DataLink, Done);
DataLink:=New(PBufStream, Init(DataName, stCreate, 2048));
Debug('Resourcefile created.');
Prepare;
end
else
LoadIndex;
end;
destructor TLibrary.Done;
begin
StoreIndex;
Debug('Destroying DataLink');
Dispose(DataLink, Done);
Debug('Destroying Index');
Dispose(Index, Done);
Debug('Destroying TLibrary');
inherited Done;
end;
procedure TLibrary.Debug;
begin
if Debugging then
LogWrite('Main', 'rDebug: ' + S);
end;
procedure TLibrary.DoError;
begin
Error:=True;
ErrorString:=S;
end;
procedure TLibrary.Prepare;
begin
Debug('Preparing resourcefile [' + Long2Str(IndexSize) + ']');
DataLink^.Seek(IndexSize);
Debug('Truncating...');
DataLink^.Truncate;
end;
procedure TLibrary.LoadIndex;
var
Count, K: Longint;
I: PItem;
begin
Debug('LoadIndex() started.');
DataLink^.Seek(0);
DataLink^.Read(Count, SizeOf(Count));
Debug('Resourcefile contains ' + Long2Str(Count) + ' resources [max ' + Long2Str(MaxResources) + ']');
if Count > MaxResources then
begin
DoError('???: Count:' + HexL(Count) + '; MaxResources:' + HexL(MaxResources) + '; it''s wrong.');
Exit;
end;
Debug('Cleaning index...');
Index^.FreeAll;
Debug('Loading index...');
for K:=1 to Count do
begin
New(I);
DataLink^.Read(I^, SizeOf(I^));
if I^.Offset > DataLink^.GetSize then
begin
DoError('???: ofs ' + HexL(I^.Offset) + ' out of resourcefile');
Break;
end;
Index^.Insert(I);
end;
end;
procedure TLibrary.StoreIndex;
var
Count, K: Longint;
I: PItem;
begin
Debug('StoreIndex() started.');
Count:=Index^.Count;
Debug('Writing indexsize...');
DataLink^.Seek(0);
DataLink^.Write(Count, SizeOf(Count));
Debug('Writing index...');
for K:=1 to Count do
begin
I:=Index^.At(K);
DataLink^.Write(I^, SizeOf(I^));
end;
DataLink^.Flush;
Debug('Ok.');
end;
procedure TLibrary.AddResource(const Name: String; S: PStream; const Size: Longint);
var
I: PItem;
begin
Debug('Adding resource "' + Name + '"');
if QueryResource(Name) <> Nil then KillResource(Name);
Debug('Creating structures...');
New(I);
FillChar(I^, SizeOf(I^), $FF);
I^.Id:=ridResource;
I^.Offset:=DataLink^.GetSize;
I^.Size:=Size;
Debug('Resource offset is ' + HexL(I^.Offset) + '; size is ' + HexL(I^.Size));
I^.Name:=Name;
Debug('Updating index...');
Index^.Insert(I);
Debug('Writing resource to the resourcefile...');
DataLink^.Seek(I^.Offset);
DataLink^.CopyFrom(S^, Size);
StoreIndex;
end;
procedure TLibrary.AddResourceFromMemory(const Name: String; Data: Pointer; const Size: Longint);
var
Stream: TMemoryStream;
begin
Debug('Adding resource "' + Name + '" from memory.');
Stream.Init;
Debug('Writing data ' + HexL(Longint(Data)) + ' to the memory stream [' + HexL(Size) + ' bytes]');
Stream.Write(Data^, Size);
Stream.Seek(0);
Debug('Calling AddResource...');
AddResource(Name, @Stream, Size);
Stream.Done;
end;
function TLibrary.QueryResource(Name: String): PItem;
var
K: Longint;
I: PItem;
begin
Debug('Querying resource "' + Name + '"');
StUpcaseEx(Name);
for K:=1 to Index^.Count do
begin
I:=Index^.At(K);
if StUpcase(I^.Name) = Name then
begin
QueryResource:=I;
Debug('Found, ' + HexL(Longint(I)) + '.');
Exit;
end;
end;
QueryResource:=Nil;
Debug('Not found.');
end;
procedure TLibrary.KillResource(const Name: String);
var
Resource: PItem;
begin
Debug('Killing resource "' + Name + '"');
Resource:=QueryResource(Name);
if Resource = Nil then Exit;
Index^.Free(Resource);
Debug('Killed.');
StoreIndex;
end;
function TLibrary.GetResourceSize(const Name: String): Longint;
var
I: PItem;
begin
I:=QueryResource(Name);
if I = Nil then
GetResourceSize:=-1
else
GetResourceSize:=I^.Size;
end;
procedure TLibrary.GetResource(const Name: String; S: PStream);
var
I: PItem;
begin
Debug('GetResource "' + Name + '" to the stream "' + HexL(Longint(S)) + '"');
I:=QueryResource(Name);
if I = Nil then Exit;
DataLink^.Seek(I^.Offset);
S^.CopyFrom(DataLink^, I^.Size);
Debug('GetResource: ' + Long2Str(I^.Size) + ' bytes ok.');
end;
procedure TLibrary.GetResourceToMemory(const Name: String; Data: Pointer);
var
S: TMemoryStream;
begin
Debug('GetResourceToMemory "' + Name + '" to "' + HexL(Longint(Data)) + '"');
S.Init;
Debug('Calling GetResource');
GetResource(Name, @S);
S.Seek(0);
Debug('Moving streamdata to destination');
S.Read(Data^, S.GetSize);
S.Done;
Debug('Ok');
end;
procedure TLibrary.Pack(Temp: PStream);
var
K: Longint;
I: PItem;
begin
Debug('Repacking of resourcefile started.');
Debug('Preparing tempstream...');
Temp^.Seek(0);
Temp^.Truncate;
Debug('Writing resources to the tempstream...');
for K:=1 to Index^.Count do
begin
I:=Index^.At(K);
DataLink^.Seek(I^.Offset);
I^.Offset:=IndexSize + Temp^.GetPos;
Temp^.CopyFrom(DataLink^, I^.Size);
end;
Debug('Writing resources back to the mainstream...');
DataLink^.Seek(IndexSize);
Temp^.Seek(0);
DataLink^.CopyFrom(Temp^, Temp^.GetSize);
DataLink^.Flush;
DataLink^.Truncate;
DataLink^.Flush;
Debug('Repacking done.');
StoreIndex;
end;
procedure TLibrary.Reset;
begin
Error:=False;
ErrorString:='';
end;
end. |
unit uShortIntStr;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
const
charShInt = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
base = 62;
type
TForm26 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form26: TForm26;
implementation
{$R *.dfm}
function IntToshInt(I: Integer): String;
var i2: Integer;
begin
Result := '';
while I>0 do begin
i2 := (I mod base)+1;
Result := Copy(charshInt, i2, 1) + result;
I := I div base;
end;
end;
function elev(a, b: Integer): Integer;
begin
if b=0 then
Result := 1 else
Result := a;
while b>1 do begin
result := result * a;
dec(b);
end;
end;
function shIntToInt(s: String): Integer;
begin
Result := 0;
while s>'' do begin
result := result + ((Pos(s[1], charshInt)-1) * elev(base, Length(s)-1));
Delete(S, 1, 1);
end;
end;
procedure TForm26.Button1Click(Sender: TObject);
var s: string;
begin
{ s := IntToshInt(477078);
showMessage(s); }
showMessage(IntToStr(shIntToInt('AAz')));
end;
end.
|
unit CaixaAplicacao;
interface
uses Classes, DB, DBClient,
{ Fluente }
Util, DataUtil, UnCaixaModelo, Componentes, UnAplicacao;
type
TCaixaAplicacao = class(TAplicacao, IResposta)
private
FCaixaMenuView: ITela;
FCaixaModelo: TCaixaModelo;
protected
procedure ExibirRegistroDeCaixa(const Chamada: TChamada);
procedure ImprimirExtratoDeCaixa;
public
function AtivarAplicacao: TAplicacao; override;
procedure Responder(const Chamada: TChamada);
function Descarregar: TAplicacao; override;
function Preparar(
const ConfiguracaoAplicacao: TConfiguracaoAplicacao): TAplicacao;override;
end;
function RetornarOperacaoDeCaixa(
const CodigoDaOperacaoDeCaixa: Integer): OperacoesDeCaixa;
implementation
uses SysUtils,
{ Fluente }
UnCaixaMenuView, UnCaixaRegistroView, UnComandaPrint;
function RetornarOperacaoDeCaixa(
const CodigoDaOperacaoDeCaixa: Integer): OperacoesDeCaixa;
begin
case CodigoDaOperacaoDeCaixa of
0: Result := odcAbertura;
1: Result := odcTroco;
2: Result := odcSaida;
3: Result := odcSuprimento;
4: Result := odcSangria;
5: Result := odcFechamento;
else
Result := odcExtrato;
end;
end;
{ TProdutoAplicacao }
function TCaixaAplicacao.AtivarAplicacao: TAplicacao;
begin
Self.FCaixaMenuView.ExibirTela;
Result := Self;
end;
procedure TCaixaAplicacao.Responder(const Chamada: TChamada);
var
_operacao: OperacoesDeCaixa;
begin
_operacao := RetornarOperacaoDeCaixa(Chamada.ObterParametros
.Ler('operacao').ComoInteiro);
if _operacao = odcExtrato then
begin
Self.FCaixaModelo.CarregarExtrato(Date, Date);
Self.ImprimirExtratoDeCaixa;
end
else
begin
Chamada.ObterParametros.Gravar('operacao', Ord(_operacao));
Self.ExibirRegistroDeCaixa(Chamada);
end;
end;
function TCaixaAplicacao.Descarregar: TAplicacao;
begin
if Self.FCaixaMenuView <> nil then
Self.FCaixaMenuView.Descarregar;
Result := Self;
end;
function TCaixaAplicacao.Preparar(
const ConfiguracaoAplicacao: TConfiguracaoAplicacao): TAplicacao;
begin
Self.FCaixaModelo := (
Self.FFabricaDeModelos.ObterModelo('CaixaModelo') as TCaixaModelo);
Self.FCaixaMenuView := TCaixaMenuView.Create(nil)
.Modelo(Self.FCaixaModelo)
.Controlador(Self)
.Preparar;
Result := Self;
end;
procedure TCaixaAplicacao.ExibirRegistroDeCaixa(const Chamada: TChamada);
var
_caixaRegistroView: ITela;
_eventoAntesDeChamar, _eventoAposChamar: TNotifyEvent;
begin
_eventoAntesDeChamar := Chamada.EventoParaExecutarAntesDeChamar;
_eventoAposChamar := Chamada.EventoParaExecutarAposChamar;
_caixaRegistroView := TCaixaRegistroView.Create(nil)
.Controlador(Self)
.Modelo(Self.FCaixaModelo)
.Preparar;
try
if Assigned(_eventoAntesDeChamar) then
_eventoAntesDeChamar(Chamada.ObterChamador);
_caixaRegistroView.ExibirTela;
if Assigned(_eventoAposChamar) then
_eventoAposChamar(Chamada.ObterChamador);
finally
_caixaRegistroView.Descarregar;
end;
end;
procedure TCaixaAplicacao.ImprimirExtratoDeCaixa;
var
_colunas: Integer;
_impressora: TComandaPrint;
_linhaSimples, _linhaDupla: string;
_dataSet: TClientDataSet;
_valor, _saldoFinal: Real;
begin
_colunas := 40;
_linhaSimples := StringOfChar('-', _colunas);
_linhaDupla := StringOfChar('=', _colunas);
// Imprime cabecalho
_impressora := TComandaPrint.Create
.DispositivoParaImpressao(ddiTela)
.DefinirLarguraDaImpressaoEmCaracteres(_colunas)
.AlinharAEsquerda
.Preparar
.IniciarImpressao
.ImprimirLinha('Lanchonete')
.ImprimirLinha(_linhaDupla)
.ImprimirLinha('Fone: 4028-1010')
.ImprimirLinha(_linhaSimples)
.ImprimirLinha(FormatDateTime('dd/mm/yy hh:nn', NOW))
.ImprimirLinha(_linhaSimples)
.ImprimirLinha(' * * * EXTRATO DE CAIXA * * *')
.ImprimirLinha(_linhaSimples)
.ImprimirLinha('Data Histórico Valor')
.ImprimirLinha(_linhaSimples);
// Imprime Contas
_dataSet := Self.FCaixaModelo.DataSet('extrato');
_dataSet.First;
_saldoFinal := 0;
while not _dataSet.Eof do
begin
_valor := Self.FUtil.iff(_dataSet.FieldByName('mcx_dc').AsInteger = Ord(dcDebito),
_dataSet.FieldByName('mcx_valor').AsFloat * -1,
_dataSet.FieldByName('mcx_valor').AsFloat);
_saldoFinal := _saldoFinal + _valor;
_impressora
.ImprimirLinha(
FormatDateTime('dd/mm/yyyy hh:nn', _dataSet.FieldByName('mcx_data').AsDateTime) + ' ' +
TText.DSpaces(Copy(_dataSet.FieldByName('mcx_historico').AsString, 1, 19), 19) + ' ' +
TText.ESpaces(FormatFloat('#,##0.00', _valor), 8)
);
_dataSet.Next;
end;
_impressora.ImprimirLinha(_linhaSimples);
// Imprime rodape
_impressora.ImprimirLinha('Saldo Final R$ ' + StringOfChar(' ', 16) +
FormatFloat('#,###,##0.00', _saldoFinal)
);
_impressora.ImprimirLinha(_linhaSimples);
_impressora.FinalizarImpressao;
end;
initialization
RegisterClass(TCaixaAplicacao);
end.
|
unit cdColdWarVeteranLimits;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus;
type
TfmColdWarVeteranLimits = class(TForm)
dsColdWarVeteranLimits: TwwDataSource;
tbColdWarVeteranLimits: TwwTable;
Panel1: TPanel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
VeteransCodeGrid: TwwDBGrid;
TitleLabel: TLabel;
Panel3: TPanel;
CloseButton: TBitBtn;
btn_SaveCode: TBitBtn;
btn_DeleteCode: TBitBtn;
btn_NewCode: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure tbColdWarVeteranLimitsBeforePost(DataSet: TDataset);
procedure FormActivate(Sender: TObject);
procedure btn_NewCodeClick(Sender: TObject);
procedure btn_DeleteCodeClick(Sender: TObject);
procedure btn_SaveCodeClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
FormAccessRights : Integer; {Read only or read write, based on security level?}
{Values = raReadOnly, raReadWrite}
Procedure InitializeForm; {Open the tables and setup.}
end;
implementation
uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils;
{$R *.DFM}
{========================================================}
Procedure TfmColdWarVeteranLimits.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TfmColdWarVeteranLimits.InitializeForm;
begin
UnitName := 'cdColdWarVeteranLimits';
If (FormAccessRights = raReadOnly)
then tbColdWarVeteranLimits.ReadOnly := True;
OpenTablesForForm(Self, GlblProcessingType);
{Set the display format for the fields.}
TFloatField(tbColdWarVeteranLimits.FieldByName('BasicLimit')).DisplayFormat := CurrencyEditDisplay;
TFloatField(tbColdWarVeteranLimits.FieldByName('BasicPercent')).DisplayFormat := CurrencyEditDisplay;
TFloatField(tbColdWarVeteranLimits.FieldByName('DisabledVetLimit')).DisplayFormat := CurrencyEditDisplay;
end; {InitializeForm}
{===================================================================}
Procedure TfmColdWarVeteranLimits.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If (Key = #13)
then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end; {FormKeyPress}
{===================================================================}
Procedure TfmColdWarVeteranLimits.tbColdWarVeteranLimitsBeforePost(DataSet: TDataset);
begin
If (tbColdWarVeteranLimits.State = dsInsert)
then tbColdWarVeteranLimits.FieldByName('Code').AsString := ANSIUpperCase(tbColdWarVeteranLimits.FieldByName('Code').AsString);
end;
{===================================================================}
Procedure TfmColdWarVeteranLimits.btn_NewCodeClick(Sender: TObject);
begin
try
tbColdWarVeteranLimits.Append;
except
end;
end;
{===================================================================}
Procedure TfmColdWarVeteranLimits.btn_DeleteCodeClick(Sender: TObject);
begin
try
tbColdWarVeteranLimits.Delete;
except
end;
end;
{===================================================================}
Procedure TfmColdWarVeteranLimits.btn_SaveCodeClick(Sender: TObject);
begin
try
tbColdWarVeteranLimits.Post;
except
end;
end;
{===================================================================}
Procedure TfmColdWarVeteranLimits.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end.
|
unit Ths.Erp.Database.Table.SysUserMacAddressException;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TSysUserMacAddressException = class(TTable)
private
FUserName: TFieldDB;
FIpAddress: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property UserName: TFieldDB read FUserName write FUserName;
Property IpAddress: TFieldDB read FIpAddress write FIpAddress;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TSysUserMacAddressException.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'sys_user_mac_address_exception';
SourceCode := '1';
FUserName := TFieldDB.Create('user_name', ftString, '');
FIpAddress := TFieldDB.Create('ip_address', ftString, '');
end;
procedure TSysUserMacAddressException.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FUserName.FieldName,
TableName + '.' + FIpAddress.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FUserName.FieldName).DisplayLabel := 'User Name';
Self.DataSource.DataSet.FindField(FIpAddress.FieldName).DisplayLabel := 'Ip Address';
end;
end;
end;
procedure TSysUserMacAddressException.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FUserName.FieldName,
TableName + '.' + FIpAddress.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FUserName.Value := FormatedVariantVal(FieldByName(FUserName.FieldName).DataType, FieldByName(FUserName.FieldName).Value);
FIpAddress.Value := FormatedVariantVal(FieldByName(FIpAddress.FieldName).DataType, FieldByName(FIpAddress.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TSysUserMacAddressException.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FUserName.FieldName,
FIpAddress.FieldName
]);
NewParamForQuery(QueryOfInsert, FUserName);
NewParamForQuery(QueryOfInsert, FIpAddress);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TSysUserMacAddressException.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FUserName.FieldName,
FIpAddress.FieldName
]);
NewParamForQuery(QueryOfUpdate, FUserName);
NewParamForQuery(QueryOfUpdate, FIpAddress);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TSysUserMacAddressException.Clone():TTable;
begin
Result := TSysUserMacAddressException.Create(Database);
Self.Id.Clone(TSysUserMacAddressException(Result).Id);
FUserName.Clone(TSysUserMacAddressException(Result).FUserName);
FIpAddress.Clone(TSysUserMacAddressException(Result).FIpAddress);
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 27 O(N) Recursive Method
}
program
GrayCode;
const
MaxL = 30;
var
K, LL, LLL, LLLL : Longint;
S : array [1 .. MaxL] of Byte;
TT : Longint;
Time : Longint absolute $40:$6C;
F : Text;
procedure ReadInput;
begin
Write('(K, L) : '); Readln(K, LL); LLL := Trunc(Ln(K - 1) / Ln(2)) + 1;
Assign(F, 'output.txt');
ReWrite(F);
if LL > LLL then LLLL := LL else LLLL := LLL;
end;
function Max (A, B : Integer) : Integer;
begin if A >= B then Max := A else Max := B; end;
procedure Gray (K : Longint; L, D, A, B : Integer);
var I : Integer;
begin
if (K = 1) or (L = 0) then begin
if A + B = 0 then begin
for I := LLLL downto 1 do Write(F, S[I]);
Writeln(F);
end;
end
else
if Odd(K) then Gray(K + 1, L, D, A + D, B + 1 - D)
else
for I := 0 to 1 do begin
S[L] := I + (1 - 2 * I) * D;
Gray(K div 2, L - 1, I, A * (1 - I), B * I);
end;
end;
begin
ReadInput;
TT := Time;
Gray(K, LLL, 0, 0, 0);
Writeln((Time - TT) / 18.2 : 0 : 2);
Close(F);
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1995, 1996 AO ROSNO }
{ Copyright (c) 1997, 1998 Master-Bank }
{ }
{ Patched by Polaris Software }
{*******************************************************}
unit rxLoginDlg;
{$I RX.INC}
interface
uses
SysUtils, Messages, Classes, Controls, Forms, Dialogs, StdCtrls,
ExtCtrls, DB, DBTables, rxDBLists, RxLogin, rxBdeUtils;
type
TCheckUserNameEvent = function(UsersTable: TTable;
const UserName, Password: string): Boolean of object;
TDialogMode = (dmAppLogin, dmDBLogin, dmUnlock);
TDBLoginDialog = class
private
FDialog: TRxLoginForm;
FMode: TDialogMode;
FSelectDatabase: Boolean;
FIniAliasName: string;
FCheckUserEvent: TCheckUserNameEvent;
FCheckUnlock: TCheckUnlockEvent;
FIconDblClick: TNotifyEvent;
procedure Login(Database: TDatabase; LoginParams: TStrings);
function GetUserInfo: Boolean;
function CheckUser(Table: TTable): Boolean;
function CheckUnlock: Boolean;
procedure OkBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
function ExecuteAppLogin: Boolean;
function ExecuteDbLogin(LoginParams: TStrings): Boolean;
function ExecuteUnlock: Boolean;
public
Database: TDatabase;
AttemptNumber: Integer;
ShowDBName: Boolean;
UsersTableName: string;
UserNameField: string;
MaxPwdLen: Integer;
LoginName: string;
IniFileName: string;
UseRegistry: Boolean;
constructor Create(DialogMode: TDialogMode; DatabaseSelect: Boolean);
destructor Destroy; override;
function Execute(LoginParams: TStrings): Boolean;
function GetUserName: string;
function CheckDatabaseChange: Boolean;
procedure FillParams(LoginParams: TStrings);
property Mode: TDialogMode read FMode;
property SelectDatabase: Boolean read FSelectDatabase;
property OnCheckUnlock: TCheckUnlockEvent read FCheckUnlock write FCheckUnlock;
property OnCheckUserEvent: TCheckUserNameEvent read FCheckUserEvent write FCheckUserEvent;
property OnIconDblClick: TNotifyEvent read FIconDblClick write FIconDblClick;
end;
procedure OnLoginDialog(Database: TDatabase; LoginParams: TStrings;
AttemptNumber: Integer; ShowDBName: Boolean);
function LoginDialog(Database: TDatabase; AttemptNumber: Integer;
const UsersTableName, UserNameField: string; MaxPwdLen: Integer;
CheckUserEvent: TCheckUserNameEvent; IconDblClick: TNotifyEvent;
var LoginName: string; const IniFileName: string;
UseRegistry, SelectDatabase: Boolean): Boolean;
function UnlockDialog(const UserName: string; OnUnlock: TCheckUnlockEvent;
IconDblClick: TNotifyEvent): Boolean;
function UnlockDialogEx(const UserName: string; OnUnlock: TCheckUnlockEvent;
IconDblClick: TNotifyEvent; MaxPwdLen, AttemptNumber: Integer): Boolean;
implementation
uses
Windows, Registry, BDE,
IniFiles, Graphics, Consts,
rxAppUtils, RxDConst, rxVclUtils, RxConst;
const
keyLastLoginUserName = 'LastUser';
keySelectDatabase = 'SelectDatabase'; { dialog never writes this value }
keyLastAliasName = 'LastAlias'; { used if SelectDatabase = True }
{ TDBLoginDialog }
constructor TDBLoginDialog.Create(DialogMode: TDialogMode; DatabaseSelect: Boolean);
begin
inherited Create;
FMode := DialogMode;
FSelectDatabase := DatabaseSelect;
FDialog := CreateLoginDialog((FMode = dmUnlock), FSelectDatabase,
FormShow, OkBtnClick);
AttemptNumber := 3;
ShowDBName := True;
end;
destructor TDBLoginDialog.Destroy;
begin
FDialog.Free;
inherited Destroy;
end;
procedure TDBLoginDialog.OkBtnClick(Sender: TObject);
var
Ok: Boolean;
SaveLogin: TDatabaseLoginEvent;
SetCursor: Boolean;
begin
if FMode = dmUnlock then begin
Ok := False;
try
Ok := CheckUnlock;
except
Application.HandleException(Self);
end;
if Ok then FDialog.ModalResult := mrOk
else FDialog.ModalResult := mrCancel;
end
else if Mode = dmAppLogin then begin
SetCursor := GetCurrentThreadID = MainThreadID;
SaveLogin := Database.OnLogin;
try
try
if Database.Connected then Database.Close; //Polaris
if FSelectDatabase then
Database.AliasName := FDialog.CustomCombo.Text;
Database.OnLogin := Login;
if SetCursor then Screen.Cursor := crHourGlass;
try
Database.Open;
finally
if SetCursor then Screen.Cursor := crDefault;
end;
except
Application.HandleException(Self);
end;
finally
Database.OnLogin := SaveLogin;
end;
if Database.Connected then
try
if SetCursor then Screen.Cursor := crHourGlass;
Ok := False;
try
Ok := GetUserInfo;
except
Application.HandleException(Self);
end;
if Ok then FDialog.ModalResult := mrOk
else begin
FDialog.ModalResult := mrNone;
Database.Close;
end;
finally
if SetCursor then Screen.Cursor := crDefault;
end;
end
else { dmDBLogin } FDialog.ModalResult := mrOk
end;
procedure TDBLoginDialog.FormShow(Sender: TObject);
var
S: string;
begin
if (FMode in [dmAppLogin, dmDBLogin]) and FSelectDatabase then begin
with TBDEItems.Create(FDialog) do
try
SessionName := Database.SessionName;
ItemType := bdDatabases;
FDialog.CustomCombo.Items.Clear;
Open;
while not Eof do begin
FDialog.CustomCombo.Items.Add(FieldByName('NAME').AsString);
Next;
end;
if FIniAliasName = '' then S := Database.AliasName
else S := FIniAliasName;
with FDialog.CustomCombo do ItemIndex := Items.IndexOf(S);
finally
Free;
end;
end;
end;
function TDBLoginDialog.ExecuteAppLogin: Boolean;
var
Ini: TObject;
begin
try
if UseRegistry then begin
Ini := TRegIniFile.Create(IniFileName);
{$IFDEF RX_D5}
TRegIniFile(Ini).Access := KEY_READ;
{$ENDIF}
end
else
Ini := TIniFile.Create(IniFileName);
try
FDialog.UserNameEdit.Text := IniReadString(Ini, FDialog.ClassName,
keyLastLoginUserName, LoginName);
FSelectDatabase := IniReadBool(Ini, FDialog.ClassName,
keySelectDatabase, FSelectDatabase);
FIniAliasName := IniReadString(Ini, FDialog.ClassName,
keyLastAliasName, '');
finally
Ini.Free;
end;
except
IniFileName := '';
end;
FDialog.SelectDatabase := SelectDatabase;
Result := (FDialog.ShowModal = mrOk);
Database.OnLogin := nil;
if Result then begin
LoginName := GetUserName;
if IniFileName <> '' then begin
if UseRegistry then Ini := TRegIniFile.Create(IniFileName)
else Ini := TIniFile.Create(IniFileName);
try
IniWriteString(Ini, FDialog.ClassName, keyLastLoginUserName, GetUserName);
IniWriteString(Ini, FDialog.ClassName, keyLastAliasName, Database.AliasName);
finally
Ini.Free;
end;
end;
end;
end;
function TDBLoginDialog.ExecuteDbLogin(LoginParams: TStrings): Boolean;
var
CurrSession: TSession;
begin
Result := False;
if (Database = nil) or not Assigned(LoginParams) then Exit;
if ShowDBName then
FDialog.AppTitleLabel.Caption := FmtLoadStr(SDatabaseName,
[Database.DatabaseName]);
FDialog.UserNameEdit.Text := LoginParams.Values[szUSERNAME];
CurrSession := Sessions.CurrentSession;
try
Result := FDialog.ShowModal = mrOk;
if Result then FillParams(LoginParams)
else SysUtils.Abort;
finally
Sessions.CurrentSession := CurrSession;
end;
end;
function TDBLoginDialog.ExecuteUnlock: Boolean;
begin
with FDialog.UserNameEdit do begin
Text := LoginName;
ReadOnly := True;
Font.Color := clGrayText;
end;
Result := (FDialog.ShowModal = mrOk);
end;
function TDBLoginDialog.Execute(LoginParams: TStrings): Boolean;
var
SaveCursor: TCursor;
begin
SaveCursor := Screen.Cursor;
Screen.Cursor := crDefault;
try
if Assigned(FIconDblClick) then begin
with FDialog.AppIcon do begin
OnDblClick := OnIconDblClick;
Cursor := crHand;
end;
with FDialog.KeyImage do begin
OnDblClick := OnIconDblClick;
Cursor := crHand;
end;
end;
FDialog.PasswordEdit.MaxLength := MaxPwdLen;
FDialog.AttemptNumber := AttemptNumber;
case FMode of
dmAppLogin: Result := ExecuteAppLogin;
dmDBLogin: Result := ExecuteDbLogin(LoginParams);
dmUnlock: Result := ExecuteUnlock;
else Result := False;
end;
if Result then LoginName := GetUserName;
finally
Screen.Cursor := SaveCursor;
end;
end;
function TDBLoginDialog.GetUserName: string;
begin
if CheckDatabaseChange then
Result := Copy(FDialog.UserNameEdit.Text, 1,
Pos('@', FDialog.UserNameEdit.Text) - 1)
else
Result := FDialog.UserNameEdit.Text;
end;
function TDBLoginDialog.CheckDatabaseChange: Boolean;
begin
Result := (FMode in [dmAppLogin, dmDBLogin]) and
(Pos('@', Fdialog.UserNameEdit.Text) > 0) and
((Database <> nil) and (Database.DriverName <> '') and
(CompareText(Database.DriverName, szCFGDBSTANDARD) <> 0));
end;
procedure TDBLoginDialog.FillParams(LoginParams: TStrings);
begin
LoginParams.Values[szUSERNAME] := GetUserName;
LoginParams.Values['PASSWORD'] := FDialog.PasswordEdit.Text;
if CheckDatabaseChange then begin
LoginParams.Values[szSERVERNAME] := Copy(FDialog.UserNameEdit.Text,
Pos('@', FDialog.UserNameEdit.Text) + 1, MaxInt)
end;
end;
procedure TDBLoginDialog.Login(Database: TDatabase; LoginParams: TStrings);
begin
FillParams(LoginParams);
end;
function TDBLoginDialog.GetUserInfo: Boolean;
var
Table: TTable;
begin
if UsersTableName = '' then Result := CheckUser(nil)
else begin
Result := False;
// Table := TTable.Create(Database);
Table := TTable.Create(Application);
try
try
Table.DatabaseName := Database.DatabaseName;
Table.SessionName := Database.SessionName;
Table.TableName := UsersTableName;
Table.IndexFieldNames := UserNameField;
Table.Open;
if Table.FindKey([GetUserName]) then begin
Result := CheckUser(Table);
if not Result then
raise EDatabaseError.Create(LoadStr(SInvalidUserName));
end
else
raise EDatabaseError.Create(LoadStr(SInvalidUserName));
except
Application.HandleException(Self);
end;
finally
Table.Free;
end;
end;
end;
function TDBLoginDialog.CheckUser(Table: TTable): Boolean;
begin
if Assigned(FCheckUserEvent) then
Result := FCheckUserEvent(Table, GetUserName, FDialog.PasswordEdit.Text)
else Result := True;
end;
function TDBLoginDialog.CheckUnlock: Boolean;
begin
if Assigned(FCheckUnlock) then
Result := FCheckUnlock(FDialog.PasswordEdit.Text)
else Result := True;
end;
{ Utility routines }
procedure OnLoginDialog(Database: TDatabase; LoginParams: TStrings;
AttemptNumber: Integer; ShowDBName: Boolean);
var
Dlg: TDBLoginDialog;
begin
Dlg := TDBLoginDialog.Create(dmDBLogin, False);
try
Dlg.Database := Database;
Dlg.ShowDBName := ShowDBName;
Dlg.AttemptNumber := AttemptNumber;
Dlg.Execute(LoginParams);
finally
Dlg.Free;
end;
end;
function UnlockDialogEx(const UserName: string; OnUnlock: TCheckUnlockEvent;
IconDblClick: TNotifyEvent; MaxPwdLen, AttemptNumber: Integer): Boolean;
var
Dlg: TDBLoginDialog;
begin
Dlg := TDBLoginDialog.Create(dmUnlock, False);
try
Dlg.LoginName := UserName;
Dlg.OnIconDblClick := IconDblClick;
Dlg.OnCheckUnlock := OnUnlock;
Dlg.MaxPwdLen := MaxPwdLen;
Dlg.AttemptNumber := AttemptNumber;
Result := Dlg.Execute(nil);
finally
Dlg.Free;
end;
end;
function UnlockDialog(const UserName: string; OnUnlock: TCheckUnlockEvent;
IconDblClick: TNotifyEvent): Boolean;
begin
Result := UnlockDialogEx(UserName, OnUnlock, IconDblClick, 0, 1);
end;
function LoginDialog(Database: TDatabase; AttemptNumber: Integer;
const UsersTableName, UserNameField: string; MaxPwdLen: Integer;
CheckUserEvent: TCheckUserNameEvent; IconDblClick: TNotifyEvent;
var LoginName: string; const IniFileName: string;
UseRegistry, SelectDatabase: Boolean): Boolean;
var
Dlg: TDBLoginDialog;
begin
Dlg := TDBLoginDialog.Create(dmAppLogin, SelectDatabase);
try
Dlg.LoginName := LoginName;
Dlg.OnIconDblClick := IconDblClick;
Dlg.OnCheckUserEvent := CheckUserEvent;
Dlg.MaxPwdLen := MaxPwdLen;
Dlg.Database := Database;
Dlg.AttemptNumber := AttemptNumber;
Dlg.UsersTableName := UsersTableName;
Dlg.UserNameField := UserNameField;
Dlg.IniFileName := IniFileName;
Dlg.UseRegistry := UseRegistry;
Result := Dlg.Execute(nil);
if Result then LoginName := Dlg.LoginName;
finally
Dlg.Free;
end;
end;
end.
|
///////////////////////////////////////////////////////////////////////////////
// LameXP - Audio Encoder Front-End
// Copyright (C) 2004-2010 LoRd_MuldeR <MuldeR2@GMX.de>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// http://www.gnu.org/licenses/gpl-2.0.txt
///////////////////////////////////////////////////////////////////////////////
unit Unit_Win7Taskbar;
//////////////////////////////////////////////////////////////////////////////
interface
//////////////////////////////////////////////////////////////////////////////
uses
Forms, Types, Windows, SysUtils, ComObj, Controls, Graphics;
type
TTaskBarProgressState = (tbpsNone, tbpsIndeterminate, tbpsNormal, tbpsError, tbpsPaused);
function InitializeTaskbarAPI: Boolean;
function SetTaskbarProgressState(const AState: TTaskBarProgressState): Boolean;
function SetTaskbarProgressValue(const ACurrent:int64; const AMax: int64): Boolean;
function SetTaskbarOverlayIcon(const AIcon: THandle; const ADescription: String): Boolean; overload;
function SetTaskbarOverlayIcon(const AIcon: TIcon; const ADescription: String): Boolean; overload;
function SetTaskbarOverlayIcon(const AList: TImageList; const IconIndex: Integer; const ADescription: String): Boolean; overload;
//////////////////////////////////////////////////////////////////////////////
implementation
//////////////////////////////////////////////////////////////////////////////
const
TASKBAR_CID: TGUID = '{56FDF344-FD6D-11d0-958A-006097C9A090}';
const
TBPF_NOPROGRESS = 0;
TBPF_INDETERMINATE = 1;
TBPF_NORMAL = 2;
TBPF_ERROR = 4;
TBPF_PAUSED = 8;
type
ITaskBarList3 = interface(IUnknown)
['{EA1AFB91-9E28-4B86-90E9-9E9F8A5EEFAF}']
function HrInit(): HRESULT; stdcall;
function AddTab(hwnd: THandle): HRESULT; stdcall;
function DeleteTab(hwnd: THandle): HRESULT; stdcall;
function ActivateTab(hwnd: THandle): HRESULT; stdcall;
function SetActiveAlt(hwnd: THandle): HRESULT; stdcall;
function MarkFullscreenWindow(hwnd: THandle; fFullscreen: Boolean): HRESULT; stdcall;
function SetProgressValue(hwnd: THandle; ullCompleted: Int64; ullTotal: Int64): HRESULT; stdcall;
function SetProgressState(hwnd: THandle; tbpFlags: Cardinal): HRESULT; stdcall;
function RegisterTab(hwnd: THandle; hwndMDI: THandle): HRESULT; stdcall;
function UnregisterTab(hwndTab: THandle): HRESULT; stdcall;
function SetTabOrder(hwndTab: THandle; hwndInsertBefore: THandle): HRESULT; stdcall;
function SetTabActive(hwndTab: THandle; hwndMDI: THandle; tbatFlags: Cardinal): HRESULT; stdcall;
function ThumbBarAddButtons(hwnd: THandle; cButtons: Cardinal; pButtons: Pointer): HRESULT; stdcall;
function ThumbBarUpdateButtons(hwnd: THandle; cButtons: Cardinal; pButtons: Pointer): HRESULT; stdcall;
function ThumbBarSetImageList(hwnd: THandle; himl: THandle): HRESULT; stdcall;
function SetOverlayIcon(hwnd: THandle; hIcon: THandle; pszDescription: PChar): HRESULT; stdcall;
function SetThumbnailTooltip(hwnd: THandle; pszDescription: PChar): HRESULT; stdcall;
function SetThumbnailClip(hwnd: THandle; var prcClip: TRect): HRESULT; stdcall;
end;
//////////////////////////////////////////////////////////////////////////////
var
GlobalTaskBarInterface: ITaskBarList3;
function InitializeTaskbarAPI: Boolean;
var
Unknown: IInterface;
Temp: ITaskBarList3;
begin
if Assigned(GlobalTaskBarInterface) then
begin
Result := True;
Exit;
end;
try
Unknown := CreateComObject(TASKBAR_CID);
if Assigned(Unknown) then
begin
Temp := Unknown as ITaskBarList3;
if Temp.HrInit() = S_OK then
begin
GlobalTaskBarInterface := Temp;
end;
end;
except
GlobalTaskBarInterface := nil;
end;
Result := Assigned(GlobalTaskBarInterface);
end;
function CheckAPI:Boolean;
begin
Result := Assigned(GlobalTaskBarInterface);
end;
//////////////////////////////////////////////////////////////////////////////
function SetTaskbarProgressState(const AState: TTaskBarProgressState): Boolean;
var
Flag: Cardinal;
begin
Result := False;
if CheckAPI then
begin
case AState of
tbpsIndeterminate: Flag := TBPF_INDETERMINATE;
tbpsNormal: Flag := TBPF_NORMAL;
tbpsError: Flag := TBPF_ERROR;
tbpsPaused: Flag := TBPF_PAUSED;
else
Flag := TBPF_NOPROGRESS;
end;
Result := GlobalTaskBarInterface.SetProgressState(Application.Handle, Flag) = S_OK;
end;
end;
function SetTaskbarProgressValue(const ACurrent:Int64; const AMax: Int64): Boolean;
begin
Result := False;
if CheckAPI then
begin
Result := GlobalTaskBarInterface.SetProgressValue(Application.Handle, ACurrent, AMax) = S_OK;
end;
end;
function SetTaskbarOverlayIcon(const AIcon: THandle; const ADescription: String): Boolean;
begin
Result := False;
if CheckAPI then
begin
Result := GlobalTaskBarInterface.SetOverlayIcon(Application.Handle, AIcon, PAnsiChar(ADescription)) = S_OK;
end;
end;
function SetTaskbarOverlayIcon(const AIcon: TIcon; const ADescription: String): Boolean;
begin
Result := False;
if CheckAPI then
begin
if Assigned(AIcon) then
begin
Result := SetTaskbarOverlayIcon(AIcon.Handle, ADescription);
end else begin
Result := SetTaskbarOverlayIcon(THandle(nil), ADescription);
end;
end;
end;
function SetTaskbarOverlayIcon(const AList: TImageList; const IconIndex: Integer; const ADescription: String): Boolean;
var
Temp: TIcon;
begin
Result := False;
if CheckAPI then
begin
if (IconIndex >= 0) and (IconIndex < AList.Count) then
begin
Temp := TIcon.Create;
try
AList.GetIcon(IconIndex, Temp);
Result := SetTaskbarOverlayIcon(Temp, ADescription);
finally
Temp.Free;
end;
end else begin
Result := SetTaskbarOverlayIcon(nil, ADescription);
end;
end;
end;
//////////////////////////////////////////////////////////////////////////////
initialization
GlobalTaskBarInterface := nil;
finalization
GlobalTaskBarInterface := nil;
//////////////////////////////////////////////////////////////////////////////
end.
|
unit uInterfaces;
interface
uses Winapi.Messages, OtlCommon, OtlTaskControl, uObj, OtlTask,
Spring.Container;
const
WM_LOG = WM_USER + 1;
WM_STOP = WM_USER + 2;
// 参数
PARAM_EMULATOR_INFO = 'EmulatorInfo'; // 模拟器信息
PARAM_ACCOUNT = 'account'; // 账号
PARAM_PASSWORD = 'password'; // 密码
PARAM_OBJ = 'obj'; // 插件对象
PARAM_ALL = 'ParamAll';
GAME_PACKAGE_NAME = 'com.tencent.ssss'; // 三生三世
type
TEmulatorInfo = packed record
index: Integer;
title: string;
ParentHwnd: Integer;
BindHwnd: Integer;
IsInAndroid: Boolean;
Pid: Integer;
VBpxPid: Integer;
end;
TGameData = packed record
EmulatorInfo: TEmulatorInfo;
Obj: IPighead;
LogHwnd: Integer;
end;
PGameData = ^TGameData;
IPighead = uObj.IPighead;
IGameConfig = interface(IInvokable)
['{CE39F86D-9054-4397-B21B-3B2DEB1ABD0C}']
end;
IGameManger = interface(IInvokable { 使继承类有RTTI } )
['{51856D60-057E-452F-ACBA-0C157EB8D8A5}']
function StartAll(monitor: IOmniTaskControlMonitor): Boolean; //
function StartExistWnds(monitor: IOmniTaskControlMonitor): Boolean;
procedure StopAll;
procedure SortWnd;
end;
ITaskExcute = interface(IInvokable)
['{DEE75FB8-C3F8-4171-8D0C-00C278E6CAF6}']
procedure Excute(task: IOmniTask; aGameData: PGameData); // 里面保存了所有相关的全局信息
end;
IGame = interface(ITaskExcute)
['{FFC22E96-D678-4BE3-936D-99ACA5C2D151}']
end;
TBase = class(TInterfacedObject, ITaskExcute)
private
FLogCount: Integer;
FLastMsg: string;
protected
FIndex: Integer;
FObj: IPighead;
FGameData: PGameData;
FTask: IOmniTask;
FValueContainer: TOmniValueContainer;
procedure Delay(const adelayTime: Integer; const interval: Integer = 100);
procedure Log(Msg: string);
procedure SendLogMessage(Msg: string);
public
procedure Excute(task: IOmniTask; aGameData: PGameData); virtual;
end;
var
gContainer: TContainer;
implementation
uses System.Diagnostics, Winapi.Windows;
{ TBase }
procedure TBase.Delay(const adelayTime, interval: Integer);
var
astopwatch: TStopwatch;
ms: Integer;
begin
astopwatch := TStopwatch.StartNew;
// if interval > 1000 then
// ms := 1000
// else
// ms := interval;
repeat
if astopwatch.ElapsedMilliseconds >= adelayTime then
Break;
Sleep(interval);
until (FTask.Terminated);
end;
procedure TBase.Excute(task: IOmniTask; aGameData: PGameData);
begin
FTask := task;
FGameData := aGameData;
FObj := FGameData.Obj;
FIndex := FGameData.EmulatorInfo.index;
// FValueContainer := task.Param[PARAM_ALL].AsArray;
// FEmulatorInfo := task.Param[PARAM_EMULATOR_INFO].ToRecord<TEmulatorInfo>;
// FObj := FValueContainer[PARAM_OBJ].AsInterface as IPighead;
end;
procedure TBase.Log(Msg: string);
var
s: string;
i: Integer;
begin
SendLogMessage(Msg);
if FGameData.LogHwnd > 0 then
begin
if Msg = FLastMsg then
begin
if FLogCount >= 10 then
FLogCount := 0;
for i := 0 to FLogCount - 1 do
s := s + '.';
end
else
begin
FLastMsg := Msg;
end;
FObj.FoobarPrintText(FGameData.LogHwnd, Msg + s, 'ff0000');
FObj.FoobarUpdate(FGameData.LogHwnd);
Inc(FLogCount);
end;
end;
procedure TBase.SendLogMessage(Msg: string);
begin
FTask.Comm.Send(WM_LOG, Msg);
end;
{ TEmulatorInfo }
initialization
finalization
end.
|
PROGRAM Zeichenkettenverarbeitung;
FUNCTION DeleteSubString(str, subStr: string): string;
BEGIN
WHILE Pos(subStr, str) <> 0 DO BEGIN
Delete(str, Pos(subStr, str), Length(subStr));
END; (* WHILE *)
DeleteSubString := str;
END; (* DeleteSubString *)
FUNCTION Trim(s: string): string;
BEGIN
Trim := DeleteSubString(s, ' ');
END; (* Trim *)
const stringToTrim = 'Lorem';
subString = 'Lorem';
BEGIN (* Main *)
WriteLn('To Trim: ', stringToTrim);
WriteLn('Output: ', Trim(stringToTrim));
WriteLn('Delete ', subString, ' from ', stringToTrim);
Write('Output: ', DeleteSubString(stringToTrim, subString));
END. |
{ Routines to manage the RENDlib device.
}
module gui_rendev;
define gui_rendev_def;
define gui_rendev_setup;
define gui_rendev_resize;
define gui_rendev_xf2d;
%include 'gui2.ins.pas';
{
********************************************************************************
*
* Subroutine GUI_RENDEV_DEF (DEV)
*
* Initialize the RENDlib device data for GUI library use, DEV. This must
* always be the first use of DEV. Values are set to defaults, but can be
* altered before the RENDlib device is used by the GUI library.
}
procedure gui_rendev_def ( {set GUI lib RENDlib dev parameters to default}
out dev: gui_rendev_t); {returned set to default or benign values}
val_param;
begin
dev.text_minpix := 13.0; {min text size in pixels}
dev.text_minfrx := 1.0 / 90.0; {min text size, fraction of X dimension}
dev.text_minfry := 1.0 / 65.0; {min text size, fraction of y dimension}
dev.iterps := [ {interpolants required by GUI library}
rend_iterp_red_k,
rend_iterp_grn_k,
rend_iterp_blu_k];
end;
{
********************************************************************************
*
* Subroutine GUI_RENDEV_SETUP (DEV)
*
* Set up the current RENDlib device and save state about it in DEV. Some
* state in DEV indicates how to set up the device. The RENDlib device will be
* set up as required by the GUI library.
*
* DEV must have been initialized with GUI_RENDEV_DEV, then possibly customized
* with additional calls to GUI_RENDEV_SET_xxx routines.
}
procedure gui_rendev_setup ( {setup RENDlib device, save related state}
in out dev: gui_rendev_t); {GUI lib state about the RENDlib device}
val_param;
var
it: rend_iterp_k_t; {current interpolant}
begin
rend_set.enter_rend^; {make sure in graphics mode}
rend_get.dev_id^ (dev.id); {save RENDlib device ID}
rend_get.text_parms^ (dev.tparm); {get existing text control parameters}
dev.tparm.width := 0.72;
dev.tparm.height := 1.0;
dev.tparm.slant := 0.0;
dev.tparm.rot := 0.0;
dev.tparm.lspace := 0.7;
dev.tparm.coor_level := rend_space_2d_k;
dev.tparm.poly := false;
rend_get.poly_parms^ (dev.pparm); {get default polygon control parameters}
dev.pparm.subpixel := true;
rend_set.poly_parms^ (dev.pparm); {set our new "base" polygon control parms}
rend_get.vect_parms^ (dev.vparm); {get default vector control parameters}
dev.vparm.width := 2.0;
dev.vparm.poly_level := rend_space_none_k;
dev.vparm.subpixel := false;
rend_set.vect_parms^ (dev.vparm); {set our new "base" vector control parameters}
rend_set.alloc_bitmap_handle^ ( {create handle for our software bitmap}
rend_scope_dev_k, {deallocate handle when device closed}
dev.bitmap_rgba); {returned bitmap handle}
dev.bitmap_alloc := false; {indicate no pixels allocated for bitmaps}
{
* Set up the mandatory interpolants. These are red, green, and blue.
}
dev.rgbasz := 0; {init RGBA pixel size}
rend_set.iterp_bitmap^ ( {connect interpolant to bitmap}
rend_iterp_red_k, dev.bitmap_rgba, dev.rgbasz);
dev.rgbasz := dev.rgbasz + 1; {update pixel size to include this interpolant}
dev.iterps := dev.iterps + [rend_iterp_red_k]; {make sure this interpolant in our list}
rend_set.iterp_bitmap^ ( {connect interpolant to bitmap}
rend_iterp_grn_k, dev.bitmap_rgba, dev.rgbasz);
dev.rgbasz := dev.rgbasz + 1; {update pixel size to include this interpolant}
dev.iterps := dev.iterps + [rend_iterp_grn_k]; {make sure this interpolant in our list}
rend_set.iterp_bitmap^ ( {connect interpolant to bitmap}
rend_iterp_blu_k, dev.bitmap_rgba, dev.rgbasz);
dev.rgbasz := dev.rgbasz + 1; {update pixel size to include this interpolant}
dev.iterps := dev.iterps + [rend_iterp_blu_k]; {make sure this interpolant in our list}
{
* Set up alpha if enabled.
}
if rend_iterp_alpha_k in dev.iterps then begin {alpha enabled ?}
rend_set.iterp_bitmap^ (rend_iterp_alpha_k, dev.bitmap_rgba, dev.rgbasz);
dev.rgbasz := dev.rgbasz + 1; {account for alpha in RGBA pixel size}
end;
{
* Set up Z if enabled.
}
dev.zsz := 0; {init to Z not in use}
if rend_iterp_z_k in dev.iterps then begin {Z enabled ?}
rend_set.alloc_bitmap_handle^ ( {create handle for Z bitmap}
rend_scope_dev_k, dev.bitmap_z);
rend_set.iterp_bitmap^ ( {connect Z interpolant to its bitmap}
rend_iterp_z_k, dev.bitmap_z, 0);
dev.zsz := dev.zsz + 2; {set Z bitmap pixel size}
end;
{
* Turn on all the interpolants that are in use.
}
for it := firstof(it) to lastof(it) do begin {loop over all possible interpolants}
if it in dev.iterps then begin {this interpolant is in use ?}
rend_set.iterp_on^ (it, true); {enable this interpolant}
end;
end;
{
* Other initialization.
}
rend_set.update_mode^ (rend_updmode_buffall_k); {buffer SW updates for speed sake}
rend_set.min_bits_vis^ (24.0); {try for high color resolution}
rend_set.event_req_close^ (true); {enable non-key events}
rend_set.event_req_wiped_resize^ (true);
rend_set.event_req_wiped_rect^ (true);
rend_set.event_req_pnt^ (true);
gui_events_init_key; {enable key events required by GUI library}
rend_set.exit_rend^; {pop back to previous graphics mode level}
gui_rendev_resize (dev); {adjust to current device dimensions}
end;
{
********************************************************************************
*
* Subroutine GUI_RENDEV_RESIZE (DEV)
*
* Adjust to the current RENDlib device size. Any existing software bitmaps
* are deallocated. New bitmaps are always allocated to match the current
* device size.
}
procedure gui_rendev_resize ( {adjust to RENDlib device size}
in out dev: gui_rendev_t); {GUI lib state about RENDlib device}
val_param;
var
r: real; {scratch floating point}
ii: sys_int_machine_t; {scratch integer}
begin
rend_set.enter_rend^; {make sure we are in graphics mode}
rend_set.dev_reconfig^; {look at device parameters and reconfigure}
rend_get.image_size^ ( {get size and aspect ratio}
dev.pixx, dev.pixy, {number of pixels in X and Y dimensions}
dev.aspect); {aspect ratio of whole device}
{
* Deallocate any existing structures fixed to the old size.
}
if dev.bitmap_alloc then begin {bitmaps previously allocated ?}
rend_set.dealloc_bitmap^ (dev.bitmap_rgba); {dealloc bitmap for RGBA components}
if dev.zsz > 0 then begin {Z bitmap in use ?}
rend_set.dealloc_bitmap^ (dev.bitmap_z); {deallocate it}
end;
end;
{
* Allocate new bitmaps to match the new device dimensions.
}
rend_set.alloc_bitmap^ ( {allocate mandatory RGBA bitmap}
dev.bitmap_rgba, {bitmap handle}
dev.pixx, dev.pixy, {bitmap dimensions in pixels}
dev.rgbasz, {min required bytes/pixel}
rend_scope_dev_k); {deallocate on device close}
if dev.zsz > 0 then begin {Z bitmap required ?}
rend_set.alloc_bitmap^ ( {allocate the optional Z bitmap}
dev.bitmap_z, {bitmap handle}
dev.pixx, dev.pixy, {bitmap dimensions in pixels}
dev.zsz, {min required bytes/pixel}
rend_scope_dev_k); {deallocate on device close}
end;
dev.bitmap_alloc := true; {indicate bitmaps are allocated}
{
* Set the text size. All the other text parameters are already set in
* DEV.TPARM.
}
r := max( {min text size according to all rules}
dev.text_minpix, {abs min, pixels}
dev.pixx * dev.text_minfrx, {min as fraction of X dimension}
dev.pixy * dev.text_minfry); {min as fraction of Y dimension}
ii := trunc(r + 0.999); {round up to full integer}
if not odd(ii) then begin {even number of pixels ?}
ii := ii + 1; {make odd, one row will be in center}
end;
dev.tparm.size := ii; {set overall text size}
rend_set.text_parms^ (dev.tparm); {update RENDlib state}
rend_set.exit_rend^; {pop back to previous graphics mode level}
{
* Set up the 2D transform so that 0,0 is the lower left corner, X is to the
* right, Y up, and both are in units of pixels.
}
gui_rendev_xf2d (dev);
end;
{
********************************************************************************
*
* Subroutine GUI_RENDEV_XF2D (DEV)
*
* Set the current RENDlib device 2D transform to the standard assumed by the
* GUI library. That is 0,0 in the lower left corner, X to the right, Y up,
* and both in units of pixels.
*
* The device size in DEV is assumed to be correct.
}
procedure gui_rendev_xf2d ( {set GUI lib standard 2D transform on RENDlib dev}
in out dev: gui_rendev_t); {GUI lib state about the RENDlib device}
val_param;
var
xb, yb, ofs: vect_2d_t; {2D transform}
begin
rend_set.enter_rend^; {make sure we are in graphics mode}
xb.y := 0.0; {fill in fixed part of transform}
yb.x := 0.0;
if dev.aspect >= 1.0
then begin {device is wider than tall}
xb.x := (2.0 * dev.aspect) / dev.pixx;
yb.y := 2.0 / dev.pixy;
ofs.x := -dev.aspect;
ofs.y := -1.0;
end
else begin {device is taller than wide}
xb.x := 2.0 / dev.pixx;
yb.y := (2.0 / dev.aspect) / dev.pixy;
ofs.x := -1.0;
ofs.y := -1.0 / dev.aspect;
end
;
rend_set.xform_2d^ (xb, yb, ofs); {set new RENDlib transform for this window}
rend_set.exit_rend^; {pop back to previous graphics mode level}
end;
|
{ ****************************************************************************** }
{ Fast KDTree Double Type support }
{ ****************************************************************************** }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit FastKDTreeD;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses, PascalStrings, UnicodeMixedLib, KM;
const
// Double float: KDTree
KDT1DD_Axis = 1;
KDT2DD_Axis = 2;
KDT3DD_Axis = 3;
KDT4DD_Axis = 4;
KDT5DD_Axis = 5;
KDT6DD_Axis = 6;
KDT7DD_Axis = 7;
KDT8DD_Axis = 8;
KDT9DD_Axis = 9;
KDT10DD_Axis = 10;
KDT11DD_Axis = 11;
KDT12DD_Axis = 12;
KDT13DD_Axis = 13;
KDT14DD_Axis = 14;
KDT15DD_Axis = 15;
KDT16DD_Axis = 16;
KDT17DD_Axis = 17;
KDT18DD_Axis = 18;
KDT19DD_Axis = 19;
KDT20DD_Axis = 20;
KDT21DD_Axis = 21;
KDT22DD_Axis = 22;
KDT23DD_Axis = 23;
KDT24DD_Axis = 24;
KDT48DD_Axis = 48;
KDT52DD_Axis = 52;
KDT64DD_Axis = 64;
KDT96DD_Axis = 96;
KDT128DD_Axis = 128;
KDT156DD_Axis = 156;
KDT192DD_Axis = 192;
KDT256DD_Axis = 256;
KDT384DD_Axis = 384;
KDT512DD_Axis = 512;
KDT800DD_Axis = 800;
KDT1024DD_Axis = 1024;
type
// Double float: KDTree
TKDT1DD = class; TKDT1DD_VecType = KM.TKMFloat; // 1D
TKDT2DD = class; TKDT2DD_VecType = KM.TKMFloat; // 2D
TKDT3DD = class; TKDT3DD_VecType = KM.TKMFloat; // 3D
TKDT4DD = class; TKDT4DD_VecType = KM.TKMFloat; // 4D
TKDT5DD = class; TKDT5DD_VecType = KM.TKMFloat; // 5D
TKDT6DD = class; TKDT6DD_VecType = KM.TKMFloat; // 6D
TKDT7DD = class; TKDT7DD_VecType = KM.TKMFloat; // 7D
TKDT8DD = class; TKDT8DD_VecType = KM.TKMFloat; // 8D
TKDT9DD = class; TKDT9DD_VecType = KM.TKMFloat; // 9D
TKDT10DD = class; TKDT10DD_VecType = KM.TKMFloat; // 10D
TKDT11DD = class; TKDT11DD_VecType = KM.TKMFloat; // 11D
TKDT12DD = class; TKDT12DD_VecType = KM.TKMFloat; // 12D
TKDT13DD = class; TKDT13DD_VecType = KM.TKMFloat; // 13D
TKDT14DD = class; TKDT14DD_VecType = KM.TKMFloat; // 14D
TKDT15DD = class; TKDT15DD_VecType = KM.TKMFloat; // 15D
TKDT16DD = class; TKDT16DD_VecType = KM.TKMFloat; // 16D
TKDT17DD = class; TKDT17DD_VecType = KM.TKMFloat; // 17D
TKDT18DD = class; TKDT18DD_VecType = KM.TKMFloat; // 18D
TKDT19DD = class; TKDT19DD_VecType = KM.TKMFloat; // 19D
TKDT20DD = class; TKDT20DD_VecType = KM.TKMFloat; // 20D
TKDT21DD = class; TKDT21DD_VecType = KM.TKMFloat; // 21D
TKDT22DD = class; TKDT22DD_VecType = KM.TKMFloat; // 22D
TKDT23DD = class; TKDT23DD_VecType = KM.TKMFloat; // 23D
TKDT24DD = class; TKDT24DD_VecType = KM.TKMFloat; // 24D
TKDT48DD = class; TKDT48DD_VecType = KM.TKMFloat; // 48D
TKDT52DD = class; TKDT52DD_VecType = KM.TKMFloat; // 52D
TKDT64DD = class; TKDT64DD_VecType = KM.TKMFloat; // 64D
TKDT96DD = class; TKDT96DD_VecType = KM.TKMFloat; // 96D
TKDT128DD = class; TKDT128DD_VecType = KM.TKMFloat; // 128D
TKDT156DD = class; TKDT156DD_VecType = KM.TKMFloat; // 156D
TKDT192DD = class; TKDT192DD_VecType = KM.TKMFloat; // 192D
TKDT256DD = class; TKDT256DD_VecType = KM.TKMFloat; // 256D
TKDT384DD = class; TKDT384DD_VecType = KM.TKMFloat; // 384D
TKDT512DD = class; TKDT512DD_VecType = KM.TKMFloat; // 512D
TKDT800DD = class; TKDT800DD_VecType = KM.TKMFloat; // 800D
TKDT1024DD = class; TKDT1024DD_VecType = KM.TKMFloat; // 1024D
// Double float: KDTree
TKDT1DD = class(TCoreClassObject)
public type
// code split
TKDT1DD_Vec = array [0 .. KDT1DD_Axis - 1] of TKDT1DD_VecType;
PKDT1DD_Vec = ^TKDT1DD_Vec;
TKDT1DD_DynamicVecBuffer = array of TKDT1DD_Vec;
PKDT1DD_DynamicVecBuffer = ^TKDT1DD_DynamicVecBuffer;
TKDT1DD_Source = record
buff: TKDT1DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT1DD_Source = ^TKDT1DD_Source;
TKDT1DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1DD_Source) - 1] of PKDT1DD_Source;
PKDT1DD_SourceBuffer = ^TKDT1DD_SourceBuffer;
TKDT1DD_DyanmicSourceBuffer = array of PKDT1DD_Source;
PKDT1DD_DyanmicSourceBuffer = ^TKDT1DD_DyanmicSourceBuffer;
TKDT1DD_DyanmicStoreBuffer = array of TKDT1DD_Source;
PKDT1DD_DyanmicStoreBuffer = ^TKDT1DD_DyanmicStoreBuffer;
PKDT1DD_Node = ^TKDT1DD_Node;
TKDT1DD_Node = record
Parent, Right, Left: PKDT1DD_Node;
Vec: PKDT1DD_Source;
end;
TKDT1DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1DD_Source; const Data: Pointer);
TKDT1DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT1DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT1DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT1DD_DyanmicStoreBuffer;
KDBuff: TKDT1DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT1DD_Node;
TestBuff: TKDT1DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DD_Node;
function GetData(const Index: NativeInt): PKDT1DD_Source;
public
RootNode: PKDT1DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT1DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT1DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT1DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT1DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT1DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DD_Node; overload;
function Search(const buff: TKDT1DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DD_Node; overload;
function Search(const buff: TKDT1DD_Vec; var SearchedDistanceMin: Double): PKDT1DD_Node; overload;
function Search(const buff: TKDT1DD_Vec): PKDT1DD_Node; overload;
function SearchToken(const buff: TKDT1DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT1DD_DynamicVecBuffer; var OutBuff: TKDT1DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT1DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT1DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT1DD_Vec; overload;
class function Vec(const v: TKDT1DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT1DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT2DD = class(TCoreClassObject)
public type
// code split
TKDT2DD_Vec = array [0 .. KDT2DD_Axis - 1] of TKDT2DD_VecType;
PKDT2DD_Vec = ^TKDT2DD_Vec;
TKDT2DD_DynamicVecBuffer = array of TKDT2DD_Vec;
PKDT2DD_DynamicVecBuffer = ^TKDT2DD_DynamicVecBuffer;
TKDT2DD_Source = record
buff: TKDT2DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT2DD_Source = ^TKDT2DD_Source;
TKDT2DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT2DD_Source) - 1] of PKDT2DD_Source;
PKDT2DD_SourceBuffer = ^TKDT2DD_SourceBuffer;
TKDT2DD_DyanmicSourceBuffer = array of PKDT2DD_Source;
PKDT2DD_DyanmicSourceBuffer = ^TKDT2DD_DyanmicSourceBuffer;
TKDT2DD_DyanmicStoreBuffer = array of TKDT2DD_Source;
PKDT2DD_DyanmicStoreBuffer = ^TKDT2DD_DyanmicStoreBuffer;
PKDT2DD_Node = ^TKDT2DD_Node;
TKDT2DD_Node = record
Parent, Right, Left: PKDT2DD_Node;
Vec: PKDT2DD_Source;
end;
TKDT2DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT2DD_Source; const Data: Pointer);
TKDT2DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT2DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT2DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT2DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT2DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT2DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT2DD_DyanmicStoreBuffer;
KDBuff: TKDT2DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT2DD_Node;
TestBuff: TKDT2DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DD_Node;
function GetData(const Index: NativeInt): PKDT2DD_Source;
public
RootNode: PKDT2DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT2DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT2DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT2DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT2DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT2DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DD_Node; overload;
function Search(const buff: TKDT2DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DD_Node; overload;
function Search(const buff: TKDT2DD_Vec; var SearchedDistanceMin: Double): PKDT2DD_Node; overload;
function Search(const buff: TKDT2DD_Vec): PKDT2DD_Node; overload;
function SearchToken(const buff: TKDT2DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT2DD_DynamicVecBuffer; var OutBuff: TKDT2DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT2DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT2DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT2DD_Vec; overload;
class function Vec(const v: TKDT2DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT2DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT3DD = class(TCoreClassObject)
public type
// code split
TKDT3DD_Vec = array [0 .. KDT3DD_Axis - 1] of TKDT3DD_VecType;
PKDT3DD_Vec = ^TKDT3DD_Vec;
TKDT3DD_DynamicVecBuffer = array of TKDT3DD_Vec;
PKDT3DD_DynamicVecBuffer = ^TKDT3DD_DynamicVecBuffer;
TKDT3DD_Source = record
buff: TKDT3DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT3DD_Source = ^TKDT3DD_Source;
TKDT3DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT3DD_Source) - 1] of PKDT3DD_Source;
PKDT3DD_SourceBuffer = ^TKDT3DD_SourceBuffer;
TKDT3DD_DyanmicSourceBuffer = array of PKDT3DD_Source;
PKDT3DD_DyanmicSourceBuffer = ^TKDT3DD_DyanmicSourceBuffer;
TKDT3DD_DyanmicStoreBuffer = array of TKDT3DD_Source;
PKDT3DD_DyanmicStoreBuffer = ^TKDT3DD_DyanmicStoreBuffer;
PKDT3DD_Node = ^TKDT3DD_Node;
TKDT3DD_Node = record
Parent, Right, Left: PKDT3DD_Node;
Vec: PKDT3DD_Source;
end;
TKDT3DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT3DD_Source; const Data: Pointer);
TKDT3DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT3DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT3DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT3DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT3DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT3DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT3DD_DyanmicStoreBuffer;
KDBuff: TKDT3DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT3DD_Node;
TestBuff: TKDT3DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DD_Node;
function GetData(const Index: NativeInt): PKDT3DD_Source;
public
RootNode: PKDT3DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT3DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT3DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT3DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT3DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT3DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DD_Node; overload;
function Search(const buff: TKDT3DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DD_Node; overload;
function Search(const buff: TKDT3DD_Vec; var SearchedDistanceMin: Double): PKDT3DD_Node; overload;
function Search(const buff: TKDT3DD_Vec): PKDT3DD_Node; overload;
function SearchToken(const buff: TKDT3DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT3DD_DynamicVecBuffer; var OutBuff: TKDT3DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT3DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT3DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT3DD_Vec; overload;
class function Vec(const v: TKDT3DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT3DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT4DD = class(TCoreClassObject)
public type
// code split
TKDT4DD_Vec = array [0 .. KDT4DD_Axis - 1] of TKDT4DD_VecType;
PKDT4DD_Vec = ^TKDT4DD_Vec;
TKDT4DD_DynamicVecBuffer = array of TKDT4DD_Vec;
PKDT4DD_DynamicVecBuffer = ^TKDT4DD_DynamicVecBuffer;
TKDT4DD_Source = record
buff: TKDT4DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT4DD_Source = ^TKDT4DD_Source;
TKDT4DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT4DD_Source) - 1] of PKDT4DD_Source;
PKDT4DD_SourceBuffer = ^TKDT4DD_SourceBuffer;
TKDT4DD_DyanmicSourceBuffer = array of PKDT4DD_Source;
PKDT4DD_DyanmicSourceBuffer = ^TKDT4DD_DyanmicSourceBuffer;
TKDT4DD_DyanmicStoreBuffer = array of TKDT4DD_Source;
PKDT4DD_DyanmicStoreBuffer = ^TKDT4DD_DyanmicStoreBuffer;
PKDT4DD_Node = ^TKDT4DD_Node;
TKDT4DD_Node = record
Parent, Right, Left: PKDT4DD_Node;
Vec: PKDT4DD_Source;
end;
TKDT4DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT4DD_Source; const Data: Pointer);
TKDT4DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT4DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT4DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT4DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT4DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT4DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT4DD_DyanmicStoreBuffer;
KDBuff: TKDT4DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT4DD_Node;
TestBuff: TKDT4DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DD_Node;
function GetData(const Index: NativeInt): PKDT4DD_Source;
public
RootNode: PKDT4DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT4DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT4DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT4DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT4DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT4DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DD_Node; overload;
function Search(const buff: TKDT4DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DD_Node; overload;
function Search(const buff: TKDT4DD_Vec; var SearchedDistanceMin: Double): PKDT4DD_Node; overload;
function Search(const buff: TKDT4DD_Vec): PKDT4DD_Node; overload;
function SearchToken(const buff: TKDT4DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT4DD_DynamicVecBuffer; var OutBuff: TKDT4DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT4DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT4DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT4DD_Vec; overload;
class function Vec(const v: TKDT4DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT4DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT5DD = class(TCoreClassObject)
public type
// code split
TKDT5DD_Vec = array [0 .. KDT5DD_Axis - 1] of TKDT5DD_VecType;
PKDT5DD_Vec = ^TKDT5DD_Vec;
TKDT5DD_DynamicVecBuffer = array of TKDT5DD_Vec;
PKDT5DD_DynamicVecBuffer = ^TKDT5DD_DynamicVecBuffer;
TKDT5DD_Source = record
buff: TKDT5DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT5DD_Source = ^TKDT5DD_Source;
TKDT5DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT5DD_Source) - 1] of PKDT5DD_Source;
PKDT5DD_SourceBuffer = ^TKDT5DD_SourceBuffer;
TKDT5DD_DyanmicSourceBuffer = array of PKDT5DD_Source;
PKDT5DD_DyanmicSourceBuffer = ^TKDT5DD_DyanmicSourceBuffer;
TKDT5DD_DyanmicStoreBuffer = array of TKDT5DD_Source;
PKDT5DD_DyanmicStoreBuffer = ^TKDT5DD_DyanmicStoreBuffer;
PKDT5DD_Node = ^TKDT5DD_Node;
TKDT5DD_Node = record
Parent, Right, Left: PKDT5DD_Node;
Vec: PKDT5DD_Source;
end;
TKDT5DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT5DD_Source; const Data: Pointer);
TKDT5DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT5DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT5DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT5DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT5DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT5DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT5DD_DyanmicStoreBuffer;
KDBuff: TKDT5DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT5DD_Node;
TestBuff: TKDT5DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DD_Node;
function GetData(const Index: NativeInt): PKDT5DD_Source;
public
RootNode: PKDT5DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT5DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT5DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT5DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT5DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT5DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DD_Node; overload;
function Search(const buff: TKDT5DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DD_Node; overload;
function Search(const buff: TKDT5DD_Vec; var SearchedDistanceMin: Double): PKDT5DD_Node; overload;
function Search(const buff: TKDT5DD_Vec): PKDT5DD_Node; overload;
function SearchToken(const buff: TKDT5DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT5DD_DynamicVecBuffer; var OutBuff: TKDT5DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT5DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT5DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT5DD_Vec; overload;
class function Vec(const v: TKDT5DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT5DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT6DD = class(TCoreClassObject)
public type
// code split
TKDT6DD_Vec = array [0 .. KDT6DD_Axis - 1] of TKDT6DD_VecType;
PKDT6DD_Vec = ^TKDT6DD_Vec;
TKDT6DD_DynamicVecBuffer = array of TKDT6DD_Vec;
PKDT6DD_DynamicVecBuffer = ^TKDT6DD_DynamicVecBuffer;
TKDT6DD_Source = record
buff: TKDT6DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT6DD_Source = ^TKDT6DD_Source;
TKDT6DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT6DD_Source) - 1] of PKDT6DD_Source;
PKDT6DD_SourceBuffer = ^TKDT6DD_SourceBuffer;
TKDT6DD_DyanmicSourceBuffer = array of PKDT6DD_Source;
PKDT6DD_DyanmicSourceBuffer = ^TKDT6DD_DyanmicSourceBuffer;
TKDT6DD_DyanmicStoreBuffer = array of TKDT6DD_Source;
PKDT6DD_DyanmicStoreBuffer = ^TKDT6DD_DyanmicStoreBuffer;
PKDT6DD_Node = ^TKDT6DD_Node;
TKDT6DD_Node = record
Parent, Right, Left: PKDT6DD_Node;
Vec: PKDT6DD_Source;
end;
TKDT6DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT6DD_Source; const Data: Pointer);
TKDT6DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT6DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT6DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT6DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT6DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT6DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT6DD_DyanmicStoreBuffer;
KDBuff: TKDT6DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT6DD_Node;
TestBuff: TKDT6DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DD_Node;
function GetData(const Index: NativeInt): PKDT6DD_Source;
public
RootNode: PKDT6DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT6DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT6DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT6DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT6DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT6DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DD_Node; overload;
function Search(const buff: TKDT6DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DD_Node; overload;
function Search(const buff: TKDT6DD_Vec; var SearchedDistanceMin: Double): PKDT6DD_Node; overload;
function Search(const buff: TKDT6DD_Vec): PKDT6DD_Node; overload;
function SearchToken(const buff: TKDT6DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT6DD_DynamicVecBuffer; var OutBuff: TKDT6DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT6DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT6DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT6DD_Vec; overload;
class function Vec(const v: TKDT6DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT6DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT7DD = class(TCoreClassObject)
public type
// code split
TKDT7DD_Vec = array [0 .. KDT7DD_Axis - 1] of TKDT7DD_VecType;
PKDT7DD_Vec = ^TKDT7DD_Vec;
TKDT7DD_DynamicVecBuffer = array of TKDT7DD_Vec;
PKDT7DD_DynamicVecBuffer = ^TKDT7DD_DynamicVecBuffer;
TKDT7DD_Source = record
buff: TKDT7DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT7DD_Source = ^TKDT7DD_Source;
TKDT7DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT7DD_Source) - 1] of PKDT7DD_Source;
PKDT7DD_SourceBuffer = ^TKDT7DD_SourceBuffer;
TKDT7DD_DyanmicSourceBuffer = array of PKDT7DD_Source;
PKDT7DD_DyanmicSourceBuffer = ^TKDT7DD_DyanmicSourceBuffer;
TKDT7DD_DyanmicStoreBuffer = array of TKDT7DD_Source;
PKDT7DD_DyanmicStoreBuffer = ^TKDT7DD_DyanmicStoreBuffer;
PKDT7DD_Node = ^TKDT7DD_Node;
TKDT7DD_Node = record
Parent, Right, Left: PKDT7DD_Node;
Vec: PKDT7DD_Source;
end;
TKDT7DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT7DD_Source; const Data: Pointer);
TKDT7DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT7DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT7DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT7DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT7DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT7DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT7DD_DyanmicStoreBuffer;
KDBuff: TKDT7DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT7DD_Node;
TestBuff: TKDT7DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DD_Node;
function GetData(const Index: NativeInt): PKDT7DD_Source;
public
RootNode: PKDT7DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT7DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT7DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT7DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT7DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT7DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DD_Node; overload;
function Search(const buff: TKDT7DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DD_Node; overload;
function Search(const buff: TKDT7DD_Vec; var SearchedDistanceMin: Double): PKDT7DD_Node; overload;
function Search(const buff: TKDT7DD_Vec): PKDT7DD_Node; overload;
function SearchToken(const buff: TKDT7DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT7DD_DynamicVecBuffer; var OutBuff: TKDT7DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT7DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT7DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT7DD_Vec; overload;
class function Vec(const v: TKDT7DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT7DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT8DD = class(TCoreClassObject)
public type
// code split
TKDT8DD_Vec = array [0 .. KDT8DD_Axis - 1] of TKDT8DD_VecType;
PKDT8DD_Vec = ^TKDT8DD_Vec;
TKDT8DD_DynamicVecBuffer = array of TKDT8DD_Vec;
PKDT8DD_DynamicVecBuffer = ^TKDT8DD_DynamicVecBuffer;
TKDT8DD_Source = record
buff: TKDT8DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT8DD_Source = ^TKDT8DD_Source;
TKDT8DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT8DD_Source) - 1] of PKDT8DD_Source;
PKDT8DD_SourceBuffer = ^TKDT8DD_SourceBuffer;
TKDT8DD_DyanmicSourceBuffer = array of PKDT8DD_Source;
PKDT8DD_DyanmicSourceBuffer = ^TKDT8DD_DyanmicSourceBuffer;
TKDT8DD_DyanmicStoreBuffer = array of TKDT8DD_Source;
PKDT8DD_DyanmicStoreBuffer = ^TKDT8DD_DyanmicStoreBuffer;
PKDT8DD_Node = ^TKDT8DD_Node;
TKDT8DD_Node = record
Parent, Right, Left: PKDT8DD_Node;
Vec: PKDT8DD_Source;
end;
TKDT8DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT8DD_Source; const Data: Pointer);
TKDT8DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT8DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT8DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT8DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT8DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT8DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT8DD_DyanmicStoreBuffer;
KDBuff: TKDT8DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT8DD_Node;
TestBuff: TKDT8DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DD_Node;
function GetData(const Index: NativeInt): PKDT8DD_Source;
public
RootNode: PKDT8DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT8DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT8DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT8DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT8DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT8DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DD_Node; overload;
function Search(const buff: TKDT8DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DD_Node; overload;
function Search(const buff: TKDT8DD_Vec; var SearchedDistanceMin: Double): PKDT8DD_Node; overload;
function Search(const buff: TKDT8DD_Vec): PKDT8DD_Node; overload;
function SearchToken(const buff: TKDT8DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT8DD_DynamicVecBuffer; var OutBuff: TKDT8DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT8DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT8DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT8DD_Vec; overload;
class function Vec(const v: TKDT8DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT8DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT9DD = class(TCoreClassObject)
public type
// code split
TKDT9DD_Vec = array [0 .. KDT9DD_Axis - 1] of TKDT9DD_VecType;
PKDT9DD_Vec = ^TKDT9DD_Vec;
TKDT9DD_DynamicVecBuffer = array of TKDT9DD_Vec;
PKDT9DD_DynamicVecBuffer = ^TKDT9DD_DynamicVecBuffer;
TKDT9DD_Source = record
buff: TKDT9DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT9DD_Source = ^TKDT9DD_Source;
TKDT9DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT9DD_Source) - 1] of PKDT9DD_Source;
PKDT9DD_SourceBuffer = ^TKDT9DD_SourceBuffer;
TKDT9DD_DyanmicSourceBuffer = array of PKDT9DD_Source;
PKDT9DD_DyanmicSourceBuffer = ^TKDT9DD_DyanmicSourceBuffer;
TKDT9DD_DyanmicStoreBuffer = array of TKDT9DD_Source;
PKDT9DD_DyanmicStoreBuffer = ^TKDT9DD_DyanmicStoreBuffer;
PKDT9DD_Node = ^TKDT9DD_Node;
TKDT9DD_Node = record
Parent, Right, Left: PKDT9DD_Node;
Vec: PKDT9DD_Source;
end;
TKDT9DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT9DD_Source; const Data: Pointer);
TKDT9DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT9DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT9DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT9DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT9DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT9DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT9DD_DyanmicStoreBuffer;
KDBuff: TKDT9DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT9DD_Node;
TestBuff: TKDT9DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DD_Node;
function GetData(const Index: NativeInt): PKDT9DD_Source;
public
RootNode: PKDT9DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT9DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT9DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT9DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT9DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT9DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DD_Node; overload;
function Search(const buff: TKDT9DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DD_Node; overload;
function Search(const buff: TKDT9DD_Vec; var SearchedDistanceMin: Double): PKDT9DD_Node; overload;
function Search(const buff: TKDT9DD_Vec): PKDT9DD_Node; overload;
function SearchToken(const buff: TKDT9DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT9DD_DynamicVecBuffer; var OutBuff: TKDT9DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT9DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT9DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT9DD_Vec; overload;
class function Vec(const v: TKDT9DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT9DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT10DD = class(TCoreClassObject)
public type
// code split
TKDT10DD_Vec = array [0 .. KDT10DD_Axis - 1] of TKDT10DD_VecType;
PKDT10DD_Vec = ^TKDT10DD_Vec;
TKDT10DD_DynamicVecBuffer = array of TKDT10DD_Vec;
PKDT10DD_DynamicVecBuffer = ^TKDT10DD_DynamicVecBuffer;
TKDT10DD_Source = record
buff: TKDT10DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT10DD_Source = ^TKDT10DD_Source;
TKDT10DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT10DD_Source) - 1] of PKDT10DD_Source;
PKDT10DD_SourceBuffer = ^TKDT10DD_SourceBuffer;
TKDT10DD_DyanmicSourceBuffer = array of PKDT10DD_Source;
PKDT10DD_DyanmicSourceBuffer = ^TKDT10DD_DyanmicSourceBuffer;
TKDT10DD_DyanmicStoreBuffer = array of TKDT10DD_Source;
PKDT10DD_DyanmicStoreBuffer = ^TKDT10DD_DyanmicStoreBuffer;
PKDT10DD_Node = ^TKDT10DD_Node;
TKDT10DD_Node = record
Parent, Right, Left: PKDT10DD_Node;
Vec: PKDT10DD_Source;
end;
TKDT10DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT10DD_Source; const Data: Pointer);
TKDT10DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT10DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT10DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT10DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT10DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT10DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT10DD_DyanmicStoreBuffer;
KDBuff: TKDT10DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT10DD_Node;
TestBuff: TKDT10DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DD_Node;
function GetData(const Index: NativeInt): PKDT10DD_Source;
public
RootNode: PKDT10DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT10DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT10DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT10DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT10DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT10DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DD_Node; overload;
function Search(const buff: TKDT10DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DD_Node; overload;
function Search(const buff: TKDT10DD_Vec; var SearchedDistanceMin: Double): PKDT10DD_Node; overload;
function Search(const buff: TKDT10DD_Vec): PKDT10DD_Node; overload;
function SearchToken(const buff: TKDT10DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT10DD_DynamicVecBuffer; var OutBuff: TKDT10DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT10DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT10DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT10DD_Vec; overload;
class function Vec(const v: TKDT10DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT10DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT11DD = class(TCoreClassObject)
public type
// code split
TKDT11DD_Vec = array [0 .. KDT11DD_Axis - 1] of TKDT11DD_VecType;
PKDT11DD_Vec = ^TKDT11DD_Vec;
TKDT11DD_DynamicVecBuffer = array of TKDT11DD_Vec;
PKDT11DD_DynamicVecBuffer = ^TKDT11DD_DynamicVecBuffer;
TKDT11DD_Source = record
buff: TKDT11DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT11DD_Source = ^TKDT11DD_Source;
TKDT11DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT11DD_Source) - 1] of PKDT11DD_Source;
PKDT11DD_SourceBuffer = ^TKDT11DD_SourceBuffer;
TKDT11DD_DyanmicSourceBuffer = array of PKDT11DD_Source;
PKDT11DD_DyanmicSourceBuffer = ^TKDT11DD_DyanmicSourceBuffer;
TKDT11DD_DyanmicStoreBuffer = array of TKDT11DD_Source;
PKDT11DD_DyanmicStoreBuffer = ^TKDT11DD_DyanmicStoreBuffer;
PKDT11DD_Node = ^TKDT11DD_Node;
TKDT11DD_Node = record
Parent, Right, Left: PKDT11DD_Node;
Vec: PKDT11DD_Source;
end;
TKDT11DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT11DD_Source; const Data: Pointer);
TKDT11DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT11DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT11DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT11DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT11DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT11DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT11DD_DyanmicStoreBuffer;
KDBuff: TKDT11DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT11DD_Node;
TestBuff: TKDT11DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DD_Node;
function GetData(const Index: NativeInt): PKDT11DD_Source;
public
RootNode: PKDT11DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT11DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT11DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT11DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT11DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT11DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DD_Node; overload;
function Search(const buff: TKDT11DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DD_Node; overload;
function Search(const buff: TKDT11DD_Vec; var SearchedDistanceMin: Double): PKDT11DD_Node; overload;
function Search(const buff: TKDT11DD_Vec): PKDT11DD_Node; overload;
function SearchToken(const buff: TKDT11DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT11DD_DynamicVecBuffer; var OutBuff: TKDT11DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT11DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT11DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT11DD_Vec; overload;
class function Vec(const v: TKDT11DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT11DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT12DD = class(TCoreClassObject)
public type
// code split
TKDT12DD_Vec = array [0 .. KDT12DD_Axis - 1] of TKDT12DD_VecType;
PKDT12DD_Vec = ^TKDT12DD_Vec;
TKDT12DD_DynamicVecBuffer = array of TKDT12DD_Vec;
PKDT12DD_DynamicVecBuffer = ^TKDT12DD_DynamicVecBuffer;
TKDT12DD_Source = record
buff: TKDT12DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT12DD_Source = ^TKDT12DD_Source;
TKDT12DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT12DD_Source) - 1] of PKDT12DD_Source;
PKDT12DD_SourceBuffer = ^TKDT12DD_SourceBuffer;
TKDT12DD_DyanmicSourceBuffer = array of PKDT12DD_Source;
PKDT12DD_DyanmicSourceBuffer = ^TKDT12DD_DyanmicSourceBuffer;
TKDT12DD_DyanmicStoreBuffer = array of TKDT12DD_Source;
PKDT12DD_DyanmicStoreBuffer = ^TKDT12DD_DyanmicStoreBuffer;
PKDT12DD_Node = ^TKDT12DD_Node;
TKDT12DD_Node = record
Parent, Right, Left: PKDT12DD_Node;
Vec: PKDT12DD_Source;
end;
TKDT12DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT12DD_Source; const Data: Pointer);
TKDT12DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT12DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT12DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT12DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT12DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT12DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT12DD_DyanmicStoreBuffer;
KDBuff: TKDT12DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT12DD_Node;
TestBuff: TKDT12DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DD_Node;
function GetData(const Index: NativeInt): PKDT12DD_Source;
public
RootNode: PKDT12DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT12DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT12DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT12DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT12DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT12DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DD_Node; overload;
function Search(const buff: TKDT12DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DD_Node; overload;
function Search(const buff: TKDT12DD_Vec; var SearchedDistanceMin: Double): PKDT12DD_Node; overload;
function Search(const buff: TKDT12DD_Vec): PKDT12DD_Node; overload;
function SearchToken(const buff: TKDT12DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT12DD_DynamicVecBuffer; var OutBuff: TKDT12DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT12DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT12DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT12DD_Vec; overload;
class function Vec(const v: TKDT12DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT12DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT13DD = class(TCoreClassObject)
public type
// code split
TKDT13DD_Vec = array [0 .. KDT13DD_Axis - 1] of TKDT13DD_VecType;
PKDT13DD_Vec = ^TKDT13DD_Vec;
TKDT13DD_DynamicVecBuffer = array of TKDT13DD_Vec;
PKDT13DD_DynamicVecBuffer = ^TKDT13DD_DynamicVecBuffer;
TKDT13DD_Source = record
buff: TKDT13DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT13DD_Source = ^TKDT13DD_Source;
TKDT13DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT13DD_Source) - 1] of PKDT13DD_Source;
PKDT13DD_SourceBuffer = ^TKDT13DD_SourceBuffer;
TKDT13DD_DyanmicSourceBuffer = array of PKDT13DD_Source;
PKDT13DD_DyanmicSourceBuffer = ^TKDT13DD_DyanmicSourceBuffer;
TKDT13DD_DyanmicStoreBuffer = array of TKDT13DD_Source;
PKDT13DD_DyanmicStoreBuffer = ^TKDT13DD_DyanmicStoreBuffer;
PKDT13DD_Node = ^TKDT13DD_Node;
TKDT13DD_Node = record
Parent, Right, Left: PKDT13DD_Node;
Vec: PKDT13DD_Source;
end;
TKDT13DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT13DD_Source; const Data: Pointer);
TKDT13DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT13DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT13DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT13DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT13DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT13DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT13DD_DyanmicStoreBuffer;
KDBuff: TKDT13DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT13DD_Node;
TestBuff: TKDT13DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DD_Node;
function GetData(const Index: NativeInt): PKDT13DD_Source;
public
RootNode: PKDT13DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT13DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT13DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT13DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT13DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT13DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DD_Node; overload;
function Search(const buff: TKDT13DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DD_Node; overload;
function Search(const buff: TKDT13DD_Vec; var SearchedDistanceMin: Double): PKDT13DD_Node; overload;
function Search(const buff: TKDT13DD_Vec): PKDT13DD_Node; overload;
function SearchToken(const buff: TKDT13DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT13DD_DynamicVecBuffer; var OutBuff: TKDT13DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT13DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT13DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT13DD_Vec; overload;
class function Vec(const v: TKDT13DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT13DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT14DD = class(TCoreClassObject)
public type
// code split
TKDT14DD_Vec = array [0 .. KDT14DD_Axis - 1] of TKDT14DD_VecType;
PKDT14DD_Vec = ^TKDT14DD_Vec;
TKDT14DD_DynamicVecBuffer = array of TKDT14DD_Vec;
PKDT14DD_DynamicVecBuffer = ^TKDT14DD_DynamicVecBuffer;
TKDT14DD_Source = record
buff: TKDT14DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT14DD_Source = ^TKDT14DD_Source;
TKDT14DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT14DD_Source) - 1] of PKDT14DD_Source;
PKDT14DD_SourceBuffer = ^TKDT14DD_SourceBuffer;
TKDT14DD_DyanmicSourceBuffer = array of PKDT14DD_Source;
PKDT14DD_DyanmicSourceBuffer = ^TKDT14DD_DyanmicSourceBuffer;
TKDT14DD_DyanmicStoreBuffer = array of TKDT14DD_Source;
PKDT14DD_DyanmicStoreBuffer = ^TKDT14DD_DyanmicStoreBuffer;
PKDT14DD_Node = ^TKDT14DD_Node;
TKDT14DD_Node = record
Parent, Right, Left: PKDT14DD_Node;
Vec: PKDT14DD_Source;
end;
TKDT14DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT14DD_Source; const Data: Pointer);
TKDT14DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT14DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT14DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT14DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT14DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT14DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT14DD_DyanmicStoreBuffer;
KDBuff: TKDT14DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT14DD_Node;
TestBuff: TKDT14DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DD_Node;
function GetData(const Index: NativeInt): PKDT14DD_Source;
public
RootNode: PKDT14DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT14DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT14DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT14DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT14DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT14DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DD_Node; overload;
function Search(const buff: TKDT14DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DD_Node; overload;
function Search(const buff: TKDT14DD_Vec; var SearchedDistanceMin: Double): PKDT14DD_Node; overload;
function Search(const buff: TKDT14DD_Vec): PKDT14DD_Node; overload;
function SearchToken(const buff: TKDT14DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT14DD_DynamicVecBuffer; var OutBuff: TKDT14DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT14DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT14DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT14DD_Vec; overload;
class function Vec(const v: TKDT14DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT14DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT15DD = class(TCoreClassObject)
public type
// code split
TKDT15DD_Vec = array [0 .. KDT15DD_Axis - 1] of TKDT15DD_VecType;
PKDT15DD_Vec = ^TKDT15DD_Vec;
TKDT15DD_DynamicVecBuffer = array of TKDT15DD_Vec;
PKDT15DD_DynamicVecBuffer = ^TKDT15DD_DynamicVecBuffer;
TKDT15DD_Source = record
buff: TKDT15DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT15DD_Source = ^TKDT15DD_Source;
TKDT15DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT15DD_Source) - 1] of PKDT15DD_Source;
PKDT15DD_SourceBuffer = ^TKDT15DD_SourceBuffer;
TKDT15DD_DyanmicSourceBuffer = array of PKDT15DD_Source;
PKDT15DD_DyanmicSourceBuffer = ^TKDT15DD_DyanmicSourceBuffer;
TKDT15DD_DyanmicStoreBuffer = array of TKDT15DD_Source;
PKDT15DD_DyanmicStoreBuffer = ^TKDT15DD_DyanmicStoreBuffer;
PKDT15DD_Node = ^TKDT15DD_Node;
TKDT15DD_Node = record
Parent, Right, Left: PKDT15DD_Node;
Vec: PKDT15DD_Source;
end;
TKDT15DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT15DD_Source; const Data: Pointer);
TKDT15DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT15DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT15DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT15DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT15DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT15DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT15DD_DyanmicStoreBuffer;
KDBuff: TKDT15DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT15DD_Node;
TestBuff: TKDT15DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DD_Node;
function GetData(const Index: NativeInt): PKDT15DD_Source;
public
RootNode: PKDT15DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT15DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT15DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT15DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT15DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT15DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DD_Node; overload;
function Search(const buff: TKDT15DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DD_Node; overload;
function Search(const buff: TKDT15DD_Vec; var SearchedDistanceMin: Double): PKDT15DD_Node; overload;
function Search(const buff: TKDT15DD_Vec): PKDT15DD_Node; overload;
function SearchToken(const buff: TKDT15DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT15DD_DynamicVecBuffer; var OutBuff: TKDT15DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT15DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT15DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT15DD_Vec; overload;
class function Vec(const v: TKDT15DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT15DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT16DD = class(TCoreClassObject)
public type
// code split
TKDT16DD_Vec = array [0 .. KDT16DD_Axis - 1] of TKDT16DD_VecType;
PKDT16DD_Vec = ^TKDT16DD_Vec;
TKDT16DD_DynamicVecBuffer = array of TKDT16DD_Vec;
PKDT16DD_DynamicVecBuffer = ^TKDT16DD_DynamicVecBuffer;
TKDT16DD_Source = record
buff: TKDT16DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT16DD_Source = ^TKDT16DD_Source;
TKDT16DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT16DD_Source) - 1] of PKDT16DD_Source;
PKDT16DD_SourceBuffer = ^TKDT16DD_SourceBuffer;
TKDT16DD_DyanmicSourceBuffer = array of PKDT16DD_Source;
PKDT16DD_DyanmicSourceBuffer = ^TKDT16DD_DyanmicSourceBuffer;
TKDT16DD_DyanmicStoreBuffer = array of TKDT16DD_Source;
PKDT16DD_DyanmicStoreBuffer = ^TKDT16DD_DyanmicStoreBuffer;
PKDT16DD_Node = ^TKDT16DD_Node;
TKDT16DD_Node = record
Parent, Right, Left: PKDT16DD_Node;
Vec: PKDT16DD_Source;
end;
TKDT16DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT16DD_Source; const Data: Pointer);
TKDT16DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT16DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT16DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT16DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT16DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT16DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT16DD_DyanmicStoreBuffer;
KDBuff: TKDT16DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT16DD_Node;
TestBuff: TKDT16DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DD_Node;
function GetData(const Index: NativeInt): PKDT16DD_Source;
public
RootNode: PKDT16DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT16DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT16DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT16DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT16DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT16DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DD_Node; overload;
function Search(const buff: TKDT16DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DD_Node; overload;
function Search(const buff: TKDT16DD_Vec; var SearchedDistanceMin: Double): PKDT16DD_Node; overload;
function Search(const buff: TKDT16DD_Vec): PKDT16DD_Node; overload;
function SearchToken(const buff: TKDT16DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT16DD_DynamicVecBuffer; var OutBuff: TKDT16DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT16DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT16DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT16DD_Vec; overload;
class function Vec(const v: TKDT16DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT16DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT17DD = class(TCoreClassObject)
public type
// code split
TKDT17DD_Vec = array [0 .. KDT17DD_Axis - 1] of TKDT17DD_VecType;
PKDT17DD_Vec = ^TKDT17DD_Vec;
TKDT17DD_DynamicVecBuffer = array of TKDT17DD_Vec;
PKDT17DD_DynamicVecBuffer = ^TKDT17DD_DynamicVecBuffer;
TKDT17DD_Source = record
buff: TKDT17DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT17DD_Source = ^TKDT17DD_Source;
TKDT17DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT17DD_Source) - 1] of PKDT17DD_Source;
PKDT17DD_SourceBuffer = ^TKDT17DD_SourceBuffer;
TKDT17DD_DyanmicSourceBuffer = array of PKDT17DD_Source;
PKDT17DD_DyanmicSourceBuffer = ^TKDT17DD_DyanmicSourceBuffer;
TKDT17DD_DyanmicStoreBuffer = array of TKDT17DD_Source;
PKDT17DD_DyanmicStoreBuffer = ^TKDT17DD_DyanmicStoreBuffer;
PKDT17DD_Node = ^TKDT17DD_Node;
TKDT17DD_Node = record
Parent, Right, Left: PKDT17DD_Node;
Vec: PKDT17DD_Source;
end;
TKDT17DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT17DD_Source; const Data: Pointer);
TKDT17DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT17DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT17DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT17DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT17DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT17DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT17DD_DyanmicStoreBuffer;
KDBuff: TKDT17DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT17DD_Node;
TestBuff: TKDT17DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DD_Node;
function GetData(const Index: NativeInt): PKDT17DD_Source;
public
RootNode: PKDT17DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT17DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT17DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT17DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT17DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT17DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DD_Node; overload;
function Search(const buff: TKDT17DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DD_Node; overload;
function Search(const buff: TKDT17DD_Vec; var SearchedDistanceMin: Double): PKDT17DD_Node; overload;
function Search(const buff: TKDT17DD_Vec): PKDT17DD_Node; overload;
function SearchToken(const buff: TKDT17DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT17DD_DynamicVecBuffer; var OutBuff: TKDT17DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT17DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT17DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT17DD_Vec; overload;
class function Vec(const v: TKDT17DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT17DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT18DD = class(TCoreClassObject)
public type
// code split
TKDT18DD_Vec = array [0 .. KDT18DD_Axis - 1] of TKDT18DD_VecType;
PKDT18DD_Vec = ^TKDT18DD_Vec;
TKDT18DD_DynamicVecBuffer = array of TKDT18DD_Vec;
PKDT18DD_DynamicVecBuffer = ^TKDT18DD_DynamicVecBuffer;
TKDT18DD_Source = record
buff: TKDT18DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT18DD_Source = ^TKDT18DD_Source;
TKDT18DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT18DD_Source) - 1] of PKDT18DD_Source;
PKDT18DD_SourceBuffer = ^TKDT18DD_SourceBuffer;
TKDT18DD_DyanmicSourceBuffer = array of PKDT18DD_Source;
PKDT18DD_DyanmicSourceBuffer = ^TKDT18DD_DyanmicSourceBuffer;
TKDT18DD_DyanmicStoreBuffer = array of TKDT18DD_Source;
PKDT18DD_DyanmicStoreBuffer = ^TKDT18DD_DyanmicStoreBuffer;
PKDT18DD_Node = ^TKDT18DD_Node;
TKDT18DD_Node = record
Parent, Right, Left: PKDT18DD_Node;
Vec: PKDT18DD_Source;
end;
TKDT18DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT18DD_Source; const Data: Pointer);
TKDT18DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT18DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT18DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT18DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT18DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT18DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT18DD_DyanmicStoreBuffer;
KDBuff: TKDT18DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT18DD_Node;
TestBuff: TKDT18DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DD_Node;
function GetData(const Index: NativeInt): PKDT18DD_Source;
public
RootNode: PKDT18DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT18DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT18DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT18DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT18DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT18DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DD_Node; overload;
function Search(const buff: TKDT18DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DD_Node; overload;
function Search(const buff: TKDT18DD_Vec; var SearchedDistanceMin: Double): PKDT18DD_Node; overload;
function Search(const buff: TKDT18DD_Vec): PKDT18DD_Node; overload;
function SearchToken(const buff: TKDT18DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT18DD_DynamicVecBuffer; var OutBuff: TKDT18DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT18DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT18DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT18DD_Vec; overload;
class function Vec(const v: TKDT18DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT18DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT19DD = class(TCoreClassObject)
public type
// code split
TKDT19DD_Vec = array [0 .. KDT19DD_Axis - 1] of TKDT19DD_VecType;
PKDT19DD_Vec = ^TKDT19DD_Vec;
TKDT19DD_DynamicVecBuffer = array of TKDT19DD_Vec;
PKDT19DD_DynamicVecBuffer = ^TKDT19DD_DynamicVecBuffer;
TKDT19DD_Source = record
buff: TKDT19DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT19DD_Source = ^TKDT19DD_Source;
TKDT19DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT19DD_Source) - 1] of PKDT19DD_Source;
PKDT19DD_SourceBuffer = ^TKDT19DD_SourceBuffer;
TKDT19DD_DyanmicSourceBuffer = array of PKDT19DD_Source;
PKDT19DD_DyanmicSourceBuffer = ^TKDT19DD_DyanmicSourceBuffer;
TKDT19DD_DyanmicStoreBuffer = array of TKDT19DD_Source;
PKDT19DD_DyanmicStoreBuffer = ^TKDT19DD_DyanmicStoreBuffer;
PKDT19DD_Node = ^TKDT19DD_Node;
TKDT19DD_Node = record
Parent, Right, Left: PKDT19DD_Node;
Vec: PKDT19DD_Source;
end;
TKDT19DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT19DD_Source; const Data: Pointer);
TKDT19DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT19DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT19DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT19DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT19DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT19DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT19DD_DyanmicStoreBuffer;
KDBuff: TKDT19DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT19DD_Node;
TestBuff: TKDT19DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DD_Node;
function GetData(const Index: NativeInt): PKDT19DD_Source;
public
RootNode: PKDT19DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT19DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT19DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT19DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT19DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT19DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DD_Node; overload;
function Search(const buff: TKDT19DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DD_Node; overload;
function Search(const buff: TKDT19DD_Vec; var SearchedDistanceMin: Double): PKDT19DD_Node; overload;
function Search(const buff: TKDT19DD_Vec): PKDT19DD_Node; overload;
function SearchToken(const buff: TKDT19DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT19DD_DynamicVecBuffer; var OutBuff: TKDT19DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT19DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT19DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT19DD_Vec; overload;
class function Vec(const v: TKDT19DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT19DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT20DD = class(TCoreClassObject)
public type
// code split
TKDT20DD_Vec = array [0 .. KDT20DD_Axis - 1] of TKDT20DD_VecType;
PKDT20DD_Vec = ^TKDT20DD_Vec;
TKDT20DD_DynamicVecBuffer = array of TKDT20DD_Vec;
PKDT20DD_DynamicVecBuffer = ^TKDT20DD_DynamicVecBuffer;
TKDT20DD_Source = record
buff: TKDT20DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT20DD_Source = ^TKDT20DD_Source;
TKDT20DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT20DD_Source) - 1] of PKDT20DD_Source;
PKDT20DD_SourceBuffer = ^TKDT20DD_SourceBuffer;
TKDT20DD_DyanmicSourceBuffer = array of PKDT20DD_Source;
PKDT20DD_DyanmicSourceBuffer = ^TKDT20DD_DyanmicSourceBuffer;
TKDT20DD_DyanmicStoreBuffer = array of TKDT20DD_Source;
PKDT20DD_DyanmicStoreBuffer = ^TKDT20DD_DyanmicStoreBuffer;
PKDT20DD_Node = ^TKDT20DD_Node;
TKDT20DD_Node = record
Parent, Right, Left: PKDT20DD_Node;
Vec: PKDT20DD_Source;
end;
TKDT20DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT20DD_Source; const Data: Pointer);
TKDT20DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT20DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT20DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT20DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT20DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT20DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT20DD_DyanmicStoreBuffer;
KDBuff: TKDT20DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT20DD_Node;
TestBuff: TKDT20DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DD_Node;
function GetData(const Index: NativeInt): PKDT20DD_Source;
public
RootNode: PKDT20DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT20DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT20DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT20DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT20DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT20DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DD_Node; overload;
function Search(const buff: TKDT20DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DD_Node; overload;
function Search(const buff: TKDT20DD_Vec; var SearchedDistanceMin: Double): PKDT20DD_Node; overload;
function Search(const buff: TKDT20DD_Vec): PKDT20DD_Node; overload;
function SearchToken(const buff: TKDT20DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT20DD_DynamicVecBuffer; var OutBuff: TKDT20DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT20DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT20DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT20DD_Vec; overload;
class function Vec(const v: TKDT20DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT20DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT21DD = class(TCoreClassObject)
public type
// code split
TKDT21DD_Vec = array [0 .. KDT21DD_Axis - 1] of TKDT21DD_VecType;
PKDT21DD_Vec = ^TKDT21DD_Vec;
TKDT21DD_DynamicVecBuffer = array of TKDT21DD_Vec;
PKDT21DD_DynamicVecBuffer = ^TKDT21DD_DynamicVecBuffer;
TKDT21DD_Source = record
buff: TKDT21DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT21DD_Source = ^TKDT21DD_Source;
TKDT21DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT21DD_Source) - 1] of PKDT21DD_Source;
PKDT21DD_SourceBuffer = ^TKDT21DD_SourceBuffer;
TKDT21DD_DyanmicSourceBuffer = array of PKDT21DD_Source;
PKDT21DD_DyanmicSourceBuffer = ^TKDT21DD_DyanmicSourceBuffer;
TKDT21DD_DyanmicStoreBuffer = array of TKDT21DD_Source;
PKDT21DD_DyanmicStoreBuffer = ^TKDT21DD_DyanmicStoreBuffer;
PKDT21DD_Node = ^TKDT21DD_Node;
TKDT21DD_Node = record
Parent, Right, Left: PKDT21DD_Node;
Vec: PKDT21DD_Source;
end;
TKDT21DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT21DD_Source; const Data: Pointer);
TKDT21DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT21DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT21DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT21DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT21DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT21DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT21DD_DyanmicStoreBuffer;
KDBuff: TKDT21DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT21DD_Node;
TestBuff: TKDT21DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DD_Node;
function GetData(const Index: NativeInt): PKDT21DD_Source;
public
RootNode: PKDT21DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT21DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT21DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT21DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT21DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT21DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DD_Node; overload;
function Search(const buff: TKDT21DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DD_Node; overload;
function Search(const buff: TKDT21DD_Vec; var SearchedDistanceMin: Double): PKDT21DD_Node; overload;
function Search(const buff: TKDT21DD_Vec): PKDT21DD_Node; overload;
function SearchToken(const buff: TKDT21DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT21DD_DynamicVecBuffer; var OutBuff: TKDT21DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT21DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT21DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT21DD_Vec; overload;
class function Vec(const v: TKDT21DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT21DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT22DD = class(TCoreClassObject)
public type
// code split
TKDT22DD_Vec = array [0 .. KDT22DD_Axis - 1] of TKDT22DD_VecType;
PKDT22DD_Vec = ^TKDT22DD_Vec;
TKDT22DD_DynamicVecBuffer = array of TKDT22DD_Vec;
PKDT22DD_DynamicVecBuffer = ^TKDT22DD_DynamicVecBuffer;
TKDT22DD_Source = record
buff: TKDT22DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT22DD_Source = ^TKDT22DD_Source;
TKDT22DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT22DD_Source) - 1] of PKDT22DD_Source;
PKDT22DD_SourceBuffer = ^TKDT22DD_SourceBuffer;
TKDT22DD_DyanmicSourceBuffer = array of PKDT22DD_Source;
PKDT22DD_DyanmicSourceBuffer = ^TKDT22DD_DyanmicSourceBuffer;
TKDT22DD_DyanmicStoreBuffer = array of TKDT22DD_Source;
PKDT22DD_DyanmicStoreBuffer = ^TKDT22DD_DyanmicStoreBuffer;
PKDT22DD_Node = ^TKDT22DD_Node;
TKDT22DD_Node = record
Parent, Right, Left: PKDT22DD_Node;
Vec: PKDT22DD_Source;
end;
TKDT22DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT22DD_Source; const Data: Pointer);
TKDT22DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT22DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT22DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT22DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT22DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT22DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT22DD_DyanmicStoreBuffer;
KDBuff: TKDT22DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT22DD_Node;
TestBuff: TKDT22DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DD_Node;
function GetData(const Index: NativeInt): PKDT22DD_Source;
public
RootNode: PKDT22DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT22DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT22DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT22DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT22DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT22DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DD_Node; overload;
function Search(const buff: TKDT22DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DD_Node; overload;
function Search(const buff: TKDT22DD_Vec; var SearchedDistanceMin: Double): PKDT22DD_Node; overload;
function Search(const buff: TKDT22DD_Vec): PKDT22DD_Node; overload;
function SearchToken(const buff: TKDT22DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT22DD_DynamicVecBuffer; var OutBuff: TKDT22DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT22DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT22DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT22DD_Vec; overload;
class function Vec(const v: TKDT22DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT22DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT23DD = class(TCoreClassObject)
public type
// code split
TKDT23DD_Vec = array [0 .. KDT23DD_Axis - 1] of TKDT23DD_VecType;
PKDT23DD_Vec = ^TKDT23DD_Vec;
TKDT23DD_DynamicVecBuffer = array of TKDT23DD_Vec;
PKDT23DD_DynamicVecBuffer = ^TKDT23DD_DynamicVecBuffer;
TKDT23DD_Source = record
buff: TKDT23DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT23DD_Source = ^TKDT23DD_Source;
TKDT23DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT23DD_Source) - 1] of PKDT23DD_Source;
PKDT23DD_SourceBuffer = ^TKDT23DD_SourceBuffer;
TKDT23DD_DyanmicSourceBuffer = array of PKDT23DD_Source;
PKDT23DD_DyanmicSourceBuffer = ^TKDT23DD_DyanmicSourceBuffer;
TKDT23DD_DyanmicStoreBuffer = array of TKDT23DD_Source;
PKDT23DD_DyanmicStoreBuffer = ^TKDT23DD_DyanmicStoreBuffer;
PKDT23DD_Node = ^TKDT23DD_Node;
TKDT23DD_Node = record
Parent, Right, Left: PKDT23DD_Node;
Vec: PKDT23DD_Source;
end;
TKDT23DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT23DD_Source; const Data: Pointer);
TKDT23DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT23DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT23DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT23DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT23DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT23DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT23DD_DyanmicStoreBuffer;
KDBuff: TKDT23DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT23DD_Node;
TestBuff: TKDT23DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DD_Node;
function GetData(const Index: NativeInt): PKDT23DD_Source;
public
RootNode: PKDT23DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT23DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT23DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT23DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT23DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT23DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DD_Node; overload;
function Search(const buff: TKDT23DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DD_Node; overload;
function Search(const buff: TKDT23DD_Vec; var SearchedDistanceMin: Double): PKDT23DD_Node; overload;
function Search(const buff: TKDT23DD_Vec): PKDT23DD_Node; overload;
function SearchToken(const buff: TKDT23DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT23DD_DynamicVecBuffer; var OutBuff: TKDT23DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT23DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT23DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT23DD_Vec; overload;
class function Vec(const v: TKDT23DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT23DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT24DD = class(TCoreClassObject)
public type
// code split
TKDT24DD_Vec = array [0 .. KDT24DD_Axis - 1] of TKDT24DD_VecType;
PKDT24DD_Vec = ^TKDT24DD_Vec;
TKDT24DD_DynamicVecBuffer = array of TKDT24DD_Vec;
PKDT24DD_DynamicVecBuffer = ^TKDT24DD_DynamicVecBuffer;
TKDT24DD_Source = record
buff: TKDT24DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT24DD_Source = ^TKDT24DD_Source;
TKDT24DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT24DD_Source) - 1] of PKDT24DD_Source;
PKDT24DD_SourceBuffer = ^TKDT24DD_SourceBuffer;
TKDT24DD_DyanmicSourceBuffer = array of PKDT24DD_Source;
PKDT24DD_DyanmicSourceBuffer = ^TKDT24DD_DyanmicSourceBuffer;
TKDT24DD_DyanmicStoreBuffer = array of TKDT24DD_Source;
PKDT24DD_DyanmicStoreBuffer = ^TKDT24DD_DyanmicStoreBuffer;
PKDT24DD_Node = ^TKDT24DD_Node;
TKDT24DD_Node = record
Parent, Right, Left: PKDT24DD_Node;
Vec: PKDT24DD_Source;
end;
TKDT24DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT24DD_Source; const Data: Pointer);
TKDT24DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT24DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT24DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT24DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT24DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT24DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT24DD_DyanmicStoreBuffer;
KDBuff: TKDT24DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT24DD_Node;
TestBuff: TKDT24DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DD_Node;
function GetData(const Index: NativeInt): PKDT24DD_Source;
public
RootNode: PKDT24DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT24DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT24DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT24DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT24DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT24DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DD_Node; overload;
function Search(const buff: TKDT24DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DD_Node; overload;
function Search(const buff: TKDT24DD_Vec; var SearchedDistanceMin: Double): PKDT24DD_Node; overload;
function Search(const buff: TKDT24DD_Vec): PKDT24DD_Node; overload;
function SearchToken(const buff: TKDT24DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT24DD_DynamicVecBuffer; var OutBuff: TKDT24DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT24DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT24DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT24DD_Vec; overload;
class function Vec(const v: TKDT24DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT24DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT48DD = class(TCoreClassObject)
public type
// code split
TKDT48DD_Vec = array [0 .. KDT48DD_Axis - 1] of TKDT48DD_VecType;
PKDT48DD_Vec = ^TKDT48DD_Vec;
TKDT48DD_DynamicVecBuffer = array of TKDT48DD_Vec;
PKDT48DD_DynamicVecBuffer = ^TKDT48DD_DynamicVecBuffer;
TKDT48DD_Source = record
buff: TKDT48DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT48DD_Source = ^TKDT48DD_Source;
TKDT48DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT48DD_Source) - 1] of PKDT48DD_Source;
PKDT48DD_SourceBuffer = ^TKDT48DD_SourceBuffer;
TKDT48DD_DyanmicSourceBuffer = array of PKDT48DD_Source;
PKDT48DD_DyanmicSourceBuffer = ^TKDT48DD_DyanmicSourceBuffer;
TKDT48DD_DyanmicStoreBuffer = array of TKDT48DD_Source;
PKDT48DD_DyanmicStoreBuffer = ^TKDT48DD_DyanmicStoreBuffer;
PKDT48DD_Node = ^TKDT48DD_Node;
TKDT48DD_Node = record
Parent, Right, Left: PKDT48DD_Node;
Vec: PKDT48DD_Source;
end;
TKDT48DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT48DD_Source; const Data: Pointer);
TKDT48DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT48DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT48DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT48DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT48DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT48DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT48DD_DyanmicStoreBuffer;
KDBuff: TKDT48DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT48DD_Node;
TestBuff: TKDT48DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DD_Node;
function GetData(const Index: NativeInt): PKDT48DD_Source;
public
RootNode: PKDT48DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT48DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT48DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT48DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT48DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT48DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DD_Node; overload;
function Search(const buff: TKDT48DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DD_Node; overload;
function Search(const buff: TKDT48DD_Vec; var SearchedDistanceMin: Double): PKDT48DD_Node; overload;
function Search(const buff: TKDT48DD_Vec): PKDT48DD_Node; overload;
function SearchToken(const buff: TKDT48DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT48DD_DynamicVecBuffer; var OutBuff: TKDT48DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT48DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT48DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT48DD_Vec; overload;
class function Vec(const v: TKDT48DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT48DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT52DD = class(TCoreClassObject)
public type
// code split
TKDT52DD_Vec = array [0 .. KDT52DD_Axis - 1] of TKDT52DD_VecType;
PKDT52DD_Vec = ^TKDT52DD_Vec;
TKDT52DD_DynamicVecBuffer = array of TKDT52DD_Vec;
PKDT52DD_DynamicVecBuffer = ^TKDT52DD_DynamicVecBuffer;
TKDT52DD_Source = record
buff: TKDT52DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT52DD_Source = ^TKDT52DD_Source;
TKDT52DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT52DD_Source) - 1] of PKDT52DD_Source;
PKDT52DD_SourceBuffer = ^TKDT52DD_SourceBuffer;
TKDT52DD_DyanmicSourceBuffer = array of PKDT52DD_Source;
PKDT52DD_DyanmicSourceBuffer = ^TKDT52DD_DyanmicSourceBuffer;
TKDT52DD_DyanmicStoreBuffer = array of TKDT52DD_Source;
PKDT52DD_DyanmicStoreBuffer = ^TKDT52DD_DyanmicStoreBuffer;
PKDT52DD_Node = ^TKDT52DD_Node;
TKDT52DD_Node = record
Parent, Right, Left: PKDT52DD_Node;
Vec: PKDT52DD_Source;
end;
TKDT52DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT52DD_Source; const Data: Pointer);
TKDT52DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT52DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT52DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT52DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT52DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT52DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT52DD_DyanmicStoreBuffer;
KDBuff: TKDT52DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT52DD_Node;
TestBuff: TKDT52DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DD_Node;
function GetData(const Index: NativeInt): PKDT52DD_Source;
public
RootNode: PKDT52DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT52DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT52DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT52DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT52DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT52DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DD_Node; overload;
function Search(const buff: TKDT52DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DD_Node; overload;
function Search(const buff: TKDT52DD_Vec; var SearchedDistanceMin: Double): PKDT52DD_Node; overload;
function Search(const buff: TKDT52DD_Vec): PKDT52DD_Node; overload;
function SearchToken(const buff: TKDT52DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT52DD_DynamicVecBuffer; var OutBuff: TKDT52DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT52DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT52DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT52DD_Vec; overload;
class function Vec(const v: TKDT52DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT52DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT64DD = class(TCoreClassObject)
public type
// code split
TKDT64DD_Vec = array [0 .. KDT64DD_Axis - 1] of TKDT64DD_VecType;
PKDT64DD_Vec = ^TKDT64DD_Vec;
TKDT64DD_DynamicVecBuffer = array of TKDT64DD_Vec;
PKDT64DD_DynamicVecBuffer = ^TKDT64DD_DynamicVecBuffer;
TKDT64DD_Source = record
buff: TKDT64DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT64DD_Source = ^TKDT64DD_Source;
TKDT64DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT64DD_Source) - 1] of PKDT64DD_Source;
PKDT64DD_SourceBuffer = ^TKDT64DD_SourceBuffer;
TKDT64DD_DyanmicSourceBuffer = array of PKDT64DD_Source;
PKDT64DD_DyanmicSourceBuffer = ^TKDT64DD_DyanmicSourceBuffer;
TKDT64DD_DyanmicStoreBuffer = array of TKDT64DD_Source;
PKDT64DD_DyanmicStoreBuffer = ^TKDT64DD_DyanmicStoreBuffer;
PKDT64DD_Node = ^TKDT64DD_Node;
TKDT64DD_Node = record
Parent, Right, Left: PKDT64DD_Node;
Vec: PKDT64DD_Source;
end;
TKDT64DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT64DD_Source; const Data: Pointer);
TKDT64DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT64DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT64DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT64DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT64DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT64DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT64DD_DyanmicStoreBuffer;
KDBuff: TKDT64DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT64DD_Node;
TestBuff: TKDT64DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DD_Node;
function GetData(const Index: NativeInt): PKDT64DD_Source;
public
RootNode: PKDT64DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT64DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT64DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT64DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT64DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT64DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DD_Node; overload;
function Search(const buff: TKDT64DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DD_Node; overload;
function Search(const buff: TKDT64DD_Vec; var SearchedDistanceMin: Double): PKDT64DD_Node; overload;
function Search(const buff: TKDT64DD_Vec): PKDT64DD_Node; overload;
function SearchToken(const buff: TKDT64DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT64DD_DynamicVecBuffer; var OutBuff: TKDT64DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT64DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT64DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT64DD_Vec; overload;
class function Vec(const v: TKDT64DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT64DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT96DD = class(TCoreClassObject)
public type
// code split
TKDT96DD_Vec = array [0 .. KDT96DD_Axis - 1] of TKDT96DD_VecType;
PKDT96DD_Vec = ^TKDT96DD_Vec;
TKDT96DD_DynamicVecBuffer = array of TKDT96DD_Vec;
PKDT96DD_DynamicVecBuffer = ^TKDT96DD_DynamicVecBuffer;
TKDT96DD_Source = record
buff: TKDT96DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT96DD_Source = ^TKDT96DD_Source;
TKDT96DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT96DD_Source) - 1] of PKDT96DD_Source;
PKDT96DD_SourceBuffer = ^TKDT96DD_SourceBuffer;
TKDT96DD_DyanmicSourceBuffer = array of PKDT96DD_Source;
PKDT96DD_DyanmicSourceBuffer = ^TKDT96DD_DyanmicSourceBuffer;
TKDT96DD_DyanmicStoreBuffer = array of TKDT96DD_Source;
PKDT96DD_DyanmicStoreBuffer = ^TKDT96DD_DyanmicStoreBuffer;
PKDT96DD_Node = ^TKDT96DD_Node;
TKDT96DD_Node = record
Parent, Right, Left: PKDT96DD_Node;
Vec: PKDT96DD_Source;
end;
TKDT96DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT96DD_Source; const Data: Pointer);
TKDT96DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT96DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT96DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT96DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT96DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT96DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT96DD_DyanmicStoreBuffer;
KDBuff: TKDT96DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT96DD_Node;
TestBuff: TKDT96DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DD_Node;
function GetData(const Index: NativeInt): PKDT96DD_Source;
public
RootNode: PKDT96DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT96DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT96DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT96DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT96DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT96DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DD_Node; overload;
function Search(const buff: TKDT96DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DD_Node; overload;
function Search(const buff: TKDT96DD_Vec; var SearchedDistanceMin: Double): PKDT96DD_Node; overload;
function Search(const buff: TKDT96DD_Vec): PKDT96DD_Node; overload;
function SearchToken(const buff: TKDT96DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT96DD_DynamicVecBuffer; var OutBuff: TKDT96DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT96DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT96DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT96DD_Vec; overload;
class function Vec(const v: TKDT96DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT96DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT128DD = class(TCoreClassObject)
public type
// code split
TKDT128DD_Vec = array [0 .. KDT128DD_Axis - 1] of TKDT128DD_VecType;
PKDT128DD_Vec = ^TKDT128DD_Vec;
TKDT128DD_DynamicVecBuffer = array of TKDT128DD_Vec;
PKDT128DD_DynamicVecBuffer = ^TKDT128DD_DynamicVecBuffer;
TKDT128DD_Source = record
buff: TKDT128DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT128DD_Source = ^TKDT128DD_Source;
TKDT128DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT128DD_Source) - 1] of PKDT128DD_Source;
PKDT128DD_SourceBuffer = ^TKDT128DD_SourceBuffer;
TKDT128DD_DyanmicSourceBuffer = array of PKDT128DD_Source;
PKDT128DD_DyanmicSourceBuffer = ^TKDT128DD_DyanmicSourceBuffer;
TKDT128DD_DyanmicStoreBuffer = array of TKDT128DD_Source;
PKDT128DD_DyanmicStoreBuffer = ^TKDT128DD_DyanmicStoreBuffer;
PKDT128DD_Node = ^TKDT128DD_Node;
TKDT128DD_Node = record
Parent, Right, Left: PKDT128DD_Node;
Vec: PKDT128DD_Source;
end;
TKDT128DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT128DD_Source; const Data: Pointer);
TKDT128DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT128DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT128DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT128DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT128DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT128DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT128DD_DyanmicStoreBuffer;
KDBuff: TKDT128DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT128DD_Node;
TestBuff: TKDT128DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DD_Node;
function GetData(const Index: NativeInt): PKDT128DD_Source;
public
RootNode: PKDT128DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT128DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT128DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT128DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT128DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT128DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DD_Node; overload;
function Search(const buff: TKDT128DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DD_Node; overload;
function Search(const buff: TKDT128DD_Vec; var SearchedDistanceMin: Double): PKDT128DD_Node; overload;
function Search(const buff: TKDT128DD_Vec): PKDT128DD_Node; overload;
function SearchToken(const buff: TKDT128DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT128DD_DynamicVecBuffer; var OutBuff: TKDT128DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT128DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT128DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT128DD_Vec; overload;
class function Vec(const v: TKDT128DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT128DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT156DD = class(TCoreClassObject)
public type
// code split
TKDT156DD_Vec = array [0 .. KDT156DD_Axis - 1] of TKDT156DD_VecType;
PKDT156DD_Vec = ^TKDT156DD_Vec;
TKDT156DD_DynamicVecBuffer = array of TKDT156DD_Vec;
PKDT156DD_DynamicVecBuffer = ^TKDT156DD_DynamicVecBuffer;
TKDT156DD_Source = record
buff: TKDT156DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT156DD_Source = ^TKDT156DD_Source;
TKDT156DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT156DD_Source) - 1] of PKDT156DD_Source;
PKDT156DD_SourceBuffer = ^TKDT156DD_SourceBuffer;
TKDT156DD_DyanmicSourceBuffer = array of PKDT156DD_Source;
PKDT156DD_DyanmicSourceBuffer = ^TKDT156DD_DyanmicSourceBuffer;
TKDT156DD_DyanmicStoreBuffer = array of TKDT156DD_Source;
PKDT156DD_DyanmicStoreBuffer = ^TKDT156DD_DyanmicStoreBuffer;
PKDT156DD_Node = ^TKDT156DD_Node;
TKDT156DD_Node = record
Parent, Right, Left: PKDT156DD_Node;
Vec: PKDT156DD_Source;
end;
TKDT156DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT156DD_Source; const Data: Pointer);
TKDT156DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT156DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT156DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT156DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT156DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT156DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT156DD_DyanmicStoreBuffer;
KDBuff: TKDT156DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT156DD_Node;
TestBuff: TKDT156DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DD_Node;
function GetData(const Index: NativeInt): PKDT156DD_Source;
public
RootNode: PKDT156DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT156DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT156DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT156DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT156DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT156DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DD_Node; overload;
function Search(const buff: TKDT156DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DD_Node; overload;
function Search(const buff: TKDT156DD_Vec; var SearchedDistanceMin: Double): PKDT156DD_Node; overload;
function Search(const buff: TKDT156DD_Vec): PKDT156DD_Node; overload;
function SearchToken(const buff: TKDT156DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT156DD_DynamicVecBuffer; var OutBuff: TKDT156DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT156DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT156DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT156DD_Vec; overload;
class function Vec(const v: TKDT156DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT156DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT192DD = class(TCoreClassObject)
public type
// code split
TKDT192DD_Vec = array [0 .. KDT192DD_Axis - 1] of TKDT192DD_VecType;
PKDT192DD_Vec = ^TKDT192DD_Vec;
TKDT192DD_DynamicVecBuffer = array of TKDT192DD_Vec;
PKDT192DD_DynamicVecBuffer = ^TKDT192DD_DynamicVecBuffer;
TKDT192DD_Source = record
buff: TKDT192DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT192DD_Source = ^TKDT192DD_Source;
TKDT192DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT192DD_Source) - 1] of PKDT192DD_Source;
PKDT192DD_SourceBuffer = ^TKDT192DD_SourceBuffer;
TKDT192DD_DyanmicSourceBuffer = array of PKDT192DD_Source;
PKDT192DD_DyanmicSourceBuffer = ^TKDT192DD_DyanmicSourceBuffer;
TKDT192DD_DyanmicStoreBuffer = array of TKDT192DD_Source;
PKDT192DD_DyanmicStoreBuffer = ^TKDT192DD_DyanmicStoreBuffer;
PKDT192DD_Node = ^TKDT192DD_Node;
TKDT192DD_Node = record
Parent, Right, Left: PKDT192DD_Node;
Vec: PKDT192DD_Source;
end;
TKDT192DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT192DD_Source; const Data: Pointer);
TKDT192DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT192DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT192DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT192DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT192DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT192DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT192DD_DyanmicStoreBuffer;
KDBuff: TKDT192DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT192DD_Node;
TestBuff: TKDT192DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DD_Node;
function GetData(const Index: NativeInt): PKDT192DD_Source;
public
RootNode: PKDT192DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT192DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT192DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT192DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT192DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT192DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DD_Node; overload;
function Search(const buff: TKDT192DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DD_Node; overload;
function Search(const buff: TKDT192DD_Vec; var SearchedDistanceMin: Double): PKDT192DD_Node; overload;
function Search(const buff: TKDT192DD_Vec): PKDT192DD_Node; overload;
function SearchToken(const buff: TKDT192DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT192DD_DynamicVecBuffer; var OutBuff: TKDT192DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT192DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT192DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT192DD_Vec; overload;
class function Vec(const v: TKDT192DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT192DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT256DD = class(TCoreClassObject)
public type
// code split
TKDT256DD_Vec = array [0 .. KDT256DD_Axis - 1] of TKDT256DD_VecType;
PKDT256DD_Vec = ^TKDT256DD_Vec;
TKDT256DD_DynamicVecBuffer = array of TKDT256DD_Vec;
PKDT256DD_DynamicVecBuffer = ^TKDT256DD_DynamicVecBuffer;
TKDT256DD_Source = record
buff: TKDT256DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT256DD_Source = ^TKDT256DD_Source;
TKDT256DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT256DD_Source) - 1] of PKDT256DD_Source;
PKDT256DD_SourceBuffer = ^TKDT256DD_SourceBuffer;
TKDT256DD_DyanmicSourceBuffer = array of PKDT256DD_Source;
PKDT256DD_DyanmicSourceBuffer = ^TKDT256DD_DyanmicSourceBuffer;
TKDT256DD_DyanmicStoreBuffer = array of TKDT256DD_Source;
PKDT256DD_DyanmicStoreBuffer = ^TKDT256DD_DyanmicStoreBuffer;
PKDT256DD_Node = ^TKDT256DD_Node;
TKDT256DD_Node = record
Parent, Right, Left: PKDT256DD_Node;
Vec: PKDT256DD_Source;
end;
TKDT256DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT256DD_Source; const Data: Pointer);
TKDT256DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT256DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT256DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT256DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT256DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT256DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT256DD_DyanmicStoreBuffer;
KDBuff: TKDT256DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT256DD_Node;
TestBuff: TKDT256DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DD_Node;
function GetData(const Index: NativeInt): PKDT256DD_Source;
public
RootNode: PKDT256DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT256DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT256DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT256DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT256DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT256DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DD_Node; overload;
function Search(const buff: TKDT256DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DD_Node; overload;
function Search(const buff: TKDT256DD_Vec; var SearchedDistanceMin: Double): PKDT256DD_Node; overload;
function Search(const buff: TKDT256DD_Vec): PKDT256DD_Node; overload;
function SearchToken(const buff: TKDT256DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT256DD_DynamicVecBuffer; var OutBuff: TKDT256DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT256DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT256DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT256DD_Vec; overload;
class function Vec(const v: TKDT256DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT256DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT384DD = class(TCoreClassObject)
public type
// code split
TKDT384DD_Vec = array [0 .. KDT384DD_Axis - 1] of TKDT384DD_VecType;
PKDT384DD_Vec = ^TKDT384DD_Vec;
TKDT384DD_DynamicVecBuffer = array of TKDT384DD_Vec;
PKDT384DD_DynamicVecBuffer = ^TKDT384DD_DynamicVecBuffer;
TKDT384DD_Source = record
buff: TKDT384DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT384DD_Source = ^TKDT384DD_Source;
TKDT384DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT384DD_Source) - 1] of PKDT384DD_Source;
PKDT384DD_SourceBuffer = ^TKDT384DD_SourceBuffer;
TKDT384DD_DyanmicSourceBuffer = array of PKDT384DD_Source;
PKDT384DD_DyanmicSourceBuffer = ^TKDT384DD_DyanmicSourceBuffer;
TKDT384DD_DyanmicStoreBuffer = array of TKDT384DD_Source;
PKDT384DD_DyanmicStoreBuffer = ^TKDT384DD_DyanmicStoreBuffer;
PKDT384DD_Node = ^TKDT384DD_Node;
TKDT384DD_Node = record
Parent, Right, Left: PKDT384DD_Node;
Vec: PKDT384DD_Source;
end;
TKDT384DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT384DD_Source; const Data: Pointer);
TKDT384DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT384DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT384DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT384DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT384DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT384DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT384DD_DyanmicStoreBuffer;
KDBuff: TKDT384DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT384DD_Node;
TestBuff: TKDT384DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DD_Node;
function GetData(const Index: NativeInt): PKDT384DD_Source;
public
RootNode: PKDT384DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT384DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT384DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT384DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT384DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT384DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DD_Node; overload;
function Search(const buff: TKDT384DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DD_Node; overload;
function Search(const buff: TKDT384DD_Vec; var SearchedDistanceMin: Double): PKDT384DD_Node; overload;
function Search(const buff: TKDT384DD_Vec): PKDT384DD_Node; overload;
function SearchToken(const buff: TKDT384DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT384DD_DynamicVecBuffer; var OutBuff: TKDT384DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT384DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT384DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT384DD_Vec; overload;
class function Vec(const v: TKDT384DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT384DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT512DD = class(TCoreClassObject)
public type
// code split
TKDT512DD_Vec = array [0 .. KDT512DD_Axis - 1] of TKDT512DD_VecType;
PKDT512DD_Vec = ^TKDT512DD_Vec;
TKDT512DD_DynamicVecBuffer = array of TKDT512DD_Vec;
PKDT512DD_DynamicVecBuffer = ^TKDT512DD_DynamicVecBuffer;
TKDT512DD_Source = record
buff: TKDT512DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT512DD_Source = ^TKDT512DD_Source;
TKDT512DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT512DD_Source) - 1] of PKDT512DD_Source;
PKDT512DD_SourceBuffer = ^TKDT512DD_SourceBuffer;
TKDT512DD_DyanmicSourceBuffer = array of PKDT512DD_Source;
PKDT512DD_DyanmicSourceBuffer = ^TKDT512DD_DyanmicSourceBuffer;
TKDT512DD_DyanmicStoreBuffer = array of TKDT512DD_Source;
PKDT512DD_DyanmicStoreBuffer = ^TKDT512DD_DyanmicStoreBuffer;
PKDT512DD_Node = ^TKDT512DD_Node;
TKDT512DD_Node = record
Parent, Right, Left: PKDT512DD_Node;
Vec: PKDT512DD_Source;
end;
TKDT512DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT512DD_Source; const Data: Pointer);
TKDT512DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT512DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT512DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT512DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT512DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT512DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT512DD_DyanmicStoreBuffer;
KDBuff: TKDT512DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT512DD_Node;
TestBuff: TKDT512DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DD_Node;
function GetData(const Index: NativeInt): PKDT512DD_Source;
public
RootNode: PKDT512DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT512DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT512DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT512DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT512DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT512DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DD_Node; overload;
function Search(const buff: TKDT512DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DD_Node; overload;
function Search(const buff: TKDT512DD_Vec; var SearchedDistanceMin: Double): PKDT512DD_Node; overload;
function Search(const buff: TKDT512DD_Vec): PKDT512DD_Node; overload;
function SearchToken(const buff: TKDT512DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT512DD_DynamicVecBuffer; var OutBuff: TKDT512DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT512DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT512DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT512DD_Vec; overload;
class function Vec(const v: TKDT512DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT512DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT800DD = class(TCoreClassObject)
public type
// code split
TKDT800DD_Vec = array [0 .. KDT800DD_Axis - 1] of TKDT800DD_VecType;
PKDT800DD_Vec = ^TKDT800DD_Vec;
TKDT800DD_DynamicVecBuffer = array of TKDT800DD_Vec;
PKDT800DD_DynamicVecBuffer = ^TKDT800DD_DynamicVecBuffer;
TKDT800DD_Source = record
buff: TKDT800DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT800DD_Source = ^TKDT800DD_Source;
TKDT800DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT800DD_Source) - 1] of PKDT800DD_Source;
PKDT800DD_SourceBuffer = ^TKDT800DD_SourceBuffer;
TKDT800DD_DyanmicSourceBuffer = array of PKDT800DD_Source;
PKDT800DD_DyanmicSourceBuffer = ^TKDT800DD_DyanmicSourceBuffer;
TKDT800DD_DyanmicStoreBuffer = array of TKDT800DD_Source;
PKDT800DD_DyanmicStoreBuffer = ^TKDT800DD_DyanmicStoreBuffer;
PKDT800DD_Node = ^TKDT800DD_Node;
TKDT800DD_Node = record
Parent, Right, Left: PKDT800DD_Node;
Vec: PKDT800DD_Source;
end;
TKDT800DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT800DD_Source; const Data: Pointer);
TKDT800DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT800DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT800DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT800DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT800DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT800DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT800DD_DyanmicStoreBuffer;
KDBuff: TKDT800DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT800DD_Node;
TestBuff: TKDT800DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DD_Node;
function GetData(const Index: NativeInt): PKDT800DD_Source;
public
RootNode: PKDT800DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT800DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT800DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT800DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT800DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT800DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DD_Node; overload;
function Search(const buff: TKDT800DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DD_Node; overload;
function Search(const buff: TKDT800DD_Vec; var SearchedDistanceMin: Double): PKDT800DD_Node; overload;
function Search(const buff: TKDT800DD_Vec): PKDT800DD_Node; overload;
function SearchToken(const buff: TKDT800DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT800DD_DynamicVecBuffer; var OutBuff: TKDT800DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT800DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT800DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT800DD_Vec; overload;
class function Vec(const v: TKDT800DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT800DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DD_Source; const Data: Pointer);
class procedure Test;
end;
TKDT1024DD = class(TCoreClassObject)
public type
// code split
TKDT1024DD_Vec = array [0 .. KDT1024DD_Axis - 1] of TKDT1024DD_VecType;
PKDT1024DD_Vec = ^TKDT1024DD_Vec;
TKDT1024DD_DynamicVecBuffer = array of TKDT1024DD_Vec;
PKDT1024DD_DynamicVecBuffer = ^TKDT1024DD_DynamicVecBuffer;
TKDT1024DD_Source = record
buff: TKDT1024DD_Vec;
Index: Int64;
Token: TPascalString;
end;
PKDT1024DD_Source = ^TKDT1024DD_Source;
TKDT1024DD_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1024DD_Source) - 1] of PKDT1024DD_Source;
PKDT1024DD_SourceBuffer = ^TKDT1024DD_SourceBuffer;
TKDT1024DD_DyanmicSourceBuffer = array of PKDT1024DD_Source;
PKDT1024DD_DyanmicSourceBuffer = ^TKDT1024DD_DyanmicSourceBuffer;
TKDT1024DD_DyanmicStoreBuffer = array of TKDT1024DD_Source;
PKDT1024DD_DyanmicStoreBuffer = ^TKDT1024DD_DyanmicStoreBuffer;
PKDT1024DD_Node = ^TKDT1024DD_Node;
TKDT1024DD_Node = record
Parent, Right, Left: PKDT1024DD_Node;
Vec: PKDT1024DD_Source;
end;
TKDT1024DD_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1024DD_Source; const Data: Pointer);
TKDT1024DD_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1024DD_Source; const Data: Pointer) of object;
{$IFDEF FPC}
TKDT1024DD_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1024DD_Source; const Data: Pointer) is nested;
{$ELSE FPC}
TKDT1024DD_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1024DD_Source; const Data: Pointer);
{$ENDIF FPC}
private
KDStoreBuff: TKDT1024DD_DyanmicStoreBuffer;
KDBuff: TKDT1024DD_DyanmicSourceBuffer;
NodeCounter: NativeInt;
KDNodes: array of PKDT1024DD_Node;
TestBuff: TKDT1024DD_DynamicVecBuffer;
function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DD_Node;
function GetData(const Index: NativeInt): PKDT1024DD_Source;
public
RootNode: PKDT1024DD_Node;
constructor Create;
destructor Destroy; override;
procedure Clear;
property Count: NativeInt read NodeCounter;
function StoreBuffPtr: PKDT1024DD_DyanmicStoreBuffer;
property SourceP[const Index: NativeInt]: PKDT1024DD_Source read GetData; default;
{ bakcall build }
procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildCall);
procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildMethod);
procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildProc);
{ fill k-means++ clusterization }
procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload;
procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DD_DynamicVecBuffer; const k, Restarts: NativeInt); overload;
{ backcall k-means++ clusterization }
procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildCall); overload;
procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildMethod); overload;
procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildProc); overload;
{ search }
function Search(const buff: TKDT1024DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DD_Node; overload;
function Search(const buff: TKDT1024DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DD_Node; overload;
function Search(const buff: TKDT1024DD_Vec; var SearchedDistanceMin: Double): PKDT1024DD_Node; overload;
function Search(const buff: TKDT1024DD_Vec): PKDT1024DD_Node; overload;
function SearchToken(const buff: TKDT1024DD_Vec): TPascalString;
{ parallel search }
procedure Search(const inBuff: TKDT1024DD_DynamicVecBuffer; var OutBuff: TKDT1024DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure Search(const inBuff: TKDT1024DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload;
procedure SaveToStream(stream: TCoreClassStream);
procedure LoadFromStream(stream: TCoreClassStream);
procedure SaveToFile(FileName: SystemString);
procedure LoadFromFile(FileName: SystemString);
procedure PrintNodeTree(const NodePtr: PKDT1024DD_Node);
procedure PrintBuffer;
class function Vec(const s: SystemString): TKDT1024DD_Vec; overload;
class function Vec(const v: TKDT1024DD_Vec): SystemString; overload;
class function Distance(const v1, v2: TKDT1024DD_Vec): Double;
// debug time
procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DD_Source; const Data: Pointer);
class procedure Test;
end;
procedure Test_All;
implementation
uses
TextParsing, MemoryStream64, DoStatusIO;
const
SaveToken = $11;
function TKDT1DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DD_Node;
function SortCompare(const p1, p2: PKDT1DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT1DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT1DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT1DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT1DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT1DD.GetData(const Index: NativeInt): PKDT1DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT1DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT1DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT1DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT1DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT1DD.StoreBuffPtr: PKDT1DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT1DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT1DD.BuildKDTreeWithCluster(const inBuff: TKDT1DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT1DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT1DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT1DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT1DD.BuildKDTreeWithCluster(const inBuff: TKDT1DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT1DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DD_BuildCall);
var
TempStoreBuff: TKDT1DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DD_BuildMethod);
var
TempStoreBuff: TKDT1DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DD_BuildProc);
var
TempStoreBuff: TKDT1DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT1DD.Search(const buff: TKDT1DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DD_Node;
var
NearestNeighbour: PKDT1DD_Node;
function FindParentNode(const buffPtr: PKDT1DD_Vec; NodePtr: PKDT1DD_Node): PKDT1DD_Node;
var
Next: PKDT1DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT1DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT1DD_Node; const buffPtr: PKDT1DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT1DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT1DD_Vec; const p1, p2: PKDT1DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT1DD_Vec);
var
i, j: NativeInt;
p, t: PKDT1DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT1DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT1DD_Node(NearestNodes[0]);
end;
end;
function TKDT1DD.Search(const buff: TKDT1DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT1DD.Search(const buff: TKDT1DD_Vec; var SearchedDistanceMin: Double): PKDT1DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1DD.Search(const buff: TKDT1DD_Vec): PKDT1DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1DD.SearchToken(const buff: TKDT1DD_Vec): TPascalString;
var
p: PKDT1DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT1DD.Search(const inBuff: TKDT1DD_DynamicVecBuffer; var OutBuff: TKDT1DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1DD_DynamicVecBuffer;
outBuffPtr: PKDT1DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1DD.Search(const inBuff: TKDT1DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT1DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT1DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT1DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT1DD_Vec)) <> SizeOf(TKDT1DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT1DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1DD.PrintNodeTree(const NodePtr: PKDT1DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT1DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT1DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT1DD.Vec(const s: SystemString): TKDT1DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT1DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT1DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT1DD.Vec(const v: TKDT1DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT1DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT1DD.Distance(const v1, v2: TKDT1DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT1DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT1DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT1DD.Test;
var
TKDT1DD_Test: TKDT1DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT1DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT1DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT1DD_Test := TKDT1DD.Create;
n.Append('...');
SetLength(TKDT1DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT1DD_Test.TestBuff) - 1 do
for j := 0 to KDT1DD_Axis - 1 do
TKDT1DD_Test.TestBuff[i][j] := i * KDT1DD_Axis + j;
{$IFDEF FPC}
TKDT1DD_Test.BuildKDTreeM(length(TKDT1DD_Test.TestBuff), nil, @TKDT1DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT1DD_Test.BuildKDTreeM(length(TKDT1DD_Test.TestBuff), nil, TKDT1DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT1DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT1DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT1DD_Test.TestBuff) - 1 do
begin
p := TKDT1DD_Test.Search(TKDT1DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT1DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT1DD_Test.TestBuff));
TKDT1DD_Test.Search(TKDT1DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT1DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT1DD_Test.Clear;
{ kMean test }
TKDT1DD_Test.BuildKDTreeWithCluster(TKDT1DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT1DD_Test.Search(TKDT1DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT1DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT1DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT1DD_Test);
DoStatus(n);
n := '';
end;
function TKDT2DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DD_Node;
function SortCompare(const p1, p2: PKDT2DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT2DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT2DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT2DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT2DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT2DD.GetData(const Index: NativeInt): PKDT2DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT2DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT2DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT2DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT2DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT2DD.StoreBuffPtr: PKDT2DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT2DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT2DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT2DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT2DD.BuildKDTreeWithCluster(const inBuff: TKDT2DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT2DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT2DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT2DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT2DD.BuildKDTreeWithCluster(const inBuff: TKDT2DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT2DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DD_BuildCall);
var
TempStoreBuff: TKDT2DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT2DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT2DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT2DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT2DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DD_BuildMethod);
var
TempStoreBuff: TKDT2DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT2DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT2DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT2DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT2DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DD_BuildProc);
var
TempStoreBuff: TKDT2DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT2DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT2DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT2DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT2DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT2DD.Search(const buff: TKDT2DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DD_Node;
var
NearestNeighbour: PKDT2DD_Node;
function FindParentNode(const buffPtr: PKDT2DD_Vec; NodePtr: PKDT2DD_Node): PKDT2DD_Node;
var
Next: PKDT2DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT2DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT2DD_Node; const buffPtr: PKDT2DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT2DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT2DD_Vec; const p1, p2: PKDT2DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT2DD_Vec);
var
i, j: NativeInt;
p, t: PKDT2DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT2DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT2DD_Node(NearestNodes[0]);
end;
end;
function TKDT2DD.Search(const buff: TKDT2DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT2DD.Search(const buff: TKDT2DD_Vec; var SearchedDistanceMin: Double): PKDT2DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT2DD.Search(const buff: TKDT2DD_Vec): PKDT2DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT2DD.SearchToken(const buff: TKDT2DD_Vec): TPascalString;
var
p: PKDT2DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT2DD.Search(const inBuff: TKDT2DD_DynamicVecBuffer; var OutBuff: TKDT2DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT2DD_DynamicVecBuffer;
outBuffPtr: PKDT2DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT2DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT2DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT2DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT2DD.Search(const inBuff: TKDT2DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT2DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT2DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT2DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT2DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT2DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT2DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT2DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT2DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT2DD_Vec)) <> SizeOf(TKDT2DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT2DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT2DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT2DD.PrintNodeTree(const NodePtr: PKDT2DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT2DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT2DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT2DD.Vec(const s: SystemString): TKDT2DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT2DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT2DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT2DD.Vec(const v: TKDT2DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT2DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT2DD.Distance(const v1, v2: TKDT2DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT2DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT2DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT2DD.Test;
var
TKDT2DD_Test: TKDT2DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT2DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT2DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT2DD_Test := TKDT2DD.Create;
n.Append('...');
SetLength(TKDT2DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT2DD_Test.TestBuff) - 1 do
for j := 0 to KDT2DD_Axis - 1 do
TKDT2DD_Test.TestBuff[i][j] := i * KDT2DD_Axis + j;
{$IFDEF FPC}
TKDT2DD_Test.BuildKDTreeM(length(TKDT2DD_Test.TestBuff), nil, @TKDT2DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT2DD_Test.BuildKDTreeM(length(TKDT2DD_Test.TestBuff), nil, TKDT2DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT2DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT2DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT2DD_Test.TestBuff) - 1 do
begin
p := TKDT2DD_Test.Search(TKDT2DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT2DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT2DD_Test.TestBuff));
TKDT2DD_Test.Search(TKDT2DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT2DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT2DD_Test.Clear;
{ kMean test }
TKDT2DD_Test.BuildKDTreeWithCluster(TKDT2DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT2DD_Test.Search(TKDT2DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT2DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT2DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT2DD_Test);
DoStatus(n);
n := '';
end;
function TKDT3DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DD_Node;
function SortCompare(const p1, p2: PKDT3DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT3DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT3DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT3DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT3DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT3DD.GetData(const Index: NativeInt): PKDT3DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT3DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT3DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT3DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT3DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT3DD.StoreBuffPtr: PKDT3DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT3DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT3DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT3DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT3DD.BuildKDTreeWithCluster(const inBuff: TKDT3DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT3DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT3DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT3DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT3DD.BuildKDTreeWithCluster(const inBuff: TKDT3DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT3DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DD_BuildCall);
var
TempStoreBuff: TKDT3DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT3DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT3DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT3DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT3DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DD_BuildMethod);
var
TempStoreBuff: TKDT3DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT3DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT3DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT3DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT3DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DD_BuildProc);
var
TempStoreBuff: TKDT3DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT3DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT3DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT3DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT3DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT3DD.Search(const buff: TKDT3DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DD_Node;
var
NearestNeighbour: PKDT3DD_Node;
function FindParentNode(const buffPtr: PKDT3DD_Vec; NodePtr: PKDT3DD_Node): PKDT3DD_Node;
var
Next: PKDT3DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT3DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT3DD_Node; const buffPtr: PKDT3DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT3DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT3DD_Vec; const p1, p2: PKDT3DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT3DD_Vec);
var
i, j: NativeInt;
p, t: PKDT3DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT3DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT3DD_Node(NearestNodes[0]);
end;
end;
function TKDT3DD.Search(const buff: TKDT3DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT3DD.Search(const buff: TKDT3DD_Vec; var SearchedDistanceMin: Double): PKDT3DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT3DD.Search(const buff: TKDT3DD_Vec): PKDT3DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT3DD.SearchToken(const buff: TKDT3DD_Vec): TPascalString;
var
p: PKDT3DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT3DD.Search(const inBuff: TKDT3DD_DynamicVecBuffer; var OutBuff: TKDT3DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT3DD_DynamicVecBuffer;
outBuffPtr: PKDT3DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT3DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT3DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT3DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT3DD.Search(const inBuff: TKDT3DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT3DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT3DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT3DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT3DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT3DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT3DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT3DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT3DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT3DD_Vec)) <> SizeOf(TKDT3DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT3DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT3DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT3DD.PrintNodeTree(const NodePtr: PKDT3DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT3DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT3DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT3DD.Vec(const s: SystemString): TKDT3DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT3DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT3DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT3DD.Vec(const v: TKDT3DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT3DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT3DD.Distance(const v1, v2: TKDT3DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT3DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT3DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT3DD.Test;
var
TKDT3DD_Test: TKDT3DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT3DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT3DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT3DD_Test := TKDT3DD.Create;
n.Append('...');
SetLength(TKDT3DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT3DD_Test.TestBuff) - 1 do
for j := 0 to KDT3DD_Axis - 1 do
TKDT3DD_Test.TestBuff[i][j] := i * KDT3DD_Axis + j;
{$IFDEF FPC}
TKDT3DD_Test.BuildKDTreeM(length(TKDT3DD_Test.TestBuff), nil, @TKDT3DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT3DD_Test.BuildKDTreeM(length(TKDT3DD_Test.TestBuff), nil, TKDT3DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT3DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT3DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT3DD_Test.TestBuff) - 1 do
begin
p := TKDT3DD_Test.Search(TKDT3DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT3DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT3DD_Test.TestBuff));
TKDT3DD_Test.Search(TKDT3DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT3DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT3DD_Test.Clear;
{ kMean test }
TKDT3DD_Test.BuildKDTreeWithCluster(TKDT3DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT3DD_Test.Search(TKDT3DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT3DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT3DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT3DD_Test);
DoStatus(n);
n := '';
end;
function TKDT4DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DD_Node;
function SortCompare(const p1, p2: PKDT4DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT4DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT4DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT4DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT4DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT4DD.GetData(const Index: NativeInt): PKDT4DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT4DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT4DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT4DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT4DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT4DD.StoreBuffPtr: PKDT4DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT4DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT4DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT4DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT4DD.BuildKDTreeWithCluster(const inBuff: TKDT4DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT4DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT4DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT4DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT4DD.BuildKDTreeWithCluster(const inBuff: TKDT4DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT4DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DD_BuildCall);
var
TempStoreBuff: TKDT4DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT4DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT4DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT4DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT4DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DD_BuildMethod);
var
TempStoreBuff: TKDT4DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT4DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT4DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT4DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT4DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DD_BuildProc);
var
TempStoreBuff: TKDT4DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT4DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT4DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT4DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT4DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT4DD.Search(const buff: TKDT4DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DD_Node;
var
NearestNeighbour: PKDT4DD_Node;
function FindParentNode(const buffPtr: PKDT4DD_Vec; NodePtr: PKDT4DD_Node): PKDT4DD_Node;
var
Next: PKDT4DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT4DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT4DD_Node; const buffPtr: PKDT4DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT4DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT4DD_Vec; const p1, p2: PKDT4DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT4DD_Vec);
var
i, j: NativeInt;
p, t: PKDT4DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT4DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT4DD_Node(NearestNodes[0]);
end;
end;
function TKDT4DD.Search(const buff: TKDT4DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT4DD.Search(const buff: TKDT4DD_Vec; var SearchedDistanceMin: Double): PKDT4DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT4DD.Search(const buff: TKDT4DD_Vec): PKDT4DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT4DD.SearchToken(const buff: TKDT4DD_Vec): TPascalString;
var
p: PKDT4DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT4DD.Search(const inBuff: TKDT4DD_DynamicVecBuffer; var OutBuff: TKDT4DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT4DD_DynamicVecBuffer;
outBuffPtr: PKDT4DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT4DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT4DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT4DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT4DD.Search(const inBuff: TKDT4DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT4DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT4DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT4DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT4DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT4DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT4DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT4DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT4DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT4DD_Vec)) <> SizeOf(TKDT4DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT4DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT4DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT4DD.PrintNodeTree(const NodePtr: PKDT4DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT4DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT4DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT4DD.Vec(const s: SystemString): TKDT4DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT4DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT4DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT4DD.Vec(const v: TKDT4DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT4DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT4DD.Distance(const v1, v2: TKDT4DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT4DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT4DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT4DD.Test;
var
TKDT4DD_Test: TKDT4DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT4DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT4DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT4DD_Test := TKDT4DD.Create;
n.Append('...');
SetLength(TKDT4DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT4DD_Test.TestBuff) - 1 do
for j := 0 to KDT4DD_Axis - 1 do
TKDT4DD_Test.TestBuff[i][j] := i * KDT4DD_Axis + j;
{$IFDEF FPC}
TKDT4DD_Test.BuildKDTreeM(length(TKDT4DD_Test.TestBuff), nil, @TKDT4DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT4DD_Test.BuildKDTreeM(length(TKDT4DD_Test.TestBuff), nil, TKDT4DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT4DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT4DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT4DD_Test.TestBuff) - 1 do
begin
p := TKDT4DD_Test.Search(TKDT4DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT4DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT4DD_Test.TestBuff));
TKDT4DD_Test.Search(TKDT4DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT4DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT4DD_Test.Clear;
{ kMean test }
TKDT4DD_Test.BuildKDTreeWithCluster(TKDT4DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT4DD_Test.Search(TKDT4DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT4DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT4DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT4DD_Test);
DoStatus(n);
n := '';
end;
function TKDT5DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DD_Node;
function SortCompare(const p1, p2: PKDT5DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT5DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT5DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT5DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT5DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT5DD.GetData(const Index: NativeInt): PKDT5DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT5DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT5DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT5DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT5DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT5DD.StoreBuffPtr: PKDT5DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT5DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT5DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT5DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT5DD.BuildKDTreeWithCluster(const inBuff: TKDT5DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT5DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT5DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT5DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT5DD.BuildKDTreeWithCluster(const inBuff: TKDT5DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT5DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DD_BuildCall);
var
TempStoreBuff: TKDT5DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT5DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT5DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT5DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT5DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DD_BuildMethod);
var
TempStoreBuff: TKDT5DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT5DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT5DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT5DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT5DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DD_BuildProc);
var
TempStoreBuff: TKDT5DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT5DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT5DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT5DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT5DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT5DD.Search(const buff: TKDT5DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DD_Node;
var
NearestNeighbour: PKDT5DD_Node;
function FindParentNode(const buffPtr: PKDT5DD_Vec; NodePtr: PKDT5DD_Node): PKDT5DD_Node;
var
Next: PKDT5DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT5DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT5DD_Node; const buffPtr: PKDT5DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT5DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT5DD_Vec; const p1, p2: PKDT5DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT5DD_Vec);
var
i, j: NativeInt;
p, t: PKDT5DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT5DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT5DD_Node(NearestNodes[0]);
end;
end;
function TKDT5DD.Search(const buff: TKDT5DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT5DD.Search(const buff: TKDT5DD_Vec; var SearchedDistanceMin: Double): PKDT5DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT5DD.Search(const buff: TKDT5DD_Vec): PKDT5DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT5DD.SearchToken(const buff: TKDT5DD_Vec): TPascalString;
var
p: PKDT5DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT5DD.Search(const inBuff: TKDT5DD_DynamicVecBuffer; var OutBuff: TKDT5DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT5DD_DynamicVecBuffer;
outBuffPtr: PKDT5DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT5DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT5DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT5DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT5DD.Search(const inBuff: TKDT5DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT5DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT5DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT5DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT5DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT5DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT5DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT5DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT5DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT5DD_Vec)) <> SizeOf(TKDT5DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT5DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT5DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT5DD.PrintNodeTree(const NodePtr: PKDT5DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT5DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT5DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT5DD.Vec(const s: SystemString): TKDT5DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT5DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT5DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT5DD.Vec(const v: TKDT5DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT5DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT5DD.Distance(const v1, v2: TKDT5DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT5DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT5DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT5DD.Test;
var
TKDT5DD_Test: TKDT5DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT5DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT5DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT5DD_Test := TKDT5DD.Create;
n.Append('...');
SetLength(TKDT5DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT5DD_Test.TestBuff) - 1 do
for j := 0 to KDT5DD_Axis - 1 do
TKDT5DD_Test.TestBuff[i][j] := i * KDT5DD_Axis + j;
{$IFDEF FPC}
TKDT5DD_Test.BuildKDTreeM(length(TKDT5DD_Test.TestBuff), nil, @TKDT5DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT5DD_Test.BuildKDTreeM(length(TKDT5DD_Test.TestBuff), nil, TKDT5DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT5DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT5DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT5DD_Test.TestBuff) - 1 do
begin
p := TKDT5DD_Test.Search(TKDT5DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT5DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT5DD_Test.TestBuff));
TKDT5DD_Test.Search(TKDT5DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT5DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT5DD_Test.Clear;
{ kMean test }
TKDT5DD_Test.BuildKDTreeWithCluster(TKDT5DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT5DD_Test.Search(TKDT5DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT5DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT5DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT5DD_Test);
DoStatus(n);
n := '';
end;
function TKDT6DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DD_Node;
function SortCompare(const p1, p2: PKDT6DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT6DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT6DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT6DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT6DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT6DD.GetData(const Index: NativeInt): PKDT6DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT6DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT6DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT6DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT6DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT6DD.StoreBuffPtr: PKDT6DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT6DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT6DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT6DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT6DD.BuildKDTreeWithCluster(const inBuff: TKDT6DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT6DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT6DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT6DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT6DD.BuildKDTreeWithCluster(const inBuff: TKDT6DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT6DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DD_BuildCall);
var
TempStoreBuff: TKDT6DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT6DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT6DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT6DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT6DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DD_BuildMethod);
var
TempStoreBuff: TKDT6DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT6DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT6DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT6DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT6DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DD_BuildProc);
var
TempStoreBuff: TKDT6DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT6DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT6DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT6DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT6DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT6DD.Search(const buff: TKDT6DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DD_Node;
var
NearestNeighbour: PKDT6DD_Node;
function FindParentNode(const buffPtr: PKDT6DD_Vec; NodePtr: PKDT6DD_Node): PKDT6DD_Node;
var
Next: PKDT6DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT6DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT6DD_Node; const buffPtr: PKDT6DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT6DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT6DD_Vec; const p1, p2: PKDT6DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT6DD_Vec);
var
i, j: NativeInt;
p, t: PKDT6DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT6DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT6DD_Node(NearestNodes[0]);
end;
end;
function TKDT6DD.Search(const buff: TKDT6DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT6DD.Search(const buff: TKDT6DD_Vec; var SearchedDistanceMin: Double): PKDT6DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT6DD.Search(const buff: TKDT6DD_Vec): PKDT6DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT6DD.SearchToken(const buff: TKDT6DD_Vec): TPascalString;
var
p: PKDT6DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT6DD.Search(const inBuff: TKDT6DD_DynamicVecBuffer; var OutBuff: TKDT6DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT6DD_DynamicVecBuffer;
outBuffPtr: PKDT6DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT6DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT6DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT6DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT6DD.Search(const inBuff: TKDT6DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT6DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT6DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT6DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT6DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT6DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT6DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT6DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT6DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT6DD_Vec)) <> SizeOf(TKDT6DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT6DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT6DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT6DD.PrintNodeTree(const NodePtr: PKDT6DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT6DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT6DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT6DD.Vec(const s: SystemString): TKDT6DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT6DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT6DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT6DD.Vec(const v: TKDT6DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT6DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT6DD.Distance(const v1, v2: TKDT6DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT6DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT6DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT6DD.Test;
var
TKDT6DD_Test: TKDT6DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT6DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT6DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT6DD_Test := TKDT6DD.Create;
n.Append('...');
SetLength(TKDT6DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT6DD_Test.TestBuff) - 1 do
for j := 0 to KDT6DD_Axis - 1 do
TKDT6DD_Test.TestBuff[i][j] := i * KDT6DD_Axis + j;
{$IFDEF FPC}
TKDT6DD_Test.BuildKDTreeM(length(TKDT6DD_Test.TestBuff), nil, @TKDT6DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT6DD_Test.BuildKDTreeM(length(TKDT6DD_Test.TestBuff), nil, TKDT6DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT6DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT6DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT6DD_Test.TestBuff) - 1 do
begin
p := TKDT6DD_Test.Search(TKDT6DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT6DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT6DD_Test.TestBuff));
TKDT6DD_Test.Search(TKDT6DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT6DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT6DD_Test.Clear;
{ kMean test }
TKDT6DD_Test.BuildKDTreeWithCluster(TKDT6DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT6DD_Test.Search(TKDT6DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT6DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT6DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT6DD_Test);
DoStatus(n);
n := '';
end;
function TKDT7DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DD_Node;
function SortCompare(const p1, p2: PKDT7DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT7DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT7DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT7DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT7DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT7DD.GetData(const Index: NativeInt): PKDT7DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT7DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT7DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT7DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT7DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT7DD.StoreBuffPtr: PKDT7DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT7DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT7DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT7DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT7DD.BuildKDTreeWithCluster(const inBuff: TKDT7DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT7DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT7DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT7DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT7DD.BuildKDTreeWithCluster(const inBuff: TKDT7DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT7DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DD_BuildCall);
var
TempStoreBuff: TKDT7DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT7DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT7DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT7DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT7DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DD_BuildMethod);
var
TempStoreBuff: TKDT7DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT7DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT7DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT7DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT7DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DD_BuildProc);
var
TempStoreBuff: TKDT7DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT7DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT7DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT7DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT7DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT7DD.Search(const buff: TKDT7DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DD_Node;
var
NearestNeighbour: PKDT7DD_Node;
function FindParentNode(const buffPtr: PKDT7DD_Vec; NodePtr: PKDT7DD_Node): PKDT7DD_Node;
var
Next: PKDT7DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT7DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT7DD_Node; const buffPtr: PKDT7DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT7DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT7DD_Vec; const p1, p2: PKDT7DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT7DD_Vec);
var
i, j: NativeInt;
p, t: PKDT7DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT7DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT7DD_Node(NearestNodes[0]);
end;
end;
function TKDT7DD.Search(const buff: TKDT7DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT7DD.Search(const buff: TKDT7DD_Vec; var SearchedDistanceMin: Double): PKDT7DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT7DD.Search(const buff: TKDT7DD_Vec): PKDT7DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT7DD.SearchToken(const buff: TKDT7DD_Vec): TPascalString;
var
p: PKDT7DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT7DD.Search(const inBuff: TKDT7DD_DynamicVecBuffer; var OutBuff: TKDT7DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT7DD_DynamicVecBuffer;
outBuffPtr: PKDT7DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT7DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT7DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT7DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT7DD.Search(const inBuff: TKDT7DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT7DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT7DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT7DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT7DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT7DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT7DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT7DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT7DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT7DD_Vec)) <> SizeOf(TKDT7DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT7DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT7DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT7DD.PrintNodeTree(const NodePtr: PKDT7DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT7DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT7DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT7DD.Vec(const s: SystemString): TKDT7DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT7DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT7DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT7DD.Vec(const v: TKDT7DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT7DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT7DD.Distance(const v1, v2: TKDT7DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT7DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT7DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT7DD.Test;
var
TKDT7DD_Test: TKDT7DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT7DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT7DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT7DD_Test := TKDT7DD.Create;
n.Append('...');
SetLength(TKDT7DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT7DD_Test.TestBuff) - 1 do
for j := 0 to KDT7DD_Axis - 1 do
TKDT7DD_Test.TestBuff[i][j] := i * KDT7DD_Axis + j;
{$IFDEF FPC}
TKDT7DD_Test.BuildKDTreeM(length(TKDT7DD_Test.TestBuff), nil, @TKDT7DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT7DD_Test.BuildKDTreeM(length(TKDT7DD_Test.TestBuff), nil, TKDT7DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT7DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT7DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT7DD_Test.TestBuff) - 1 do
begin
p := TKDT7DD_Test.Search(TKDT7DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT7DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT7DD_Test.TestBuff));
TKDT7DD_Test.Search(TKDT7DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT7DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT7DD_Test.Clear;
{ kMean test }
TKDT7DD_Test.BuildKDTreeWithCluster(TKDT7DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT7DD_Test.Search(TKDT7DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT7DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT7DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT7DD_Test);
DoStatus(n);
n := '';
end;
function TKDT8DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DD_Node;
function SortCompare(const p1, p2: PKDT8DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT8DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT8DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT8DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT8DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT8DD.GetData(const Index: NativeInt): PKDT8DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT8DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT8DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT8DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT8DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT8DD.StoreBuffPtr: PKDT8DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT8DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT8DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT8DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT8DD.BuildKDTreeWithCluster(const inBuff: TKDT8DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT8DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT8DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT8DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT8DD.BuildKDTreeWithCluster(const inBuff: TKDT8DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT8DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DD_BuildCall);
var
TempStoreBuff: TKDT8DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT8DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT8DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT8DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT8DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DD_BuildMethod);
var
TempStoreBuff: TKDT8DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT8DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT8DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT8DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT8DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DD_BuildProc);
var
TempStoreBuff: TKDT8DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT8DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT8DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT8DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT8DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT8DD.Search(const buff: TKDT8DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DD_Node;
var
NearestNeighbour: PKDT8DD_Node;
function FindParentNode(const buffPtr: PKDT8DD_Vec; NodePtr: PKDT8DD_Node): PKDT8DD_Node;
var
Next: PKDT8DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT8DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT8DD_Node; const buffPtr: PKDT8DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT8DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT8DD_Vec; const p1, p2: PKDT8DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT8DD_Vec);
var
i, j: NativeInt;
p, t: PKDT8DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT8DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT8DD_Node(NearestNodes[0]);
end;
end;
function TKDT8DD.Search(const buff: TKDT8DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT8DD.Search(const buff: TKDT8DD_Vec; var SearchedDistanceMin: Double): PKDT8DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT8DD.Search(const buff: TKDT8DD_Vec): PKDT8DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT8DD.SearchToken(const buff: TKDT8DD_Vec): TPascalString;
var
p: PKDT8DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT8DD.Search(const inBuff: TKDT8DD_DynamicVecBuffer; var OutBuff: TKDT8DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT8DD_DynamicVecBuffer;
outBuffPtr: PKDT8DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT8DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT8DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT8DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT8DD.Search(const inBuff: TKDT8DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT8DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT8DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT8DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT8DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT8DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT8DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT8DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT8DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT8DD_Vec)) <> SizeOf(TKDT8DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT8DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT8DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT8DD.PrintNodeTree(const NodePtr: PKDT8DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT8DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT8DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT8DD.Vec(const s: SystemString): TKDT8DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT8DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT8DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT8DD.Vec(const v: TKDT8DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT8DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT8DD.Distance(const v1, v2: TKDT8DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT8DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT8DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT8DD.Test;
var
TKDT8DD_Test: TKDT8DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT8DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT8DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT8DD_Test := TKDT8DD.Create;
n.Append('...');
SetLength(TKDT8DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT8DD_Test.TestBuff) - 1 do
for j := 0 to KDT8DD_Axis - 1 do
TKDT8DD_Test.TestBuff[i][j] := i * KDT8DD_Axis + j;
{$IFDEF FPC}
TKDT8DD_Test.BuildKDTreeM(length(TKDT8DD_Test.TestBuff), nil, @TKDT8DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT8DD_Test.BuildKDTreeM(length(TKDT8DD_Test.TestBuff), nil, TKDT8DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT8DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT8DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT8DD_Test.TestBuff) - 1 do
begin
p := TKDT8DD_Test.Search(TKDT8DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT8DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT8DD_Test.TestBuff));
TKDT8DD_Test.Search(TKDT8DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT8DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT8DD_Test.Clear;
{ kMean test }
TKDT8DD_Test.BuildKDTreeWithCluster(TKDT8DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT8DD_Test.Search(TKDT8DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT8DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT8DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT8DD_Test);
DoStatus(n);
n := '';
end;
function TKDT9DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DD_Node;
function SortCompare(const p1, p2: PKDT9DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT9DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT9DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT9DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT9DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT9DD.GetData(const Index: NativeInt): PKDT9DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT9DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT9DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT9DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT9DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT9DD.StoreBuffPtr: PKDT9DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT9DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT9DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT9DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT9DD.BuildKDTreeWithCluster(const inBuff: TKDT9DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT9DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT9DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT9DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT9DD.BuildKDTreeWithCluster(const inBuff: TKDT9DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT9DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DD_BuildCall);
var
TempStoreBuff: TKDT9DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT9DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT9DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT9DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT9DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DD_BuildMethod);
var
TempStoreBuff: TKDT9DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT9DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT9DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT9DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT9DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DD_BuildProc);
var
TempStoreBuff: TKDT9DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT9DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT9DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT9DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT9DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT9DD.Search(const buff: TKDT9DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DD_Node;
var
NearestNeighbour: PKDT9DD_Node;
function FindParentNode(const buffPtr: PKDT9DD_Vec; NodePtr: PKDT9DD_Node): PKDT9DD_Node;
var
Next: PKDT9DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT9DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT9DD_Node; const buffPtr: PKDT9DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT9DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT9DD_Vec; const p1, p2: PKDT9DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT9DD_Vec);
var
i, j: NativeInt;
p, t: PKDT9DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT9DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT9DD_Node(NearestNodes[0]);
end;
end;
function TKDT9DD.Search(const buff: TKDT9DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT9DD.Search(const buff: TKDT9DD_Vec; var SearchedDistanceMin: Double): PKDT9DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT9DD.Search(const buff: TKDT9DD_Vec): PKDT9DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT9DD.SearchToken(const buff: TKDT9DD_Vec): TPascalString;
var
p: PKDT9DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT9DD.Search(const inBuff: TKDT9DD_DynamicVecBuffer; var OutBuff: TKDT9DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT9DD_DynamicVecBuffer;
outBuffPtr: PKDT9DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT9DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT9DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT9DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT9DD.Search(const inBuff: TKDT9DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT9DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT9DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT9DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT9DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT9DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT9DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT9DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT9DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT9DD_Vec)) <> SizeOf(TKDT9DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT9DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT9DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT9DD.PrintNodeTree(const NodePtr: PKDT9DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT9DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT9DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT9DD.Vec(const s: SystemString): TKDT9DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT9DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT9DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT9DD.Vec(const v: TKDT9DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT9DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT9DD.Distance(const v1, v2: TKDT9DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT9DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT9DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT9DD.Test;
var
TKDT9DD_Test: TKDT9DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT9DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT9DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT9DD_Test := TKDT9DD.Create;
n.Append('...');
SetLength(TKDT9DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT9DD_Test.TestBuff) - 1 do
for j := 0 to KDT9DD_Axis - 1 do
TKDT9DD_Test.TestBuff[i][j] := i * KDT9DD_Axis + j;
{$IFDEF FPC}
TKDT9DD_Test.BuildKDTreeM(length(TKDT9DD_Test.TestBuff), nil, @TKDT9DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT9DD_Test.BuildKDTreeM(length(TKDT9DD_Test.TestBuff), nil, TKDT9DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT9DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT9DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT9DD_Test.TestBuff) - 1 do
begin
p := TKDT9DD_Test.Search(TKDT9DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT9DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT9DD_Test.TestBuff));
TKDT9DD_Test.Search(TKDT9DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT9DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT9DD_Test.Clear;
{ kMean test }
TKDT9DD_Test.BuildKDTreeWithCluster(TKDT9DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT9DD_Test.Search(TKDT9DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT9DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT9DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT9DD_Test);
DoStatus(n);
n := '';
end;
function TKDT10DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DD_Node;
function SortCompare(const p1, p2: PKDT10DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT10DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT10DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT10DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT10DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT10DD.GetData(const Index: NativeInt): PKDT10DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT10DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT10DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT10DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT10DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT10DD.StoreBuffPtr: PKDT10DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT10DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT10DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT10DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT10DD.BuildKDTreeWithCluster(const inBuff: TKDT10DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT10DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT10DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT10DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT10DD.BuildKDTreeWithCluster(const inBuff: TKDT10DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT10DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DD_BuildCall);
var
TempStoreBuff: TKDT10DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT10DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT10DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT10DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT10DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DD_BuildMethod);
var
TempStoreBuff: TKDT10DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT10DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT10DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT10DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT10DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DD_BuildProc);
var
TempStoreBuff: TKDT10DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT10DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT10DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT10DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT10DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT10DD.Search(const buff: TKDT10DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DD_Node;
var
NearestNeighbour: PKDT10DD_Node;
function FindParentNode(const buffPtr: PKDT10DD_Vec; NodePtr: PKDT10DD_Node): PKDT10DD_Node;
var
Next: PKDT10DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT10DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT10DD_Node; const buffPtr: PKDT10DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT10DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT10DD_Vec; const p1, p2: PKDT10DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT10DD_Vec);
var
i, j: NativeInt;
p, t: PKDT10DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT10DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT10DD_Node(NearestNodes[0]);
end;
end;
function TKDT10DD.Search(const buff: TKDT10DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT10DD.Search(const buff: TKDT10DD_Vec; var SearchedDistanceMin: Double): PKDT10DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT10DD.Search(const buff: TKDT10DD_Vec): PKDT10DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT10DD.SearchToken(const buff: TKDT10DD_Vec): TPascalString;
var
p: PKDT10DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT10DD.Search(const inBuff: TKDT10DD_DynamicVecBuffer; var OutBuff: TKDT10DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT10DD_DynamicVecBuffer;
outBuffPtr: PKDT10DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT10DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT10DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT10DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT10DD.Search(const inBuff: TKDT10DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT10DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT10DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT10DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT10DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT10DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT10DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT10DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT10DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT10DD_Vec)) <> SizeOf(TKDT10DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT10DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT10DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT10DD.PrintNodeTree(const NodePtr: PKDT10DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT10DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT10DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT10DD.Vec(const s: SystemString): TKDT10DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT10DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT10DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT10DD.Vec(const v: TKDT10DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT10DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT10DD.Distance(const v1, v2: TKDT10DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT10DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT10DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT10DD.Test;
var
TKDT10DD_Test: TKDT10DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT10DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT10DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT10DD_Test := TKDT10DD.Create;
n.Append('...');
SetLength(TKDT10DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT10DD_Test.TestBuff) - 1 do
for j := 0 to KDT10DD_Axis - 1 do
TKDT10DD_Test.TestBuff[i][j] := i * KDT10DD_Axis + j;
{$IFDEF FPC}
TKDT10DD_Test.BuildKDTreeM(length(TKDT10DD_Test.TestBuff), nil, @TKDT10DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT10DD_Test.BuildKDTreeM(length(TKDT10DD_Test.TestBuff), nil, TKDT10DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT10DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT10DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT10DD_Test.TestBuff) - 1 do
begin
p := TKDT10DD_Test.Search(TKDT10DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT10DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT10DD_Test.TestBuff));
TKDT10DD_Test.Search(TKDT10DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT10DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT10DD_Test.Clear;
{ kMean test }
TKDT10DD_Test.BuildKDTreeWithCluster(TKDT10DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT10DD_Test.Search(TKDT10DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT10DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT10DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT10DD_Test);
DoStatus(n);
n := '';
end;
function TKDT11DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DD_Node;
function SortCompare(const p1, p2: PKDT11DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT11DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT11DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT11DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT11DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT11DD.GetData(const Index: NativeInt): PKDT11DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT11DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT11DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT11DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT11DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT11DD.StoreBuffPtr: PKDT11DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT11DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT11DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT11DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT11DD.BuildKDTreeWithCluster(const inBuff: TKDT11DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT11DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT11DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT11DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT11DD.BuildKDTreeWithCluster(const inBuff: TKDT11DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT11DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DD_BuildCall);
var
TempStoreBuff: TKDT11DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT11DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT11DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT11DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT11DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DD_BuildMethod);
var
TempStoreBuff: TKDT11DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT11DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT11DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT11DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT11DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DD_BuildProc);
var
TempStoreBuff: TKDT11DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT11DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT11DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT11DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT11DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT11DD.Search(const buff: TKDT11DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DD_Node;
var
NearestNeighbour: PKDT11DD_Node;
function FindParentNode(const buffPtr: PKDT11DD_Vec; NodePtr: PKDT11DD_Node): PKDT11DD_Node;
var
Next: PKDT11DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT11DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT11DD_Node; const buffPtr: PKDT11DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT11DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT11DD_Vec; const p1, p2: PKDT11DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT11DD_Vec);
var
i, j: NativeInt;
p, t: PKDT11DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT11DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT11DD_Node(NearestNodes[0]);
end;
end;
function TKDT11DD.Search(const buff: TKDT11DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT11DD.Search(const buff: TKDT11DD_Vec; var SearchedDistanceMin: Double): PKDT11DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT11DD.Search(const buff: TKDT11DD_Vec): PKDT11DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT11DD.SearchToken(const buff: TKDT11DD_Vec): TPascalString;
var
p: PKDT11DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT11DD.Search(const inBuff: TKDT11DD_DynamicVecBuffer; var OutBuff: TKDT11DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT11DD_DynamicVecBuffer;
outBuffPtr: PKDT11DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT11DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT11DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT11DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT11DD.Search(const inBuff: TKDT11DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT11DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT11DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT11DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT11DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT11DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT11DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT11DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT11DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT11DD_Vec)) <> SizeOf(TKDT11DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT11DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT11DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT11DD.PrintNodeTree(const NodePtr: PKDT11DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT11DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT11DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT11DD.Vec(const s: SystemString): TKDT11DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT11DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT11DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT11DD.Vec(const v: TKDT11DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT11DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT11DD.Distance(const v1, v2: TKDT11DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT11DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT11DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT11DD.Test;
var
TKDT11DD_Test: TKDT11DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT11DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT11DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT11DD_Test := TKDT11DD.Create;
n.Append('...');
SetLength(TKDT11DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT11DD_Test.TestBuff) - 1 do
for j := 0 to KDT11DD_Axis - 1 do
TKDT11DD_Test.TestBuff[i][j] := i * KDT11DD_Axis + j;
{$IFDEF FPC}
TKDT11DD_Test.BuildKDTreeM(length(TKDT11DD_Test.TestBuff), nil, @TKDT11DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT11DD_Test.BuildKDTreeM(length(TKDT11DD_Test.TestBuff), nil, TKDT11DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT11DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT11DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT11DD_Test.TestBuff) - 1 do
begin
p := TKDT11DD_Test.Search(TKDT11DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT11DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT11DD_Test.TestBuff));
TKDT11DD_Test.Search(TKDT11DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT11DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT11DD_Test.Clear;
{ kMean test }
TKDT11DD_Test.BuildKDTreeWithCluster(TKDT11DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT11DD_Test.Search(TKDT11DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT11DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT11DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT11DD_Test);
DoStatus(n);
n := '';
end;
function TKDT12DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DD_Node;
function SortCompare(const p1, p2: PKDT12DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT12DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT12DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT12DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT12DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT12DD.GetData(const Index: NativeInt): PKDT12DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT12DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT12DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT12DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT12DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT12DD.StoreBuffPtr: PKDT12DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT12DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT12DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT12DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT12DD.BuildKDTreeWithCluster(const inBuff: TKDT12DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT12DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT12DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT12DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT12DD.BuildKDTreeWithCluster(const inBuff: TKDT12DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT12DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DD_BuildCall);
var
TempStoreBuff: TKDT12DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT12DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT12DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT12DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT12DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DD_BuildMethod);
var
TempStoreBuff: TKDT12DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT12DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT12DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT12DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT12DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DD_BuildProc);
var
TempStoreBuff: TKDT12DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT12DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT12DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT12DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT12DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT12DD.Search(const buff: TKDT12DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DD_Node;
var
NearestNeighbour: PKDT12DD_Node;
function FindParentNode(const buffPtr: PKDT12DD_Vec; NodePtr: PKDT12DD_Node): PKDT12DD_Node;
var
Next: PKDT12DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT12DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT12DD_Node; const buffPtr: PKDT12DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT12DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT12DD_Vec; const p1, p2: PKDT12DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT12DD_Vec);
var
i, j: NativeInt;
p, t: PKDT12DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT12DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT12DD_Node(NearestNodes[0]);
end;
end;
function TKDT12DD.Search(const buff: TKDT12DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT12DD.Search(const buff: TKDT12DD_Vec; var SearchedDistanceMin: Double): PKDT12DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT12DD.Search(const buff: TKDT12DD_Vec): PKDT12DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT12DD.SearchToken(const buff: TKDT12DD_Vec): TPascalString;
var
p: PKDT12DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT12DD.Search(const inBuff: TKDT12DD_DynamicVecBuffer; var OutBuff: TKDT12DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT12DD_DynamicVecBuffer;
outBuffPtr: PKDT12DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT12DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT12DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT12DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT12DD.Search(const inBuff: TKDT12DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT12DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT12DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT12DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT12DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT12DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT12DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT12DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT12DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT12DD_Vec)) <> SizeOf(TKDT12DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT12DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT12DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT12DD.PrintNodeTree(const NodePtr: PKDT12DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT12DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT12DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT12DD.Vec(const s: SystemString): TKDT12DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT12DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT12DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT12DD.Vec(const v: TKDT12DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT12DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT12DD.Distance(const v1, v2: TKDT12DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT12DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT12DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT12DD.Test;
var
TKDT12DD_Test: TKDT12DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT12DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT12DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT12DD_Test := TKDT12DD.Create;
n.Append('...');
SetLength(TKDT12DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT12DD_Test.TestBuff) - 1 do
for j := 0 to KDT12DD_Axis - 1 do
TKDT12DD_Test.TestBuff[i][j] := i * KDT12DD_Axis + j;
{$IFDEF FPC}
TKDT12DD_Test.BuildKDTreeM(length(TKDT12DD_Test.TestBuff), nil, @TKDT12DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT12DD_Test.BuildKDTreeM(length(TKDT12DD_Test.TestBuff), nil, TKDT12DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT12DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT12DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT12DD_Test.TestBuff) - 1 do
begin
p := TKDT12DD_Test.Search(TKDT12DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT12DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT12DD_Test.TestBuff));
TKDT12DD_Test.Search(TKDT12DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT12DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT12DD_Test.Clear;
{ kMean test }
TKDT12DD_Test.BuildKDTreeWithCluster(TKDT12DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT12DD_Test.Search(TKDT12DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT12DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT12DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT12DD_Test);
DoStatus(n);
n := '';
end;
function TKDT13DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DD_Node;
function SortCompare(const p1, p2: PKDT13DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT13DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT13DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT13DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT13DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT13DD.GetData(const Index: NativeInt): PKDT13DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT13DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT13DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT13DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT13DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT13DD.StoreBuffPtr: PKDT13DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT13DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT13DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT13DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT13DD.BuildKDTreeWithCluster(const inBuff: TKDT13DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT13DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT13DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT13DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT13DD.BuildKDTreeWithCluster(const inBuff: TKDT13DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT13DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DD_BuildCall);
var
TempStoreBuff: TKDT13DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT13DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT13DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT13DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT13DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DD_BuildMethod);
var
TempStoreBuff: TKDT13DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT13DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT13DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT13DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT13DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DD_BuildProc);
var
TempStoreBuff: TKDT13DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT13DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT13DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT13DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT13DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT13DD.Search(const buff: TKDT13DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DD_Node;
var
NearestNeighbour: PKDT13DD_Node;
function FindParentNode(const buffPtr: PKDT13DD_Vec; NodePtr: PKDT13DD_Node): PKDT13DD_Node;
var
Next: PKDT13DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT13DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT13DD_Node; const buffPtr: PKDT13DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT13DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT13DD_Vec; const p1, p2: PKDT13DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT13DD_Vec);
var
i, j: NativeInt;
p, t: PKDT13DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT13DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT13DD_Node(NearestNodes[0]);
end;
end;
function TKDT13DD.Search(const buff: TKDT13DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT13DD.Search(const buff: TKDT13DD_Vec; var SearchedDistanceMin: Double): PKDT13DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT13DD.Search(const buff: TKDT13DD_Vec): PKDT13DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT13DD.SearchToken(const buff: TKDT13DD_Vec): TPascalString;
var
p: PKDT13DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT13DD.Search(const inBuff: TKDT13DD_DynamicVecBuffer; var OutBuff: TKDT13DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT13DD_DynamicVecBuffer;
outBuffPtr: PKDT13DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT13DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT13DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT13DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT13DD.Search(const inBuff: TKDT13DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT13DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT13DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT13DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT13DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT13DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT13DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT13DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT13DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT13DD_Vec)) <> SizeOf(TKDT13DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT13DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT13DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT13DD.PrintNodeTree(const NodePtr: PKDT13DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT13DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT13DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT13DD.Vec(const s: SystemString): TKDT13DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT13DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT13DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT13DD.Vec(const v: TKDT13DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT13DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT13DD.Distance(const v1, v2: TKDT13DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT13DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT13DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT13DD.Test;
var
TKDT13DD_Test: TKDT13DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT13DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT13DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT13DD_Test := TKDT13DD.Create;
n.Append('...');
SetLength(TKDT13DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT13DD_Test.TestBuff) - 1 do
for j := 0 to KDT13DD_Axis - 1 do
TKDT13DD_Test.TestBuff[i][j] := i * KDT13DD_Axis + j;
{$IFDEF FPC}
TKDT13DD_Test.BuildKDTreeM(length(TKDT13DD_Test.TestBuff), nil, @TKDT13DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT13DD_Test.BuildKDTreeM(length(TKDT13DD_Test.TestBuff), nil, TKDT13DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT13DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT13DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT13DD_Test.TestBuff) - 1 do
begin
p := TKDT13DD_Test.Search(TKDT13DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT13DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT13DD_Test.TestBuff));
TKDT13DD_Test.Search(TKDT13DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT13DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT13DD_Test.Clear;
{ kMean test }
TKDT13DD_Test.BuildKDTreeWithCluster(TKDT13DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT13DD_Test.Search(TKDT13DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT13DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT13DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT13DD_Test);
DoStatus(n);
n := '';
end;
function TKDT14DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DD_Node;
function SortCompare(const p1, p2: PKDT14DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT14DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT14DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT14DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT14DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT14DD.GetData(const Index: NativeInt): PKDT14DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT14DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT14DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT14DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT14DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT14DD.StoreBuffPtr: PKDT14DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT14DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT14DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT14DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT14DD.BuildKDTreeWithCluster(const inBuff: TKDT14DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT14DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT14DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT14DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT14DD.BuildKDTreeWithCluster(const inBuff: TKDT14DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT14DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DD_BuildCall);
var
TempStoreBuff: TKDT14DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT14DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT14DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT14DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT14DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DD_BuildMethod);
var
TempStoreBuff: TKDT14DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT14DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT14DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT14DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT14DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DD_BuildProc);
var
TempStoreBuff: TKDT14DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT14DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT14DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT14DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT14DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT14DD.Search(const buff: TKDT14DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DD_Node;
var
NearestNeighbour: PKDT14DD_Node;
function FindParentNode(const buffPtr: PKDT14DD_Vec; NodePtr: PKDT14DD_Node): PKDT14DD_Node;
var
Next: PKDT14DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT14DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT14DD_Node; const buffPtr: PKDT14DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT14DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT14DD_Vec; const p1, p2: PKDT14DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT14DD_Vec);
var
i, j: NativeInt;
p, t: PKDT14DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT14DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT14DD_Node(NearestNodes[0]);
end;
end;
function TKDT14DD.Search(const buff: TKDT14DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT14DD.Search(const buff: TKDT14DD_Vec; var SearchedDistanceMin: Double): PKDT14DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT14DD.Search(const buff: TKDT14DD_Vec): PKDT14DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT14DD.SearchToken(const buff: TKDT14DD_Vec): TPascalString;
var
p: PKDT14DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT14DD.Search(const inBuff: TKDT14DD_DynamicVecBuffer; var OutBuff: TKDT14DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT14DD_DynamicVecBuffer;
outBuffPtr: PKDT14DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT14DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT14DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT14DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT14DD.Search(const inBuff: TKDT14DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT14DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT14DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT14DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT14DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT14DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT14DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT14DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT14DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT14DD_Vec)) <> SizeOf(TKDT14DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT14DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT14DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT14DD.PrintNodeTree(const NodePtr: PKDT14DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT14DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT14DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT14DD.Vec(const s: SystemString): TKDT14DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT14DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT14DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT14DD.Vec(const v: TKDT14DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT14DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT14DD.Distance(const v1, v2: TKDT14DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT14DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT14DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT14DD.Test;
var
TKDT14DD_Test: TKDT14DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT14DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT14DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT14DD_Test := TKDT14DD.Create;
n.Append('...');
SetLength(TKDT14DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT14DD_Test.TestBuff) - 1 do
for j := 0 to KDT14DD_Axis - 1 do
TKDT14DD_Test.TestBuff[i][j] := i * KDT14DD_Axis + j;
{$IFDEF FPC}
TKDT14DD_Test.BuildKDTreeM(length(TKDT14DD_Test.TestBuff), nil, @TKDT14DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT14DD_Test.BuildKDTreeM(length(TKDT14DD_Test.TestBuff), nil, TKDT14DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT14DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT14DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT14DD_Test.TestBuff) - 1 do
begin
p := TKDT14DD_Test.Search(TKDT14DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT14DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT14DD_Test.TestBuff));
TKDT14DD_Test.Search(TKDT14DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT14DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT14DD_Test.Clear;
{ kMean test }
TKDT14DD_Test.BuildKDTreeWithCluster(TKDT14DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT14DD_Test.Search(TKDT14DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT14DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT14DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT14DD_Test);
DoStatus(n);
n := '';
end;
function TKDT15DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DD_Node;
function SortCompare(const p1, p2: PKDT15DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT15DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT15DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT15DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT15DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT15DD.GetData(const Index: NativeInt): PKDT15DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT15DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT15DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT15DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT15DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT15DD.StoreBuffPtr: PKDT15DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT15DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT15DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT15DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT15DD.BuildKDTreeWithCluster(const inBuff: TKDT15DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT15DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT15DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT15DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT15DD.BuildKDTreeWithCluster(const inBuff: TKDT15DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT15DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DD_BuildCall);
var
TempStoreBuff: TKDT15DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT15DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT15DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT15DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT15DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DD_BuildMethod);
var
TempStoreBuff: TKDT15DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT15DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT15DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT15DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT15DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DD_BuildProc);
var
TempStoreBuff: TKDT15DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT15DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT15DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT15DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT15DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT15DD.Search(const buff: TKDT15DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DD_Node;
var
NearestNeighbour: PKDT15DD_Node;
function FindParentNode(const buffPtr: PKDT15DD_Vec; NodePtr: PKDT15DD_Node): PKDT15DD_Node;
var
Next: PKDT15DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT15DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT15DD_Node; const buffPtr: PKDT15DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT15DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT15DD_Vec; const p1, p2: PKDT15DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT15DD_Vec);
var
i, j: NativeInt;
p, t: PKDT15DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT15DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT15DD_Node(NearestNodes[0]);
end;
end;
function TKDT15DD.Search(const buff: TKDT15DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT15DD.Search(const buff: TKDT15DD_Vec; var SearchedDistanceMin: Double): PKDT15DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT15DD.Search(const buff: TKDT15DD_Vec): PKDT15DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT15DD.SearchToken(const buff: TKDT15DD_Vec): TPascalString;
var
p: PKDT15DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT15DD.Search(const inBuff: TKDT15DD_DynamicVecBuffer; var OutBuff: TKDT15DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT15DD_DynamicVecBuffer;
outBuffPtr: PKDT15DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT15DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT15DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT15DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT15DD.Search(const inBuff: TKDT15DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT15DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT15DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT15DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT15DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT15DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT15DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT15DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT15DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT15DD_Vec)) <> SizeOf(TKDT15DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT15DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT15DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT15DD.PrintNodeTree(const NodePtr: PKDT15DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT15DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT15DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT15DD.Vec(const s: SystemString): TKDT15DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT15DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT15DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT15DD.Vec(const v: TKDT15DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT15DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT15DD.Distance(const v1, v2: TKDT15DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT15DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT15DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT15DD.Test;
var
TKDT15DD_Test: TKDT15DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT15DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT15DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT15DD_Test := TKDT15DD.Create;
n.Append('...');
SetLength(TKDT15DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT15DD_Test.TestBuff) - 1 do
for j := 0 to KDT15DD_Axis - 1 do
TKDT15DD_Test.TestBuff[i][j] := i * KDT15DD_Axis + j;
{$IFDEF FPC}
TKDT15DD_Test.BuildKDTreeM(length(TKDT15DD_Test.TestBuff), nil, @TKDT15DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT15DD_Test.BuildKDTreeM(length(TKDT15DD_Test.TestBuff), nil, TKDT15DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT15DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT15DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT15DD_Test.TestBuff) - 1 do
begin
p := TKDT15DD_Test.Search(TKDT15DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT15DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT15DD_Test.TestBuff));
TKDT15DD_Test.Search(TKDT15DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT15DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT15DD_Test.Clear;
{ kMean test }
TKDT15DD_Test.BuildKDTreeWithCluster(TKDT15DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT15DD_Test.Search(TKDT15DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT15DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT15DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT15DD_Test);
DoStatus(n);
n := '';
end;
function TKDT16DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DD_Node;
function SortCompare(const p1, p2: PKDT16DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT16DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT16DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT16DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT16DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT16DD.GetData(const Index: NativeInt): PKDT16DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT16DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT16DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT16DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT16DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT16DD.StoreBuffPtr: PKDT16DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT16DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT16DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT16DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT16DD.BuildKDTreeWithCluster(const inBuff: TKDT16DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT16DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT16DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT16DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT16DD.BuildKDTreeWithCluster(const inBuff: TKDT16DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT16DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DD_BuildCall);
var
TempStoreBuff: TKDT16DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT16DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT16DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT16DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT16DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DD_BuildMethod);
var
TempStoreBuff: TKDT16DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT16DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT16DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT16DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT16DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DD_BuildProc);
var
TempStoreBuff: TKDT16DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT16DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT16DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT16DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT16DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT16DD.Search(const buff: TKDT16DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DD_Node;
var
NearestNeighbour: PKDT16DD_Node;
function FindParentNode(const buffPtr: PKDT16DD_Vec; NodePtr: PKDT16DD_Node): PKDT16DD_Node;
var
Next: PKDT16DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT16DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT16DD_Node; const buffPtr: PKDT16DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT16DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT16DD_Vec; const p1, p2: PKDT16DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT16DD_Vec);
var
i, j: NativeInt;
p, t: PKDT16DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT16DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT16DD_Node(NearestNodes[0]);
end;
end;
function TKDT16DD.Search(const buff: TKDT16DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT16DD.Search(const buff: TKDT16DD_Vec; var SearchedDistanceMin: Double): PKDT16DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT16DD.Search(const buff: TKDT16DD_Vec): PKDT16DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT16DD.SearchToken(const buff: TKDT16DD_Vec): TPascalString;
var
p: PKDT16DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT16DD.Search(const inBuff: TKDT16DD_DynamicVecBuffer; var OutBuff: TKDT16DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT16DD_DynamicVecBuffer;
outBuffPtr: PKDT16DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT16DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT16DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT16DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT16DD.Search(const inBuff: TKDT16DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT16DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT16DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT16DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT16DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT16DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT16DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT16DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT16DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT16DD_Vec)) <> SizeOf(TKDT16DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT16DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT16DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT16DD.PrintNodeTree(const NodePtr: PKDT16DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT16DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT16DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT16DD.Vec(const s: SystemString): TKDT16DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT16DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT16DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT16DD.Vec(const v: TKDT16DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT16DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT16DD.Distance(const v1, v2: TKDT16DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT16DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT16DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT16DD.Test;
var
TKDT16DD_Test: TKDT16DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT16DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT16DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT16DD_Test := TKDT16DD.Create;
n.Append('...');
SetLength(TKDT16DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT16DD_Test.TestBuff) - 1 do
for j := 0 to KDT16DD_Axis - 1 do
TKDT16DD_Test.TestBuff[i][j] := i * KDT16DD_Axis + j;
{$IFDEF FPC}
TKDT16DD_Test.BuildKDTreeM(length(TKDT16DD_Test.TestBuff), nil, @TKDT16DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT16DD_Test.BuildKDTreeM(length(TKDT16DD_Test.TestBuff), nil, TKDT16DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT16DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT16DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT16DD_Test.TestBuff) - 1 do
begin
p := TKDT16DD_Test.Search(TKDT16DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT16DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT16DD_Test.TestBuff));
TKDT16DD_Test.Search(TKDT16DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT16DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT16DD_Test.Clear;
{ kMean test }
TKDT16DD_Test.BuildKDTreeWithCluster(TKDT16DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT16DD_Test.Search(TKDT16DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT16DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT16DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT16DD_Test);
DoStatus(n);
n := '';
end;
function TKDT17DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DD_Node;
function SortCompare(const p1, p2: PKDT17DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT17DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT17DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT17DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT17DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT17DD.GetData(const Index: NativeInt): PKDT17DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT17DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT17DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT17DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT17DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT17DD.StoreBuffPtr: PKDT17DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT17DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT17DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT17DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT17DD.BuildKDTreeWithCluster(const inBuff: TKDT17DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT17DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT17DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT17DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT17DD.BuildKDTreeWithCluster(const inBuff: TKDT17DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT17DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DD_BuildCall);
var
TempStoreBuff: TKDT17DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT17DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT17DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT17DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT17DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DD_BuildMethod);
var
TempStoreBuff: TKDT17DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT17DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT17DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT17DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT17DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DD_BuildProc);
var
TempStoreBuff: TKDT17DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT17DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT17DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT17DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT17DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT17DD.Search(const buff: TKDT17DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DD_Node;
var
NearestNeighbour: PKDT17DD_Node;
function FindParentNode(const buffPtr: PKDT17DD_Vec; NodePtr: PKDT17DD_Node): PKDT17DD_Node;
var
Next: PKDT17DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT17DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT17DD_Node; const buffPtr: PKDT17DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT17DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT17DD_Vec; const p1, p2: PKDT17DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT17DD_Vec);
var
i, j: NativeInt;
p, t: PKDT17DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT17DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT17DD_Node(NearestNodes[0]);
end;
end;
function TKDT17DD.Search(const buff: TKDT17DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT17DD.Search(const buff: TKDT17DD_Vec; var SearchedDistanceMin: Double): PKDT17DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT17DD.Search(const buff: TKDT17DD_Vec): PKDT17DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT17DD.SearchToken(const buff: TKDT17DD_Vec): TPascalString;
var
p: PKDT17DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT17DD.Search(const inBuff: TKDT17DD_DynamicVecBuffer; var OutBuff: TKDT17DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT17DD_DynamicVecBuffer;
outBuffPtr: PKDT17DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT17DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT17DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT17DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT17DD.Search(const inBuff: TKDT17DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT17DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT17DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT17DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT17DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT17DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT17DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT17DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT17DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT17DD_Vec)) <> SizeOf(TKDT17DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT17DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT17DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT17DD.PrintNodeTree(const NodePtr: PKDT17DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT17DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT17DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT17DD.Vec(const s: SystemString): TKDT17DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT17DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT17DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT17DD.Vec(const v: TKDT17DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT17DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT17DD.Distance(const v1, v2: TKDT17DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT17DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT17DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT17DD.Test;
var
TKDT17DD_Test: TKDT17DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT17DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT17DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT17DD_Test := TKDT17DD.Create;
n.Append('...');
SetLength(TKDT17DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT17DD_Test.TestBuff) - 1 do
for j := 0 to KDT17DD_Axis - 1 do
TKDT17DD_Test.TestBuff[i][j] := i * KDT17DD_Axis + j;
{$IFDEF FPC}
TKDT17DD_Test.BuildKDTreeM(length(TKDT17DD_Test.TestBuff), nil, @TKDT17DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT17DD_Test.BuildKDTreeM(length(TKDT17DD_Test.TestBuff), nil, TKDT17DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT17DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT17DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT17DD_Test.TestBuff) - 1 do
begin
p := TKDT17DD_Test.Search(TKDT17DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT17DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT17DD_Test.TestBuff));
TKDT17DD_Test.Search(TKDT17DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT17DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT17DD_Test.Clear;
{ kMean test }
TKDT17DD_Test.BuildKDTreeWithCluster(TKDT17DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT17DD_Test.Search(TKDT17DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT17DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT17DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT17DD_Test);
DoStatus(n);
n := '';
end;
function TKDT18DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DD_Node;
function SortCompare(const p1, p2: PKDT18DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT18DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT18DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT18DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT18DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT18DD.GetData(const Index: NativeInt): PKDT18DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT18DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT18DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT18DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT18DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT18DD.StoreBuffPtr: PKDT18DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT18DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT18DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT18DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT18DD.BuildKDTreeWithCluster(const inBuff: TKDT18DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT18DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT18DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT18DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT18DD.BuildKDTreeWithCluster(const inBuff: TKDT18DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT18DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DD_BuildCall);
var
TempStoreBuff: TKDT18DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT18DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT18DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT18DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT18DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DD_BuildMethod);
var
TempStoreBuff: TKDT18DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT18DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT18DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT18DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT18DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DD_BuildProc);
var
TempStoreBuff: TKDT18DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT18DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT18DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT18DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT18DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT18DD.Search(const buff: TKDT18DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DD_Node;
var
NearestNeighbour: PKDT18DD_Node;
function FindParentNode(const buffPtr: PKDT18DD_Vec; NodePtr: PKDT18DD_Node): PKDT18DD_Node;
var
Next: PKDT18DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT18DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT18DD_Node; const buffPtr: PKDT18DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT18DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT18DD_Vec; const p1, p2: PKDT18DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT18DD_Vec);
var
i, j: NativeInt;
p, t: PKDT18DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT18DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT18DD_Node(NearestNodes[0]);
end;
end;
function TKDT18DD.Search(const buff: TKDT18DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT18DD.Search(const buff: TKDT18DD_Vec; var SearchedDistanceMin: Double): PKDT18DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT18DD.Search(const buff: TKDT18DD_Vec): PKDT18DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT18DD.SearchToken(const buff: TKDT18DD_Vec): TPascalString;
var
p: PKDT18DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT18DD.Search(const inBuff: TKDT18DD_DynamicVecBuffer; var OutBuff: TKDT18DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT18DD_DynamicVecBuffer;
outBuffPtr: PKDT18DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT18DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT18DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT18DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT18DD.Search(const inBuff: TKDT18DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT18DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT18DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT18DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT18DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT18DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT18DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT18DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT18DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT18DD_Vec)) <> SizeOf(TKDT18DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT18DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT18DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT18DD.PrintNodeTree(const NodePtr: PKDT18DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT18DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT18DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT18DD.Vec(const s: SystemString): TKDT18DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT18DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT18DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT18DD.Vec(const v: TKDT18DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT18DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT18DD.Distance(const v1, v2: TKDT18DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT18DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT18DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT18DD.Test;
var
TKDT18DD_Test: TKDT18DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT18DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT18DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT18DD_Test := TKDT18DD.Create;
n.Append('...');
SetLength(TKDT18DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT18DD_Test.TestBuff) - 1 do
for j := 0 to KDT18DD_Axis - 1 do
TKDT18DD_Test.TestBuff[i][j] := i * KDT18DD_Axis + j;
{$IFDEF FPC}
TKDT18DD_Test.BuildKDTreeM(length(TKDT18DD_Test.TestBuff), nil, @TKDT18DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT18DD_Test.BuildKDTreeM(length(TKDT18DD_Test.TestBuff), nil, TKDT18DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT18DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT18DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT18DD_Test.TestBuff) - 1 do
begin
p := TKDT18DD_Test.Search(TKDT18DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT18DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT18DD_Test.TestBuff));
TKDT18DD_Test.Search(TKDT18DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT18DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT18DD_Test.Clear;
{ kMean test }
TKDT18DD_Test.BuildKDTreeWithCluster(TKDT18DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT18DD_Test.Search(TKDT18DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT18DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT18DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT18DD_Test);
DoStatus(n);
n := '';
end;
function TKDT19DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DD_Node;
function SortCompare(const p1, p2: PKDT19DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT19DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT19DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT19DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT19DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT19DD.GetData(const Index: NativeInt): PKDT19DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT19DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT19DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT19DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT19DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT19DD.StoreBuffPtr: PKDT19DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT19DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT19DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT19DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT19DD.BuildKDTreeWithCluster(const inBuff: TKDT19DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT19DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT19DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT19DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT19DD.BuildKDTreeWithCluster(const inBuff: TKDT19DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT19DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DD_BuildCall);
var
TempStoreBuff: TKDT19DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT19DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT19DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT19DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT19DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DD_BuildMethod);
var
TempStoreBuff: TKDT19DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT19DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT19DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT19DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT19DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DD_BuildProc);
var
TempStoreBuff: TKDT19DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT19DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT19DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT19DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT19DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT19DD.Search(const buff: TKDT19DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DD_Node;
var
NearestNeighbour: PKDT19DD_Node;
function FindParentNode(const buffPtr: PKDT19DD_Vec; NodePtr: PKDT19DD_Node): PKDT19DD_Node;
var
Next: PKDT19DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT19DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT19DD_Node; const buffPtr: PKDT19DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT19DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT19DD_Vec; const p1, p2: PKDT19DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT19DD_Vec);
var
i, j: NativeInt;
p, t: PKDT19DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT19DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT19DD_Node(NearestNodes[0]);
end;
end;
function TKDT19DD.Search(const buff: TKDT19DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT19DD.Search(const buff: TKDT19DD_Vec; var SearchedDistanceMin: Double): PKDT19DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT19DD.Search(const buff: TKDT19DD_Vec): PKDT19DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT19DD.SearchToken(const buff: TKDT19DD_Vec): TPascalString;
var
p: PKDT19DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT19DD.Search(const inBuff: TKDT19DD_DynamicVecBuffer; var OutBuff: TKDT19DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT19DD_DynamicVecBuffer;
outBuffPtr: PKDT19DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT19DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT19DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT19DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT19DD.Search(const inBuff: TKDT19DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT19DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT19DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT19DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT19DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT19DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT19DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT19DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT19DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT19DD_Vec)) <> SizeOf(TKDT19DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT19DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT19DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT19DD.PrintNodeTree(const NodePtr: PKDT19DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT19DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT19DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT19DD.Vec(const s: SystemString): TKDT19DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT19DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT19DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT19DD.Vec(const v: TKDT19DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT19DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT19DD.Distance(const v1, v2: TKDT19DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT19DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT19DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT19DD.Test;
var
TKDT19DD_Test: TKDT19DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT19DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT19DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT19DD_Test := TKDT19DD.Create;
n.Append('...');
SetLength(TKDT19DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT19DD_Test.TestBuff) - 1 do
for j := 0 to KDT19DD_Axis - 1 do
TKDT19DD_Test.TestBuff[i][j] := i * KDT19DD_Axis + j;
{$IFDEF FPC}
TKDT19DD_Test.BuildKDTreeM(length(TKDT19DD_Test.TestBuff), nil, @TKDT19DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT19DD_Test.BuildKDTreeM(length(TKDT19DD_Test.TestBuff), nil, TKDT19DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT19DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT19DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT19DD_Test.TestBuff) - 1 do
begin
p := TKDT19DD_Test.Search(TKDT19DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT19DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT19DD_Test.TestBuff));
TKDT19DD_Test.Search(TKDT19DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT19DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT19DD_Test.Clear;
{ kMean test }
TKDT19DD_Test.BuildKDTreeWithCluster(TKDT19DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT19DD_Test.Search(TKDT19DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT19DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT19DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT19DD_Test);
DoStatus(n);
n := '';
end;
function TKDT20DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DD_Node;
function SortCompare(const p1, p2: PKDT20DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT20DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT20DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT20DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT20DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT20DD.GetData(const Index: NativeInt): PKDT20DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT20DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT20DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT20DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT20DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT20DD.StoreBuffPtr: PKDT20DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT20DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT20DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT20DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT20DD.BuildKDTreeWithCluster(const inBuff: TKDT20DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT20DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT20DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT20DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT20DD.BuildKDTreeWithCluster(const inBuff: TKDT20DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT20DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DD_BuildCall);
var
TempStoreBuff: TKDT20DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT20DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT20DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT20DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT20DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DD_BuildMethod);
var
TempStoreBuff: TKDT20DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT20DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT20DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT20DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT20DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DD_BuildProc);
var
TempStoreBuff: TKDT20DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT20DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT20DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT20DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT20DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT20DD.Search(const buff: TKDT20DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DD_Node;
var
NearestNeighbour: PKDT20DD_Node;
function FindParentNode(const buffPtr: PKDT20DD_Vec; NodePtr: PKDT20DD_Node): PKDT20DD_Node;
var
Next: PKDT20DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT20DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT20DD_Node; const buffPtr: PKDT20DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT20DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT20DD_Vec; const p1, p2: PKDT20DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT20DD_Vec);
var
i, j: NativeInt;
p, t: PKDT20DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT20DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT20DD_Node(NearestNodes[0]);
end;
end;
function TKDT20DD.Search(const buff: TKDT20DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT20DD.Search(const buff: TKDT20DD_Vec; var SearchedDistanceMin: Double): PKDT20DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT20DD.Search(const buff: TKDT20DD_Vec): PKDT20DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT20DD.SearchToken(const buff: TKDT20DD_Vec): TPascalString;
var
p: PKDT20DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT20DD.Search(const inBuff: TKDT20DD_DynamicVecBuffer; var OutBuff: TKDT20DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT20DD_DynamicVecBuffer;
outBuffPtr: PKDT20DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT20DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT20DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT20DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT20DD.Search(const inBuff: TKDT20DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT20DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT20DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT20DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT20DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT20DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT20DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT20DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT20DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT20DD_Vec)) <> SizeOf(TKDT20DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT20DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT20DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT20DD.PrintNodeTree(const NodePtr: PKDT20DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT20DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT20DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT20DD.Vec(const s: SystemString): TKDT20DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT20DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT20DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT20DD.Vec(const v: TKDT20DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT20DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT20DD.Distance(const v1, v2: TKDT20DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT20DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT20DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT20DD.Test;
var
TKDT20DD_Test: TKDT20DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT20DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT20DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT20DD_Test := TKDT20DD.Create;
n.Append('...');
SetLength(TKDT20DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT20DD_Test.TestBuff) - 1 do
for j := 0 to KDT20DD_Axis - 1 do
TKDT20DD_Test.TestBuff[i][j] := i * KDT20DD_Axis + j;
{$IFDEF FPC}
TKDT20DD_Test.BuildKDTreeM(length(TKDT20DD_Test.TestBuff), nil, @TKDT20DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT20DD_Test.BuildKDTreeM(length(TKDT20DD_Test.TestBuff), nil, TKDT20DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT20DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT20DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT20DD_Test.TestBuff) - 1 do
begin
p := TKDT20DD_Test.Search(TKDT20DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT20DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT20DD_Test.TestBuff));
TKDT20DD_Test.Search(TKDT20DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT20DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT20DD_Test.Clear;
{ kMean test }
TKDT20DD_Test.BuildKDTreeWithCluster(TKDT20DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT20DD_Test.Search(TKDT20DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT20DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT20DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT20DD_Test);
DoStatus(n);
n := '';
end;
function TKDT21DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DD_Node;
function SortCompare(const p1, p2: PKDT21DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT21DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT21DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT21DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT21DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT21DD.GetData(const Index: NativeInt): PKDT21DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT21DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT21DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT21DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT21DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT21DD.StoreBuffPtr: PKDT21DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT21DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT21DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT21DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT21DD.BuildKDTreeWithCluster(const inBuff: TKDT21DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT21DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT21DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT21DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT21DD.BuildKDTreeWithCluster(const inBuff: TKDT21DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT21DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DD_BuildCall);
var
TempStoreBuff: TKDT21DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT21DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT21DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT21DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT21DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DD_BuildMethod);
var
TempStoreBuff: TKDT21DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT21DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT21DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT21DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT21DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DD_BuildProc);
var
TempStoreBuff: TKDT21DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT21DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT21DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT21DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT21DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT21DD.Search(const buff: TKDT21DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DD_Node;
var
NearestNeighbour: PKDT21DD_Node;
function FindParentNode(const buffPtr: PKDT21DD_Vec; NodePtr: PKDT21DD_Node): PKDT21DD_Node;
var
Next: PKDT21DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT21DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT21DD_Node; const buffPtr: PKDT21DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT21DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT21DD_Vec; const p1, p2: PKDT21DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT21DD_Vec);
var
i, j: NativeInt;
p, t: PKDT21DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT21DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT21DD_Node(NearestNodes[0]);
end;
end;
function TKDT21DD.Search(const buff: TKDT21DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT21DD.Search(const buff: TKDT21DD_Vec; var SearchedDistanceMin: Double): PKDT21DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT21DD.Search(const buff: TKDT21DD_Vec): PKDT21DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT21DD.SearchToken(const buff: TKDT21DD_Vec): TPascalString;
var
p: PKDT21DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT21DD.Search(const inBuff: TKDT21DD_DynamicVecBuffer; var OutBuff: TKDT21DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT21DD_DynamicVecBuffer;
outBuffPtr: PKDT21DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT21DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT21DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT21DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT21DD.Search(const inBuff: TKDT21DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT21DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT21DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT21DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT21DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT21DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT21DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT21DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT21DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT21DD_Vec)) <> SizeOf(TKDT21DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT21DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT21DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT21DD.PrintNodeTree(const NodePtr: PKDT21DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT21DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT21DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT21DD.Vec(const s: SystemString): TKDT21DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT21DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT21DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT21DD.Vec(const v: TKDT21DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT21DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT21DD.Distance(const v1, v2: TKDT21DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT21DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT21DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT21DD.Test;
var
TKDT21DD_Test: TKDT21DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT21DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT21DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT21DD_Test := TKDT21DD.Create;
n.Append('...');
SetLength(TKDT21DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT21DD_Test.TestBuff) - 1 do
for j := 0 to KDT21DD_Axis - 1 do
TKDT21DD_Test.TestBuff[i][j] := i * KDT21DD_Axis + j;
{$IFDEF FPC}
TKDT21DD_Test.BuildKDTreeM(length(TKDT21DD_Test.TestBuff), nil, @TKDT21DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT21DD_Test.BuildKDTreeM(length(TKDT21DD_Test.TestBuff), nil, TKDT21DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT21DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT21DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT21DD_Test.TestBuff) - 1 do
begin
p := TKDT21DD_Test.Search(TKDT21DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT21DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT21DD_Test.TestBuff));
TKDT21DD_Test.Search(TKDT21DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT21DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT21DD_Test.Clear;
{ kMean test }
TKDT21DD_Test.BuildKDTreeWithCluster(TKDT21DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT21DD_Test.Search(TKDT21DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT21DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT21DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT21DD_Test);
DoStatus(n);
n := '';
end;
function TKDT22DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DD_Node;
function SortCompare(const p1, p2: PKDT22DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT22DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT22DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT22DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT22DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT22DD.GetData(const Index: NativeInt): PKDT22DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT22DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT22DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT22DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT22DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT22DD.StoreBuffPtr: PKDT22DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT22DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT22DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT22DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT22DD.BuildKDTreeWithCluster(const inBuff: TKDT22DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT22DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT22DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT22DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT22DD.BuildKDTreeWithCluster(const inBuff: TKDT22DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT22DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DD_BuildCall);
var
TempStoreBuff: TKDT22DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT22DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT22DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT22DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT22DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DD_BuildMethod);
var
TempStoreBuff: TKDT22DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT22DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT22DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT22DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT22DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DD_BuildProc);
var
TempStoreBuff: TKDT22DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT22DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT22DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT22DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT22DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT22DD.Search(const buff: TKDT22DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DD_Node;
var
NearestNeighbour: PKDT22DD_Node;
function FindParentNode(const buffPtr: PKDT22DD_Vec; NodePtr: PKDT22DD_Node): PKDT22DD_Node;
var
Next: PKDT22DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT22DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT22DD_Node; const buffPtr: PKDT22DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT22DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT22DD_Vec; const p1, p2: PKDT22DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT22DD_Vec);
var
i, j: NativeInt;
p, t: PKDT22DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT22DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT22DD_Node(NearestNodes[0]);
end;
end;
function TKDT22DD.Search(const buff: TKDT22DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT22DD.Search(const buff: TKDT22DD_Vec; var SearchedDistanceMin: Double): PKDT22DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT22DD.Search(const buff: TKDT22DD_Vec): PKDT22DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT22DD.SearchToken(const buff: TKDT22DD_Vec): TPascalString;
var
p: PKDT22DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT22DD.Search(const inBuff: TKDT22DD_DynamicVecBuffer; var OutBuff: TKDT22DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT22DD_DynamicVecBuffer;
outBuffPtr: PKDT22DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT22DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT22DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT22DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT22DD.Search(const inBuff: TKDT22DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT22DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT22DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT22DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT22DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT22DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT22DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT22DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT22DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT22DD_Vec)) <> SizeOf(TKDT22DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT22DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT22DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT22DD.PrintNodeTree(const NodePtr: PKDT22DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT22DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT22DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT22DD.Vec(const s: SystemString): TKDT22DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT22DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT22DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT22DD.Vec(const v: TKDT22DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT22DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT22DD.Distance(const v1, v2: TKDT22DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT22DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT22DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT22DD.Test;
var
TKDT22DD_Test: TKDT22DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT22DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT22DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT22DD_Test := TKDT22DD.Create;
n.Append('...');
SetLength(TKDT22DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT22DD_Test.TestBuff) - 1 do
for j := 0 to KDT22DD_Axis - 1 do
TKDT22DD_Test.TestBuff[i][j] := i * KDT22DD_Axis + j;
{$IFDEF FPC}
TKDT22DD_Test.BuildKDTreeM(length(TKDT22DD_Test.TestBuff), nil, @TKDT22DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT22DD_Test.BuildKDTreeM(length(TKDT22DD_Test.TestBuff), nil, TKDT22DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT22DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT22DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT22DD_Test.TestBuff) - 1 do
begin
p := TKDT22DD_Test.Search(TKDT22DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT22DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT22DD_Test.TestBuff));
TKDT22DD_Test.Search(TKDT22DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT22DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT22DD_Test.Clear;
{ kMean test }
TKDT22DD_Test.BuildKDTreeWithCluster(TKDT22DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT22DD_Test.Search(TKDT22DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT22DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT22DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT22DD_Test);
DoStatus(n);
n := '';
end;
function TKDT23DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DD_Node;
function SortCompare(const p1, p2: PKDT23DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT23DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT23DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT23DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT23DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT23DD.GetData(const Index: NativeInt): PKDT23DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT23DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT23DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT23DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT23DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT23DD.StoreBuffPtr: PKDT23DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT23DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT23DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT23DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT23DD.BuildKDTreeWithCluster(const inBuff: TKDT23DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT23DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT23DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT23DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT23DD.BuildKDTreeWithCluster(const inBuff: TKDT23DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT23DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DD_BuildCall);
var
TempStoreBuff: TKDT23DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT23DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT23DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT23DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT23DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DD_BuildMethod);
var
TempStoreBuff: TKDT23DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT23DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT23DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT23DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT23DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DD_BuildProc);
var
TempStoreBuff: TKDT23DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT23DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT23DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT23DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT23DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT23DD.Search(const buff: TKDT23DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DD_Node;
var
NearestNeighbour: PKDT23DD_Node;
function FindParentNode(const buffPtr: PKDT23DD_Vec; NodePtr: PKDT23DD_Node): PKDT23DD_Node;
var
Next: PKDT23DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT23DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT23DD_Node; const buffPtr: PKDT23DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT23DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT23DD_Vec; const p1, p2: PKDT23DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT23DD_Vec);
var
i, j: NativeInt;
p, t: PKDT23DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT23DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT23DD_Node(NearestNodes[0]);
end;
end;
function TKDT23DD.Search(const buff: TKDT23DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT23DD.Search(const buff: TKDT23DD_Vec; var SearchedDistanceMin: Double): PKDT23DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT23DD.Search(const buff: TKDT23DD_Vec): PKDT23DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT23DD.SearchToken(const buff: TKDT23DD_Vec): TPascalString;
var
p: PKDT23DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT23DD.Search(const inBuff: TKDT23DD_DynamicVecBuffer; var OutBuff: TKDT23DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT23DD_DynamicVecBuffer;
outBuffPtr: PKDT23DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT23DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT23DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT23DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT23DD.Search(const inBuff: TKDT23DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT23DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT23DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT23DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT23DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT23DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT23DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT23DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT23DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT23DD_Vec)) <> SizeOf(TKDT23DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT23DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT23DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT23DD.PrintNodeTree(const NodePtr: PKDT23DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT23DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT23DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT23DD.Vec(const s: SystemString): TKDT23DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT23DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT23DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT23DD.Vec(const v: TKDT23DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT23DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT23DD.Distance(const v1, v2: TKDT23DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT23DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT23DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT23DD.Test;
var
TKDT23DD_Test: TKDT23DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT23DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT23DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT23DD_Test := TKDT23DD.Create;
n.Append('...');
SetLength(TKDT23DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT23DD_Test.TestBuff) - 1 do
for j := 0 to KDT23DD_Axis - 1 do
TKDT23DD_Test.TestBuff[i][j] := i * KDT23DD_Axis + j;
{$IFDEF FPC}
TKDT23DD_Test.BuildKDTreeM(length(TKDT23DD_Test.TestBuff), nil, @TKDT23DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT23DD_Test.BuildKDTreeM(length(TKDT23DD_Test.TestBuff), nil, TKDT23DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT23DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT23DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT23DD_Test.TestBuff) - 1 do
begin
p := TKDT23DD_Test.Search(TKDT23DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT23DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT23DD_Test.TestBuff));
TKDT23DD_Test.Search(TKDT23DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT23DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT23DD_Test.Clear;
{ kMean test }
TKDT23DD_Test.BuildKDTreeWithCluster(TKDT23DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT23DD_Test.Search(TKDT23DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT23DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT23DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT23DD_Test);
DoStatus(n);
n := '';
end;
function TKDT24DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DD_Node;
function SortCompare(const p1, p2: PKDT24DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT24DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT24DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT24DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT24DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT24DD.GetData(const Index: NativeInt): PKDT24DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT24DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT24DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT24DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT24DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT24DD.StoreBuffPtr: PKDT24DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT24DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT24DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT24DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT24DD.BuildKDTreeWithCluster(const inBuff: TKDT24DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT24DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT24DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT24DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT24DD.BuildKDTreeWithCluster(const inBuff: TKDT24DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT24DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DD_BuildCall);
var
TempStoreBuff: TKDT24DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT24DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT24DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT24DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT24DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DD_BuildMethod);
var
TempStoreBuff: TKDT24DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT24DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT24DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT24DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT24DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DD_BuildProc);
var
TempStoreBuff: TKDT24DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT24DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT24DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT24DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT24DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT24DD.Search(const buff: TKDT24DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DD_Node;
var
NearestNeighbour: PKDT24DD_Node;
function FindParentNode(const buffPtr: PKDT24DD_Vec; NodePtr: PKDT24DD_Node): PKDT24DD_Node;
var
Next: PKDT24DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT24DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT24DD_Node; const buffPtr: PKDT24DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT24DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT24DD_Vec; const p1, p2: PKDT24DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT24DD_Vec);
var
i, j: NativeInt;
p, t: PKDT24DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT24DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT24DD_Node(NearestNodes[0]);
end;
end;
function TKDT24DD.Search(const buff: TKDT24DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT24DD.Search(const buff: TKDT24DD_Vec; var SearchedDistanceMin: Double): PKDT24DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT24DD.Search(const buff: TKDT24DD_Vec): PKDT24DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT24DD.SearchToken(const buff: TKDT24DD_Vec): TPascalString;
var
p: PKDT24DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT24DD.Search(const inBuff: TKDT24DD_DynamicVecBuffer; var OutBuff: TKDT24DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT24DD_DynamicVecBuffer;
outBuffPtr: PKDT24DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT24DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT24DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT24DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT24DD.Search(const inBuff: TKDT24DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT24DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT24DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT24DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT24DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT24DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT24DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT24DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT24DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT24DD_Vec)) <> SizeOf(TKDT24DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT24DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT24DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT24DD.PrintNodeTree(const NodePtr: PKDT24DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT24DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT24DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT24DD.Vec(const s: SystemString): TKDT24DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT24DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT24DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT24DD.Vec(const v: TKDT24DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT24DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT24DD.Distance(const v1, v2: TKDT24DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT24DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT24DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT24DD.Test;
var
TKDT24DD_Test: TKDT24DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT24DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT24DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT24DD_Test := TKDT24DD.Create;
n.Append('...');
SetLength(TKDT24DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT24DD_Test.TestBuff) - 1 do
for j := 0 to KDT24DD_Axis - 1 do
TKDT24DD_Test.TestBuff[i][j] := i * KDT24DD_Axis + j;
{$IFDEF FPC}
TKDT24DD_Test.BuildKDTreeM(length(TKDT24DD_Test.TestBuff), nil, @TKDT24DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT24DD_Test.BuildKDTreeM(length(TKDT24DD_Test.TestBuff), nil, TKDT24DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT24DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT24DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT24DD_Test.TestBuff) - 1 do
begin
p := TKDT24DD_Test.Search(TKDT24DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT24DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT24DD_Test.TestBuff));
TKDT24DD_Test.Search(TKDT24DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT24DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT24DD_Test.Clear;
{ kMean test }
TKDT24DD_Test.BuildKDTreeWithCluster(TKDT24DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT24DD_Test.Search(TKDT24DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT24DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT24DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT24DD_Test);
DoStatus(n);
n := '';
end;
function TKDT48DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DD_Node;
function SortCompare(const p1, p2: PKDT48DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT48DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT48DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT48DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT48DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT48DD.GetData(const Index: NativeInt): PKDT48DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT48DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT48DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT48DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT48DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT48DD.StoreBuffPtr: PKDT48DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT48DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT48DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT48DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT48DD.BuildKDTreeWithCluster(const inBuff: TKDT48DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT48DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT48DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT48DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT48DD.BuildKDTreeWithCluster(const inBuff: TKDT48DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT48DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DD_BuildCall);
var
TempStoreBuff: TKDT48DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT48DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT48DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT48DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT48DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DD_BuildMethod);
var
TempStoreBuff: TKDT48DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT48DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT48DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT48DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT48DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DD_BuildProc);
var
TempStoreBuff: TKDT48DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT48DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT48DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT48DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT48DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT48DD.Search(const buff: TKDT48DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DD_Node;
var
NearestNeighbour: PKDT48DD_Node;
function FindParentNode(const buffPtr: PKDT48DD_Vec; NodePtr: PKDT48DD_Node): PKDT48DD_Node;
var
Next: PKDT48DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT48DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT48DD_Node; const buffPtr: PKDT48DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT48DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT48DD_Vec; const p1, p2: PKDT48DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT48DD_Vec);
var
i, j: NativeInt;
p, t: PKDT48DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT48DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT48DD_Node(NearestNodes[0]);
end;
end;
function TKDT48DD.Search(const buff: TKDT48DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT48DD.Search(const buff: TKDT48DD_Vec; var SearchedDistanceMin: Double): PKDT48DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT48DD.Search(const buff: TKDT48DD_Vec): PKDT48DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT48DD.SearchToken(const buff: TKDT48DD_Vec): TPascalString;
var
p: PKDT48DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT48DD.Search(const inBuff: TKDT48DD_DynamicVecBuffer; var OutBuff: TKDT48DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT48DD_DynamicVecBuffer;
outBuffPtr: PKDT48DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT48DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT48DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT48DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT48DD.Search(const inBuff: TKDT48DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT48DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT48DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT48DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT48DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT48DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT48DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT48DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT48DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT48DD_Vec)) <> SizeOf(TKDT48DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT48DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT48DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT48DD.PrintNodeTree(const NodePtr: PKDT48DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT48DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT48DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT48DD.Vec(const s: SystemString): TKDT48DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT48DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT48DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT48DD.Vec(const v: TKDT48DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT48DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT48DD.Distance(const v1, v2: TKDT48DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT48DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT48DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT48DD.Test;
var
TKDT48DD_Test: TKDT48DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT48DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT48DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT48DD_Test := TKDT48DD.Create;
n.Append('...');
SetLength(TKDT48DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT48DD_Test.TestBuff) - 1 do
for j := 0 to KDT48DD_Axis - 1 do
TKDT48DD_Test.TestBuff[i][j] := i * KDT48DD_Axis + j;
{$IFDEF FPC}
TKDT48DD_Test.BuildKDTreeM(length(TKDT48DD_Test.TestBuff), nil, @TKDT48DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT48DD_Test.BuildKDTreeM(length(TKDT48DD_Test.TestBuff), nil, TKDT48DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT48DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT48DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT48DD_Test.TestBuff) - 1 do
begin
p := TKDT48DD_Test.Search(TKDT48DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT48DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT48DD_Test.TestBuff));
TKDT48DD_Test.Search(TKDT48DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT48DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT48DD_Test.Clear;
{ kMean test }
TKDT48DD_Test.BuildKDTreeWithCluster(TKDT48DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT48DD_Test.Search(TKDT48DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT48DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT48DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT48DD_Test);
DoStatus(n);
n := '';
end;
function TKDT52DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DD_Node;
function SortCompare(const p1, p2: PKDT52DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT52DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT52DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT52DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT52DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT52DD.GetData(const Index: NativeInt): PKDT52DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT52DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT52DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT52DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT52DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT52DD.StoreBuffPtr: PKDT52DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT52DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT52DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT52DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT52DD.BuildKDTreeWithCluster(const inBuff: TKDT52DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT52DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT52DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT52DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT52DD.BuildKDTreeWithCluster(const inBuff: TKDT52DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT52DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DD_BuildCall);
var
TempStoreBuff: TKDT52DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT52DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT52DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT52DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT52DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DD_BuildMethod);
var
TempStoreBuff: TKDT52DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT52DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT52DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT52DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT52DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DD_BuildProc);
var
TempStoreBuff: TKDT52DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT52DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT52DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT52DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT52DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT52DD.Search(const buff: TKDT52DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DD_Node;
var
NearestNeighbour: PKDT52DD_Node;
function FindParentNode(const buffPtr: PKDT52DD_Vec; NodePtr: PKDT52DD_Node): PKDT52DD_Node;
var
Next: PKDT52DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT52DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT52DD_Node; const buffPtr: PKDT52DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT52DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT52DD_Vec; const p1, p2: PKDT52DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT52DD_Vec);
var
i, j: NativeInt;
p, t: PKDT52DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT52DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT52DD_Node(NearestNodes[0]);
end;
end;
function TKDT52DD.Search(const buff: TKDT52DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT52DD.Search(const buff: TKDT52DD_Vec; var SearchedDistanceMin: Double): PKDT52DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT52DD.Search(const buff: TKDT52DD_Vec): PKDT52DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT52DD.SearchToken(const buff: TKDT52DD_Vec): TPascalString;
var
p: PKDT52DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT52DD.Search(const inBuff: TKDT52DD_DynamicVecBuffer; var OutBuff: TKDT52DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT52DD_DynamicVecBuffer;
outBuffPtr: PKDT52DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT52DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT52DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT52DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT52DD.Search(const inBuff: TKDT52DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT52DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT52DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT52DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT52DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT52DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT52DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT52DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT52DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT52DD_Vec)) <> SizeOf(TKDT52DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT52DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT52DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT52DD.PrintNodeTree(const NodePtr: PKDT52DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT52DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT52DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT52DD.Vec(const s: SystemString): TKDT52DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT52DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT52DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT52DD.Vec(const v: TKDT52DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT52DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT52DD.Distance(const v1, v2: TKDT52DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT52DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT52DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT52DD.Test;
var
TKDT52DD_Test: TKDT52DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT52DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT52DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT52DD_Test := TKDT52DD.Create;
n.Append('...');
SetLength(TKDT52DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT52DD_Test.TestBuff) - 1 do
for j := 0 to KDT52DD_Axis - 1 do
TKDT52DD_Test.TestBuff[i][j] := i * KDT52DD_Axis + j;
{$IFDEF FPC}
TKDT52DD_Test.BuildKDTreeM(length(TKDT52DD_Test.TestBuff), nil, @TKDT52DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT52DD_Test.BuildKDTreeM(length(TKDT52DD_Test.TestBuff), nil, TKDT52DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT52DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT52DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT52DD_Test.TestBuff) - 1 do
begin
p := TKDT52DD_Test.Search(TKDT52DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT52DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT52DD_Test.TestBuff));
TKDT52DD_Test.Search(TKDT52DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT52DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT52DD_Test.Clear;
{ kMean test }
TKDT52DD_Test.BuildKDTreeWithCluster(TKDT52DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT52DD_Test.Search(TKDT52DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT52DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT52DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT52DD_Test);
DoStatus(n);
n := '';
end;
function TKDT64DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DD_Node;
function SortCompare(const p1, p2: PKDT64DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT64DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT64DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT64DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT64DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT64DD.GetData(const Index: NativeInt): PKDT64DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT64DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT64DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT64DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT64DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT64DD.StoreBuffPtr: PKDT64DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT64DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT64DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT64DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT64DD.BuildKDTreeWithCluster(const inBuff: TKDT64DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT64DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT64DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT64DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT64DD.BuildKDTreeWithCluster(const inBuff: TKDT64DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT64DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DD_BuildCall);
var
TempStoreBuff: TKDT64DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT64DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT64DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT64DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT64DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DD_BuildMethod);
var
TempStoreBuff: TKDT64DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT64DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT64DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT64DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT64DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DD_BuildProc);
var
TempStoreBuff: TKDT64DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT64DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT64DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT64DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT64DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT64DD.Search(const buff: TKDT64DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DD_Node;
var
NearestNeighbour: PKDT64DD_Node;
function FindParentNode(const buffPtr: PKDT64DD_Vec; NodePtr: PKDT64DD_Node): PKDT64DD_Node;
var
Next: PKDT64DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT64DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT64DD_Node; const buffPtr: PKDT64DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT64DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT64DD_Vec; const p1, p2: PKDT64DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT64DD_Vec);
var
i, j: NativeInt;
p, t: PKDT64DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT64DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT64DD_Node(NearestNodes[0]);
end;
end;
function TKDT64DD.Search(const buff: TKDT64DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT64DD.Search(const buff: TKDT64DD_Vec; var SearchedDistanceMin: Double): PKDT64DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT64DD.Search(const buff: TKDT64DD_Vec): PKDT64DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT64DD.SearchToken(const buff: TKDT64DD_Vec): TPascalString;
var
p: PKDT64DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT64DD.Search(const inBuff: TKDT64DD_DynamicVecBuffer; var OutBuff: TKDT64DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT64DD_DynamicVecBuffer;
outBuffPtr: PKDT64DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT64DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT64DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT64DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT64DD.Search(const inBuff: TKDT64DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT64DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT64DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT64DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT64DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT64DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT64DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT64DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT64DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT64DD_Vec)) <> SizeOf(TKDT64DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT64DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT64DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT64DD.PrintNodeTree(const NodePtr: PKDT64DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT64DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT64DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT64DD.Vec(const s: SystemString): TKDT64DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT64DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT64DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT64DD.Vec(const v: TKDT64DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT64DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT64DD.Distance(const v1, v2: TKDT64DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT64DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT64DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT64DD.Test;
var
TKDT64DD_Test: TKDT64DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT64DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT64DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT64DD_Test := TKDT64DD.Create;
n.Append('...');
SetLength(TKDT64DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT64DD_Test.TestBuff) - 1 do
for j := 0 to KDT64DD_Axis - 1 do
TKDT64DD_Test.TestBuff[i][j] := i * KDT64DD_Axis + j;
{$IFDEF FPC}
TKDT64DD_Test.BuildKDTreeM(length(TKDT64DD_Test.TestBuff), nil, @TKDT64DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT64DD_Test.BuildKDTreeM(length(TKDT64DD_Test.TestBuff), nil, TKDT64DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT64DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT64DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT64DD_Test.TestBuff) - 1 do
begin
p := TKDT64DD_Test.Search(TKDT64DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT64DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT64DD_Test.TestBuff));
TKDT64DD_Test.Search(TKDT64DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT64DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT64DD_Test.Clear;
{ kMean test }
TKDT64DD_Test.BuildKDTreeWithCluster(TKDT64DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT64DD_Test.Search(TKDT64DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT64DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT64DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT64DD_Test);
DoStatus(n);
n := '';
end;
function TKDT96DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DD_Node;
function SortCompare(const p1, p2: PKDT96DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT96DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT96DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT96DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT96DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT96DD.GetData(const Index: NativeInt): PKDT96DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT96DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT96DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT96DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT96DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT96DD.StoreBuffPtr: PKDT96DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT96DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT96DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT96DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT96DD.BuildKDTreeWithCluster(const inBuff: TKDT96DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT96DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT96DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT96DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT96DD.BuildKDTreeWithCluster(const inBuff: TKDT96DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT96DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DD_BuildCall);
var
TempStoreBuff: TKDT96DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT96DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT96DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT96DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT96DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DD_BuildMethod);
var
TempStoreBuff: TKDT96DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT96DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT96DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT96DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT96DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DD_BuildProc);
var
TempStoreBuff: TKDT96DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT96DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT96DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT96DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT96DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT96DD.Search(const buff: TKDT96DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DD_Node;
var
NearestNeighbour: PKDT96DD_Node;
function FindParentNode(const buffPtr: PKDT96DD_Vec; NodePtr: PKDT96DD_Node): PKDT96DD_Node;
var
Next: PKDT96DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT96DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT96DD_Node; const buffPtr: PKDT96DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT96DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT96DD_Vec; const p1, p2: PKDT96DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT96DD_Vec);
var
i, j: NativeInt;
p, t: PKDT96DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT96DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT96DD_Node(NearestNodes[0]);
end;
end;
function TKDT96DD.Search(const buff: TKDT96DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT96DD.Search(const buff: TKDT96DD_Vec; var SearchedDistanceMin: Double): PKDT96DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT96DD.Search(const buff: TKDT96DD_Vec): PKDT96DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT96DD.SearchToken(const buff: TKDT96DD_Vec): TPascalString;
var
p: PKDT96DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT96DD.Search(const inBuff: TKDT96DD_DynamicVecBuffer; var OutBuff: TKDT96DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT96DD_DynamicVecBuffer;
outBuffPtr: PKDT96DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT96DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT96DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT96DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT96DD.Search(const inBuff: TKDT96DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT96DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT96DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT96DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT96DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT96DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT96DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT96DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT96DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT96DD_Vec)) <> SizeOf(TKDT96DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT96DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT96DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT96DD.PrintNodeTree(const NodePtr: PKDT96DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT96DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT96DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT96DD.Vec(const s: SystemString): TKDT96DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT96DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT96DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT96DD.Vec(const v: TKDT96DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT96DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT96DD.Distance(const v1, v2: TKDT96DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT96DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT96DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT96DD.Test;
var
TKDT96DD_Test: TKDT96DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT96DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT96DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT96DD_Test := TKDT96DD.Create;
n.Append('...');
SetLength(TKDT96DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT96DD_Test.TestBuff) - 1 do
for j := 0 to KDT96DD_Axis - 1 do
TKDT96DD_Test.TestBuff[i][j] := i * KDT96DD_Axis + j;
{$IFDEF FPC}
TKDT96DD_Test.BuildKDTreeM(length(TKDT96DD_Test.TestBuff), nil, @TKDT96DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT96DD_Test.BuildKDTreeM(length(TKDT96DD_Test.TestBuff), nil, TKDT96DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT96DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT96DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT96DD_Test.TestBuff) - 1 do
begin
p := TKDT96DD_Test.Search(TKDT96DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT96DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT96DD_Test.TestBuff));
TKDT96DD_Test.Search(TKDT96DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT96DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT96DD_Test.Clear;
{ kMean test }
TKDT96DD_Test.BuildKDTreeWithCluster(TKDT96DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT96DD_Test.Search(TKDT96DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT96DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT96DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT96DD_Test);
DoStatus(n);
n := '';
end;
function TKDT128DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DD_Node;
function SortCompare(const p1, p2: PKDT128DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT128DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT128DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT128DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT128DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT128DD.GetData(const Index: NativeInt): PKDT128DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT128DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT128DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT128DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT128DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT128DD.StoreBuffPtr: PKDT128DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT128DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT128DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT128DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT128DD.BuildKDTreeWithCluster(const inBuff: TKDT128DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT128DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT128DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT128DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT128DD.BuildKDTreeWithCluster(const inBuff: TKDT128DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT128DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DD_BuildCall);
var
TempStoreBuff: TKDT128DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT128DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT128DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT128DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT128DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DD_BuildMethod);
var
TempStoreBuff: TKDT128DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT128DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT128DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT128DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT128DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DD_BuildProc);
var
TempStoreBuff: TKDT128DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT128DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT128DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT128DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT128DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT128DD.Search(const buff: TKDT128DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DD_Node;
var
NearestNeighbour: PKDT128DD_Node;
function FindParentNode(const buffPtr: PKDT128DD_Vec; NodePtr: PKDT128DD_Node): PKDT128DD_Node;
var
Next: PKDT128DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT128DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT128DD_Node; const buffPtr: PKDT128DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT128DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT128DD_Vec; const p1, p2: PKDT128DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT128DD_Vec);
var
i, j: NativeInt;
p, t: PKDT128DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT128DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT128DD_Node(NearestNodes[0]);
end;
end;
function TKDT128DD.Search(const buff: TKDT128DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT128DD.Search(const buff: TKDT128DD_Vec; var SearchedDistanceMin: Double): PKDT128DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT128DD.Search(const buff: TKDT128DD_Vec): PKDT128DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT128DD.SearchToken(const buff: TKDT128DD_Vec): TPascalString;
var
p: PKDT128DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT128DD.Search(const inBuff: TKDT128DD_DynamicVecBuffer; var OutBuff: TKDT128DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT128DD_DynamicVecBuffer;
outBuffPtr: PKDT128DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT128DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT128DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT128DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT128DD.Search(const inBuff: TKDT128DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT128DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT128DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT128DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT128DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT128DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT128DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT128DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT128DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT128DD_Vec)) <> SizeOf(TKDT128DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT128DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT128DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT128DD.PrintNodeTree(const NodePtr: PKDT128DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT128DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT128DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT128DD.Vec(const s: SystemString): TKDT128DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT128DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT128DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT128DD.Vec(const v: TKDT128DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT128DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT128DD.Distance(const v1, v2: TKDT128DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT128DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT128DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT128DD.Test;
var
TKDT128DD_Test: TKDT128DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT128DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT128DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT128DD_Test := TKDT128DD.Create;
n.Append('...');
SetLength(TKDT128DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT128DD_Test.TestBuff) - 1 do
for j := 0 to KDT128DD_Axis - 1 do
TKDT128DD_Test.TestBuff[i][j] := i * KDT128DD_Axis + j;
{$IFDEF FPC}
TKDT128DD_Test.BuildKDTreeM(length(TKDT128DD_Test.TestBuff), nil, @TKDT128DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT128DD_Test.BuildKDTreeM(length(TKDT128DD_Test.TestBuff), nil, TKDT128DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT128DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT128DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT128DD_Test.TestBuff) - 1 do
begin
p := TKDT128DD_Test.Search(TKDT128DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT128DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT128DD_Test.TestBuff));
TKDT128DD_Test.Search(TKDT128DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT128DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT128DD_Test.Clear;
{ kMean test }
TKDT128DD_Test.BuildKDTreeWithCluster(TKDT128DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT128DD_Test.Search(TKDT128DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT128DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT128DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT128DD_Test);
DoStatus(n);
n := '';
end;
function TKDT156DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DD_Node;
function SortCompare(const p1, p2: PKDT156DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT156DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT156DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT156DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT156DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT156DD.GetData(const Index: NativeInt): PKDT156DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT156DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT156DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT156DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT156DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT156DD.StoreBuffPtr: PKDT156DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT156DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT156DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT156DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT156DD.BuildKDTreeWithCluster(const inBuff: TKDT156DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT156DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT156DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT156DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT156DD.BuildKDTreeWithCluster(const inBuff: TKDT156DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT156DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DD_BuildCall);
var
TempStoreBuff: TKDT156DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT156DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT156DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT156DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT156DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DD_BuildMethod);
var
TempStoreBuff: TKDT156DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT156DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT156DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT156DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT156DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DD_BuildProc);
var
TempStoreBuff: TKDT156DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT156DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT156DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT156DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT156DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT156DD.Search(const buff: TKDT156DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DD_Node;
var
NearestNeighbour: PKDT156DD_Node;
function FindParentNode(const buffPtr: PKDT156DD_Vec; NodePtr: PKDT156DD_Node): PKDT156DD_Node;
var
Next: PKDT156DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT156DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT156DD_Node; const buffPtr: PKDT156DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT156DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT156DD_Vec; const p1, p2: PKDT156DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT156DD_Vec);
var
i, j: NativeInt;
p, t: PKDT156DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT156DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT156DD_Node(NearestNodes[0]);
end;
end;
function TKDT156DD.Search(const buff: TKDT156DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT156DD.Search(const buff: TKDT156DD_Vec; var SearchedDistanceMin: Double): PKDT156DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT156DD.Search(const buff: TKDT156DD_Vec): PKDT156DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT156DD.SearchToken(const buff: TKDT156DD_Vec): TPascalString;
var
p: PKDT156DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT156DD.Search(const inBuff: TKDT156DD_DynamicVecBuffer; var OutBuff: TKDT156DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT156DD_DynamicVecBuffer;
outBuffPtr: PKDT156DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT156DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT156DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT156DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT156DD.Search(const inBuff: TKDT156DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT156DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT156DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT156DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT156DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT156DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT156DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT156DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT156DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT156DD_Vec)) <> SizeOf(TKDT156DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT156DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT156DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT156DD.PrintNodeTree(const NodePtr: PKDT156DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT156DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT156DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT156DD.Vec(const s: SystemString): TKDT156DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT156DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT156DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT156DD.Vec(const v: TKDT156DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT156DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT156DD.Distance(const v1, v2: TKDT156DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT156DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT156DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT156DD.Test;
var
TKDT156DD_Test: TKDT156DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT156DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT156DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT156DD_Test := TKDT156DD.Create;
n.Append('...');
SetLength(TKDT156DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT156DD_Test.TestBuff) - 1 do
for j := 0 to KDT156DD_Axis - 1 do
TKDT156DD_Test.TestBuff[i][j] := i * KDT156DD_Axis + j;
{$IFDEF FPC}
TKDT156DD_Test.BuildKDTreeM(length(TKDT156DD_Test.TestBuff), nil, @TKDT156DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT156DD_Test.BuildKDTreeM(length(TKDT156DD_Test.TestBuff), nil, TKDT156DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT156DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT156DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT156DD_Test.TestBuff) - 1 do
begin
p := TKDT156DD_Test.Search(TKDT156DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT156DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT156DD_Test.TestBuff));
TKDT156DD_Test.Search(TKDT156DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT156DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT156DD_Test.Clear;
{ kMean test }
TKDT156DD_Test.BuildKDTreeWithCluster(TKDT156DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT156DD_Test.Search(TKDT156DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT156DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT156DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT156DD_Test);
DoStatus(n);
n := '';
end;
function TKDT192DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DD_Node;
function SortCompare(const p1, p2: PKDT192DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT192DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT192DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT192DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT192DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT192DD.GetData(const Index: NativeInt): PKDT192DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT192DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT192DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT192DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT192DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT192DD.StoreBuffPtr: PKDT192DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT192DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT192DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT192DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT192DD.BuildKDTreeWithCluster(const inBuff: TKDT192DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT192DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT192DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT192DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT192DD.BuildKDTreeWithCluster(const inBuff: TKDT192DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT192DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DD_BuildCall);
var
TempStoreBuff: TKDT192DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT192DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT192DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT192DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT192DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DD_BuildMethod);
var
TempStoreBuff: TKDT192DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT192DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT192DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT192DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT192DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DD_BuildProc);
var
TempStoreBuff: TKDT192DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT192DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT192DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT192DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT192DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT192DD.Search(const buff: TKDT192DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DD_Node;
var
NearestNeighbour: PKDT192DD_Node;
function FindParentNode(const buffPtr: PKDT192DD_Vec; NodePtr: PKDT192DD_Node): PKDT192DD_Node;
var
Next: PKDT192DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT192DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT192DD_Node; const buffPtr: PKDT192DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT192DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT192DD_Vec; const p1, p2: PKDT192DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT192DD_Vec);
var
i, j: NativeInt;
p, t: PKDT192DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT192DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT192DD_Node(NearestNodes[0]);
end;
end;
function TKDT192DD.Search(const buff: TKDT192DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT192DD.Search(const buff: TKDT192DD_Vec; var SearchedDistanceMin: Double): PKDT192DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT192DD.Search(const buff: TKDT192DD_Vec): PKDT192DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT192DD.SearchToken(const buff: TKDT192DD_Vec): TPascalString;
var
p: PKDT192DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT192DD.Search(const inBuff: TKDT192DD_DynamicVecBuffer; var OutBuff: TKDT192DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT192DD_DynamicVecBuffer;
outBuffPtr: PKDT192DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT192DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT192DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT192DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT192DD.Search(const inBuff: TKDT192DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT192DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT192DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT192DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT192DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT192DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT192DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT192DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT192DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT192DD_Vec)) <> SizeOf(TKDT192DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT192DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT192DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT192DD.PrintNodeTree(const NodePtr: PKDT192DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT192DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT192DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT192DD.Vec(const s: SystemString): TKDT192DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT192DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT192DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT192DD.Vec(const v: TKDT192DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT192DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT192DD.Distance(const v1, v2: TKDT192DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT192DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT192DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT192DD.Test;
var
TKDT192DD_Test: TKDT192DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT192DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT192DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT192DD_Test := TKDT192DD.Create;
n.Append('...');
SetLength(TKDT192DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT192DD_Test.TestBuff) - 1 do
for j := 0 to KDT192DD_Axis - 1 do
TKDT192DD_Test.TestBuff[i][j] := i * KDT192DD_Axis + j;
{$IFDEF FPC}
TKDT192DD_Test.BuildKDTreeM(length(TKDT192DD_Test.TestBuff), nil, @TKDT192DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT192DD_Test.BuildKDTreeM(length(TKDT192DD_Test.TestBuff), nil, TKDT192DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT192DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT192DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT192DD_Test.TestBuff) - 1 do
begin
p := TKDT192DD_Test.Search(TKDT192DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT192DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT192DD_Test.TestBuff));
TKDT192DD_Test.Search(TKDT192DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT192DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT192DD_Test.Clear;
{ kMean test }
TKDT192DD_Test.BuildKDTreeWithCluster(TKDT192DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT192DD_Test.Search(TKDT192DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT192DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT192DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT192DD_Test);
DoStatus(n);
n := '';
end;
function TKDT256DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DD_Node;
function SortCompare(const p1, p2: PKDT256DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT256DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT256DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT256DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT256DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT256DD.GetData(const Index: NativeInt): PKDT256DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT256DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT256DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT256DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT256DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT256DD.StoreBuffPtr: PKDT256DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT256DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT256DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT256DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT256DD.BuildKDTreeWithCluster(const inBuff: TKDT256DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT256DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT256DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT256DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT256DD.BuildKDTreeWithCluster(const inBuff: TKDT256DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT256DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DD_BuildCall);
var
TempStoreBuff: TKDT256DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT256DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT256DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT256DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT256DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DD_BuildMethod);
var
TempStoreBuff: TKDT256DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT256DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT256DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT256DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT256DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DD_BuildProc);
var
TempStoreBuff: TKDT256DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT256DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT256DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT256DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT256DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT256DD.Search(const buff: TKDT256DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DD_Node;
var
NearestNeighbour: PKDT256DD_Node;
function FindParentNode(const buffPtr: PKDT256DD_Vec; NodePtr: PKDT256DD_Node): PKDT256DD_Node;
var
Next: PKDT256DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT256DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT256DD_Node; const buffPtr: PKDT256DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT256DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT256DD_Vec; const p1, p2: PKDT256DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT256DD_Vec);
var
i, j: NativeInt;
p, t: PKDT256DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT256DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT256DD_Node(NearestNodes[0]);
end;
end;
function TKDT256DD.Search(const buff: TKDT256DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT256DD.Search(const buff: TKDT256DD_Vec; var SearchedDistanceMin: Double): PKDT256DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT256DD.Search(const buff: TKDT256DD_Vec): PKDT256DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT256DD.SearchToken(const buff: TKDT256DD_Vec): TPascalString;
var
p: PKDT256DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT256DD.Search(const inBuff: TKDT256DD_DynamicVecBuffer; var OutBuff: TKDT256DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT256DD_DynamicVecBuffer;
outBuffPtr: PKDT256DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT256DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT256DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT256DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT256DD.Search(const inBuff: TKDT256DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT256DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT256DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT256DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT256DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT256DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT256DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT256DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT256DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT256DD_Vec)) <> SizeOf(TKDT256DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT256DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT256DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT256DD.PrintNodeTree(const NodePtr: PKDT256DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT256DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT256DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT256DD.Vec(const s: SystemString): TKDT256DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT256DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT256DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT256DD.Vec(const v: TKDT256DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT256DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT256DD.Distance(const v1, v2: TKDT256DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT256DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT256DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT256DD.Test;
var
TKDT256DD_Test: TKDT256DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT256DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT256DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT256DD_Test := TKDT256DD.Create;
n.Append('...');
SetLength(TKDT256DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT256DD_Test.TestBuff) - 1 do
for j := 0 to KDT256DD_Axis - 1 do
TKDT256DD_Test.TestBuff[i][j] := i * KDT256DD_Axis + j;
{$IFDEF FPC}
TKDT256DD_Test.BuildKDTreeM(length(TKDT256DD_Test.TestBuff), nil, @TKDT256DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT256DD_Test.BuildKDTreeM(length(TKDT256DD_Test.TestBuff), nil, TKDT256DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT256DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT256DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT256DD_Test.TestBuff) - 1 do
begin
p := TKDT256DD_Test.Search(TKDT256DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT256DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT256DD_Test.TestBuff));
TKDT256DD_Test.Search(TKDT256DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT256DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT256DD_Test.Clear;
{ kMean test }
TKDT256DD_Test.BuildKDTreeWithCluster(TKDT256DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT256DD_Test.Search(TKDT256DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT256DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT256DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT256DD_Test);
DoStatus(n);
n := '';
end;
function TKDT384DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DD_Node;
function SortCompare(const p1, p2: PKDT384DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT384DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT384DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT384DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT384DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT384DD.GetData(const Index: NativeInt): PKDT384DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT384DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT384DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT384DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT384DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT384DD.StoreBuffPtr: PKDT384DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT384DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT384DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT384DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT384DD.BuildKDTreeWithCluster(const inBuff: TKDT384DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT384DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT384DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT384DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT384DD.BuildKDTreeWithCluster(const inBuff: TKDT384DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT384DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DD_BuildCall);
var
TempStoreBuff: TKDT384DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT384DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT384DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT384DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT384DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DD_BuildMethod);
var
TempStoreBuff: TKDT384DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT384DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT384DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT384DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT384DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DD_BuildProc);
var
TempStoreBuff: TKDT384DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT384DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT384DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT384DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT384DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT384DD.Search(const buff: TKDT384DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DD_Node;
var
NearestNeighbour: PKDT384DD_Node;
function FindParentNode(const buffPtr: PKDT384DD_Vec; NodePtr: PKDT384DD_Node): PKDT384DD_Node;
var
Next: PKDT384DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT384DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT384DD_Node; const buffPtr: PKDT384DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT384DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT384DD_Vec; const p1, p2: PKDT384DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT384DD_Vec);
var
i, j: NativeInt;
p, t: PKDT384DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT384DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT384DD_Node(NearestNodes[0]);
end;
end;
function TKDT384DD.Search(const buff: TKDT384DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT384DD.Search(const buff: TKDT384DD_Vec; var SearchedDistanceMin: Double): PKDT384DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT384DD.Search(const buff: TKDT384DD_Vec): PKDT384DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT384DD.SearchToken(const buff: TKDT384DD_Vec): TPascalString;
var
p: PKDT384DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT384DD.Search(const inBuff: TKDT384DD_DynamicVecBuffer; var OutBuff: TKDT384DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT384DD_DynamicVecBuffer;
outBuffPtr: PKDT384DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT384DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT384DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT384DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT384DD.Search(const inBuff: TKDT384DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT384DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT384DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT384DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT384DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT384DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT384DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT384DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT384DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT384DD_Vec)) <> SizeOf(TKDT384DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT384DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT384DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT384DD.PrintNodeTree(const NodePtr: PKDT384DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT384DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT384DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT384DD.Vec(const s: SystemString): TKDT384DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT384DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT384DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT384DD.Vec(const v: TKDT384DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT384DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT384DD.Distance(const v1, v2: TKDT384DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT384DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT384DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT384DD.Test;
var
TKDT384DD_Test: TKDT384DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT384DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT384DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT384DD_Test := TKDT384DD.Create;
n.Append('...');
SetLength(TKDT384DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT384DD_Test.TestBuff) - 1 do
for j := 0 to KDT384DD_Axis - 1 do
TKDT384DD_Test.TestBuff[i][j] := i * KDT384DD_Axis + j;
{$IFDEF FPC}
TKDT384DD_Test.BuildKDTreeM(length(TKDT384DD_Test.TestBuff), nil, @TKDT384DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT384DD_Test.BuildKDTreeM(length(TKDT384DD_Test.TestBuff), nil, TKDT384DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT384DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT384DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT384DD_Test.TestBuff) - 1 do
begin
p := TKDT384DD_Test.Search(TKDT384DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT384DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT384DD_Test.TestBuff));
TKDT384DD_Test.Search(TKDT384DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT384DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT384DD_Test.Clear;
{ kMean test }
TKDT384DD_Test.BuildKDTreeWithCluster(TKDT384DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT384DD_Test.Search(TKDT384DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT384DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT384DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT384DD_Test);
DoStatus(n);
n := '';
end;
function TKDT512DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DD_Node;
function SortCompare(const p1, p2: PKDT512DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT512DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT512DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT512DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT512DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT512DD.GetData(const Index: NativeInt): PKDT512DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT512DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT512DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT512DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT512DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT512DD.StoreBuffPtr: PKDT512DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT512DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT512DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT512DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT512DD.BuildKDTreeWithCluster(const inBuff: TKDT512DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT512DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT512DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT512DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT512DD.BuildKDTreeWithCluster(const inBuff: TKDT512DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT512DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DD_BuildCall);
var
TempStoreBuff: TKDT512DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT512DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT512DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT512DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT512DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DD_BuildMethod);
var
TempStoreBuff: TKDT512DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT512DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT512DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT512DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT512DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DD_BuildProc);
var
TempStoreBuff: TKDT512DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT512DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT512DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT512DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT512DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT512DD.Search(const buff: TKDT512DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DD_Node;
var
NearestNeighbour: PKDT512DD_Node;
function FindParentNode(const buffPtr: PKDT512DD_Vec; NodePtr: PKDT512DD_Node): PKDT512DD_Node;
var
Next: PKDT512DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT512DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT512DD_Node; const buffPtr: PKDT512DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT512DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT512DD_Vec; const p1, p2: PKDT512DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT512DD_Vec);
var
i, j: NativeInt;
p, t: PKDT512DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT512DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT512DD_Node(NearestNodes[0]);
end;
end;
function TKDT512DD.Search(const buff: TKDT512DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT512DD.Search(const buff: TKDT512DD_Vec; var SearchedDistanceMin: Double): PKDT512DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT512DD.Search(const buff: TKDT512DD_Vec): PKDT512DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT512DD.SearchToken(const buff: TKDT512DD_Vec): TPascalString;
var
p: PKDT512DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT512DD.Search(const inBuff: TKDT512DD_DynamicVecBuffer; var OutBuff: TKDT512DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT512DD_DynamicVecBuffer;
outBuffPtr: PKDT512DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT512DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT512DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT512DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT512DD.Search(const inBuff: TKDT512DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT512DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT512DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT512DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT512DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT512DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT512DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT512DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT512DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT512DD_Vec)) <> SizeOf(TKDT512DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT512DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT512DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT512DD.PrintNodeTree(const NodePtr: PKDT512DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT512DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT512DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT512DD.Vec(const s: SystemString): TKDT512DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT512DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT512DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT512DD.Vec(const v: TKDT512DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT512DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT512DD.Distance(const v1, v2: TKDT512DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT512DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT512DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT512DD.Test;
var
TKDT512DD_Test: TKDT512DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT512DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT512DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT512DD_Test := TKDT512DD.Create;
n.Append('...');
SetLength(TKDT512DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT512DD_Test.TestBuff) - 1 do
for j := 0 to KDT512DD_Axis - 1 do
TKDT512DD_Test.TestBuff[i][j] := i * KDT512DD_Axis + j;
{$IFDEF FPC}
TKDT512DD_Test.BuildKDTreeM(length(TKDT512DD_Test.TestBuff), nil, @TKDT512DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT512DD_Test.BuildKDTreeM(length(TKDT512DD_Test.TestBuff), nil, TKDT512DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT512DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT512DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT512DD_Test.TestBuff) - 1 do
begin
p := TKDT512DD_Test.Search(TKDT512DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT512DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT512DD_Test.TestBuff));
TKDT512DD_Test.Search(TKDT512DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT512DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT512DD_Test.Clear;
{ kMean test }
TKDT512DD_Test.BuildKDTreeWithCluster(TKDT512DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT512DD_Test.Search(TKDT512DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT512DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT512DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT512DD_Test);
DoStatus(n);
n := '';
end;
function TKDT800DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DD_Node;
function SortCompare(const p1, p2: PKDT800DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT800DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT800DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT800DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT800DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT800DD.GetData(const Index: NativeInt): PKDT800DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT800DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT800DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT800DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT800DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT800DD.StoreBuffPtr: PKDT800DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT800DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT800DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT800DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT800DD.BuildKDTreeWithCluster(const inBuff: TKDT800DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT800DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT800DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT800DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT800DD.BuildKDTreeWithCluster(const inBuff: TKDT800DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT800DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DD_BuildCall);
var
TempStoreBuff: TKDT800DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT800DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT800DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT800DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT800DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DD_BuildMethod);
var
TempStoreBuff: TKDT800DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT800DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT800DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT800DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT800DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DD_BuildProc);
var
TempStoreBuff: TKDT800DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT800DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT800DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT800DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT800DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT800DD.Search(const buff: TKDT800DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DD_Node;
var
NearestNeighbour: PKDT800DD_Node;
function FindParentNode(const buffPtr: PKDT800DD_Vec; NodePtr: PKDT800DD_Node): PKDT800DD_Node;
var
Next: PKDT800DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT800DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT800DD_Node; const buffPtr: PKDT800DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT800DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT800DD_Vec; const p1, p2: PKDT800DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT800DD_Vec);
var
i, j: NativeInt;
p, t: PKDT800DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT800DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT800DD_Node(NearestNodes[0]);
end;
end;
function TKDT800DD.Search(const buff: TKDT800DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT800DD.Search(const buff: TKDT800DD_Vec; var SearchedDistanceMin: Double): PKDT800DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT800DD.Search(const buff: TKDT800DD_Vec): PKDT800DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT800DD.SearchToken(const buff: TKDT800DD_Vec): TPascalString;
var
p: PKDT800DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT800DD.Search(const inBuff: TKDT800DD_DynamicVecBuffer; var OutBuff: TKDT800DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT800DD_DynamicVecBuffer;
outBuffPtr: PKDT800DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT800DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT800DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT800DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT800DD.Search(const inBuff: TKDT800DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT800DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT800DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT800DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT800DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT800DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT800DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT800DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT800DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT800DD_Vec)) <> SizeOf(TKDT800DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT800DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT800DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT800DD.PrintNodeTree(const NodePtr: PKDT800DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT800DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT800DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT800DD.Vec(const s: SystemString): TKDT800DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT800DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT800DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT800DD.Vec(const v: TKDT800DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT800DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT800DD.Distance(const v1, v2: TKDT800DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT800DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT800DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT800DD.Test;
var
TKDT800DD_Test: TKDT800DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT800DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT800DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT800DD_Test := TKDT800DD.Create;
n.Append('...');
SetLength(TKDT800DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT800DD_Test.TestBuff) - 1 do
for j := 0 to KDT800DD_Axis - 1 do
TKDT800DD_Test.TestBuff[i][j] := i * KDT800DD_Axis + j;
{$IFDEF FPC}
TKDT800DD_Test.BuildKDTreeM(length(TKDT800DD_Test.TestBuff), nil, @TKDT800DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT800DD_Test.BuildKDTreeM(length(TKDT800DD_Test.TestBuff), nil, TKDT800DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT800DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT800DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT800DD_Test.TestBuff) - 1 do
begin
p := TKDT800DD_Test.Search(TKDT800DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT800DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT800DD_Test.TestBuff));
TKDT800DD_Test.Search(TKDT800DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT800DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT800DD_Test.Clear;
{ kMean test }
TKDT800DD_Test.BuildKDTreeWithCluster(TKDT800DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT800DD_Test.Search(TKDT800DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT800DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT800DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT800DD_Test);
DoStatus(n);
n := '';
end;
function TKDT1024DD.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DD_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DD_Node;
function SortCompare(const p1, p2: PKDT1024DD_Source; const axis: NativeInt): ShortInt;
begin
if p1^.buff[axis] = p2^.buff[axis] then
begin
if p1^.Index = p2^.Index then
Result := 0
else if p1^.Index < p2^.Index then
Result := -1
else
Result := 1;
end
else if p1^.buff[axis] < p2^.buff[axis] then
Result := -1
else
Result := 1;
end;
procedure InternalSort(const SortBuffer: PKDT1024DD_SourceBuffer; L, R: NativeInt; const axis: NativeInt);
var
i, j: NativeInt;
p, t: PKDT1024DD_Source;
begin
repeat
i := L;
j := R;
p := SortBuffer^[(L + R) shr 1];
repeat
while SortCompare(SortBuffer^[i], p, axis) < 0 do
Inc(i);
while SortCompare(SortBuffer^[j], p, axis) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer^[i];
SortBuffer^[i] := SortBuffer^[j];
SortBuffer^[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, axis);
L := i;
until i >= R;
end;
var
M: NativeInt;
axis: NativeInt;
kdBuffPtr: PKDT1024DD_SourceBuffer;
begin
Result := nil;
if PlanCount = 0 then
Exit;
if PlanCount = 1 then
begin
new(Result);
Result^.Parent := nil;
Result^.Right := nil;
Result^.Left := nil;
Result^.Vec := KDSourceBufferPtr^[0];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
end
else
begin
axis := Depth mod KDT1024DD_Axis;
M := PlanCount div 2;
kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer));
CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer));
if PlanCount > 1 then
InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis);
new(Result);
Result^.Parent := nil;
Result^.Vec := kdBuffPtr^[M];
KDNodes[NodeCounter] := Result;
Inc(NodeCounter);
Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1);
if Result^.Left <> nil then
Result^.Left^.Parent := Result;
Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1);
if Result^.Right <> nil then
Result^.Right^.Parent := Result;
FreeMemory(kdBuffPtr);
end;
end;
function TKDT1024DD.GetData(const Index: NativeInt): PKDT1024DD_Source;
begin
Result := @KDStoreBuff[Index];
end;
constructor TKDT1024DD.Create;
begin
inherited Create;
NodeCounter := 0;
RootNode := nil;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
Clear;
end;
destructor TKDT1024DD.Destroy;
begin
Clear;
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
inherited Destroy;
end;
procedure TKDT1024DD.Clear;
var
i: NativeInt;
begin
i := 0;
while i < length(KDNodes) do
begin
Dispose(PKDT1024DD_Node(KDNodes[i]));
Inc(i);
end;
for i := 0 to length(KDStoreBuff) - 1 do
KDStoreBuff[i].Token := '';
SetLength(KDNodes, 0);
SetLength(KDStoreBuff, 0);
SetLength(KDBuff, 0);
NodeCounter := 0;
RootNode := nil;
end;
function TKDT1024DD.StoreBuffPtr: PKDT1024DD_DyanmicStoreBuffer;
begin
Result := @KDStoreBuff;
end;
procedure TKDT1024DD.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildCall);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1024DD.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildMethod);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
procedure TKDT1024DD.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildProc);
var
i, j: NativeInt;
begin
Clear;
if PlanCount <= 0 then
Exit;
SetLength(KDStoreBuff, PlanCount);
SetLength(KDBuff, PlanCount);
SetLength(KDNodes, PlanCount);
i := 0;
while i < PlanCount do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec), 0);
OnTrigger(i, KDStoreBuff[i], Data);
Inc(i);
end;
j := PlanCount;
RootNode := InternalBuildKdTree(@KDBuff[0], j, 0);
end;
{ k-means++ clusterization }
procedure TKDT1024DD.BuildKDTreeWithCluster(const inBuff: TKDT1024DD_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray);
var
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
SetLength(Source, length(inBuff), KDT1024DD_Axis);
for i := 0 to length(inBuff) - 1 do
for j := 0 to KDT1024DD_Axis - 1 do
Source[i, j] := inBuff[i, j];
if KMeansCluster(Source, KDT1024DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
SetLength(KArray, 0);
end;
SetLength(Source, 0);
end;
procedure TKDT1024DD.BuildKDTreeWithCluster(const inBuff: TKDT1024DD_DynamicVecBuffer; const k, Restarts: NativeInt);
var
OutIndex: TKMIntegerArray;
begin
BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex);
SetLength(OutIndex, 0);
end;
procedure TKDT1024DD.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildCall);
var
TempStoreBuff: TKDT1024DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1024DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1024DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1024DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1024DD.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildMethod);
var
TempStoreBuff: TKDT1024DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1024DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1024DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1024DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
procedure TKDT1024DD.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DD_BuildProc);
var
TempStoreBuff: TKDT1024DD_DyanmicStoreBuffer;
Source: TKMFloat2DArray;
KArray: TKMFloat2DArray;
i, j: NativeInt;
begin
Clear;
SetLength(TempStoreBuff, PlanCount);
i := 0;
while i < PlanCount do
begin
TempStoreBuff[i].Index := i;
TempStoreBuff[i].Token := '';
FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec), 0);
OnTrigger(i, TempStoreBuff[i], Data);
Inc(i);
end;
SetLength(Source, length(TempStoreBuff), KDT1024DD_Axis);
for i := 0 to length(TempStoreBuff) - 1 do
for j := 0 to KDT1024DD_Axis - 1 do
Source[i, j] := TempStoreBuff[i].buff[j];
if KMeansCluster(Source, KDT1024DD_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then
begin
SetLength(KDStoreBuff, k);
SetLength(KDBuff, k);
SetLength(KDNodes, k);
for i := 0 to k - 1 do
begin
KDBuff[i] := @KDStoreBuff[i];
KDStoreBuff[i].Index := i;
KDStoreBuff[i].Token := '';
for j := 0 to KDT1024DD_Axis - 1 do
KDStoreBuff[i].buff[j] := KArray[j, i];
end;
RootNode := InternalBuildKdTree(@KDBuff[0], k, 0);
for i := 0 to length(OutIndex) - 1 do
OutIndex[i] := TempStoreBuff[OutIndex[i]].Index;
SetLength(KArray, 0);
end;
SetLength(TempStoreBuff, 0);
SetLength(Source, 0);
end;
function TKDT1024DD.Search(const buff: TKDT1024DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DD_Node;
var
NearestNeighbour: PKDT1024DD_Node;
function FindParentNode(const buffPtr: PKDT1024DD_Vec; NodePtr: PKDT1024DD_Node): PKDT1024DD_Node;
var
Next: PKDT1024DD_Node;
Depth, axis: NativeInt;
begin
Result := nil;
Depth := 0;
Next := NodePtr;
while Next <> nil do
begin
Result := Next;
axis := Depth mod KDT1024DD_Axis;
if buffPtr^[axis] > Next^.Vec^.buff[axis] then
Next := Next^.Right
else
Next := Next^.Left;
Depth := Depth + 1;
end;
end;
procedure ScanSubtree(const NodePtr: PKDT1024DD_Node; const buffPtr: PKDT1024DD_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList);
var
Dist: Double;
axis: NativeInt;
begin
if NodePtr = nil then
Exit;
Inc(SearchedCounter);
if NearestNodes <> nil then
NearestNodes.Add(NodePtr);
Dist := Distance(buffPtr^, NodePtr^.Vec^.buff);
if Dist < SearchedDistanceMin then
begin
SearchedDistanceMin := Dist;
NearestNeighbour := NodePtr;
end
else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then
NearestNeighbour := NodePtr;
axis := Depth mod KDT1024DD_Axis;
Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis];
if Dist * Dist > SearchedDistanceMin then
begin
if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes)
else
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end
else
begin
ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes);
ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes);
end;
end;
function SortCompare(const buffPtr: PKDT1024DD_Vec; const p1, p2: PKDT1024DD_Node): ShortInt;
var
d1, d2: Double;
begin
d1 := Distance(buffPtr^, p1^.Vec^.buff);
d2 := Distance(buffPtr^, p2^.Vec^.buff);
if d1 = d2 then
begin
if p1^.Vec^.Index = p2^.Vec^.Index then
Result := 0
else if p1^.Vec^.Index < p2^.Vec^.Index then
Result := -1
else
Result := 1;
end
else if d1 < d2 then
Result := -1
else
Result := 1;
end;
procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT1024DD_Vec);
var
i, j: NativeInt;
p, t: PKDT1024DD_Node;
begin
repeat
i := L;
j := R;
p := SortBuffer[(L + R) shr 1];
repeat
while SortCompare(buffPtr, SortBuffer[i], p) < 0 do
Inc(i);
while SortCompare(buffPtr, SortBuffer[j], p) > 0 do
Dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortBuffer[i];
SortBuffer[i] := SortBuffer[j];
SortBuffer[j] := t;
end;
Inc(i);
Dec(j);
end;
until i > j;
if L < j then
InternalSort(SortBuffer, L, j, buffPtr);
L := i;
until i >= R;
end;
var
Parent: PKDT1024DD_Node;
begin
Result := nil;
SearchedDistanceMin := 0;
SearchedCounter := 0;
NearestNeighbour := nil;
if NearestNodes <> nil then
NearestNodes.Clear;
if RootNode = nil then
Exit;
if Count = 0 then
Exit;
Parent := FindParentNode(@buff[0], RootNode);
NearestNeighbour := Parent;
SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff);
ScanSubtree(RootNode, @buff[0], 0, NearestNodes);
if NearestNeighbour = nil then
NearestNeighbour := RootNode;
Result := NearestNeighbour;
if NearestNodes <> nil then
begin
Result := NearestNeighbour;
if NearestNodes.Count > 1 then
InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]);
if NearestNodes.Count > 0 then
Result := PKDT1024DD_Node(NearestNodes[0]);
end;
end;
function TKDT1024DD.Search(const buff: TKDT1024DD_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DD_Node;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil);
end;
function TKDT1024DD.Search(const buff: TKDT1024DD_Vec; var SearchedDistanceMin: Double): PKDT1024DD_Node;
var
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1024DD.Search(const buff: TKDT1024DD_Vec): PKDT1024DD_Node;
var
SearchedDistanceMin: Double;
SearchedCounter: NativeInt;
begin
Result := Search(buff, SearchedDistanceMin, SearchedCounter);
end;
function TKDT1024DD.SearchToken(const buff: TKDT1024DD_Vec): TPascalString;
var
p: PKDT1024DD_Node;
begin
p := Search(buff);
if p <> nil then
Result := p^.Vec^.Token
else
Result := '';
end;
procedure TKDT1024DD.Search(const inBuff: TKDT1024DD_DynamicVecBuffer; var OutBuff: TKDT1024DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1024DD_DynamicVecBuffer;
outBuffPtr: PKDT1024DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1024DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outBuffPtr := @OutBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1024DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outBuffPtr^[pass] := p^.Vec^.buff;
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1024DD_Node;
begin
if length(OutBuff) <> length(OutIndex) then
Exit;
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutBuff[i] := p^.Vec^.buff;
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1024DD.Search(const inBuff: TKDT1024DD_DynamicVecBuffer; var OutIndex: TKMIntegerArray);
{$IFDEF parallel}
var
inBuffPtr: PKDT1024DD_DynamicVecBuffer;
outIndexPtr: PKMIntegerArray;
{$IFDEF FPC}
procedure FPC_ParallelFor(pass: Integer);
var
p: PKDT1024DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end;
{$ENDIF FPC}
begin
if length(inBuff) <> length(OutIndex) then
Exit;
inBuffPtr := @inBuff;
outIndexPtr := @OutIndex;
GlobalMemoryHook.V := False;
try
{$IFDEF FPC}
FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1);
{$ELSE FPC}
DelphiParallelFor(0, length(inBuff) - 1,
procedure(pass: Int64)
var
p: PKDT1024DD_Node;
begin
p := Search(inBuffPtr^[pass]);
outIndexPtr^[pass] := p^.Vec^.Index;
end);
{$ENDIF FPC}
finally
GlobalMemoryHook.V := True;
end;
end;
{$ELSE parallel}
var
i: NativeInt;
p: PKDT1024DD_Node;
begin
if length(inBuff) <> length(OutIndex) then
Exit;
for i := 0 to length(inBuff) - 1 do
begin
p := Search(inBuff[i]);
OutIndex[i] := p^.Vec^.Index;
end;
end;
{$ENDIF parallel}
procedure TKDT1024DD.SaveToStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
cnt := length(KDStoreBuff);
st := SaveToken;
ID := KDT1024DD_Axis;
stream.write(st, 4);
stream.write(ID, 4);
stream.write(cnt, 8);
i := 0;
while i < cnt do
begin
stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec));
stream.write(KDStoreBuff[i].Index, 8);
token_B := KDStoreBuff[i].Token.Bytes;
token_L := length(token_B);
stream.write(token_L, 4);
if token_L > 0 then
begin
stream.write(token_B[0], token_L);
SetLength(token_B, 0);
end;
Inc(i);
end;
end;
procedure TKDT1024DD.LoadFromStream(stream: TCoreClassStream);
var
cnt: Int64;
st, ID: Integer;
i: NativeInt;
token_B: TBytes;
token_L: Integer;
begin
Clear;
stream.read(st, 4);
stream.read(ID, 4);
if st <> SaveToken then
RaiseInfo('kdtree token error!');
if ID <> KDT1024DD_Axis then
RaiseInfo('kdtree axis error!');
stream.read(cnt, 8);
SetLength(KDStoreBuff, cnt);
i := 0;
try
while i < cnt do
begin
if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT1024DD_Vec)) <> SizeOf(TKDT1024DD_Vec) then
begin
Clear;
Exit;
end;
if stream.read(KDStoreBuff[i].Index, 8) <> 8 then
begin
Clear;
Exit;
end;
if stream.read(token_L, 4) <> 4 then
begin
Clear;
Exit;
end;
if token_L > 0 then
begin
SetLength(token_B, token_L);
if stream.read(token_B[0], token_L) <> token_L then
begin
Clear;
Exit;
end;
KDStoreBuff[i].Token.Bytes := token_B;
SetLength(token_B, 0);
end
else
KDStoreBuff[i].Token := '';
Inc(i);
end;
except
Clear;
Exit;
end;
SetLength(KDBuff, cnt);
SetLength(KDNodes, cnt);
i := 0;
while i < cnt do
begin
KDBuff[i] := @KDStoreBuff[i];
Inc(i);
end;
if cnt > 0 then
RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0);
end;
procedure TKDT1024DD.SaveToFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
fs := TCoreClassFileStream.Create(FileName, fmCreate);
try
SaveToStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1024DD.LoadFromFile(FileName: SystemString);
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
LoadFromStream(fs);
finally
DisposeObject(fs);
end;
end;
procedure TKDT1024DD.PrintNodeTree(const NodePtr: PKDT1024DD_Node);
procedure DoPrintNode(prefix: SystemString; const p: PKDT1024DD_Node);
begin
DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]);
if p^.Left <> nil then
DoPrintNode(prefix + ' |-----', p^.Left);
if p^.Right <> nil then
DoPrintNode(prefix + ' |-----', p^.Right);
end;
begin
DoPrintNode('', NodePtr);
end;
procedure TKDT1024DD.PrintBuffer;
var
i: NativeInt;
begin
for i := 0 to length(KDStoreBuff) - 1 do
DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]);
end;
class function TKDT1024DD.Vec(const s: SystemString): TKDT1024DD_Vec;
var
t: TTextParsing;
SplitOutput: TArrayPascalString;
i, j: NativeInt;
begin
for i := 0 to KDT1024DD_Axis - 1 do
Result[i] := 0;
t := TTextParsing.Create(s, tsText, nil);
if t.SplitChar(1, ', ', '', SplitOutput) > 0 then
begin
j := 0;
for i := 0 to length(SplitOutput) - 1 do
if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then
begin
Result[j] := umlStrToFloat(SplitOutput[i], 0);
Inc(j);
if j >= KDT1024DD_Axis then
Break;
end;
end;
DisposeObject(t);
end;
class function TKDT1024DD.Vec(const v: TKDT1024DD_Vec): SystemString;
var
i: NativeInt;
begin
Result := '';
for i := 0 to KDT1024DD_Axis - 1 do
begin
if i > 0 then
Result := Result + ',';
Result := Result + umlFloatToStr(v[i]);
end;
end;
class function TKDT1024DD.Distance(const v1, v2: TKDT1024DD_Vec): Double;
var
i: NativeInt;
begin
Result := 0;
for i := 0 to KDT1024DD_Axis - 1 do
Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]);
end;
procedure TKDT1024DD.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DD_Source; const Data: Pointer);
begin
Source.buff := TestBuff[IndexFor];
Source.Token := umlIntToStr(IndexFor);
end;
class procedure TKDT1024DD.Test;
var
TKDT1024DD_Test: TKDT1024DD;
t: TTimeTick;
i, j: NativeInt;
TestResultBuff: TKDT1024DD_DynamicVecBuffer;
TestResultIndex: TKMIntegerArray;
KMeanOutIndex: TKMIntegerArray;
errored: Boolean;
m64: TMemoryStream64;
p: PKDT1024DD_Node;
n: TPascalString;
begin
errored := False;
n := PFormat('test %s...', [ClassName]);
t := GetTimeTick;
n.Append('...build');
TKDT1024DD_Test := TKDT1024DD.Create;
n.Append('...');
SetLength(TKDT1024DD_Test.TestBuff, 1000);
for i := 0 to length(TKDT1024DD_Test.TestBuff) - 1 do
for j := 0 to KDT1024DD_Axis - 1 do
TKDT1024DD_Test.TestBuff[i][j] := i * KDT1024DD_Axis + j;
{$IFDEF FPC}
TKDT1024DD_Test.BuildKDTreeM(length(TKDT1024DD_Test.TestBuff), nil, @TKDT1024DD_Test.Test_BuildM);
{$ELSE FPC}
TKDT1024DD_Test.BuildKDTreeM(length(TKDT1024DD_Test.TestBuff), nil, TKDT1024DD_Test.Test_BuildM);
{$ENDIF FPC}
{ save/load test }
n.Append('...save/load');
m64 := TMemoryStream64.CustomCreate(1024 * 1024);
TKDT1024DD_Test.SaveToStream(m64);
m64.Position := 0;
TKDT1024DD_Test.LoadFromStream(m64);
for i := 0 to length(TKDT1024DD_Test.TestBuff) - 1 do
begin
p := TKDT1024DD_Test.Search(TKDT1024DD_Test.TestBuff[i]);
if p^.Vec^.Index <> i then
errored := True;
if not p^.Vec^.Token.Same(umlIntToStr(i)) then
errored := True;
if errored then
Break;
end;
DisposeObject(m64);
if not errored then
begin
{ parallel search test }
n.Append('...parallel');
SetLength(TestResultBuff, length(TKDT1024DD_Test.TestBuff));
SetLength(TestResultIndex, length(TKDT1024DD_Test.TestBuff));
TKDT1024DD_Test.Search(TKDT1024DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if Distance(TKDT1024DD_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then
errored := True;
end;
if not errored then
begin
n.Append('...kMean');
TKDT1024DD_Test.Clear;
{ kMean test }
TKDT1024DD_Test.BuildKDTreeWithCluster(TKDT1024DD_Test.TestBuff, 10, 1, KMeanOutIndex);
{ parallel search test }
TKDT1024DD_Test.Search(TKDT1024DD_Test.TestBuff, TestResultBuff, TestResultIndex);
for i := 0 to length(TestResultIndex) - 1 do
if TestResultIndex[i] <> KMeanOutIndex[i] then
errored := True;
end;
SetLength(TKDT1024DD_Test.TestBuff, 0);
SetLength(TestResultBuff, 0);
SetLength(TestResultIndex, 0);
SetLength(KMeanOutIndex, 0);
TKDT1024DD_Test.Clear;
n.Append('...');
if errored then
n.Append('error!')
else
n.Append('passed ok %dms', [GetTimeTick - t]);
DisposeObject(TKDT1024DD_Test);
DoStatus(n);
n := '';
end;
procedure Test_All;
begin
TKDT1DD.Test();
TKDT2DD.Test();
TKDT3DD.Test();
TKDT4DD.Test();
TKDT5DD.Test();
TKDT6DD.Test();
TKDT7DD.Test();
TKDT8DD.Test();
TKDT9DD.Test();
TKDT10DD.Test();
TKDT11DD.Test();
TKDT12DD.Test();
TKDT13DD.Test();
TKDT14DD.Test();
TKDT15DD.Test();
TKDT16DD.Test();
TKDT17DD.Test();
TKDT18DD.Test();
TKDT19DD.Test();
TKDT20DD.Test();
TKDT21DD.Test();
TKDT22DD.Test();
TKDT23DD.Test();
TKDT24DD.Test();
TKDT48DD.Test();
TKDT52DD.Test();
TKDT64DD.Test();
TKDT96DD.Test();
TKDT128DD.Test();
TKDT156DD.Test();
TKDT192DD.Test();
TKDT256DD.Test();
TKDT384DD.Test();
TKDT512DD.Test();
TKDT800DD.Test();
TKDT1024DD.Test();
end;
initialization
finalization
end.
|
unit gameobject;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, renderobject, math;
type
TGameObject=class(TRenderobject)
{
Render object with game mechanics like hitboxes and
}
private
fRange: single;
fRenderCollision: boolean;
function getRange: single;
protected
// procedure renderRelative; override;
public
function checkCollision(other: TGameObject):boolean; virtual;
property range: single read getRange;
property renderCollision: boolean read fRenderCollision write fRenderCollision;
end;
implementation
{
procedure TGameObject.renderRelative;
begin
inherited renderRelative;
if fRenderCollision then
begin
//todo: render collision box/sphere
end;
end; }
function TGameObject.getRange: single;
begin
if fRange=0 then
frange:=(width+height)/4; //just an average
result:=frange;
end;
function TGameObject.checkCollision(other: TGameObject):boolean;
//only circle ranges are handled atm. So don't use very rectangular objects
//todo: Add rectangular support, including rotated rectangles
//todo2: polygon collision
//honestly though, everyone is free to add this, I only need this basic stuff for the tutorial
var
range_other: single;
range_self: single;
distance: single;
begin
range_other:=other.range;
range_self:=range;
distance:=sqrt(sqr(abs(other.x-x))+sqr(abs(other.y-y)));
result:=distance<(range_other+range_self);
end;
end.
|
{***************************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2000-2001 Borland Software Corporation }
{ }
{***************************************************************}
unit WSDLPub;
interface
uses InvokeRegistry, Classes, HTTPApp, AutoDisp, Masks, Types;
type
IWSDLPublish = interface(IInvokable)
['{ECD820DD-F242-11D4-928A-00C04F990435}']
procedure GetPortTypeList(var PortTypes: TWideStringDynArray); stdcall;
function GetWSDLForPortType(PortType: WideString): WideString; stdcall;
procedure GetTypeSystemsList(TypeSystems: TWideStringDynArray); stdcall;
function GetXSDForTypeSystem(TypeSystem: WideString): WideString; stdcall;
end;
TWSDLPublish = class(TInvokableClass, IWSDLPublish)
private
Locations: array of WideString;
PortNames: array of WideString;
public
procedure GetPortTypeEntries(var Entries: TInvRegIntfEntryArray);
{ IWSDLPublish }
procedure GetPortTypeList(var PortTypes: TWideStringDynArray); stdcall;
procedure GetTypeSystemsList(TypeSystems: TWideStringDynArray); stdcall;
function GetWSDLForPortType(PortType: WideString): WideString; stdcall;
function GetXSDForTypeSystem(TypeSystem: WideString): WideString; stdcall;
end;
TWSDLHTMLPublish = class(TComponent, IWebDispatch)
private
Pub: TWSDLPublish;
FWebDispatch: TWebDispatch;
FAdminEnabled: Boolean;
procedure SetWebDispatch(const Value: TWebDispatch);
protected
procedure AddInterfaceList(htmldoc: TStringList; const WSDLBaseURL: String);
procedure AddPortList(htmldoc: TStringList; const PortType: String);
procedure UpdatePortList(PortList: TStrings; const PortType, Command: String);
function GetHostScriptBaseURL(Request: TWebRequest): String;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ IWebDispatch }
function DispatchEnabled: Boolean;
function DispatchMask: TMask;
function DispatchMethodType: TMethodType;
function DispatchRequest(Sender: TObject; Request: TWebRequest;
Response: TWebResponse): Boolean;
published
property WebDispatch: TWebDispatch read FWebDispatch write SetWebDispatch;
property AdminEnabled: Boolean read FAdminEnabled write FAdminEnabled;
end;
procedure WSDLPubFactory(out obj: TObject);
implementation
uses windows, SysUtils, TypInfo, IntfInfo, XMLSchema, WSDLIntf, WebServExp, WSDLBind,
WSDLItems, WSDLSoap, IniFiles, OPToSoapDomConv, Controls, ActiveX;
{ TWSDLPublish }
const
TableStyle = 'border=1 cellspacing=1 cellpadding=1 style=''border-collapse:collapse;border:none''';
var
AdminIniFile: string;
ModuleName: array[0..255] of char;
resourcestring
sWebServiceListing = 'WebService Listing';
sWebServiceListingAdmin = 'WebService Listing Administrator';
sPortType = 'Port Type';
sNameSpaceURI = 'Namespace URI';
sDocumentation = 'Documentation';
sWSDL = 'WSDL';
sPortName = 'PortName';
sAddress = 'Address';
sInterfaceNotFound = '<HTML><P>Interface %s not found</P></HTML>';
sWSDLPortsforPortType = 'WSDL Ports for PortType';
sWSDLFor = 'WSDL for ';
procedure AddElem(htmldoc: TStringList; const Elem: string);
begin
htmldoc.Add('<td>' + Elem + '</td>');
end;
procedure TWSDLHTMLPublish.AddInterfaceList(htmldoc: TStringList; const WSDLBaseURL: String);
var
I: Integer;
Entries: TInvRegIntfEntryArray;
begin
htmldoc.Add('<table ' + TableStyle + '>');
htmldoc.Add('<tr>');
AddElem(htmldoc, sPortType);
AddElem(htmldoc, sNamespaceURI);
AddElem(htmldoc, sDocumentation);
AddElem(htmldoc, sWSDL);
htmldoc.Add('</tr>');
Pub.GetPortTypeEntries(Entries);
for I := 0 to Length(Entries) - 1 do
with Entries[I] do
begin
htmldoc.Add('<tr>');
AddElem(htmldoc, Name);
AddElem(htmldoc, Namespace);
AddElem(htmldoc, Documentation);
AddElem(htmldoc, '<a href="' + WSDLBaseURL + '/' + Name + '">' + sWSDLFor + Name + '</a>');
htmldoc.Add('</tr>');
end;
htmldoc.Add('</table>');
end;
procedure TWSDLHTMLPublish.AddPortList(htmldoc: TStringList; const PortType: string);
var
I: Integer;
IniFile: TMemIniFile;
PortList: TStringList;
begin
IniFile := TMemIniFile.Create(AdminIniFile);
try
htmldoc.Add('<table ' + TableStyle + '>');
htmldoc.Add('<tr>');
AddElem(htmldoc, sPortName);
AddElem(htmldoc, sAddress);
htmldoc.Add('</tr>');
if IniFile.SectionExists(PortType) then
begin
PortList := TStringList.Create;
try
IniFile.ReadSectionValues(PortType, PortList);
for I := 0 to PortList.Count - 1 do
begin
htmldoc.Add('<tr>');
AddElem(htmldoc, PortList.Names[I]);
AddElem(htmldoc, PortList.Values[PortList.Names[I]]);
htmldoc.Add('</tr>');
end;
finally
PortList.Free;
end;
end;
htmldoc.Add('</table>');
finally
IniFile.Free;
end;
end;
procedure TWSDLHTMLPublish.UpdatePortList(PortList: TStrings; const PortType, Command: String);
var
IniFile: TMemIniFile;
begin
if PortList.Count > 0 then
begin
IniFile := TMemIniFile.Create(AdminIniFile);
try
if PortList.Values['PortName'] <> '' then
if UpperCase(Command) = 'ADD' then
IniFile.WriteString(PortType, PortList.Values[sPortName], PortList.Values[sAddress])
else if UpperCase(Command) = 'REMOVE' then
IniFile.DeleteKey(PortType, PortList.Values[sPortName]);
IniFile.UpdateFile;
finally
IniFile.Free;
end;
end;
end;
function TWSDLHTMLPublish.GetHostScriptBaseURL(Request: TWebRequest): String;
begin
Result := 'http://' + Request.Host + Request.InternalScriptName; { do not localize }
end;
procedure TWSDLPublish.GetPortTypeList(var PortTypes: TWideStringDynArray);
var
I, Count: Integer;
IntfEntry: InvRegIntfEntry;
begin
// use invrg to list all the interfaces registered, add new method if necessary
Count := InvRegistry.GetInterfaceCount;
SetLength(PortTypes, Count);
for I:= 0 to Count -1 do
begin
IntfEntry := InvRegistry.GetInterface(I);
PortTypes[I] := IntfEntry.Name;
end;
end;
procedure TWSDLPublish.GetTypeSystemsList(TypeSystems: TWideStringDynArray);
var
I, Count: Integer;
URIMap: TRemRegEntry;
TypeSystemList: TStringList;
begin
TypeSystemList := TStringList.Create; // can this handle widestrings ?
try
// use xsdclasses to list all the unique URIs registered, add new implementation if necessary
Count := RemClassRegistry.GetURICount;
for I := 0 to Count -1 do
begin
URIMap := RemClassRegistry.GetURIMap(I);
if TypeSystemList.IndexOf(URIMap.URI) = -1 then
TypeSystemList.Add(URIMap.URI)
end;
SetLength(TypeSystems, Count);
for I := 0 to Count -1 do
TypeSystems[I] := TypeSystemList[I];
finally
TypeSystemList.Free;
end;
end;
function TWSDLPublish.GetWSDLForPortType(PortType: WideString): WideString;
var
IID: TGUID;
Info: PTypeInfo;
WSDLDoc: IWSDLDocument;
WebServExp: TWebServExp;
begin
try
// use invrg to get typeinfo for porttype name ( interface name )
// convert to WSDL fragement
InvRegistry.GetInterfaceInfoFromName ('', PortType, Info, IID);
//Need to throw an exception if interface is not registered.
if Info <> nil then
begin
WSDLDoc := TWSDLDocument.Create(nil);
WSDLDoc.Active := True;
WebServExp := TWebServExp.Create;
try
WSDLDoc.Encoding := 'utf-8';
WebServExp.BindingType := btSoap;
WebServExp.WSDLElements := WebServExp.WSDLElements + [weService];
WebServExp.GetWSDLForInterface(Info, WSDLDoc, PortNames, Locations);
WSDLDoc.SaveToXML(Result);
finally
WebServExp.Free;
end;
end;
finally
end;
end;
function TWSDLPublish.GetXSDForTypeSystem(TypeSystem: WideString): WideString;
var
I, Count: Integer;
URIMap: TRemRegEntry;
WebServExp: TWebServExp;
XMLDoc: IXMLSchemaDoc;
begin
// use xsdclasses to get list of all classes registered with same URI and
// create XML schema doc for this.
Count := RemClassRegistry.GetURICount;
for I := 0 to Count -1 do
begin
URIMap := RemClassRegistry.GetURIMap(I);
if TypeSystem = URIMap.URI then
begin
WebServExp := TWebServExp.Create;
try
XMLDoc := NewXmlSchema;
WebServExp.GenerateXMLSchema(XMLDoc, PTypeInfo(URIMap.ClassType.ClassInfo), nil, '');
XMLDoc.SaveToXML(Result);
finally
WebServExp.Free;
end;
end;
end;
end;
procedure WSDLPubFactory(out obj: TObject);
begin
obj := TWSDLPublish.Create;
end;
procedure TWSDLPublish.GetPortTypeEntries(var Entries: TInvRegIntfEntryArray);
var
I, Count: Integer;
// IntfEntry: InvRegIntfEntry;
begin
Count := InvRegistry.GetInterfaceCount;
SetLength(Entries, Count);
for I:= 0 to Count -1 do
begin
Entries[I] := InvRegistry.GetInterface(I);
end;
end;
{ TWSDLHTMLPublish }
constructor TWSDLHTMLPublish.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FWebDispatch := TWebDispatch.Create(Self);
FWebDispatch.PathInfo := 'wsdl*';
FWebDispatch.MethodType := mtAny;
end;
destructor TWSDLHTMLPublish.Destroy;
begin
inherited Destroy;
FWebDispatch.Free;
end;
function TWSDLHTMLPublish.DispatchEnabled: Boolean;
begin
Result := True;
end;
function TWSDLHTMLPublish.DispatchMask: TMask;
begin
Result := FWebDispatch.Mask;
end;
function TWSDLHTMLPublish.DispatchMethodType: TMethodType;
begin
Result := FWebDispatch.MethodType;
end;
function TWSDLHTMLPublish.DispatchRequest(Sender: TObject;
Request: TWebRequest; Response: TWebResponse): Boolean;
var
Resp: TStringList;
Pub: TWSDLPublish;
Path: string;
LastName, PreName: string;
WSDL: string;
WSDLBaseURL: String;
procedure AddAdmin(const URL: string);
begin
Resp.Add('<FORM NAME="admin" METHOD="GET" ACTION=' + '"' + URL + '"' + '>'); { do not localize }
Resp.Add('<INPUT TYPE="SUBMIT" VALUE="Administrator">'); { do not localize }
Resp.Add('</FORM>'); { do not localize }
end;
procedure CreateDefaultEntries;
var
I: Integer;
Entries: TInvRegIntfEntryArray;
IniFile: TMemIniFile;
begin
if not FileExists(AdminIniFile) then
begin
IniFile := TMemIniFile.Create(AdminIniFile);
try
Pub.GetPortTypeEntries(Entries);
for I := 0 to Length(Entries) - 1 do
with Entries[I] do
IniFile.WriteString(Name, Name + 'Port', GetHostScriptBaseURL(Request) + '/soap/' + Name); { do not localize }
IniFile.UpdateFile;
finally
IniFile.Free;
end;
end;
end;
procedure NewServicePortForm;
begin
Resp.Add('<FORM NAME="admin" METHOD="GET" ACTION=' + '"' + { do not localize }
GetHostScriptBaseURL(Request) + Request.InternalPathInfo + '"' + '>');
Resp.Add('<table>'); { do not localize }
Resp.Add('<tr>'); { do not localize }
AddElem(Resp, sPortName);
AddElem(Resp, sAddress);
Resp.Add('</tr>'); { do not localize }
Resp.Add('<tr>'); { do not localize }
AddElem(Resp, '<INPUT TYPE="TEXT" NAME="' + sPortName + '" SIZE="20" VALUE="" MAXLENGTH="4096">'); { do not localize }
AddElem(Resp, '<INPUT TYPE="TEXT" NAME="' + sAddress + '" SIZE="40" VALUE="" MAXLENGTH="4096">'); { do not localize }
Resp.Add('</tr>'); { do not localize }
Resp.Add('</table>'); { do not localize }
Resp.Add('<p>'); { do not localize }
Resp.Add('<INPUT TYPE="SUBMIT" VALUE="Add" NAME="COMMAND">'); { do not localize }
Resp.Add('<INPUT TYPE="SUBMIT" VALUE="Remove" NAME="COMMAND">'); { do not localize }
Resp.Add('</FORM>'); { do not localize }
end;
procedure GetServicePorts(PortType: string);
var
I: Integer;
IniFile: TMemIniFile;
PortList: TStringList;
begin
IniFile := TMemIniFile.Create(AdminIniFile);
try
if IniFile.SectionExists(PortType) then
begin
PortList := TStringList.Create;
try
IniFile.ReadSectionValues(PortType, PortList);
Pub.PortNames := nil;
Pub.Locations := nil;
SetLength(Pub.PortNames, PortList.Count);
SetLength(Pub.Locations, PortList.Count);
for I := 0 to PortList.Count - 1 do
begin
Pub.PortNames[I] := PortList.Names[I];
Pub.Locations[I] := PortList.Values[PortList.Names[I]];
end;
finally
PortList.Free;
end;
end;
finally
IniFile.Free;
end;
end;
begin
Result := False;
try
Path := Request.InternalPathInfo;
LastName := Copy(Path, LastDelimiter('/', Path) + 1, High(Integer));
PreName := Copy(Path, 1, LastDelimiter('/', Path) - 1);
PreName := Copy(PreName, LastDelimiter('/', PreName) + 1, High(Integer));
WSDLBaseURL := GetHostScriptBaseURL(Request) + Path;
Resp := nil;
Pub := nil;
CoInitialize(nil);
try
Resp := TStringList.Create;
Pub := TWSDLPublish.Create;
CreateDefaultEntries;
if LastName = 'wsdl' then { do not localize }
begin
Resp.Add('<html><body>'); { do not localize }
Resp.Add('<title>' + sWebServiceListing + '</title>'); { do not localize }
Resp.Add('<h1>' + sWebServiceListing + '</h1><p>'); { do not localize }
AddInterfaceList(Resp, WSDLBaseURL);
if AdminEnabled then
AddAdmin(WSDLBaseURL + '/' + 'admin'); { do not localize }
Resp.Add('</html></body>');
Response.Content := Resp.Text;
Response.ContentType := 'text/html'; { do not localize }
Result := True;
end
else if LastName = 'admin' then { do not localize }
begin
Resp.Add('<html><body>'); { do not localize }
Resp.Add('<title>' + sWebServiceListingAdmin + '</title>'); { do not localize }
Resp.Add('<h1>' + sWebServiceListingAdmin + '</h1><p>'); { do not localize }
AddInterfaceList(Resp, WSDLBaseURL);
Resp.Add('</html></body>'); { do not localize }
Response.Content := Resp.Text;
Response.ContentType := 'text/html'; { do not localize }
Result := True;
end
else
begin
if PreName = 'wsdl' then { do not localize }
begin
GetServicePorts(LastName);
WSDL := Pub.GetWSDLForPortType(LastName);
if WSDL <> '' then
begin
Response.Content := UTF8Encode(WSDL);
Response.ContentType := 'text/xml'; { do not localize }
Result := True;
end
else
begin
//interface not found...
Response.Content := Format(sInterfaceNotFound, [LastName]);
Response.ContentType := 'text/html'; { do not localize }
Result := True;
end;
end
else if PreName = 'admin' then { do not localize }
begin
UpdatePortList(Request.QueryFields, LastName, Request.QueryFields.Values['COMMAND']); { do not localize }
Resp.Add('<html><body>'); { do not localize }
Resp.Add('<title>' + sWSDLPortsforPortType + ' ' + LastName + '</title>'); { do not localize }
Resp.Add('<h1>' + sWSDLPortsforPortType + ' ' + LastName + '</h1><p>'); { do not localize }
AddPortList(Resp, LastName);
Resp.Add('<p>');
NewServicePortForm; { do not localize }
Resp.Add('</html></body>'); { do not localize }
Response.Content := Resp.Text;
Response.ContentType := 'text/html'; { do not localize }
Result := True;
end;
end;
finally
CoUnInitialize;
Pub.Free;
Resp.Free;
end;
except
Result := False;
end;
end;
procedure TWSDLHTMLPublish.SetWebDispatch(const Value: TWebDispatch);
begin
FWebDispatch.Assign(Value);
end;
initialization
GroupDescendentsWith(TWSDLHTMLPublish, Controls.TControl);
InvRegistry.RegisterInterface(TypeInfo(IWSDLPublish), '', 'Lists all the PortTypes published by this URL');
InvRegistry.RegisterInvokableClass(TWSDLPublish);
GetModuleFileName(HInstance, ModuleName, SizeOf(ModuleName));
AdminIniFile := Copy(ModuleName, 1, StrLen(ModuleName) - Length(ExtractFileExt(ModuleName))) + '_WSDLADMIN.INI'; { do not localize }
end.
|
program commdev;
uses
WinDos, Crt;
{ OOP Communications Device Unit - Written by Mike Fricker, April 96 }
type
pCommObj = ^tCommObj;
tCommObj = object
constructor init;
function detect : Boolean; virtual;
function open(pn, br : Word; pr : Byte) : Boolean; virtual;
procedure close; virtual;
procedure outch(ch : Char); virtual;
function more : Boolean; virtual;
function getch : Char; virtual;
function carrier : Boolean; virtual;
destructor done;
end;
pFossilObj = ^tFossilObj;
tFossilObj = object(tCommObj)
constructor init;
function detect : Boolean; virtual;
function open(pn, br : Word; pr : Byte) : Boolean; virtual;
procedure close; virtual;
procedure outch(ch : Char); virtual;
function more : Boolean; virtual;
function getch : Char; virtual;
function carrier : Boolean; virtual;
end;
pAsynchObj = ^tAsynchObj;
tAsynchObj = object(tCommObj)
constructor init;
function detect : Boolean; virtual;
function open(pn, br : Word; pr : Byte) : Boolean; virtual;
procedure close; virtual;
procedure outch(ch : Char); virtual;
function more : Boolean; virtual;
function getch : Char; virtual;
function carrier : Boolean; virtual;
end;
tBuffer = array[0..64000] of Char;
tComBuffer = record
Active : Boolean;
R_Buffer : ^tBuffer;
R_Head : Word;
R_Tail : Word;
R_Size : Word;
T_Buffer : ^tBuffer;
T_Head : Word;
T_Tail : Word;
T_Size : Word;
UART_Data : Word;
UART_IER : Word;
UART_IIR : Word;
UART_LCR : Word;
UART_MCR : Word;
UART_LSR : Word;
UART_MSR : Word;
OLD_MCR : Byte;
Org_Vector : Pointer;
end;
const
portBase : array[1..4] of Word = ($3F8,$2F8,$3E8,$2E8);
portIRQ : array[1..4] of Byte = ( 4, 3, 4, 3);
var
cport : Word;
commBuf : array[1..4] of tComBuffer;
commTsize, commRsize : Word;
commFossil : pFossilObj;
commAsynch : pAsynchObj;
comm : pCommObj;
{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%[ tCommObj methods ]%%% }
constructor tCommObj.init;
begin
end;
function tCommObj.detect : Boolean;
begin
detect := True;
end;
function tCommObj.open(pn, br : Word; pr : Byte) : Boolean;
begin
open := True;
end;
procedure tCommObj.close;
begin
end;
procedure tCommObj.outch(ch : Char);
begin
end;
function tCommObj.more : Boolean;
begin
more := False;
end;
function tCommObj.getch : Char;
begin
getch := #0;
end;
function tCommObj.carrier : Boolean;
begin
carrier := False;
end;
destructor tCommObj.done;
begin
end;
{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%[ tFossilObj methods ]%%% }
constructor tFossilObj.init;
begin
end;
function tFossilObj.detect : Boolean;
var w : Word;
begin
asm
mov ah,04h
mov dx,00ffh
int 14h
mov w,ax
end;
detect := w = $1954;
end;
function tFossilObj.open(pn, br : Word; pr : Byte) : Boolean;
var w : Word;
begin
open := False;
cport := pn-1;
asm
mov ah,04h
mov dx,cport
int 14h
end;
case br of
300 : br := $40; { 01000000 }
600 : br := $60; { 01100000 }
1200 : br := $80; { 10000000 }
2400 : br := $a0; { 10100000 }
4800 : br := $c0; { 11000000 }
9600 : br := $e0; { 11100000 }
19200 : br := $00; { 00000000 }
38400,
14400,
16800 : br := $20; { 00100000 }
else br := $23;
end;
pr := pr or br; { merge baud bits with parm bits }
asm
mov ah,00h
mov al,pr
mov dx,cport
int 14h
mov w,ax
end;
open := ((w and $10) = $10) or { clear to send }
((w and $20) = $20) or { data set ready }
((w and $40) = $40) or { ring indicator }
((w and $80) = $80); { data carrier detect }
end;
procedure tFossilObj.close; assembler;
asm
mov ax,05h
mov dx,cport
int 14h
end;
procedure tFossilObj.outch(ch : Char);
var b : Byte; i : Integer;
label resend;
begin
b := Byte(ch);
resend:
asm
mov ah,0Bh
mov al,b
mov dx,cport
int 14h
mov i,ax
end;
if i <> $0001 then goto resend;
{ begin
cCheckIt;
if HangUp then Exit else goto Send;
end;}
end;
function tFossilObj.more : Boolean;
var b : Byte;
begin
asm
mov ah,03h
mov dx,cport
int 14h
mov b,ah
end;
more := (b and $01) = $01; { character waiting }
end;
function tFossilObj.getch : Char;
var b : Byte;
begin
asm
mov ah,02h
mov dx,cport
int 14h
mov b,al
end;
getch := Char(b);
end;
function tFossilObj.carrier : Boolean;
var d : Byte;
begin
asm
mov ah,03h
mov dx,cport
int 14h
mov d,al
end;
carrier := (d and $80) = $80;
end;
{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%[ tAsynchObj methods ]%%% }
procedure commISR; interrupt;
const
Ktr : Byte = 0;
IIR : Byte = 0;
begin
for Ktr := 1 to 4 do
begin
with commBuf[Ktr] do
begin
if Active then
begin
iir := Port[UART_IIR];
while not Odd(IIR) do
begin
case (iir shr 1) of
0 : iir := Port[UART_MSR];
1 : if T_Head = T_Tail then Port[UART_IER] := Port[UART_IER] and not 2 else
begin
Port[UART_DATA] := Byte(T_Buffer^[T_Head]);
Inc(T_Head);
if T_Head > T_Size then T_Head := 0;
end;
2 : begin
R_Buffer^[R_Tail] := Char(Port[Uart_Data]);
Inc(R_Tail);
if R_Tail > R_Size then R_Tail := 0;
if R_Tail = R_Head then
begin
Inc(R_Head);
if R_Head > R_Size then R_Head := 0;
end;
end;
3 : iir := Port[UART_LSR];
end;
iir := Port[UART_IIR];
end;
end;
end;
end;
Port[$20] := $20;
end;
constructor tAsynchObj.init;
begin
commTsize := 4096;
commRsize := 4096;
end;
function tAsynchObj.detect : Boolean;
begin
detect := True;
end;
function tAsynchObj.open(pn, br : Word; pr : Byte) : Boolean;
var inUse : Boolean; Ktr, lcr : Byte; divs : Word;
begin
open := False;
divs := 115200 div br;
cport := pn;
if (pn < 1) or (pn > 4) or (commBuf[pn].active) then Exit;
GetMem(commBuf[cport].R_Buffer,commRsize);
commBuf[cport].R_Size := commRsize;
GetMem(commBuf[cport].T_Buffer,commTsize);
commBuf[cport].T_Size := commTsize;
commBuf[cport].UART_DATA := portBase[cport]+0;
commBuf[cport].UART_IER := portBase[cport]+1;
commBuf[cport].UART_IIR := portBase[cport]+2;
commBuf[cport].UART_LCR := portBase[cport]+3;
commBuf[cport].UART_MCR := portBase[cport]+4;
commBuf[cport].UART_LSR := portBase[cport]+5;
commBuf[cport].UART_MSR := portBase[cport]+6;
inUse := False;
for Ktr := 1 to 4 do
if (portIRQ[Ktr] = portIRQ[cport]) and commBuf[Ktr].Active then
inUse := True;
inline($FA);
if not inUse then
begin
Port[$21] := Port[$21] or (1 shl portIRQ[cport]);
GetIntVec(8+portIRQ[cport],commBuf[cport].Org_Vector);
SetIntVec(8+portIRQ[cport],@commISR);
Port[$21] := Port[$21] and not (1 shl portIRQ[cport]);
end;
commBuf[cport].Old_MCR := Port[commBuf[cport].UART_MCR];
Port[commBuf[cport].UART_LCR] := 3;
Port[commBuf[cport].UART_IER] := 1;
commBuf[cport].Active := True;
Port [commBuf[cport].uart_lcr ] := Port[commBuf[cport].uart_lcr] or $80;
Portw[commBuf[cport].uart_Data] := divs;
Port [commBuf[cport].uart_lcr] := Port[commBuf[cport].uart_lcr] and not $80;
lcr:= $00 or $03;
{ case upcase(Parity) Of
'N': lcr:= $00 or $03;
'E': lcr:= $18 or $02;
'O': lcr:= $08 Or $02;
'S': lcr:= $38 Or $02;
'M': lcr:= $28 OR $02;
Else}
{ End;}
{ If StopBits = 2 Then lcr:= Lcr OR $04;}
Port[commBuf[cport].Uart_lcr] := Port[commBuf[cport].uart_lcr] and $40 or lcr;
Port[commBuf[cport].Uart_MCR] := 11;
inline($FB);
open := True;
end;
procedure tAsynchObj.close;
var inUse : Boolean; Ktr : byte;
begin
inUse := False;
for Ktr := 1 to 4 do
if (portIRQ[Ktr] = portIRQ[cport]) and commBuf[Ktr].Active then
inUse := True;
inline($FA);
Port[commBuf[cport].UART_MCR] := commBuf[cport].Old_MCR;
Port[commBuf[cport].UART_IER] := 0;
if not inUse then
begin
Port[$21] := Port[$21] or ($01 shr portIRQ[cport]);
SetIntVec(8+portIRQ[cport],commBuf[cport].Org_Vector);
end;
inline($FB);
cport := 0;
Freemem(commBuf[cport].R_Buffer,commBuf[cport].R_Size);
Freemem(commBuf[cport].T_Buffer,commBuf[cport].T_Size);
commBuf[cport].Active := False;
end;
procedure tAsynchObj.outch(ch : Char);
begin
with commBuf[cport] do
begin
T_Buffer^[T_Tail] := ch;
Inc(T_Tail);
if T_Tail > T_Size then T_Tail := 0;
if T_Tail = T_Head then
begin
Inc(T_Head);
if T_Head > T_Size then T_Head := 0;
end;
inline($FA);
Port[UART_IER] := Port[UART_IER] or 2;
inline($FB);
end;
end;
function tAsynchObj.more : Boolean;
begin
more := commBuf[cport].R_Head <> commBuf[cport].R_Tail;
end;
function tAsynchObj.getch : Char;
begin
getch := #0;
with commBuf[cport] do
begin
if R_Head = R_Tail then getch := #0 else
begin
getch := R_Buffer^[R_Head];
Inc(R_Head);
if R_Head > R_Size then R_Head := 0;
end;
end;
end;
function tAsynchObj.carrier : Boolean;
begin
carrier := Port[commBuf[cport].UART_MSR] and $80 > 0;
end;
{ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% }
var done : Boolean; c : Char; z : Byte;
begin
for z := 1 to 4 do
begin
commBuf[z].Active := False;
commBuf[z].R_Buffer := nil;
commBuf[z].R_Head := 0;
commBuf[z].R_Tail := 0;
commBuf[z].R_Size := 0;
commBuf[z].T_Buffer := nil;
commBuf[z].T_Head := 0;
commBuf[z].T_Tail := 0;
commBuf[z].T_Size := 0;
end;
New(commAsynch,init);
comm := commAsynch;
clrscr;
if not comm^.detect then Halt;
if not comm^.open(2,19200,$03) then Halt;
if comm^.carrier then WriteLn('carrier detected.') else WriteLn('loaded.');
done := False;
repeat
if keypressed then
begin
c := readkey;
if c = #27 then done := True else
comm^.outch(c);
end;
while comm^.more do Write(comm^.getch);
until done;
comm^.close;
Dispose(commAsynch,done);
end.
|
unit ASN1.TestCase;
interface
uses
TestFramework;
(* Online encoder / decoder:
1. https://asn1.io/asn1playground/
2. https://lapo.it/asn1js/
3. https://www.mobilefish.com/services/big_number/big_number.php
*)
type
TASN1_TestCase = class(TTestCase)
public
class constructor Create;
published
procedure Test_Boolean;
procedure Test_Integer;
procedure Test_BitString;
procedure Test_Null;
procedure Test_ObjectIdentifier;
procedure Test_Sequence;
procedure Test_PEM;
procedure DER_EncodeLength;
procedure X509_RSA;
procedure X509_EC;
end;
implementation
uses
System.SysUtils, System.NetEncoding,
ASN1, ASN1.X509, System.NetEncoding.Base64Url;
class constructor TASN1_TestCase.Create;
begin
RegisterTest(Suite);
end;
procedure TASN1_TestCase.DER_EncodeLength;
begin
for var i := 0 to 127 do
CheckEqualsMem(TBytes.Create(i), TASN1_DER.EncodeLength(i), 1);
CheckEqualsMem(TBytes.Create($81, $80), TASN1_DER.EncodeLength(128), 2);
CheckEqualsMem(TBytes.Create($82, $01, $01), TASN1_DER.EncodeLength(257), 2);
CheckEqualsMem(TBytes.Create($82, $13, $46), TASN1_DER.EncodeLength(4934), 2);
StartExpectingException(Exception);
TASN1_DER.EncodeLength(-1);
end;
procedure TASN1_TestCase.Test_BitString;
begin
var a: TASN1_BitString;
CheckTrue(asnBitString = a.DataType);
CheckEquals(0, Length(a.Value));
var c := TBytes.Create(
$47, $eb, $99, $5a, $df, $9e, $70, $0d, $fb, $a7, $31, $32, $c1, $5f, $5c, $24
, $c2, $e0, $bf, $c6, $24, $af, $15, $66, $0e, $b8, $6a, $2e, $ab, $2b, $c4, $97
, $1f, $e3, $cb, $dc, $63, $a5, $25, $ec, $c7, $b4, $28, $61, $66, $36, $a1, $31
, $1b, $bf, $dd, $d0, $fc, $bf, $17, $94, $90, $1d, $e5, $5e, $c7, $11, $5e, $c9
, $55, $9f, $eb, $a3, $3e, $14, $c7, $99, $a6, $cb, $ba, $a1, $46, $0f, $39, $d4
, $44, $c4, $c8, $4b, $76, $0e, $20, $5d, $6d, $a9, $34, $9e, $d4, $d5, $87, $42
, $eb, $24, $26, $51, $14, $90, $b4, $0f, $06, $5e, $52, $88, $32, $7a, $95, $20
, $a0, $fd, $f7, $e5, $7d, $60, $dd, $72, $68, $9b, $f5, $7b, $05, $8f, $6d, $1e
);
a := c;
CheckEqualsMem(TBytes.Create($03, $81, $81, $00) + c, TASN1_DER.Encode(a), 4 + Length(c));
end;
procedure TASN1_TestCase.Test_Boolean;
begin
var a: TASN1_Boolean;
CheckTrue(asnBoolean = a.DataType);
a := False;
CheckFalse(a);
CheckEqualsMem(TBytes.Create($01, $01, $00), TASN1_DER.Encode(a), 3);
a := True;
CheckTrue(a);
CheckEqualsMem(TBytes.Create($01, $01, $FF), TASN1_DER.Encode(a), 3);
end;
procedure TASN1_TestCase.Test_Integer;
begin
var a: TASN1_Integer;
CheckTrue(asnInteger = a.DataType);
CheckEquals(1, a.DataSize);
CheckEqualsMem(TBytes.Create($02, $01, $00), TASN1_DER.Encode(a), 3);
a := 127;
CheckEqualsMem(TBytes.Create($02, $01, $7F), TASN1_DER.Encode(a), 3);
a := 128;
CheckEqualsMem(TBytes.Create($02, $02, $00, $80), TASN1_DER.Encode(a), 4);
a := High(Int64); // 9223372036854775807
CheckEqualsMem(TBytes.Create($02, $08, $7F, $FF, $FF, $FF, $FF, $FF, $FF, $FF), TASN1_DER.Encode(a), 10);
var c := TBytes.Create(
$0F, $FD, $5B, $25, $87, $A7, $01, $73, $49, $10, $A6, $F5, $20, $B4, $40, $EE,
$1B, $03, $EF, $FC, $91, $4A, $1C, $46, $32, $84, $A1, $8E, $4D, $F3, $6D, $9A,
$C7, $61, $53, $21, $05, $04, $52, $C3, $1D, $E1, $7B, $1E, $7D, $8A, $66, $46,
$8A, $48, $8E, $5C, $A3, $BE, $38, $88, $B8, $AF, $90, $76, $67, $04, $D6, $F3,
$96, $B8, $74, $75, $AB, $C9, $86, $FB, $A2, $F0, $3D, $D9, $02, $8F, $47, $1F,
$8D, $79, $74, $7E, $FB, $C1, $99, $15, $8E, $21, $19, $93, $1F, $90, $BD, $98,
$6F, $50, $D5, $E5, $E7, $EB, $00, $1B, $51, $E3, $B7, $25, $A5, $01, $C2, $A0,
$17, $88, $A9, $93, $5E, $24, $3D, $11, $61, $EF, $7B, $F1, $4B, $AC, $CF, $F1,
$96, $CE, $3F, $0A, $D2
);
a := c;
CheckEqualsMem(TBytes.Create($02, $81, $85) + c, TASN1_DER.Encode(a), Length(c) + 3);
a := -1;
CheckEqualsMem(TBytes.Create($02, $01, $FF), TASN1_DER.Encode(a), 3);
a := -2;
CheckEqualsMem(TBytes.Create($02, $01, $FE), TASN1_DER.Encode(a), 3);
a := -127;
CheckEqualsMem(TBytes.Create($02, $01, $81), TASN1_DER.Encode(a), 3);
a := -128;
CheckEqualsMem(TBytes.Create($02, $01, $80), TASN1_DER.Encode(a), 3);
a := 65537;
CheckEqualsMem(TBytes.Create($02, $03, $01, $00, $01), TASN1_DER.Encode(a), 5);
end;
procedure TASN1_TestCase.Test_Null;
begin
var a: TASN1_Null;
CheckTrue(asnNull = a.DataType);
CheckEqualsMem(TBytes.Create($05, $00), TASN1_DER.Encode(a), 2);
end;
procedure TASN1_TestCase.Test_ObjectIdentifier;
begin
var a: TASN1_ObjectIdentifier;
CheckTrue(asnObjectIdentifier = a.DataType);
a := '1.2.840.113549.1.1.1';
CheckEqualsMem(TBytes.Create($06, $09, $2a, $86, $48, $86, $f7, $0d, $01, $01, $01), TASN1_DER.Encode(a), 11);
a := '1.3.6.1.4.1.311.21.20';
CheckEqualsMem(TBytes.Create($06, $09, $2b, $06, $01, $04, $01, $82, $37, $15, $14), TASN1_DER.Encode(a), 11);
a := '1.2.840.10045.2.1';
CheckEqualsMem(TBytes.Create($06, $07, $2a, $86, $48, $ce, $3d, $02, $01), TASN1_DER.Encode(a), 9);
end;
procedure TASN1_TestCase.Test_PEM;
begin
var a := '-----BEGIN PUBLIC KEY-----' + sLineBreak
+ 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEg9JCShMJJ2ZJ44+xDqizdxZd+djtmb/HTnI6ckkx' + sLineBreak
+ 'o0wvcEs52f8NS967o3RWL0zuuh+gF9E9DlQ5wDgMIRqIEA==' + sLineBreak
+ '-----END PUBLIC KEY-----' + sLineBreak;
var D := TBytes.Create(
$30, $59, $30, $13, $06, $07, $2a, $86, $48, $ce, $3d, $02, $01, $06, $08, $2a
, $86, $48, $ce, $3d, $03, $01, $07, $03, $42, $00, $04, $83, $d2, $42, $4a, $13
, $09, $27, $66, $49, $e3, $8f, $b1, $0e, $a8, $b3, $77, $16, $5d, $f9, $d8, $ed
, $99, $bf, $c7, $4e, $72, $3a, $72, $49, $31, $a3, $4c, $2f, $70, $4b, $39, $d9
, $ff, $0d, $4b, $de, $bb, $a3, $74, $56, $2f, $4c, $ee, $ba, $1f, $a0, $17, $d1
, $3d, $0e, $54, $39, $c0, $38, $0c, $21, $1a, $88, $10
);
var P: TPEM;
P.SetValue('PUBLIC KEY', D);
CheckEquals(a, P);
P := a;
CheckEquals(a, P);
end;
procedure TASN1_TestCase.Test_Sequence;
begin
var a: TASN1_Sequence;
CheckTrue(asnSequence = a.DataType);
var c := TBytes.Create($30, $0B, $02, $03, $01, $00, $01, $02, $01, $00, $01, $01, $FF);
a.Add(TASN1_Integer(65537));
a.Add(TASN1_Integer(0));
a.Add(TASN1_Boolean(True));
CheckEqualsMem(c, TASN1_DER.Encode(a), Length(c));
end;
procedure TASN1_TestCase.X509_EC;
begin
var a := TBytes.Create(
$30, $59,
$30, $13,
$06, $07,
$2a, $86, $48, $ce, $3d, $02, $01,
$06, $08,
$2a, $86, $48, $ce, $3d, $03, $01, $07,
$03, $42,
$00,
$04, $83, $d2, $42, $4a, $13, $09, $27, $66, $49, $e3, $8f, $b1, $0e, $a8, $b3,
$77, $16, $5d, $f9, $d8, $ed, $99, $bf, $c7, $4e, $72, $3a, $72, $49, $31, $a3,
$4c, $2f, $70, $4b, $39, $d9, $ff, $0d, $4b, $de, $bb, $a3, $74, $56, $2f, $4c,
$ee, $ba, $1f, $a0, $17, $d1, $3d, $0e, $54, $39, $c0, $38, $0c, $21, $1a, $88,
$10
);
var b := X509_PublicKeyInfo_ECC.Create(
TNetEncoding.Base64Url.DecodeStringToBytes('g9JCShMJJ2ZJ44-xDqizdxZd-djtmb_HTnI6ckkxo0w'),
TNetEncoding.Base64Url.DecodeStringToBytes('L3BLOdn/DUveu6N0Vi9M7rofoBfRPQ5UOcA4DCEaiBA')
);
CheckEqualsMem(a, TASN1_DER.Encode(b), Length(a));
end;
procedure TASN1_TestCase.X509_RSA;
begin
var a := TBytes.Create(
$30, $82, $01, $22,
$30, $0d,
$06, $09,
$2a, $86, $48, $86, $f7, $0d, $01, $01, $01,
$05, $00,
$03, $82, $01, $0f,
$00,
$30, $82, $01, $0a,
$02, $82, $01, $01,
$00,
$c5, $89, $b5, $61, $07, $17, $99, $50, $34, $66, $87, $af, $ce, $01, $a5, $14,
$a5, $33, $14, $f8, $81, $95, $b5, $5e, $99, $31, $39, $66, $f5, $a9, $fa, $7f,
$b8, $b5, $08, $cc, $88, $b9, $df, $31, $5a, $b7, $36, $6f, $63, $ed, $e7, $12,
$d9, $31, $cf, $ea, $ff, $7d, $76, $cf, $df, $23, $c9, $28, $f9, $ac, $f8, $9e,
$f3, $b5, $2a, $33, $59, $4c, $42, $1d, $8f, $f9, $ef, $09, $b2, $6f, $6a, $9d,
$0e, $fb, $89, $d1, $1a, $0e, $9a, $44, $53, $11, $0a, $aa, $e6, $d4, $dd, $14,
$ef, $19, $36, $70, $83, $8e, $eb, $56, $a9, $d2, $42, $e7, $c9, $eb, $84, $a3,
$65, $8b, $84, $ec, $9c, $75, $3a, $83, $12, $1e, $9f, $0d, $8e, $e5, $1f, $05,
$98, $7b, $59, $3d, $56, $77, $ee, $e7, $5a, $1d, $3f, $1c, $ce, $5c, $61, $b9,
$76, $74, $19, $2f, $cb, $32, $bb, $fe, $b8, $6c, $d2, $f7, $46, $25, $0b, $ff,
$f2, $c7, $af, $7d, $46, $66, $ec, $6b, $a4, $18, $3e, $6d, $1b, $bb, $31, $ab,
$98, $a9, $5e, $80, $d7, $b8, $ed, $46, $24, $b1, $67, $4d, $8e, $65, $1b, $77,
$6a, $99, $87, $07, $2f, $73, $a6, $ab, $28, $ac, $30, $9e, $39, $7c, $02, $86,
$a2, $9a, $2e, $e6, $82, $34, $91, $47, $a6, $c6, $00, $68, $cf, $7b, $38, $37,
$11, $cf, $61, $9a, $14, $8b, $47, $ea, $e5, $30, $e0, $aa, $6b, $a8, $6a, $a1,
$ba, $59, $3c, $54, $80, $56, $8e, $89, $ea, $43, $36, $36, $74, $2f, $69, $cb,
$02, $03,
$01, $00, $01
);
var b := X509_PublicKeyInfo_Rsa.Create(
TNetEncoding.Base64Url.DecodeStringToBytes(
'xYm1YQcXmVA0ZoevzgGlFKUzFPiBlbVemTE5ZvWp-n-4tQjMiLnfMVq3Nm9j7ecS2'
+ 'THP6v99ds_fI8ko-az4nvO1KjNZTEIdj_nvCbJvap0O-4nRGg6aRFMRCqrm1N0U7x'
+ 'k2cIOO61ap0kLnyeuEo2WLhOycdTqDEh6fDY7lHwWYe1k9Vnfu51odPxzOXGG5dnQ'
+ 'ZL8syu_64bNL3RiUL__LHr31GZuxrpBg-bRu7MauYqV6A17jtRiSxZ02OZRt3apmH'
+ 'By9zpqsorDCeOXwChqKaLuaCNJFHpsYAaM97ODcRz2GaFItH6uUw4KprqGqhulk8V'
+ 'IBWjonqQzY2dC9pyw'
),
TNetEncoding.Base64Url.DecodeStringToBytes('AQAB')
);
CheckEqualsMem(a, TASN1_DER.Encode(b), Length(a));
end;
initialization
TASN1_TestCase.ClassName;
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ *********************************************************** }
unit tfRC5;
{$I TFL.inc}
{$POINTERMATH ON}
interface
uses
tfTypes;
type
PRC5Algorithm = ^TRC5Algorithm;
TRC5Algorithm = record
private const
MAX_ROUNDS = 255;
MAX_KEYLEN = 255;
private type
PRC5Block = ^TRC5Block;
TRC5Block = record
case Byte of
0: (Word16: array[0..1] of Word);
1: (Word32: array[0..1] of UInt32);
2: (Word64: array[0..1] of UInt64);
end;
TDummy = array[0..0] of UInt64; // to ensure 64-bit alignment
private
{$HINTS OFF} // -- inherited fields begin --
// from tfRecord
FVTable: Pointer;
FRefCount: Integer;
// from tfBlockCipher
FValidKey: Boolean;
FDir: UInt32;
FMode: UInt32;
FPadding: UInt32;
FIVector: TRC5Block; // -- inherited fields end --
{$HINTS ON}
FBlockSize: Cardinal; // 4, 8, 16
FRounds: Cardinal; // 0..255
FSubKeys: TDummy;
public
class function Release(Inst: PRC5Algorithm): Integer; stdcall; static;
class function ExpandKey32(Inst: PRC5Algorithm; Key: PByte; KeySize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function ExpandKey64(Inst: PRC5Algorithm; Key: PByte; KeySize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function ExpandKey128(Inst: PRC5Algorithm; Key: PByte; KeySize: Cardinal): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetBlockSize(Inst: PRC5Algorithm): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function DuplicateKey(Inst: PRC5Algorithm; var Key: PRC5Algorithm): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class procedure DestroyKey(Inst: PRC5Algorithm);{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function EncryptBlock32(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function EncryptBlock64(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function EncryptBlock128(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function DecryptBlock32(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function DecryptBlock64(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function DecryptBlock128(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
function GetRC5Algorithm(var A: PRC5Algorithm): TF_RESULT;
function GetRC5AlgorithmEx(var A: PRC5Algorithm; BlockSize, Rounds: Integer): TF_RESULT;
implementation
uses tfRecords, tfBaseCiphers;
//const
// MAX_BLOCK_SIZE = 16; // 16 bytes = 128 bits
const
RC5VTable32: array[0..16] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TRC5Algorithm.Release,
@TRC5Algorithm.DestroyKey,
@TRC5Algorithm.DuplicateKey,
@TRC5Algorithm.ExpandKey32,
@TBaseBlockCipher.SetKeyParam,
@TBaseBlockCipher.GetKeyParam,
@TRC5Algorithm.GetBlockSize,
@TBaseBlockCipher.Encrypt,
@TBaseBlockCipher.Decrypt,
@TRC5Algorithm.EncryptBlock32,
@TRC5Algorithm.DecryptBlock32,
@TBaseBlockCipher.GetRand,
@TBaseBlockCipher.RandBlock,
@TBaseBlockCipher.RandCrypt,
@TBaseBlockCipher.GetIsBlockCipher
);
RC5VTable64: array[0..16] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TRC5Algorithm.Release,
@TRC5Algorithm.DestroyKey,
@TRC5Algorithm.DuplicateKey,
@TRC5Algorithm.ExpandKey64,
@TBaseBlockCipher.SetKeyParam,
@TBaseBlockCipher.GetKeyParam,
@TRC5Algorithm.GetBlockSize,
@TBaseBlockCipher.Encrypt,
@TBaseBlockCipher.Decrypt,
@TRC5Algorithm.EncryptBlock64,
@TRC5Algorithm.DecryptBlock64,
@TBaseBlockCipher.GetRand,
@TBaseBlockCipher.RandBlock,
@TBaseBlockCipher.RandCrypt,
@TBaseBlockCipher.GetIsBlockCipher
);
RC5VTable128: array[0..16] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TRC5Algorithm.Release,
@TRC5Algorithm.DestroyKey,
@TRC5Algorithm.DuplicateKey,
@TRC5Algorithm.ExpandKey128,
@TBaseBlockCipher.SetKeyParam,
@TBaseBlockCipher.GetKeyParam,
@TRC5Algorithm.GetBlockSize,
@TBaseBlockCipher.Encrypt,
@TBaseBlockCipher.Decrypt,
@TRC5Algorithm.EncryptBlock128,
@TRC5Algorithm.DecryptBlock128,
@TBaseBlockCipher.GetRand,
@TBaseBlockCipher.RandBlock,
@TBaseBlockCipher.RandCrypt,
@TBaseBlockCipher.GetIsBlockCipher
);
procedure BurnKey(Inst: PRC5Algorithm); inline;
var
BurnSize: Integer;
TmpBlockSize: Integer;
TmpRounds: Integer;
begin
// if Inst.FSubKeys <> nil then begin
// FillChar(Inst.FSubKeys^, (Inst.FRounds + 1) * Inst.FBlockSize, 0);
// FreeMem(Inst.FSubKeys);
// end;
TmpBlockSize:= Inst.FBlockSize;
TmpRounds:= Inst.FRounds;
BurnSize:= SizeOf(TRC5Algorithm)
- SizeOf(TRC5Algorithm.TDummy)
+ (TmpRounds + 1) * TmpBlockSize
- Integer(@PRC5Algorithm(nil)^.FValidKey);
// BurnSize:= Integer(@PRC5Algorithm(nil)^.FSubKeys)
// - Integer(@PRC5Algorithm(nil)^.FValidKey);
FillChar(Inst.FValidKey, BurnSize, 0);
Inst.FBlockSize:= TmpBlockSize;
Inst.FRounds:= TmpRounds;
// if Inst.FSubKeys <> nil then begin
// FillChar(Inst.FSubKeys.GetRawData^, Inst.FSubKeys.GetLen, 0);
// end;
end;
class function TRC5Algorithm.Release(Inst: PRC5Algorithm): Integer;
begin
if Inst.FRefCount > 0 then begin
Result:= tfDecrement(Inst.FRefCount);
if Result = 0 then begin
BurnKey(Inst);
// if Inst.FSubKeys <> nil then Inst.FSubKeys._Release;
FreeMem(Inst);
end;
end
else
Result:= Inst.FRefCount;
end;
function GetRC5Algorithm(var A: PRC5Algorithm): TF_RESULT;
begin
Result:= GetRC5AlgorithmEx(A, // "standard" RC5:
8, // 64-bit block (8 bytes)
12 // 12 rounds
);
end;
function GetRC5AlgorithmEx(var A: PRC5Algorithm; BlockSize, Rounds: Integer): TF_RESULT;
var
Tmp: PRC5Algorithm;
begin
if ((BlockSize <> 4) and (BlockSize <> 8) and (BlockSize <> 16))
or (Rounds < 1) or (Rounds > 255)
then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
// BlockSize:= BlockSize shr 3;
try
Tmp:= AllocMem(SizeOf(TRC5Algorithm)
- SizeOf(TRC5Algorithm.TDummy)
+ (Rounds + 1) * BlockSize);
case BlockSize of
4: Tmp^.FVTable:= @RC5VTable32;
8: Tmp^.FVTable:= @RC5VTable64;
16: Tmp^.FVTable:= @RC5VTable128;
end;
Tmp^.FRefCount:= 1;
Tmp^.FBlockSize:= BlockSize;
Tmp^.FRounds:= Rounds;
if A <> nil then TRC5Algorithm.Release(A);
A:= Tmp;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
class procedure TRC5Algorithm.DestroyKey(Inst: PRC5Algorithm);
begin
BurnKey(Inst);
end;
class function TRC5Algorithm.DuplicateKey(Inst: PRC5Algorithm;
var Key: PRC5Algorithm): TF_RESULT;
begin
Result:= GetRC5AlgorithmEx(Key, Inst.FBlockSize, Inst.FRounds);
if Result = TF_S_OK then begin
Key.FValidKey:= Inst.FValidKey;
Key.FDir:= Inst.FDir;
Key.FMode:= Inst.FMode;
Key.FPadding:= Inst.FPadding;
Key.FIVector:= Inst.FIVector;
Key.FRounds:= Inst.FRounds;
Key.FBlockSize:= Inst.FBlockSize;
// Result:= Key.FSubKeys.CopyBytes(Inst.FSubKeys);
Move(Inst.FSubKeys, Key.FSubKeys, (Inst.FRounds + 1) * Inst.FBlockSize);
end;
end;
function Rol16(Value: Word; Shift: Cardinal): Word; inline;
begin
Result:= (Value shl Shift) or (Value shr (16 - Shift));
end;
function Rol32(Value: UInt32; Shift: Cardinal): UInt32; inline;
begin
Result:= (Value shl Shift) or (Value shr (32 - Shift));
end;
function Rol64(Value: UInt64; Shift: Cardinal): UInt64; inline;
begin
Result:= (Value shl Shift) or (Value shr (64 - Shift));
end;
function Ror16(Value: Word; Shift: Cardinal): Word; inline;
begin
Result:= (Value shr Shift) or (Value shl (16 - Shift));
end;
function Ror32(Value: UInt32; Shift: Cardinal): UInt32; inline;
begin
Result:= (Value shr Shift) or (Value shl (32 - Shift));
end;
function Ror64(Value: UInt64; Shift: Cardinal): UInt64; inline;
begin
Result:= (Value shr Shift) or (Value shl (64 - Shift));
end;
class function TRC5Algorithm.EncryptBlock32(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
type
PRC5Word = ^RC5Word;
RC5Word = Word;
var
A, B: RC5Word;
S: PRC5Word;
I: Integer;
begin
S:= @Inst.FSubKeys;
A:= PRC5Word(Data)[0] + S^;
Inc(S);
B:= PRC5Word(Data)[1] + S^;
I:= Inst.FRounds;
repeat
Inc(S);
A:= Rol16(A xor B, B) + S^;
Inc(S);
B:= Rol16(B xor A, A) + S^;
Dec(I);
until I = 0;
PRC5Word(Data)[0]:= A;
PRC5Word(Data)[1]:= B;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.EncryptBlock64(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
type
PRC5Word = ^RC5Word;
RC5Word = UInt32;
var
A, B: RC5Word;
S: PRC5Word;
I: Integer;
begin
S:= @Inst.FSubKeys;
A:= PRC5Word(Data)[0] + S^;
Inc(S);
B:= PRC5Word(Data)[1] + S^;
I:= Inst.FRounds;
repeat
Inc(S);
A:= Rol32(A xor B, B) + S^;
Inc(S);
B:= Rol32(B xor A, A) + S^;
Dec(I);
until I = 0;
PRC5Word(Data)[0]:= A;
PRC5Word(Data)[1]:= B;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.EncryptBlock128(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
type
PRC5Word = ^RC5Word;
RC5Word = UInt64;
var
A, B: RC5Word;
S: PRC5Word;
I: Integer;
begin
S:= @Inst.FSubKeys;
A:= PRC5Word(Data)[0] + S^;
Inc(S);
B:= PRC5Word(Data)[1] + S^;
I:= Inst.FRounds;
repeat
Inc(S);
A:= Rol64(A xor B, B) + S^;
Inc(S);
B:= Rol64(B xor A, A) + S^;
Dec(I);
until I = 0;
PRC5Word(Data)[0]:= A;
PRC5Word(Data)[1]:= B;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.DecryptBlock32(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
type
PRC5Word = ^RC5Word;
RC5Word = Word;
var
A, B: RC5Word;
S: PRC5Word;
I: Integer;
begin
A:= PRC5Word(Data)[0];
B:= PRC5Word(Data)[1];
I:= Inst.FRounds;
S:= PRC5Word(@Inst.FSubKeys) + 2 * Inst.FRounds + 1;
repeat
B:= Ror16(B - S^, A) xor A;
Dec(S);
A:= Ror16(A - S^, B) xor B;
Dec(S);
Dec(I);
until I = 0;
PRC5Word(Data)[1]:= B - S^;
Dec(S);
PRC5Word(Data)[0]:= A - S^;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.DecryptBlock64(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
type
PRC5Word = ^RC5Word;
RC5Word = UInt32;
var
A, B: RC5Word;
S: PRC5Word;
I: Integer;
begin
A:= PRC5Word(Data)[0];
B:= PRC5Word(Data)[1];
I:= Inst.FRounds;
S:= PRC5Word(@Inst.FSubKeys) + 2 * Inst.FRounds + 1;
repeat
B:= Ror32(B - S^, A) xor A;
Dec(S);
A:= Ror32(A - S^, B) xor B;
Dec(S);
Dec(I);
until I = 0;
PRC5Word(Data)[1]:= B - S^;
Dec(S);
PRC5Word(Data)[0]:= A - S^;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.DecryptBlock128(Inst: PRC5Algorithm; Data: PByte): TF_RESULT;
type
PRC5Word = ^RC5Word;
RC5Word = UInt64;
var
A, B: RC5Word;
S: PRC5Word;
I: Integer;
begin
A:= PRC5Word(Data)[0];
B:= PRC5Word(Data)[1];
I:= Inst.FRounds;
S:= PRC5Word(@Inst.FSubKeys) + 2 * Inst.FRounds + 1;
repeat
B:= Ror64(B - S^, A) xor A;
Dec(S);
A:= Ror64(A - S^, B) xor B;
Dec(S);
Dec(I);
until I = 0;
PRC5Word(Data)[1]:= B - S^;
Dec(S);
PRC5Word(Data)[0]:= A - S^;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.ExpandKey32(Inst: PRC5Algorithm; Key: PByte;
KeySize: Cardinal): TF_RESULT;
type
RC5Word = Word; // RC5 "word" size = 2 bytes
PWArray = ^TWArray;
TWArray = array[0..$FFFF] of RC5Word;
const
Pw = $B7E1;
Qw = $9E37;
kShift = 1;
var
L: array[0..(256 div SizeOf(RC5Word) - 1)] of RC5Word;
S: PWArray;
LLen: Integer;
T: Integer;
I, J, N: Integer;
X, Y: RC5Word;
NSteps: Integer;
begin
if (KeySize > 255) then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
// Convert secret key from bytes to RC5 words, K[0..KLen-1] --> L[0..LLen-1]
LLen:= (KeySize + SizeOf(RC5Word) - 1) shr kShift;
FillChar(L, LLen * SizeOf(RC5Word), 0);
Move(Key^, L, KeySize);
S:= @Inst.FSubKeys;
// Initialize the array of subkeys, FSubKeys[0..T-1]
T:= 2 * (Inst.FRounds + 1);
S^[0]:= Pw;
for I:= 1 to T - 1 do
S^[I]:= S^[I-1] + Qw;
// Mix in the secret key
if LLen > T
then NSteps:= 3 * LLen
else NSteps:= 3 * T;
X:= 0; Y:= 0; I:= 0; J:= 0;
for N:= 0 to NSteps - 1 do begin
S^[I]:= Rol16((S^[I] + X + Y), 3);
X:= S^[I];
L[J]:= Rol16((L[J] + X + Y), (X + Y) and $1F);
Y:= L[J];
I:= (I + 1) mod T;
J:= (J + 1) mod LLen;
end;
FillChar(L, LLen * SizeOf(RC5Word), 0);
Inst.FValidKey:= True;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.ExpandKey64(Inst: PRC5Algorithm; Key: PByte;
KeySize: Cardinal): TF_RESULT;
type
RC5Word = UInt32; // RC5 "word" size = 4 bytes
PWArray = ^TWArray;
TWArray = array[0..$FFFF] of RC5Word;
const
Pw = $B7E15163;
Qw = $9E3779B9;
kShift = 2;
var
L: array[0..(256 div SizeOf(RC5Word) - 1)] of RC5Word;
S: PWArray;
LLen: Integer;
T: Integer;
I, J, N: Integer;
X, Y: RC5Word;
NSteps: Integer;
begin
if (KeySize > 255) then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
// Convert secret key from bytes to RC5 words, K[0..KLen-1] --> L[0..LLen-1]
LLen:= (KeySize + SizeOf(RC5Word) - 1) shr kShift;
FillChar(L, LLen * SizeOf(RC5Word), 0);
Move(Key^, L, KeySize);
S:= @Inst.FSubKeys;
// Initialize the array of subkeys, FSubKeys[0..T-1]
T:= 2 * (Inst.FRounds + 1);
S^[0]:= Pw;
for I:= 1 to T - 1 do
S^[I]:= S^[I-1] + Qw;
// Mix in the secret key
if LLen > T
then NSteps:= 3 * LLen
else NSteps:= 3 * T;
X:= 0; Y:= 0; I:= 0; J:= 0;
for N:= 0 to NSteps - 1 do begin
S^[I]:= Rol32((S^[I] + X + Y), 3);
X:= S^[I];
L[J]:= Rol32((L[J] + X + Y), (X + Y) and $1F);
Y:= L[J];
I:= (I + 1) mod T;
J:= (J + 1) mod LLen;
end;
FillChar(L, LLen * SizeOf(RC5Word), 0);
Inst.FValidKey:= True;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.ExpandKey128(Inst: PRC5Algorithm; Key: PByte;
KeySize: Cardinal): TF_RESULT;
type
RC5Word = UInt64; // RC5 "word" size = 8 bytes
PWArray = ^TWArray;
TWArray = array[0..$FFFF] of RC5Word;
const
Pw = $B7E151628AED2A6B;
Qw = $9E3779B97F4A7C15;
kShift = 3;
var
L: array[0..(256 div SizeOf(RC5Word) - 1)] of RC5Word;
S: PWArray;
LLen: Integer;
T: Integer;
I, J, N: Integer;
X, Y: RC5Word;
NSteps: Integer;
begin
if (KeySize > 255) then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
// Convert secret key from bytes to RC5 words, K[0..KLen-1] --> L[0..LLen-1]
LLen:= (KeySize + SizeOf(RC5Word) - 1) shr kShift;
FillChar(L, LLen * SizeOf(RC5Word), 0);
Move(Key^, L, KeySize);
S:= @Inst.FSubKeys;
// Initialize the array of subkeys, FSubKeys[0..T-1]
T:= 2 * (Inst.FRounds + 1);
S^[0]:= Pw;
for I:= 1 to T - 1 do
S^[I]:= S^[I-1] + Qw;
// Mix in the secret key
if LLen > T
then NSteps:= 3 * LLen
else NSteps:= 3 * T;
X:= 0; Y:= 0; I:= 0; J:= 0;
for N:= 0 to NSteps - 1 do begin
S^[I]:= Rol64((S^[I] + X + Y), 3);
X:= S^[I];
L[J]:= Rol64((L[J] + X + Y), (X + Y) and $1F);
Y:= L[J];
I:= (I + 1) mod T;
J:= (J + 1) mod LLen;
end;
FillChar(L, LLen * SizeOf(RC5Word), 0);
Inst.FValidKey:= True;
Result:= TF_S_OK;
end;
class function TRC5Algorithm.GetBlockSize(Inst: PRC5Algorithm): Integer;
begin
Result:= Inst.FBlockSize;
end;
end.
|
unit Reference;
interface
uses
Entity, ADODB, DB;
type
TReference = class(TEntity)
private
FFirstname: string;
FLastname: string;
FMiddlename: string;
FName: string;
FRefType: string;
FIsDependent: boolean;
FIsStudent: boolean;
public
procedure Add; override;
procedure Save; override;
procedure Edit; override;
procedure Cancel; override;
procedure CopyClientAddress;
property Firstname: string read FFirstname write FFirstname;
property Lastname: string read FLastname write FLastname;
property Middlename: string read FMiddlename write FMiddlename;
property Name: string read FName write FName;
property RefType: string read FRefType write FRefType;
property IsDependent: boolean read FIsDependent write FIsDependent;
property IsStudent: boolean read FIsStudent write FIsStudent;
constructor Create; overload;
constructor Create(const id, name, refType: string; const isDependent, isStudent: boolean); overload;
constructor Create(const id, firstname, lastname, middlename: string); overload;
end;
var
refc: TReference;
implementation
uses
RefData, ClientData;
constructor TReference.Create;
begin
inherited Create;
end;
constructor TReference.Create(const id, name, refType: string;
const isDependent: boolean; const isStudent: boolean);
begin
FId := id;
FName := name;
FRefType := refType;
FIsDependent := isDependent;
FIsStudent := isStudent;
end;
constructor TReference.Create(const id: string; const firstname: string;
const lastname: string; const middlename: string);
begin
FId := id;
FFirstname := firstname;
FLastname := lastname;
FMiddlename := middlename;
end;
procedure TReference.Add;
var
i: integer;
begin
with dmRef do
begin
for i:=0 to ComponentCount - 1 do
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [3,4] then
begin
(Components[i] as TADODataSet).Open;
(Components[i] as TADODataSet).Append;
end;
end;
end;
procedure TReference.Save;
var
i: integer;
begin
with dmRef do
begin
for i:=0 to ComponentCount - 1 do
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [3,4] then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Post;
end;
end;
procedure TReference.Edit;
begin
end;
procedure TReference.Cancel;
var
i: integer;
begin
with dmRef do
begin
for i:=0 to ComponentCount - 1 do
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [3,4] then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Cancel;
end;
end;
procedure TReference.CopyClientAddress;
var
i: integer;
begin
with dmRef, dmClient.dstAddressInfo do
begin
if dstAddressInfo.RecordCount > 0 then
dstAddressInfo.Edit
else
dstAddressInfo.Append;
for i := 0 to FieldCount - 1 do
if dstAddressInfo.Fields.FindField(Fields[i].FieldName) <> nil then
if dstAddressInfo.Fields[i].FieldName <> 'entity_id' then // exclude primary key
if not dstAddressInfo.Fields[i].ReadOnly then
dstAddressInfo.FieldByName(Fields[i].FieldName).Value := FieldByName(Fields[i].FieldName).Value;
end;
end;
end.
|
unit g_flyers;
interface
uses
OpenGL, u_math, g_class_gameobject, g_game_objects, g_player, g_rockets;
type
TEnemyFlyer = class (TGameObject)
Target : TGameObject;
FireTime : Integer;
procedure Move; override;
procedure Render; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
procedure Death; override;
constructor Create;
end;
var
TestEnemy : TEnemyFlyer;
implementation
uses
g_world;
{ TEnemyFlyer }
constructor TEnemyFlyer.Create;
begin
Radius := 0.5;
Collision := True;
Health := 100;
FireTime := 100;
Speed := 0;
end;
procedure TEnemyFlyer.Death;
var
Expl : TExplosion;
begin
Expl := TExplosion.Create;
Expl.Pos := Pos;
ObjectsEngine.AddObject(Expl);
inc(World.Score, 500);
end;
procedure TEnemyFlyer.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
inherited;
end;
procedure TEnemyFlyer.Move;
var
Rocket : TSimpleRocket;
begin
inherited;
if Distance(Pos, Target.Pos) < 30 then
begin
Angle := AngleTo(Pos.x, Pos.z, Target.Pos.x, Target.Pos.z);
if Distance(Pos, Target.Pos) < 20 then
begin
if FireTime = 0 then
begin
Rocket := TSimpleRocket.Create;
Rocket.Pos := AddVector(Pos, MakeNormalVector(Cosinus(Angle)*2, 0.0, Sinus(Angle)*2));
Rocket.LockOn := Player;
Rocket.FiredBy := Self;
Rocket.Speed := 0.20;
ObjectsEngine.AddObject(Rocket);
FireTime := 100;
end;
Dec(FireTime);
if Speed > 0 then
Speed := Speed - 0.001;
end else
begin
Speed := Speed + 0.002;
end;
end;
if Speed > 0.15 then Speed := 0.14;
MVector := MultiplyVectorScalar(MakeVector(Cosinus(Angle), 0, Sinus(Angle)), Speed);
Pos := AddVector(Pos, MVector);
end;
procedure TEnemyFlyer.Render;
begin
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glRotatef(90-Angle, 0.0, 1.0, 0.0);
glColor3f(1 - (Health / 100), Health / 100, 0.0);
glBegin(GL_LINE_LOOP);
glVertex3f(0.0, 0.0, 1.2);
glVertex3f(0.5, 0.0, -1.2);
glVertex3f(-0.5, 0.0, -1.2);
glEnd;
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex3f(-0.5, 0.0, -1.2);
glVertex3f(0.0, 0.0, -2 + (random(100)/100));
glVertex3f(0.5, 0.0, -1.2);
glEnd;
glPopMatrix;
end;
end.
|
{===============================================================================
Copyright(c) 2007-2009, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,接线图绘图单元
+ TWE_DIAGRAM 接线图
===============================================================================}
unit U_WE_DIAGRAM;
interface
uses SysUtils, Classes, Windows, Graphics, U_WIRING_ERROR, system.Types;
type
/// <summary>
/// 接线图
/// </summary>
TWE_DIAGRAM = class( TComponent )
private
FCanvas : TCanvas;
FDiagram3 : TBitmap;
FDiagram4 : TBitmap;
FWiringError : TWIRING_ERROR;
FRect : TRect;
procedure SetWiringError( const Value : TWIRING_ERROR );
procedure SetRect( const Value : TRect );
protected
procedure DrawDiagram;
procedure DrawDiagram3;
procedure DrawDiagram4;
/// <summary>
/// 画连接线
/// </summary>
/// <param name="APosStart">起点</param>
/// <param name="APosEnd">终点</param>
/// <param name="AStraightLine">是否为直线</param>
procedure DrawConnection( APosStart, APosEnd : TPoint;
AStraightLine : Boolean = False; AColor : TColor = clBlack );
/// <summary>
/// 画断线
/// </summary>
procedure DrawBroken( APosStart, APosEnd : TPoint );
/// <summary>
/// 切换相序
/// </summary>
procedure ChangeSequence( var AOrder : array of TPoint; ASequence : TWE_SEQUENCE_TYPE );
public
constructor Create( AOwner : TComponent ); override;
destructor Destroy; override;
public
/// <summary>
/// 画布
/// </summary>
property Canvas : TCanvas read FCanvas write FCanvas;
/// <summary>
/// 绘图的区域
/// </summary>
property Rect : TRect read FRect write SetRect;
/// <summary>
/// 错误接线
/// </summary>
property WiringError : TWIRING_ERROR read FWiringError write
SetWiringError;
end;
implementation
{ TWE_DIAGRAM }
{$R wediagram.res}
procedure TWE_DIAGRAM.ChangeSequence( var AOrder: array of TPoint;
ASequence: TWE_SEQUENCE_TYPE);
var
OldOrder : array of TPoint;
i: Integer;
begin
if Length( AOrder ) <> 3 then
Exit;
SetLength( OldOrder, 3 );
for i := 0 to 3 - 1 do
OldOrder[ i ] := AOrder[ i ];
case ASequence of
stACB:
begin
AOrder[ 0 ] := OldOrder[ 0 ];
AOrder[ 1 ] := OldOrder[ 2 ];
AOrder[ 2 ] := OldOrder[ 1 ];
end;
stBAC:
begin
AOrder[ 0 ] := OldOrder[ 1 ];
AOrder[ 1 ] := OldOrder[ 0 ];
AOrder[ 2 ] := OldOrder[ 2 ];
end;
stBCA:
begin
AOrder[ 0 ] := OldOrder[ 1 ];
AOrder[ 1 ] := OldOrder[ 2 ];
AOrder[ 2 ] := OldOrder[ 0 ];
end;
stCAB:
begin
AOrder[ 0 ] := OldOrder[ 2 ];
AOrder[ 1 ] := OldOrder[ 0 ];
AOrder[ 2 ] := OldOrder[ 1 ];
end;
stCBA:
begin
AOrder[ 0 ] := OldOrder[ 2 ];
AOrder[ 1 ] := OldOrder[ 1 ];
AOrder[ 2 ] := OldOrder[ 0 ];
end;
end;
end;
constructor TWE_DIAGRAM.Create( AOwner : TComponent );
begin
inherited;
FWiringError := TWIRING_ERROR.Create;
FDiagram3 := TBitmap.Create;
FDiagram4 := TBitmap.Create;
FDiagram3.LoadFromResourceID( HInstance, 7203 );
FDiagram4.LoadFromResourceID( HInstance, 7204 );
end;
destructor TWE_DIAGRAM.Destroy;
begin
FWiringError.Free;
FDiagram3.Free;
FDiagram4.Free;
inherited;
end;
procedure TWE_DIAGRAM.DrawBroken(APosStart, APosEnd: TPoint);
var
pO : TPoint;
begin
pO.X := (APosStart.X + APosEnd.X) div 2;
pO.Y := (APosStart.Y + APosEnd.Y) div 2;
with FCanvas do
begin
// 清连接线
Pen.Color := Pixels[ 0, 0 ];
Polyline([ APosStart, APosEnd ] );
// 画 X
Pen.Color := clRed;
Polyline([Point(po.X - 4, pO.Y - 4),Point(pO.X + 5, pO.Y + 5)]);
Polyline([Point(po.X - 4, pO.Y + 4),Point(pO.X + 5, pO.Y - 5)]);
end;
end;
procedure TWE_DIAGRAM.DrawConnection( APosStart, APosEnd : TPoint;
AStraightLine : Boolean; AColor : TColor );
begin
with FCanvas do
begin
Pen.Color := AColor;
if ( APosStart.X = APosEnd.X ) or ( APosStart.Y = APosEnd.Y ) or
AStraightLine then
Polyline( [ APosStart, APosEnd ] )
else
begin
Polyline( [ APosStart, Point( APosEnd.X, APosStart.Y ) ] );
Polyline( [ Point( APosEnd.X, APosStart.Y ), APosEnd ] );
end;
end;
end;
procedure TWE_DIAGRAM.DrawDiagram;
begin
if not Assigned( FCanvas ) then
Exit;
if FWiringError.PhaseType = ptThree then
begin
FCanvas.Draw( FRect.Left, FRect.Top, FDiagram3 );
DrawDiagram3;
end
else
begin
FCanvas.Draw( FRect.Left, FRect.Top, FDiagram4 );
DrawDiagram4;
end;
end;
procedure TWE_DIAGRAM.DrawDiagram3;
var
pSa, pSb, pSc : TPoint; // 电压线 出
pSUa, pSUb, pSUc : TPoint; // 电压线圈 进
pTVa_P, pTVa_N, pTVc_P, pTVc_N : TPoint; // 副边线圈
pSign_Ua_In, pSign_Ub_In, pSign_Uc_In : TPoint; // 电压副边标志 进
pSign_Ua_Out, pSign_Ub_Out, pSign_Uc_Out : TPoint; // 电压副边标志 出
pUa, pUb, pUc : TPoint; // 电压
pTAa_P, pTAa_N, pTAc_P, pTAc_N : TPoint; // 电流线圈
pSign_Ia_P_In, pSign_Ia_N_In,
pSign_Ic_P_In, pSign_Ic_N_In : TPoint; // 电流标志 进
pSign_Ia_P_Out, pSign_Ia_N_Out,
pSign_Ic_P_Out, pSign_Ic_N_Out : TPoint; // 电流标志 进
pIa_P, pIa_N, pIc_P, pIc_N : TPoint; // 电流 正反
pU_Order : array[0..2] of TPoint; // 电压相序
pI_Order : array[0..3] of TPoint; // 电流相序
// bInIsTaken : Boolean; // In 是否使用
begin
// 电压线 出
pSa := Point(FRect.Left +110, FRect.Top + 103);
pSb := Point(FRect.Left +110, FRect.Top + 135);
pSc := Point(FRect.Left +110, FRect.Top + 167);
// 电压线圈 进
pSUa := Point(FRect.Left +120, FRect.Top + 103);
pSUb := Point(FRect.Left +120, FRect.Top + 135);
pSUc := Point(FRect.Left +120, FRect.Top + 167);
// 电压线圈 出
pTVa_P := Point(FRect.Left +172, FRect.Top + 103);
pTVa_N := Point(FRect.Left +172, FRect.Top + 130);
pTVc_P := Point(FRect.Left +172, FRect.Top + 140);
pTVc_N := Point(FRect.Left +172, FRect.Top + 167);
// 电压标志 进
pSign_Ua_In := Point(FRect.Left +180, FRect.Top + 103);
pSign_Ub_In := Point(FRect.Left +180, FRect.Top + 135);
pSign_Uc_In := Point(FRect.Left +180, FRect.Top + 167);
// 电压标志 出
pSign_Ua_Out := Point(FRect.Left +209, FRect.Top + 103);
pSign_Ub_Out := Point(FRect.Left +209, FRect.Top + 135);
pSign_Uc_Out := Point(FRect.Left +209, FRect.Top + 167);
// 电压
pUa := Point(FRect.Left +233, FRect.Top + 103);
pUb := Point(FRect.Left +233, FRect.Top + 135);
pUc := Point(FRect.Left +233, FRect.Top + 167);
// 电流线圈 出
pTAa_P := Point(FRect.Left +41, FRect.Top + 237);
pTAa_N := Point(FRect.Left +41, FRect.Top + 273);
pTAc_P := Point(FRect.Left +125, FRect.Top + 237);
pTAc_N := Point(FRect.Left +125, FRect.Top + 273);
// 电流标志 进
pSign_Ia_P_In := Point(FRect.Left +52, FRect.Top + 213);
pSign_Ia_N_In := Point(FRect.Left +52, FRect.Top + 285);
pSign_Ic_P_In := Point(FRect.Left +136, FRect.Top + 237);
pSign_Ic_N_In := Point(FRect.Left +136, FRect.Top + 285);
// 电流标志 出
pSign_Ia_P_Out := Point(FRect.Left +186, FRect.Top + 213);
pSign_Ia_N_Out := Point(FRect.Left +186, FRect.Top + 285);
pSign_Ic_P_Out := Point(FRect.Left +186, FRect.Top + 237);
pSign_Ic_N_Out := Point(FRect.Left +186, FRect.Top + 285);
// 电流
pIa_P := Point(FRect.Left + 254, FRect.Top + 206);
pIa_N := Point(FRect.Left + 290, FRect.Top + 206);
pIc_P := Point(FRect.Left + 326, FRect.Top + 206);
pIc_N := Point(FRect.Left + 362, FRect.Top + 206);
//----------------------------------------------------------------------------
// 电压副边 方向
//----------------------------------------------------------------------------
if FWiringError.PT1Reverse then // PT1反
begin
DrawConnection( pTVa_N, pSign_Ua_In );
DrawConnection( pTVa_N, pTVa_P );
end
else
begin
DrawConnection( pTVa_P, pSign_Ua_In );
end;
if FWiringError.PT2Reverse then // PT2反
begin
DrawConnection( pTVc_P, pSign_Uc_In );
DrawConnection( pTVc_P, pTVc_N );
end
else
begin
DrawConnection( pTVc_N, pSign_Uc_In );
end;
//----------------------------------------------------------------------------
// 电压副边 相序
//----------------------------------------------------------------------------
pU_Order[0] := pSign_Ua_Out;
pU_Order[1] := pSign_Ub_Out;
pU_Order[2] := pSign_Uc_Out;
ChangeSequence( pU_Order, FWiringError.USequence );
DrawConnection( pU_Order[0], pUa, True );
DrawConnection( pU_Order[1], pUb, True );
DrawConnection( pU_Order[2], pUc, True );
//----------------------------------------------------------------------------
// 电流开路短路
//----------------------------------------------------------------------------
// 二次电流开路
if FWiringError.InBroken then
DrawBroken( Point( 170, pSign_Ic_N_In.Y ),
Point( 180, pSign_Ic_N_In.Y ) );
if FWiringError.IaBroken then
DrawBroken( Point( 170, pSign_Ia_P_In.Y ),
Point( 180, pSign_Ia_P_In.Y ) );
if FWiringError.IcBroken then
DrawBroken( Point( 170, pSign_Ic_P_In.Y ),
Point( 180, pSign_Ic_P_In.Y ) );
// 二次电流短路
if FWiringError.CT1Short then
DrawConnection( Point( pTAa_P.X - 6, pTAa_P.Y + 2 ),
Point( pTAa_N.X - 6, pTAa_N.Y - 2 ), True, clRed );
if FWiringError.CT2Short then
DrawConnection( Point( pTAc_P.X - 6, pTAc_P.Y + 2 ),
Point( pTAc_N.X - 6, pTAc_N.Y - 2 ), True, clRed );
//----------------------------------------------------------------------------
// 电流副边 方向
//----------------------------------------------------------------------------
if FWiringError.CT1Reverse then // Ia 反
begin
DrawConnection( pTAa_N, pSign_Ia_P_In );
DrawConnection( pSign_Ia_N_In, pTAa_P );
end
else
begin
DrawConnection( pTAa_P, pSign_Ia_P_In );
DrawConnection( pTAa_N, pSign_Ia_N_In );
end;
if FWiringError.CT2Reverse then // Ic 反
begin
DrawConnection( pTAc_N, pSign_Ic_P_In );
DrawConnection( pSign_Ic_N_In, pTAc_P );
end
else
begin
DrawConnection( pTAc_P, pSign_Ic_P_In );
DrawConnection( pTAc_N, pSign_Ic_N_In );
end;
//----------------------------------------------------------------------------
// 电流 相序
//----------------------------------------------------------------------------
case FWiringError.I1In of
plA: pI_Order[ 0 ] := pSign_Ia_P_Out;
plN: pI_Order[ 0 ] := pSign_Ia_N_Out;
plC: pI_Order[ 0 ] := pSign_Ic_P_Out;
end;
case FWiringError.I1Out of
plA: pI_Order[ 1 ] := pSign_Ia_P_Out;
plN: pI_Order[ 1 ] := pSign_Ia_N_Out;
plC: pI_Order[ 1 ] := pSign_Ic_P_Out;
end;
case FWiringError.I2In of
plA: pI_Order[ 2 ] := pSign_Ia_P_Out;
plN: pI_Order[ 2 ] := pSign_Ic_N_Out;
plC: pI_Order[ 2 ] := pSign_Ic_P_Out;
end;
case FWiringError.I2Out of
plA: pI_Order[ 3 ] := pSign_Ia_P_Out;
plN: pI_Order[ 3 ] := pSign_Ic_N_Out;
plC: pI_Order[ 3 ] := pSign_Ic_P_Out;
end;
DrawConnection( pI_Order[0], pIa_P, False );
DrawConnection( pI_Order[1], pIa_N, False );
DrawConnection( pI_Order[2], pIc_P, False );
DrawConnection( pI_Order[3], pIc_N, False );
//----------------------------------------------------------------------------
// 电压断相
//----------------------------------------------------------------------------
if FWiringError.UaBroken then // Ua 一次断
DrawBroken( pSa, pSUa );
if FWiringError.UbBroken then // Ub 一次断
DrawBroken( pSb, pSUb );
if FWiringError.UcBroken then // Uc 一次断
DrawBroken( pSc, pSUc );
if FWiringError.UsaBroken then // Ua 二次断
DrawBroken( Point( pSign_Ua_Out.X - 11, pSign_Ua_Out.Y ),
Point( pSign_Ua_Out.X, pSign_Ua_Out.Y ) );
if FWiringError.UsbBroken then // Ub 二次断
DrawBroken( Point( pSign_Ub_Out.X - 11, pSign_Ub_Out.Y ),
Point( pSign_Ub_Out.X, pSign_Ub_Out.Y ) );
if FWiringError.UscBroken then // Uc 二次断
DrawBroken( Point( pSign_Uc_Out.X - 11, pSign_Uc_Out.Y ),
Point( pSign_Uc_Out.X, pSign_Uc_Out.Y ) );
end;
procedure TWE_DIAGRAM.DrawDiagram4;
var
pSUa, pSUb, pSUc, pSUn : TPoint; // 电压源
pUa, pUb, pUc, pUn : TPoint; // 电压
pTAa_P, pTAa_N,
pTAb_P, pTAb_N,
pTAc_P, pTAc_N : TPoint; // 电流线圈
pSign_Ia_P_In, pSign_Ia_N_In,
pSign_Ib_P_In, pSign_Ib_N_In,
pSign_Ic_P_In, pSign_Ic_N_In : TPoint; // 电流标志 进
pSign_Ia_P_Out, pSign_Ia_N_Out,
pSign_Ib_P_Out, pSign_Ib_N_Out,
pSign_Ic_P_Out, pSign_Ic_N_Out : TPoint; // 电流标志 出
pIa_P, pIa_N,
pIb_P, pIb_N,
pIc_P, pIc_N : TPoint; // 电流 正反
pU_Order : array[0..2] of TPoint; // 电压相序
pI_Order : array[0..2] of TPoint; // 电流相序
begin
// 电压源
pSUa := Point( FRect.Left + 159, FRect.Top + 94 );
pSUb := Point( FRect.Left + 159, FRect.Top + 112 );
pSUc := Point( FRect.Left + 159, FRect.Top + 130 );
pSUn := Point( FRect.Left + 159, FRect.Top + 148 );
// 电压
pUa := Point( FRect.Left + 179, FRect.Top + 94 );
pUb := Point( FRect.Left + 179, FRect.Top + 112 );
pUc := Point( FRect.Left + 179, FRect.Top + 130 );
pUn := Point( FRect.Left + 179, FRect.Top + 148 );
// 电流线圈 出
pTAa_P := Point( FRect.Left + 61, FRect.Top + 198 );
pTAa_N := Point( FRect.Left + 61, FRect.Top + 222 );
pTAb_P := Point( FRect.Left + 103, FRect.Top + 225 );
pTAb_N := Point( FRect.Left + 103, FRect.Top + 249 );
pTAc_P := Point( FRect.Left + 145, FRect.Top + 252 );
pTAc_N := Point( FRect.Left + 145, FRect.Top + 276 );
// 电流标志 进
pSign_Ia_P_In := Point(FRect.Left + 69, FRect.Top + 198);
pSign_Ia_N_In := Point(FRect.Left + 61, FRect.Top + 289);
pSign_Ib_P_In := Point(FRect.Left + 111,FRect.Top + 225);
pSign_Ib_N_In := Point(FRect.Left + 103,FRect.Top + 289);
pSign_Ic_P_In := Point(FRect.Left + 153,FRect.Top + 252);
pSign_Ic_N_In := Point(FRect.Left + 145,FRect.Top + 289);
// 电流标志 出
pSign_Ia_P_Out := Point(FRect.Left + 172, FRect.Top + 198);
pSign_Ia_N_Out := Point(FRect.Left + 172, FRect.Top + 289);
pSign_Ib_P_Out := Point(FRect.Left + 172, FRect.Top + 225);
pSign_Ib_N_Out := Point(FRect.Left + 172, FRect.Top + 289);
pSign_Ic_P_Out := Point(FRect.Left + 172, FRect.Top + 252);
pSign_Ic_N_Out := Point(FRect.Left + 172, FRect.Top + 289);
// 电流
pIa_P := Point(FRect.Left + 189, FRect.Top + 198);
pIa_N := Point(FRect.Left + 189, FRect.Top + 289);
pIb_P := Point(FRect.Left + 189, FRect.Top + 225);
pIb_N := Point(FRect.Left + 189, FRect.Top + 289);
pIc_P := Point(FRect.Left + 189, FRect.Top + 252);
pIc_N := Point(FRect.Left + 189, FRect.Top + 289);
//----------------------------------------------------------------------------
// 电压 相序
//----------------------------------------------------------------------------
pU_Order[0] := pSUa;
pU_Order[1] := pSUb;
pU_Order[2] := pSUc;
ChangeSequence( pU_Order, FWiringError.USequence );
DrawConnection( pU_Order[0], pUa, True );
DrawConnection( pU_Order[1], pUb, True );
DrawConnection( pU_Order[2], pUc, True );
DrawConnection( pSUn, pUn, True );
//----------------------------------------------------------------------------
// 电流 方向
//----------------------------------------------------------------------------
if FWiringError.CT1Reverse then // Ia 反
begin
DrawConnection( pTAa_N, pSign_Ia_P_In );
DrawConnection( pSign_Ia_N_In, pTAa_P );
end
else
begin
DrawConnection( pTAa_P, pSign_Ia_P_In );
DrawConnection( pTAa_N, pSign_Ia_N_In );
end;
if FWiringError.CT2Reverse then // Ib 反
begin
DrawConnection( pTAb_N, pSign_Ib_P_In );
DrawConnection( pSign_Ib_N_In, pTAb_P );
end
else
begin
DrawConnection( pTAb_P, pSign_Ib_P_In );
DrawConnection( pTAb_N, pSign_Ib_N_In );
end;
if FWiringError.CT3Reverse then // Ic 反
begin
DrawConnection( pTAc_N, pSign_Ic_P_In );
DrawConnection( pSign_Ic_N_In, pTAc_P );
end
else
begin
DrawConnection( pTAc_P, pSign_Ic_P_In );
DrawConnection( pTAc_N, pSign_Ic_N_In );
end;
//----------------------------------------------------------------------------
// 电流 相序
//----------------------------------------------------------------------------
pI_Order[0] := pSign_Ia_P_Out;
pI_Order[1] := pSign_Ib_P_Out;
pI_Order[2] := pSign_Ic_P_Out;
ChangeSequence( pI_Order, FWiringError.ISequence );
DrawConnection( pI_Order[0], pIa_P, True );
DrawConnection( pI_Order[1], pIb_P, True );
DrawConnection( pI_Order[2], pIc_P, True );
pI_Order[0] := pSign_Ia_N_Out;
pI_Order[1] := pSign_Ib_N_Out;
pI_Order[2] := pSign_Ic_N_Out;
ChangeSequence( pI_Order, FWiringError.ISequence );
DrawConnection( pI_Order[0], pIa_N, True );
DrawConnection( pI_Order[1], pIb_N, True );
DrawConnection( pI_Order[2], pIc_N, True );
//----------------------------------------------------------------------------
// 电压断相
//----------------------------------------------------------------------------
if FWiringError.UaBroken then
DrawBroken( Point(pSUa.X - 15, pSUa.Y), Point(pSUa.X - 5, pSUa.Y) );
if FWiringError.UbBroken then
DrawBroken( Point(pSUb.X - 15, pSUb.Y), Point(pSUb.X - 5, pSUb.Y) );
if FWiringError.UcBroken then
DrawBroken( Point(pSUc.X - 15, pSUc.Y), Point(pSUc.X - 5, pSUc.Y) );
if FWiringError.UnBroken then
DrawBroken( Point(pSUn.X - 15, pSUn.Y), Point(pSUn.X - 5, pSUn.Y) );
//----------------------------------------------------------------------------
// 二次电流开路
//----------------------------------------------------------------------------
if FWiringError.IaBroken then
DrawBroken( Point(pSign_Ia_P_Out.X - 12, pSign_Ia_P_Out.Y),
Point(pSign_Ia_P_Out.X - 2, pSign_Ia_P_Out.Y) );
if FWiringError.IbBroken then
DrawBroken( Point(pSign_Ib_P_Out.X - 12, pSign_Ib_P_Out.Y),
Point(pSign_Ib_P_Out.X - 2, pSign_Ib_P_Out.Y) );
if FWiringError.IcBroken then
DrawBroken( Point(pSign_Ic_P_Out.X - 12, pSign_Ic_P_Out.Y),
Point(pSign_Ic_P_Out.X - 2, pSign_Ic_P_Out.Y) );
//----------------------------------------------------------------------------
// 二次电流短路
//----------------------------------------------------------------------------
if FWiringError.CT1Short then
DrawConnection( Point( pTAa_P.X - 5, pTAa_P.Y + 2 ),
Point( pTAa_N.X - 5, pTAa_N.Y - 2 ), True, clRed );
if FWiringError.CT2Short then
DrawConnection( Point( pTAb_P.X - 5, pTAb_P.Y + 2 ),
Point( pTAb_N.X - 5, pTAb_N.Y - 2 ), True, clRed );
if FWiringError.CT3Short then
DrawConnection( Point( pTAc_P.X - 5, pTAc_P.Y + 2 ),
Point( pTAc_N.X - 5, pTAc_N.Y - 2 ), True, clRed );
end;
procedure TWE_DIAGRAM.SetRect( const Value : TRect );
begin
FRect := Value;
end;
procedure TWE_DIAGRAM.SetWiringError( const Value : TWIRING_ERROR );
begin
if Assigned( Value ) then
begin
FWiringError.Assign( Value );
DrawDiagram;
end;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit EnvironmentImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
DependencyIntf,
EnvironmentIntf;
type
(*!------------------------------------------------
* basic having capability to retrieve
* CGI environment variable
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*--------------------------------------------------*)
TCGIEnvironment = class(TInterfacedObject, ICGIEnvironment, IDependency)
public
{-----------------------------------------
Retrieve an environment variable
------------------------------------------}
function env(const key : string) : string;
{-----------------------------------------
Retrieve GATEWAY_INTERFACE environment variable
------------------------------------------}
function gatewayInterface() : string;
{-----------------------------------------
Retrieve REMOTE_ADDR environment variable
------------------------------------------}
function remoteAddr() : string;
{-----------------------------------------
Retrieve REMOTE_PORT environment variable
------------------------------------------}
function remotePort() : string;
{-----------------------------------------
Retrieve SERVER_ADDR environment variable
------------------------------------------}
function serverAddr() : string;
{-----------------------------------------
Retrieve SERVER_PORT environment variable
------------------------------------------}
function serverPort() : string;
{-----------------------------------------
Retrieve DOCUMENT_ROOT environment variable
------------------------------------------}
function documentRoot() : string;
{-----------------------------------------
Retrieve REQUEST_METHOD environment variable
------------------------------------------}
function requestMethod() : string;
{-----------------------------------------
Retrieve REQUEST_SCHEME environment variable
------------------------------------------}
function requestScheme() : string;
{-----------------------------------------
Retrieve REQUEST_URI environment variable
------------------------------------------}
function requestUri() : string;
{-----------------------------------------
Retrieve QUERY_STRING environment variable
------------------------------------------}
function queryString() : string;
{-----------------------------------------
Retrieve SERVER_NAME environment variable
------------------------------------------}
function serverName() : string;
{-----------------------------------------
Retrieve CONTENT_TYPE environment variable
------------------------------------------}
function contentType() : string;
{-----------------------------------------
Retrieve CONTENT_LENGTH environment variable
------------------------------------------}
function contentLength() : string;
{-----------------------------------------
Retrieve HTTP_HOST environment variable
------------------------------------------}
function httpHost() : string;
{-----------------------------------------
Retrieve HTTP_USER_AGENT environment variable
------------------------------------------}
function httpUserAgent() : string;
{-----------------------------------------
Retrieve HTTP_ACCEPT environment variable
------------------------------------------}
function httpAccept() : string;
{-----------------------------------------
Retrieve HTTP_ACCEPT_LANGUAGE environment variable
------------------------------------------}
function httpAcceptLanguage() : string;
{-----------------------------------------
Retrieve HTTP_COOKIE environment variable
------------------------------------------}
function httpCookie() : string;
end;
implementation
uses
dos;
{-----------------------------------------
Retrieve an environment variable
------------------------------------------}
function TCGIEnvironment.env(const key : string) : string;
begin
result := getenv(key);
end;
{-----------------------------------------
Retrieve GATEWAY_INTERFACE environment variable
------------------------------------------}
function TCGIEnvironment.gatewayInterface() : string;
begin
result := getenv('GATEWAY_INTERFACE');
end;
{-----------------------------------------
Retrieve REMOTE_ADDR environment variable
------------------------------------------}
function TCGIEnvironment.remoteAddr() : string;
begin
result := getenv('REMOTE_ADDR');
end;
{-----------------------------------------
Retrieve REMOTE_PORT environment variable
------------------------------------------}
function TCGIEnvironment.remotePort() : string;
begin
result := getenv('REMOTE_PORT');
end;
{-----------------------------------------
Retrieve SERVER_ADDR environment variable
------------------------------------------}
function TCGIEnvironment.serverAddr() : string;
begin
result := getenv('SERVER_ADDR');
end;
{-----------------------------------------
Retrieve SERVER_PORT environment variable
------------------------------------------}
function TCGIEnvironment.serverPort() : string;
begin
result := getenv('SERVER_PORT');
end;
{-----------------------------------------
Retrieve DOCUMENT_ROOT environment variable
------------------------------------------}
function TCGIEnvironment.documentRoot() : string;
begin
result := getenv('DOCUMENT_ROOT');
end;
{-----------------------------------------
Retrieve REQUEST_METHOD environment variable
------------------------------------------}
function TCGIEnvironment.requestMethod() : string;
begin
result := getenv('REQUEST_METHOD');
end;
{-----------------------------------------
Retrieve REQUEST_SCHEME environment variable
------------------------------------------}
function TCGIEnvironment.requestScheme() : string;
begin
result := getenv('REQUEST_SCHEME');
end;
{-----------------------------------------
Retrieve REQUEST_URI environment variable
------------------------------------------}
function TCGIEnvironment.requestUri() : string;
begin
result := getenv('REQUEST_URI');
end;
{-----------------------------------------
Retrieve QUERY_STRING environment variable
------------------------------------------}
function TCGIEnvironment.queryString() : string;
begin
result := getenv('QUERY_STRING');
end;
{-----------------------------------------
Retrieve SERVER_NAME environment variable
------------------------------------------}
function TCGIEnvironment.serverName() : string;
begin
result := getenv('SERVER_NAME');
end;
{-----------------------------------------
Retrieve CONTENT_TYPE environment variable
------------------------------------------}
function TCGIEnvironment.contentType() : string;
begin
result := getenv('CONTENT_TYPE');
end;
{-----------------------------------------
Retrieve CONTENT_LENGTH environment variable
------------------------------------------}
function TCGIEnvironment.contentLength() : string;
begin
result := getenv('CONTENT_LENGTH');
end;
{-----------------------------------------
Retrieve HTTP_HOST environment variable
------------------------------------------}
function TCGIEnvironment.httpHost() : string;
begin
result := getenv('HTTP_HOST');
end;
{-----------------------------------------
Retrieve HTTP_USER_AGENT environment variable
------------------------------------------}
function TCGIEnvironment.httpUserAgent() : string;
begin
result := getenv('HTTP_USER_AGENT');
end;
{-----------------------------------------
Retrieve HTTP_ACCEPT environment variable
------------------------------------------}
function TCGIEnvironment.httpAccept() : string;
begin
result := getenv('HTTP_ACCEPT');
end;
{-----------------------------------------
Retrieve HTTP_ACCEPT_LANGUAGE environment variable
------------------------------------------}
function TCGIEnvironment.httpAcceptLanguage() : string;
begin
result := getenv('HTTP_ACCEPT_LANGUAGE');
end;
{-----------------------------------------
Retrieve HTTP_COOKIE environment variable
------------------------------------------}
function TCGIEnvironment.httpCookie() : string;
begin
result := getenv('HTTP_COOKIE');
end;
end.
|
unit chrome_browser;
{$mode delphi}{$H+}
{$WARN 5024 off : Parameter "$1" not used}
{$I vrode.inc}
interface
uses
Classes, SysUtils, Controls, LCLIntf, LazUTF8, Forms,
vr_intfs, vr_SysUtils, vr_utils,
chrome_common,
uCEFChromiumWindow, uCEFApplication, uCEFInterfaces, uCEFTypes,
uCEFProcessMessage, uCEFConstants, uCEFv8Value, uCEFv8Handler, uCEFv8Context,
uCEFMiscFunctions, uCEFListValue, uCEFValue, uCEFStringVisitor;
type
TCustomChromeRender = class;
TCustomChromeRenderClass = class of TCustomChromeRender;
TChromeBrowserState = (cbsNone, cbsBrowserCreated);
TChromeBrowserStates = set of TChromeBrowserState;
{ TCustomChromeBrowser }
TCustomChromeBrowser = class(TChromiumWindow, IWebBrowser)
private
FStates: TChromeBrowserStates;
FUrl: ustring;
FLoadString: ustring;
FOnKeyDown: TWBKeyEvent;
FOnBeforeLoad: TOnBeforeLoad;
FOnLoad: TNotifyEvent;
FOnShowContextMenu: TOnShowContextMenu;
FOnFocused: TNotifyEvent;
procedure OnIdleLoadUrl(Sender: TObject; var Done: Boolean);
procedure OnIdleLoadString(Sender: TObject; var Done: Boolean);
procedure CheckBrowserCreated;
function IgnoreUrl(const AUrl: ustring): Boolean;
protected
function GetInitialized: Boolean;
function GetOnBeforeLoad: TOnBeforeLoad;
function GetOnFocused: TNotifyEvent;
function GetOnKeyDown: TWBKeyEvent;
function GetOnLoad: TNotifyEvent;
function GetOnShowContextMenu: TOnShowContextMenu;
procedure SetOnBeforeLoad(AValue: TOnBeforeLoad);
procedure SetOnFocused(AValue: TNotifyEvent);
procedure SetOnKeyDown(AValue: TWBKeyEvent);
procedure SetOnLoad(AValue: TNotifyEvent);
procedure SetOnShowContextMenu(AValue: TOnShowContextMenu);
private
FSyncResult: Boolean;
FSyncPos: TPoint;
FSyncUrl: string;
FRenderCmdIdThs: ustring;
FRenderCmdMsgThs: ICefProcessMessage;
procedure WBProcessMessageReceived(Sender: TObject;
const browser: ICefBrowser; sourceProcess: TCefProcessId;
const message: ICefProcessMessage; out Result: Boolean);
procedure WBPreKeyEvent(Sender: TObject; const browser: ICefBrowser;
const event: PCefKeyEvent; osEvent: TCefEventHandle; out
isKeyboardShortcut: Boolean; out Result: Boolean);
procedure WBRunContextMenu(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; const params: ICefContextMenuParams;
const model: ICefMenuModel; const callback: ICefRunContextMenuCallback;
var aResult: Boolean);
procedure WBBeforeBrowse(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; const request: ICefRequest; user_gesture,
isRedirect: Boolean; out Result: Boolean);
procedure WBLoadEnd(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; httpStatusCode: Integer);
procedure WBGotFocus(Sender: TObject; const browser: ICefBrowser);
protected
//function GetRenderClass: TCustomChromeRenderClass; virtual;
procedure DoRunContextMenu(Data: PtrInt); virtual;
procedure DoBeforeBrowse; virtual;
procedure DoLoadEnd(Data: PtrInt); virtual;
procedure DoGotFocus(Data: PtrInt); virtual;
procedure DoEvent(const EVENT_: Integer; const AMsg: ICefProcessMessage); virtual;
procedure DoCmdResult(const IDM_: Integer; const AMsg: ICefProcessMessage;
out AResult: ICefValue); virtual;
protected
procedure ExecRenderCmd(const ACmd: Integer; const AParams: array of const);
function ExecRenderCmdAsBool(const ACmd: Integer; const AParams: array of const;
const ADefault: Boolean = False; const AWaitMSec: Integer = 3000): Boolean;
function ExecRenderCmdAsInt(const ACmd: Integer; const AParams: array of const;
const ADefault: Integer = 0; const AWaitMSec: Integer = 3000): Integer;
function ExecRenderCmdAsStr(const ACmd: Integer; const AParams: array of const;
const ADefault: string = ''; const AWaitMSec: Integer = 3000): string;
function ExecRenderCmdAndWait(const ACmd: Integer; const AParams: array of const;
out AResult: ICefValue; const AWaitMSec: Integer = 3000): Boolean;
public
constructor Create(AOwner: TComponent); override;
constructor CreateWithParent(AOwner: TComponent; AParent: TWinControl);
procedure AfterConstruction; override;
procedure LoadURL(const AUrl : ustring);
public
procedure Navigate(const AUrl: string);
procedure Refresh(const AIgnoreCache: Boolean = False);
function LoadFromString(const S : string): Integer;
function SaveToString: string;
procedure PrintToPDF(const AFileName: string);
function Focused: Boolean; override;
function ClearSelection: Boolean;
function SelectAll: Boolean;
procedure ExecuteJavaScript(const ACode: string);
property OnKeyDown: TWBKeyEvent read GetOnKeyDown write SetOnKeyDown;//may be not In MainThread (Chromium Embedded)
property OnBeforeLoad: TOnBeforeLoad read GetOnBeforeLoad write SetOnBeforeLoad;
property OnLoad: TNotifyEvent read GetOnLoad write SetOnLoad;
property OnShowContextMenu: TOnShowContextMenu read GetOnShowContextMenu write SetOnShowContextMenu;
property OnFocused: TNotifyEvent read GetOnFocused write SetOnFocused;
//property Initialized: Boolean read GetInitialized;
end;
{ TCustomChromeRender }
TCustomChromeRender = class
protected
FContext: ICefv8Context;
procedure GlobalCEFApp_OnContextCreated(const browser: ICefBrowser;
const frame: ICefFrame; const context: ICefv8Context); virtual;
procedure GlobalCEFApp_OnContextReleased(const browser: ICefBrowser;
const frame: ICefFrame; const context: ICefv8Context); virtual;
procedure GlobalCEFApp_OnLoadEnd(const browser: ICefBrowser;
const frame: ICefFrame; httpStatusCode: Integer); virtual;
procedure GlobalCEFApp_OnProcessMessageReceived(const browser: ICefBrowser;
sourceProcess: TCefProcessId; const message: ICefProcessMessage;
var aHandled: boolean); virtual;
procedure GlobalCEFApp_OnWebKitInitializedEvent(); virtual;
public
constructor Create; virtual;
function DoFunction(const AFunc: ICefv8Value; out AResult: ICefv8Value;
const Args: TCefv8ValueArray = nil; const AThis: ICefv8Value = nil): Boolean;
end;
{ TCefStringVisitorCommon }
TCefStringVisitorCommon = class(TCefStringVisitorOwn)
private
FStr: ustring;
protected
procedure Visit(const str: ustring); override;
public
property Str: ustring read FStr;
end;
//var
// DefaultChromeRenderClass: TCustomChromeRenderClass = nil;
implementation
{ TCustomChromeBrowser }
procedure TCustomChromeBrowser.OnIdleLoadUrl(Sender: TObject; var Done: Boolean);
begin
CheckBrowserCreated;
if Initialized then
begin
Application.RemoveOnIdleHandler(OnIdleLoadUrl);
TChromiumWindow(Self).LoadURL(FUrl);
end;
end;
procedure TCustomChromeBrowser.OnIdleLoadString(Sender: TObject; var Done: Boolean);
begin
CheckBrowserCreated;
if Initialized then
begin
Application.RemoveOnIdleHandler(OnIdleLoadString);
FChromium.LoadString(FLoadString, '');
end;
end;
procedure TCustomChromeBrowser.CheckBrowserCreated;
begin
if not (cbsBrowserCreated in FStates) then
if CreateBrowser then
Include(FStates, cbsBrowserCreated);
end;
function TCustomChromeBrowser.IgnoreUrl(const AUrl: ustring): Boolean;
begin
Result := WideCompareText('about:blank', AUrl) = 0;
end;
function TCustomChromeBrowser.GetInitialized: Boolean;
begin
Result := Initialized;
end;
function TCustomChromeBrowser.GetOnBeforeLoad: TOnBeforeLoad;
begin
Result := FOnBeforeLoad;
end;
function TCustomChromeBrowser.GetOnFocused: TNotifyEvent;
begin
Result := FOnFocused;
end;
function TCustomChromeBrowser.GetOnKeyDown: TWBKeyEvent;
begin
Result := FOnKeyDown;
end;
function TCustomChromeBrowser.GetOnLoad: TNotifyEvent;
begin
Result := FOnLoad;
end;
function TCustomChromeBrowser.GetOnShowContextMenu: TOnShowContextMenu;
begin
Result := FOnShowContextMenu;
end;
procedure TCustomChromeBrowser.SetOnBeforeLoad(AValue: TOnBeforeLoad);
begin
FOnBeforeLoad := AValue;
end;
procedure TCustomChromeBrowser.SetOnFocused(AValue: TNotifyEvent);
begin
FOnFocused := AValue;
end;
procedure TCustomChromeBrowser.SetOnKeyDown(AValue: TWBKeyEvent);
begin
FOnKeyDown := AValue;
end;
procedure TCustomChromeBrowser.SetOnLoad(AValue: TNotifyEvent);
begin
FOnLoad := AValue;
end;
procedure TCustomChromeBrowser.SetOnShowContextMenu(AValue: TOnShowContextMenu);
begin
FOnShowContextMenu := AValue;
end;
procedure TCustomChromeBrowser.WBProcessMessageReceived(Sender: TObject;
const browser: ICefBrowser; sourceProcess: TCefProcessId;
const message: ICefProcessMessage; out Result: Boolean);
procedure _DoEvent;
var
msg: ICefProcessMessage;
args: ICefListValue;
iEvent: Integer;
begin
msg := message.Copy;//message ReadOnly
args := msg.ArgumentList;
iEvent := args.GetInt(0);
args.Remove(0);
DoEvent(iEvent, msg);
end;
var
sName: ustring;
begin
sName := message.Name;
if sName = MSG_EVENT then
begin
Result := True;
_DoEvent;
end
else if LockedStringGet(FRenderCmdIdThs) = sName then //Result of ExecRenderCmdAndWait()
begin
LockedIntefaceSet(FRenderCmdMsgThs, message.Copy);
Result := True;
end
else
Result := False;
end;
procedure TCustomChromeBrowser.WBPreKeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent;
osEvent: TCefEventHandle; out isKeyboardShortcut: Boolean; out Result: Boolean);
var
Key: Word;
begin
if event.kind <> KEYEVENT_RAWKEYDOWN then
Exit;
if Assigned(FOnKeyDown) and Assigned(osEvent) and Initialized then
begin
Key := osEvent.wParam;
FOnKeyDown(Self, Key, GetKeyShiftState, osEvent);
if Key = 0 then
Result := True;
end;
end;
procedure TCustomChromeBrowser.DoRunContextMenu(Data: PtrInt);
begin
if IsAppState(apsClosing) then Exit;
if Assigned(FOnShowContextMenu) then
FOnShowContextMenu(Self, FSyncPos, FSyncResult);
FSyncResult := True;
end;
procedure TCustomChromeBrowser.WBRunContextMenu(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame;
const params: ICefContextMenuParams; const model: ICefMenuModel;
const callback: ICefRunContextMenuCallback; var aResult: Boolean);
begin
if Assigned(FOnShowContextMenu) then
begin
aResult := True;
GetCursorPos(FSyncPos);//FSyncPos := Point(params.XCoord, params.YCoord);
FSyncResult := aResult;
Application.QueueAsyncCall(DoRunContextMenu, 0);
//TThread.Synchronize(nil, DoRunContextMenu);
//aResult := FSyncResult;
end;
end;
procedure TCustomChromeBrowser.DoBeforeBrowse;
begin
if Assigned(FOnBeforeLoad) then
FOnBeforeLoad(Self, FSyncUrl, FSyncResult);
end;
procedure TCustomChromeBrowser.WBBeforeBrowse(Sender: TObject;
const browser: ICefBrowser; const frame: ICefFrame;
const request: ICefRequest; user_gesture, isRedirect: Boolean; out
Result: Boolean);
var
sUrl: String;
begin
if IgnoreUrl(request.Url) then Exit;
FSyncUrl := UTF8Encode(request.Url);
sUrl := FSyncUrl;
FSyncResult := False;
TThread.Synchronize(nil, DoBeforeBrowse);
Result := FSyncResult;
if Result and (sUrl <> FSyncUrl) then
request.Url := UTF8Decode(sUrl);
end;
procedure TCustomChromeBrowser.DoLoadEnd(Data: PtrInt);
begin
if not IsAppState(apsClosing) and Assigned(FOnLoad) then
FOnLoad(Self);
end;
procedure TCustomChromeBrowser.WBLoadEnd(Sender: TObject; const browser: ICefBrowser;
const frame: ICefFrame; httpStatusCode: Integer);
begin
if IgnoreUrl(frame.Url) then Exit;
Application.QueueAsyncCall(DoLoadEnd, 0);
end;
procedure TCustomChromeBrowser.DoGotFocus(Data: PtrInt);
begin
if not IsAppState(apsClosing) and Assigned(FOnFocused) then
FOnFocused(Self);
end;
procedure TCustomChromeBrowser.DoEvent(const EVENT_: Integer;
const AMsg: ICefProcessMessage);
begin
end;
procedure TCustomChromeBrowser.DoCmdResult(const IDM_: Integer;
const AMsg: ICefProcessMessage; out AResult: ICefValue);
begin
end;
procedure TCustomChromeBrowser.ExecRenderCmd(const ACmd: Integer;
const AParams: array of const);
var
val: ICefValue;
begin
ExecRenderCmdAndWait(ACmd, AParams, val, 0);
end;
function TCustomChromeBrowser.ExecRenderCmdAsBool(const ACmd: Integer;
const AParams: array of const; const ADefault: Boolean;
const AWaitMSec: Integer): Boolean;
var
val: ICefValue;
begin
if ExecRenderCmdAndWait(ACmd, AParams, val, AWaitMSec) and
(val.GetType = VTYPE_BOOL) then
Result := val.GetBool
else
Result := ADefault;
end;
function TCustomChromeBrowser.ExecRenderCmdAsInt(const ACmd: Integer;
const AParams: array of const; const ADefault: Integer;
const AWaitMSec: Integer): Integer;
var
val: ICefValue;
begin
if ExecRenderCmdAndWait(ACmd, AParams, val, AWaitMSec) and
(val.GetType = VTYPE_INT) then
Result := val.GetInt
else
Result := ADefault;
end;
function TCustomChromeBrowser.ExecRenderCmdAsStr(const ACmd: Integer;
const AParams: array of const; const ADefault: string;
const AWaitMSec: Integer): string;
var
val: ICefValue;
begin
if ExecRenderCmdAndWait(ACmd, AParams, val, AWaitMSec) and
(val.GetType = VTYPE_STRING) then
Result := utf_16To8(val.GetString)
else
Result := ADefault;
end;
var
_NextCmdId: Cardinal = 0;
function TCustomChromeBrowser.ExecRenderCmdAndWait(const ACmd: Integer;
const AParams: array of const; out AResult: ICefValue;
const AWaitMSec: Integer): Boolean;
var
msg: ICefProcessMessage;
args: ICefListValue;
procedure _SetArgs(const ACmdId: Integer);
var
i: Integer;
begin
args.SetInt(0, ACmdId);
args.SetInt(1, ACmd);
for i := 0 to Length(AParams) - 1 do
AddVarToCefListValue(args, i + 2, AParams[i]);
end;
function _Wait: Boolean;
var
i: QWord;
AMsg: ICefProcessMessage;
args: ICefListValue;
iCmd: Integer;
begin
i := vr_utils.GetTickCount + {$IFDEF DEBUG_MODE}IfThen(GlobalCEFApp.SingleProcess, 15000, AWaitMSec){$ELSE}AWaitMSec{$ENDIF};
while (i > vr_utils.GetTickCount) do
begin
if not LockedVarIsNil(FRenderCmdMsgThs) then
begin
//{$IFDEF DEBUG_MODE}iDebugTemp := vr_utils.GetTickCount - i;{$ENDIF}
LockVar;
try
AMsg := FRenderCmdMsgThs;
args := AMsg.ArgumentList;
iCmd := args.GetInt(0);
args.Remove(0);
finally
UnLockVar;
end;
DoCmdResult(iCmd, AMsg, AResult);
Result := AResult <> nil;
if not Result and (args.GetSize > 0) then
begin
AResult := args.GetValue(0);
Result := True;
end;
Exit;
end;
{$IFDEF DEBUG_MODE}
if GlobalCEFApp.SingleProcess then
Sleep(1);{$ENDIF}
end;
Result := False;
end;
begin
Result := False;
//Execute('myFunc()');
//Execute('window.register()');
msg := TCefProcessMessageRef.New(MSG_CMD);
args := msg.ArgumentList;
if AWaitMSec > 0 then
begin
Inc(_NextCmdId);
LockedStringSet(FRenderCmdIdThs, IntToStr(_NextCmdId){%H-});
LockedIntefaceSet(FRenderCmdMsgThs, nil);
_SetArgs(_NextCmdId);
FChromium.SendProcessMessage(PID_RENDERER, msg);
Result := _Wait;
LockedStringSet(FRenderCmdIdThs, '');
LockedIntefaceSet(FRenderCmdMsgThs, nil);
end
else
begin
_SetArgs(0);
FChromium.SendProcessMessage(PID_RENDERER, msg);
end;
end;
constructor TCustomChromeBrowser.Create(AOwner: TComponent);
begin
//if _ChromeRender = nil then
// _ChromeRender := GetRenderClass.Create;
inherited Create(AOwner);
end;
constructor TCustomChromeBrowser.CreateWithParent(AOwner: TComponent;
AParent: TWinControl);
begin
Create(AOwner);
Parent := AParent;
end;
procedure TCustomChromeBrowser.AfterConstruction;
begin
inherited AfterConstruction;
FChromium.OnProcessMessageReceived := WBProcessMessageReceived;
FChromium.OnPreKeyEvent := WBPreKeyEvent;
FChromium.OnRunContextMenu := WBRunContextMenu;
FChromium.OnBeforeBrowse := WBBeforeBrowse;
FChromium.OnLoadEnd := WBLoadEnd;
//FChromium.OnSetFocus := WBSetFocus;
FChromium.OnGotFocus := WBGotFocus;
end;
procedure TCustomChromeBrowser.LoadURL(const AUrl: ustring);
begin
Application.AddOnIdleHandler(OnIdleLoadUrl);
FUrl := AUrl;
end;
procedure TCustomChromeBrowser.WBGotFocus(Sender: TObject; const browser: ICefBrowser);
begin
Application.QueueAsyncCall(DoGotFocus, 0);
end;
//function TCustomChromeBrowser.GetRenderClass: TCustomChromeRenderClass;
//begin
// Result := TCustomChromeRender;
//end;
procedure TCustomChromeBrowser.Navigate(const AUrl: string);
begin
Application.AddOnIdleHandler(OnIdleLoadUrl);
FUrl := UTF8Decode(AUrl);
end;
procedure TCustomChromeBrowser.Refresh(const AIgnoreCache: Boolean);
begin
if AIgnoreCache then
FChromium.ReloadIgnoreCache
else
FChromium.Reload;
end;
function TCustomChromeBrowser.LoadFromString(const S: string): Integer;
begin
Result := 0;
Application.AddOnIdleHandler(OnIdleLoadString);
FLoadString := UTF8Decode(S);
end;
function TCustomChromeBrowser.SaveToString: string;
var
TempFrame: ICefFrame;
TempVisitor: TCefStringVisitorCommon;
begin
Result := '';
if Initialized then
begin
TempFrame := FChromium.Browser.MainFrame;
if (TempFrame <> nil) then
begin
TempVisitor := TCefStringVisitorCommon.Create;
TempFrame.GetSource(TempVisitor);
Result := UTF8Encode(TempVisitor.Str);
end;
end;
end;
procedure TCustomChromeBrowser.PrintToPDF(const AFileName: string);
begin
ChromiumBrowser.PrintToPDF(utf_8To16(AFileName), '', '');
end;
function TCustomChromeBrowser.Focused: Boolean;
begin
Result := inherited Focused;
//Result := Initialized and FChromium.Browser.MainFrame.IsFocused; //FChromium.FrameIsFocused;
end;
function TCustomChromeBrowser.ClearSelection: Boolean;
begin
Result := True;
ExecuteJavaScript('document.getSelection().empty()');
end;
function TCustomChromeBrowser.SelectAll: Boolean;
begin
Result := True;
FChromium.SelectAll;
end;
procedure TCustomChromeBrowser.ExecuteJavaScript(const ACode: string);
begin
FChromium.ExecuteJavaScript(UTF8Decode(ACode), '');
end;
{ TCustomChromeRender }
procedure TCustomChromeRender.GlobalCEFApp_OnContextCreated(
const browser: ICefBrowser; const frame: ICefFrame;
const context: ICefv8Context);
begin
FContext := context;
end;
procedure TCustomChromeRender.GlobalCEFApp_OnContextReleased(
const browser: ICefBrowser; const frame: ICefFrame;
const context: ICefv8Context);
begin
FContext := nil;
end;
procedure TCustomChromeRender.GlobalCEFApp_OnLoadEnd(
const browser: ICefBrowser; const frame: ICefFrame; httpStatusCode: Integer);
begin
end;
procedure TCustomChromeRender.GlobalCEFApp_OnProcessMessageReceived(
const browser: ICefBrowser; sourceProcess: TCefProcessId;
const message: ICefProcessMessage; var aHandled: boolean);
begin
end;
procedure TCustomChromeRender.GlobalCEFApp_OnWebKitInitializedEvent();
begin
end;
constructor TCustomChromeRender.Create;
begin
GlobalCEFApp.OnContextCreated := GlobalCEFApp_OnContextCreated;
GlobalCEFApp.OnContextReleased := GlobalCEFApp_OnContextReleased;
GlobalCEFApp.OnLoadEnd := GlobalCEFApp_OnLoadEnd;
GlobalCEFApp.OnWebKitInitialized := GlobalCEFApp_OnWebKitInitializedEvent;
GlobalCEFApp.OnProcessMessageReceived := GlobalCEFApp_OnProcessMessageReceived;
end;
function TCustomChromeRender.DoFunction(const AFunc: ICefv8Value; out
AResult: ICefv8Value; const Args: TCefv8ValueArray; const AThis: ICefv8Value
): Boolean;
begin
if (FContext = nil) or (AFunc = nil) then Exit(False);
AResult := AFunc.ExecuteFunctionWithContext(FContext, AThis, Args);
Result := (AResult <> nil) and AResult.IsValid;
end;
{ TCefStringVisitorCommon }
procedure TCefStringVisitorCommon.Visit(const str: ustring);
begin
FStr := str;
end;
procedure _AfterGlobalCEFAppCreate;
begin
//if DefaultChromeRenderClass = nil then
// DefaultChromeRenderClass := TCustomChromeRender;
//_ChromeRender := DefaultChromeRenderClass.Create;
end;
//initialization
// OnAfterGlobalCEFAppCreate := _AfterGlobalCEFAppCreate;
//finalization
// FreeAndNil(_ChromeRender);
end.
|
unit UFrmRoleEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DBClient;
type
TFrmRoleEdit = class(TForm)
lblRoleID: TLabel;
lblRoleName: TLabel;
lblRemark: TLabel;
edtRoleID: TEdit;
edtRoleName: TEdit;
mmoRemark: TMemo;
btnOk: TButton;
btnCancel: TButton;
procedure btnOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FAction: string;
FDataSet: TClientDataSet;
public
class function ShowRoleEdit(AAction: string; DataSet: TClientDataSet): Boolean;
end;
var
FrmRoleEdit: TFrmRoleEdit;
implementation
uses UDBAccess, UPubFunLib;
{$R *.dfm}
procedure TFrmRoleEdit.FormShow(Sender: TObject);
begin
if FAction = 'Edit' then
begin
edtRoleID.Text := FDataSet.FindField('RoleID').AsString;
edtRoleName.Text := FDataSet.FindField('RoleName').AsString;
mmoRemark.Text := FDataSet.FindField('Remark').AsString;
end;
end;
class function TFrmRoleEdit.ShowRoleEdit(AAction: string;
DataSet: TClientDataSet): Boolean;
begin
with TFrmRoleEdit.Create(nil) do
try
FAction := AAction;
FDataSet := DataSet;
Result := ShowModal = mrOk;
finally
Free;
end;
end;
procedure TFrmRoleEdit.btnOkClick(Sender: TObject);
begin
if Trim(edtRoleID.Text) = '' then
begin
edtRoleID.SetFocus;
ShowMessage('角色编号不能为空!');
Exit;
end;
if Trim(edtRoleName.Text) = '' then
begin
edtRoleName.SetFocus;
ShowMessage('角色编号不能为空!');
Exit;
end;
if FAction = 'Append' then
begin
FDataSet.Append;
FDataSet.FindField('Guid').AsString := CreateGUIDStr;
FDataSet.FindField('Deleted').AsInteger := 0;
end
else
FDataSet.Edit;
FDataSet.FindField('RoleID').AsString := Trim(edtRoleID.Text);
FDataSet.FindField('RoleName').AsString := Trim(edtRoleName.Text);
FDataSet.FindField('Remark').AsString := Trim(mmoRemark.Text);
FDataSet.Post;
if DBAccess.ApplyUpdates('S_ROLE', FDataSet.Delta) then
FDataSet.MergeChangeLog
else
begin
FDataSet.CancelUpdates;
ShowMessage('数据保存失败,请重新操作!');
Exit;
end;
ModalResult := mrOk;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_RecastRasterization;
interface
uses
Math, SysUtils, RN_Helper, RN_Recast;
/// Adds a span to the specified heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in,out] hf An initialized heightfield.
/// @param[in] x The width index where the span is to be added.
/// [Limits: 0 <= value < rcHeightfield::width]
/// @param[in] y The height index where the span is to be added.
/// [Limits: 0 <= value < rcHeightfield::height]
/// @param[in] smin The minimum height of the span. [Limit: < @p smax] [Units: vx]
/// @param[in] smax The maximum height of the span. [Limit: <= #RC_SPAN_MAX_HEIGHT] [Units: vx]
/// @param[in] area The area id of the span. [Limit: <= #RC_WALKABLE_AREA)
/// @param[in] flagMergeThr The merge theshold. [Limit: >= 0] [Units: vx]
procedure rcAddSpan(ctx: TrcContext; var hf: TrcHeightfield; const x, y: Integer;
const smin, smax: Word;
const area: Byte; const flagMergeThr: Integer);
/// Rasterizes a triangle into the specified heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] v0 Triangle vertex 0 [(x, y, z)]
/// @param[in] v1 Triangle vertex 1 [(x, y, z)]
/// @param[in] v2 Triangle vertex 2 [(x, y, z)]
/// @param[in] area The area id of the triangle. [Limit: <= #RC_WALKABLE_AREA]
/// @param[in,out] solid An initialized heightfield.
/// @param[in] flagMergeThr The distance where the walkable flag is favored over the non-walkable flag.
/// [Limit: >= 0] [Units: vx]
procedure rcRasterizeTriangle(ctx: TrcContext; const v0, v1, v2: PSingle;
const area: Byte; var solid: TrcHeightfield;
const flagMergeThr: Integer = 1);
/// Rasterizes an indexed triangle mesh into the specified heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] verts The vertices. [(x, y, z) * @p nv]
/// @param[in] nv The number of vertices.
/// @param[in] tris The triangle indices. [(vertA, vertB, vertC) * @p nt]
/// @param[in] areas The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt]
/// @param[in] nt The number of triangles.
/// @param[in,out] solid An initialized heightfield.
/// @param[in] flagMergeThr The distance where the walkable flag is favored over the non-walkable flag.
/// [Limit: >= 0] [Units: vx]
procedure rcRasterizeTriangles(ctx: TrcContext; const verts: PSingle; const nv: Integer;
const tris: PInteger; const areas: PByte; const nt: Integer;
var solid: TrcHeightfield; const flagMergeThr: Integer = 1); overload;
/// Rasterizes an indexed triangle mesh into the specified heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] verts The vertices. [(x, y, z) * @p nv]
/// @param[in] nv The number of vertices.
/// @param[in] tris The triangle indices. [(vertA, vertB, vertC) * @p nt]
/// @param[in] areas The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt]
/// @param[in] nt The number of triangles.
/// @param[in,out] solid An initialized heightfield.
/// @param[in] flagMergeThr The distance where the walkable flag is favored over the non-walkable flag.
/// [Limit: >= 0] [Units: vx]
procedure rcRasterizeTriangles(ctx: TrcContext; const verts: PSingle; const nv: Integer;
const tris: PWord; const areas: PByte; const nt: Integer;
var solid: TrcHeightfield; const flagMergeThr: Integer = 1); overload;
/// Rasterizes triangles into the specified heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] verts The triangle vertices. [(ax, ay, az, bx, by, bz, cx, by, cx) * @p nt]
/// @param[in] areas The area id's of the triangles. [Limit: <= #RC_WALKABLE_AREA] [Size: @p nt]
/// @param[in] nt The number of triangles.
/// @param[in,out] solid An initialized heightfield.
/// @param[in] flagMergeThr The distance where the walkable flag is favored over the non-walkable flag.
/// [Limit: >= 0] [Units: vx]
procedure rcRasterizeTriangles(ctx: TrcContext; const verts: PSingle; const areas: PByte; const nt: Integer;
var solid: TrcHeightfield; const flagMergeThr: Integer = 1); overload;
implementation
uses RN_RecastHelper;
function overlapBounds(const amin, amax, bmin, bmax: PSingle): Boolean;
var overlap: Boolean;
begin
overlap := true;
if (amin[0] > bmax[0]) or (amax[0] < bmin[0]) then overlap := false;
if (amin[1] > bmax[1]) or (amax[1] < bmin[1]) then overlap := false;
if (amin[2] > bmax[2]) or (amax[2] < bmin[2]) then overlap := false;
Result := overlap;
end;
function overlapInterval(amin, amax, bmin, bmax: Word): Boolean;
begin
if (amax < bmin) then Exit(false);
if (amin > bmax) then Exit(false);
Result := true;
end;
function allocSpan(var hf: TrcHeightfield): PrcSpan;
var pool: PrcSpanPool; freelist,head,it: PrcSpan;
begin
// If running out of memory, allocate new page and update the freelist.
if (hf.freelist = nil) or (hf.freelist.next = nil) then
begin
// Create new page.
// Allocate memory for the new pool.
GetMem(pool, SizeOf(TrcSpanPool));
// Add the pool into the list of pools.
pool.next := hf.pools;
hf.pools := pool;
// Add new items to the free list.
freelist := hf.freelist;
head := @pool.items[0];
it := @pool.items[RC_SPANS_PER_POOL-1]; Inc(it); // Delphi: Need this trick because Delphi refuses to give pointer to last+1 element
repeat
Dec(it);
it.next := freelist;
freelist := it;
until (it = head);
hf.freelist := it;
end;
// Pop item from in front of the free list.
it := hf.freelist;
hf.freelist := hf.freelist.next;
Result := it;
end;
procedure freeSpan(var hf: TrcHeightfield; ptr: PrcSpan);
begin
if (ptr = nil) then Exit;
// Add the node in front of the free list.
ptr.next := hf.freelist;
hf.freelist := ptr;
end;
procedure addSpan(var hf: TrcHeightfield; const x, y: Integer;
const smin, smax: Word;
const area: Byte; const flagMergeThr: Integer);
var idx: Integer; s: PrcSpan; prev,cur,next: PrcSpan;
begin
idx := x + y*hf.width;
s := allocSpan(hf);
s.smin := smin;
s.smax := smax;
s.area := area;
s.next := nil;
// Empty cell, add the first span.
if (hf.spans[idx] = nil) then
begin
hf.spans[idx] := s;
Exit;
end;
prev := nil;
cur := hf.spans[idx];
// Insert and merge spans.
while (cur <> nil) do
begin
if (cur.smin > s.smax) then
begin
// Current span is further than the new span, break.
break;
end
else if (cur.smax < s.smin) then
begin
// Current span is before the new span advance.
prev := cur;
cur := cur.next;
end
else
begin
// Merge spans.
if (cur.smin < s.smin) then
s.smin := cur.smin;
if (cur.smax > s.smax) then
s.smax := cur.smax;
// Merge flags.
if (Abs(s.smax - cur.smax) <= flagMergeThr) then
s.area := rcMax(s.area, cur.area);
// Remove current span.
next := cur.next;
freeSpan(hf, cur);
if (prev <> nil) then
prev.next := next
else
hf.spans[idx] := next;
cur := next;
end;
end;
// Insert new span.
if (prev <> nil) then
begin
s.next := prev.next;
prev.next := s;
end
else
begin
s.next := hf.spans[idx];
hf.spans[idx] := s;
end;
end;
/// @par
///
/// The span addition can be set to favor flags. If the span is merged to
/// another span and the new @p smax is within @p flagMergeThr units
/// from the existing span, the span flags are merged.
///
/// @see rcHeightfield, rcSpan.
procedure rcAddSpan(ctx: TrcContext; var hf: TrcHeightfield; const x, y: Integer;
const smin, smax: Word;
const area: Byte; const flagMergeThr: Integer);
begin
// rcAssert(ctx);
addSpan(hf, x,y, smin, smax, area, flagMergeThr);
end;
// divides a convex polygons into two convex polygons on both sides of a line
procedure dividePoly(&in: PSingle; nin: Integer;
out1: PSingle; nout1: PInteger;
out2: PSingle; nout2: PInteger;
x: Single; axis: Integer);
var d: array [0..11] of Single; m,n,i,j: Integer; ina,inb: Boolean; s: Single;
begin
for i := 0 to nin - 1 do
d[i] := x - &in[i*3+axis];
m := 0; n := 0;
//for (int i = 0, j = nin-1; i < nin; j=i, ++i)
i := 0;
j := nin-1;
while (i < nin) do
begin
ina := d[j] >= 0;
inb := d[i] >= 0;
if (ina <> inb) then
begin
s := d[j] / (d[j] - d[i]);
out1[m*3+0] := &in[j*3+0] + (&in[i*3+0] - &in[j*3+0])*s;
out1[m*3+1] := &in[j*3+1] + (&in[i*3+1] - &in[j*3+1])*s;
out1[m*3+2] := &in[j*3+2] + (&in[i*3+2] - &in[j*3+2])*s;
rcVcopy(out2 + n*3, out1 + m*3);
Inc(m);
Inc(n);
// add the i'th point to the right polygon. Do NOT add points that are on the dividing line
// since these were already added above
if (d[i] > 0) then
begin
rcVcopy(out1 + m*3, &in + i*3);
Inc(m);
end
else if (d[i] < 0) then
begin
rcVcopy(out2 + n*3, &in + i*3);
Inc(n);
end;
end
else // same side
begin
// add the i'th point to the right polygon. Addition is done even for points on the dividing line
if (d[i] >= 0) then
begin
rcVcopy(out1 + m*3, &in + i*3);
Inc(m);
if (d[i] <> 0) then
begin
//C++ seems to be doing loop increase, so do we
j := i;
Inc(i);
continue;
end;
end;
rcVcopy(out2 + n*3, &in + i*3);
Inc(n);
end;
j := i;
Inc(i);
end;
nout1^ := m;
nout2^ := n;
end;
procedure rasterizeTri(const v0, v1, v2: PSingle;
const area: Byte; var hf: TrcHeightfield;
bmin, bmax: PSingle;
cs,ics,ich: Single;
const flagMergeThr: Integer);
var w,h: Integer; tmin,tmax: array [0..2] of Single; by: Single; y0,y1: Integer; buf: array [0..7*3*4-1] of Single;
&in, inrow, p1, p2: PSingle; nvrow,nvIn,x,y,i,nv,nv2: Integer; cx, cz, minX, maxX,smin,smax: Single; x0,x1: Integer;
ismin,ismax: Word;
begin
w := hf.width;
h := hf.height;
by := bmax[1] - bmin[1];
// Calculate the bounding box of the triangle.
rcVcopy(@tmin[0], v0);
rcVcopy(@tmax[0], v0);
rcVmin(@tmin[0], v1);
rcVmin(@tmin[0], v2);
rcVmax(@tmax[0], v1);
rcVmax(@tmax[0], v2);
// If the triangle does not touch the bbox of the heightfield, skip the triagle.
if (not overlapBounds(bmin, bmax, @tmin[0], @tmax[0])) then
Exit;
// Calculate the footprint of the triangle on the grid's y-axis
y0 := Trunc((tmin[2] - bmin[2])*ics);
y1 := Trunc((tmax[2] - bmin[2])*ics);
y0 := rcClamp(y0, 0, h-1);
y1 := rcClamp(y1, 0, h-1);
// Clip the triangle into all grid cells it touches.
//float buf[7*3*4];
//float *in = buf, *inrow = buf+7*3, *p1 = inrow+7*3, *p2 = p1+7*3;
&in := @buf[0];
inrow := @buf[7*3];
p1 := @buf[14*3];
p2 := @buf[21*3];
rcVcopy(@&in[0], v0);
rcVcopy(@&in[1*3], v1);
rcVcopy(@&in[2*3], v2);
nvIn := 3;
for y := y0 to y1 do
begin
// Clip polygon to row. Store the remaining polygon as well
cz := bmin[2] + y*cs;
dividePoly(&in, nvIn, inrow, @nvrow, p1, @nvIn, cz+cs, 2);
rcSwap(&in, p1);
if (nvrow < 3) then continue;
// find the horizontal bounds in the row
minX := inrow[0]; maxX := inrow[0];
for i := 1 to nvrow - 1 do
begin
if (minX > inrow[i*3]) then minX := inrow[i*3];
if (maxX < inrow[i*3]) then maxX := inrow[i*3];
end;
x0 := Trunc((minX - bmin[0])*ics);
x1 := Trunc((maxX - bmin[0])*ics);
x0 := rcClamp(x0, 0, w-1);
x1 := rcClamp(x1, 0, w-1);
nv2 := nvrow;
for x := x0 to x1 do
begin
// Clip polygon to column. store the remaining polygon as well
cx := bmin[0] + x*cs;
dividePoly(inrow, nv2, p1, @nv, p2, @nv2, cx+cs, 0);
rcSwap(inrow, p2);
if (nv < 3) then continue;
// Calculate min and max of the span.
smin := p1[1]; smax := p1[1];
for i := 1 to nv - 1 do
begin
smin := rcMin(smin, p1[i*3+1]);
smax := rcMax(smax, p1[i*3+1]);
end;
smin := smin - bmin[1];
smax := smax - bmin[1];
// Skip the span if it is outside the heightfield bbox
if (smax < 0.0) then continue;
if (smin > by) then continue;
// Clamp the span to the heightfield bbox.
if (smin < 0.0) then smin := 0;
if (smax > by) then smax := by;
// Snap the span to the heightfield height grid.
ismin := rcClamp(floor(smin * ich), 0, RC_SPAN_MAX_HEIGHT);
ismax := rcClamp(ceil(smax * ich), ismin+1, RC_SPAN_MAX_HEIGHT);
addSpan(hf, x, y, ismin, ismax, area, flagMergeThr);
end;
end;
end;
/// @par
///
/// No spans will be added if the triangle does not overlap the heightfield grid.
///
/// @see rcHeightfield
procedure rcRasterizeTriangle(ctx: TrcContext; const v0, v1, v2: PSingle;
const area: Byte; var solid: TrcHeightfield;
const flagMergeThr: Integer = 1);
var ics,ich: Single;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
ics := 1.0/solid.cs;
ich := 1.0/solid.ch;
rasterizeTri(v0, v1, v2, area, solid, @solid.bmin[0], @solid.bmax[0], solid.cs, ics, ich, flagMergeThr);
ctx.stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
end;
/// @par
///
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
procedure rcRasterizeTriangles(ctx: TrcContext; const verts: PSingle; const nv: Integer;
const tris: PInteger; const areas: PByte; const nt: Integer;
var solid: TrcHeightfield; const flagMergeThr: Integer = 1);
var ics,ich: Single; i: Integer; v0,v1,v2: PSingle;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
ics := 1.0/solid.cs;
ich := 1.0/solid.ch;
// Rasterize triangles.
for i := 0 to nt - 1 do
begin
v0 := @verts[tris[i*3+0]*3];
v1 := @verts[tris[i*3+1]*3];
v2 := @verts[tris[i*3+2]*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, @solid.bmin[0], @solid.bmax[0], solid.cs, ics, ich, flagMergeThr);
end;
ctx.stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
end;
/// @par
///
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
procedure rcRasterizeTriangles(ctx: TrcContext; const verts: PSingle; const nv: Integer;
const tris: PWord; const areas: PByte; const nt: Integer;
var solid: TrcHeightfield; const flagMergeThr: Integer = 1); overload;
var ics,ich: Single; i: Integer; v0,v1,v2: PSingle;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
ics := 1.0/solid.cs;
ich := 1.0/solid.ch;
// Rasterize triangles.
for i := 0 to nt - 1 do
begin
v0 := @verts[tris[i*3+0]*3];
v1 := @verts[tris[i*3+1]*3];
v2 := @verts[tris[i*3+2]*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, @solid.bmin[0], @solid.bmax[0], solid.cs, ics, ich, flagMergeThr);
end;
ctx.stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
end;
/// @par
///
/// Spans will only be added for triangles that overlap the heightfield grid.
///
/// @see rcHeightfield
procedure rcRasterizeTriangles(ctx: TrcContext; const verts: PSingle; const areas: PByte; const nt: Integer;
var solid: TrcHeightfield; const flagMergeThr: Integer = 1); overload;
var ics,ich: Single; i: Integer; v0,v1,v2: PSingle;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_RASTERIZE_TRIANGLES);
ics := 1.0/solid.cs;
ich := 1.0/solid.ch;
// Rasterize triangles.
for i := 0 to nt - 1 do
begin
v0 := @verts[(i*3+0)*3];
v1 := @verts[(i*3+1)*3];
v2 := @verts[(i*3+2)*3];
// Rasterize.
rasterizeTri(v0, v1, v2, areas[i], solid, @solid.bmin[0], @solid.bmax[0], solid.cs, ics, ich, flagMergeThr);
end;
ctx.stopTimer(RC_TIMER_RASTERIZE_TRIANGLES);
end;
end.
|
{ History:
Yar - 19/06/11 - Fixed names of entry points in Windows (thanks to Johannes Pretorius, Bugtracker ID = 3319369)
DaStr - 07/11/09 - Added $I GLScene.inc for Delhi 5 compatibility
Improved FPC compatibility (thanks Predator) (BugtrackerID = 2893580)
}
{ ============================================================================================ }
{ FMOD Main header file. Copyright (c), FireLight Technologies Pty, Ltd. 1999-2003. }
{ =========================================================================================== }
{
NOTE: For the demos to run you must have either fmod.dll (in Windows)
or libfmod-3.75.so (in Linux) installed.
In Windows, copy the fmod.dll file found in the api directory to either of
the following locations (in order of preference)
- your application directory
- Windows\System (95/98) or WinNT\System32 (NT/2000/XP)
In Linux, make sure you are signed in as root and copy the libfmod-3.75.so
file from the api directory to your /usr/lib/ directory.
Then via a command line, navigate to the /usr/lib/ directory and create
a symbolic link between libfmod-3.75.so and libfmod.so. This is done with
the following command (assuming you are in /usr/lib/)...
ln -s libfmod-3.75.so libfmod.so.
}
{ =============================================================================================== }
unit fmoddyn;
interface
{$I GLScene.inc}
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
fmodtypes;
// ===============================================================================================
// FUNCTION PROTOTYPES
// ===============================================================================================
{ ================================== }
{ Library load/unload functions. }
{ ================================== }
{
If no library name is passed to FMOD_Load, then the default library name
used.
}
function FMOD_Load(LibName: PChar = nil): boolean;
procedure FMOD_Unload;
{ ================================== }
{ Initialization / Global functions. }
{ ================================== }
{
Pre FSOUND_Init functions. These can't be called after FSOUND_Init is
called (they will fail). They set up FMOD system functionality.
}
var
FSOUND_SetOutput: function(OutputType: TFSoundOutputTypes): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetDriver: function(Driver: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetMixer: function(Mixer: TFSoundMixerTypes): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetBufferSize: function(LenMs: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetHWND: function(Hwnd: THandle): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetMinHardwareChannels: function(Min: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetMaxHardwareChannels: function(Max: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetMemorySystem: function(Pool: Pointer; PoolLen: integer;
UserAlloc: TFSoundAllocCallback; UserRealloc: TFSoundReallocCallback;
UserFree: TFSoundFreeCallback): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Main initialization / closedown functions
Note : Use FSOUND_INIT_USEDEFAULTMIDISYNTH with FSOUND_Init for software override with MIDI playback.
: Use FSOUND_INIT_GLOBALFOCUS with FSOUND_Init to make sound audible
no matter which window is in focus. (FSOUND_OUTPUT_DSOUND only)
}
var
FSOUND_Init: function(MixRate: integer; MaxSoftwareChannels: integer;
Flags: cardinal): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Close: procedure; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Runtime system level functions
}
var
FSOUND_Update: procedure; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
// This is called to update 3d sound / non-realtime output
FSOUND_SetSpeakerMode: procedure(SpeakerMode: cardinal);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetSFXMasterVolume: procedure(Volume: integer);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetPanSeperation: procedure(PanSep: single);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_File_SetCallbacks: procedure(OpenCallback: TFSoundOpenCallback;
CloseCallback: TFSoundCloseCallback; ReadCallback: TFSoundReadCallback;
SeekCallback: TFSoundSeekCallback; TellCallback: TFSoundTellCallback);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
System information functions
}
var
FSOUND_GetError: function: TFModErrors; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetVersion: function: single; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetOutput: function: TFSoundOutputTypes;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetOutputHandle: function: Pointer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetDriver: function: integer; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetMixer: function: TFSoundMixerTypes;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetNumDrivers: function: integer; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetDriverName: function(Id: integer): PChar;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetDriverCaps: function(Id: integer; var Caps: cardinal): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
var
FSOUND_GetOutputRate: function: integer; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetMaxChannels: function: integer; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetMaxSamples: function: integer; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetSpeakerMode: function: integer; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetSFXMasterVolume: function: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetNumHWChannels: function(var Num2D: integer; var Num3D: integer;
var Total: integer): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetChannelsPlaying: function: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetCPUUsage: function: single; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_GetMemoryStats: procedure(var CurrentAlloced: cardinal;
var MaxAlloced: cardinal); {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ =================================== }
{ Sample management / load functions. }
{ =================================== }
{
Sample creation and management functions
Note : Use FSOUND_LOADMEMORY flag with FSOUND_Sample_Load to load from memory.
Use FSOUND_LOADRAW flag with FSOUND_Sample_Load to treat as as raw pcm data.
}
var
FSOUND_Sample_Load: function(Index: integer; const NameOrData: PChar;
Mode: cardinal; Offset: integer; Length: integer): PFSoundSample;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_Alloc: function(Index: integer; Length: integer; Mode: cardinal;
DefFreq: integer; DefVol: integer; DefPan: integer; DefPri: integer)
: PFSoundSample; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_Free: procedure(Sptr: PFSoundSample);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_Upload: function(Sptr: PFSoundSample; SrcData: Pointer;
Mode: cardinal): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_Lock: function(Sptr: PFSoundSample; Offset: integer;
Length: integer; var Ptr1: Pointer; var Ptr2: Pointer; var Len1: cardinal;
var Len2: cardinal): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_Unlock: function(Sptr: PFSoundSample; Ptr1: Pointer;
Ptr2: Pointer; Len1: cardinal; Len2: cardinal): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Sample control functions
}
var
FSOUND_Sample_SetMode: function(Sptr: PFSoundSample; Mode: cardinal)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_SetLoopPoints: function(Sptr: PFSoundSample;
LoopStart, LoopEnd: integer): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_Sample_SetDefaults: function(Sptr: PFSoundSample;
DefFreq, DefVol, DefPan, DefPri: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_SetDefaultsEx: function(Sptr: PFSoundSample;
DefFreq, DefVol, DefPan, DefPri, VarFreq, VarVol, VarPan: integer)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_SetMinMaxDistance: function(Sptr: PFSoundSample;
Min, Max: single): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_SetMaxPlaybacks: function(Sptr: PFSoundSample; Max: integer)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Sample information functions
}
var
FSOUND_Sample_Get: function(SampNo: integer): PFSoundSample;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_GetName: function(Sptr: PFSoundSample): PChar;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_GetLength: function(Sptr: PFSoundSample): cardinal;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_GetLoopPoints: function(Sptr: PFSoundSample;
var LoopStart: integer; var LoopEnd: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_GetDefaults: function(Sptr: PFSoundSample; var DefFreq: integer;
var DefVol: integer; var DefPan: integer; var DefPri: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_GetDefaultsEx: function(Sptr: PFSoundSample;
var DefFreq: integer; var DefVol: integer; var DefPan: integer;
var DefPri: integer; var VarFreq: integer; var VarVol: integer; var VarPan)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_GetMode: function(Sptr: PFSoundSample): cardinal;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Sample_GetMinMaxDistance: function(Sptr: PFSoundSample;
var Min: single; var Max: single): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ ============================ }
{ Channel control functions. }
{ ============================ }
{
Playing and stopping sounds.
Note : Use FSOUND_FREE as the 'channel' variable, to let FMOD pick a free channel for you.
Use FSOUND_ALL as the 'channel' variable to control ALL channels with one function call!
}
var
FSOUND_PlaySound: function(Channel: integer; Sptr: PFSoundSample): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_PlaySoundEx: function(Channel: integer; Sptr: PFSoundSample;
Dsp: PFSoundDSPUnit; StartPaused: bytebool): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_StopSound: function(Channel: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Functions to control playback of a channel.
}
var
FSOUND_SetFrequency: function(Channel: integer; Freq: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetVolume: function(Channel: integer; Vol: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetVolumeAbsolute: function(Channel: integer; Vol: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetPan: function(Channel: integer; Pan: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetSurround: function(Channel: integer; Surround: bytebool): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetMute: function(Channel: integer; Mute: bytebool): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetPriority: function(Channel: integer; Priority: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetReserved: function(Channel: integer; Reserved: bytebool): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetPaused: function(Channel: integer; Paused: bytebool): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetLoopMode: function(Channel: integer; LoopMode: cardinal): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_SetCurrentPosition: function(Channel: integer; Offset: cardinal)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_SetAttributes: function(Channel: integer; Pos: PFSoundVector;
Vel: PFSoundVector): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_SetMinMaxDistance: function(Channel: integer; Min: single;
Max: single): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Channel information functions
}
var
FSOUND_IsPlaying: function(Channel: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetFrequency: function(Channel: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetVolume: function(Channel: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetAmplitude: function(Channel: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetPan: function(Channel: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetSurround: function(Channel: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetMute: function(Channel: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetPriority: function(Channel: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetReserved: function(Channel: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetPaused: function(Channel: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetLoopMode: function(Channel: integer): cardinal;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetCurrentPosition: function(Channel: integer): cardinal;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetCurrentSample: function(Channel: integer): PFSoundSample;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetCurrentLevels: function(Channel: integer; L, R: PSingle): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetNumSubChannels: function(Channel: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_GetSubChannel: function(Channel: integer; SubChannel: integer)
: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_GetAttributes: function(Channel: integer; Pos: PFSoundVector;
Vel: PFSoundVector): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_GetMinMaxDistance: function(Channel: integer; var Min: single;
var Max: single): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ =================== }
{ 3D sound functions. }
{ =================== }
{
See also 3d sample and channel based functions above.
Call FSOUND_Update once a frame to process 3d information.
}
var
FSOUND_3D_Listener_SetCurrent: procedure(current: integer);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_Listener_SetAttributes: procedure(Pos: PFSoundVector;
Vel: PFSoundVector; fx: single; fy: single; fz: single; tx: single;
ty: single; tz: single); {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_Listener_GetAttributes: procedure(Pos: PFSoundVector;
Vel: PFSoundVector; fx: PSingle; fy: PSingle; fz: PSingle; tx: PSingle;
ty: PSingle; tz: PSingle); {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_SetDopplerFactor: procedure(Scale: single);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_SetDistanceFactor: procedure(Scale: single);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_3D_SetRolloffFactor: procedure(Scale: single);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ =================== }
{ FX functions. }
{ =================== }
{
Functions to control DX8 only effects processing.
- FX enabled samples can only be played once at a time, not multiple times at once.
- Sounds have to be created with FSOUND_HW2D or FSOUND_HW3D for this to work.
- FSOUND_INIT_ENABLESYSTEMCHANNELFX can be used to apply hardware effect processing to the
global mixed output of FMOD's software channels.
- FSOUND_FX_Enable returns an FX handle that you can use to alter fx parameters.
- FSOUND_FX_Enable can be called multiple times in a row, even on the same FX type,
it will return a unique handle for each FX.
- FSOUND_FX_Enable cannot be called if the sound is playing or locked.
- Stopping or starting a sound resets all FX and they must be re-enabled each time
if this happens.
}
var
FSOUND_FX_Enable: function(Channel: integer; fx: TFSoundFXModes): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF}; { Set bits to enable following fx }
FSOUND_FX_Disable: function(Channel: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetChorus: function(FXId: integer; WetDryMix, Depth, Feedback,
Frequency: single; Waveform: integer; Delay: single; Phase: integer)
: bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetCompressor: function(FXId: integer;
Gain, Attack, Release, Threshold, Ratio, Predelay: single): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetDistortion: function(FXId: integer;
Gain, Edge, PostEQCenterFrequency, PostEQBandwidth, PreLowpassCutoff
: single): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetEcho: function(FXId: integer; WetDryMix, Feedback, LeftDelay,
RightDelay: single; PanDelay: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetFlanger: function(FXId: integer;
WetDryMix, Depth, Feedback, Frequency: single; Waveform: integer;
Delay: single; Phase: integer): bytebool; {$IFDEF UNIX} cdecl
{$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetGargle: function(FXId, RateHz, WaveShape: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetI3DL2Reverb: function(FXId, Room, RoomHF: integer;
RoomRolloffFactor, DecayTime, DecayHFRatio: single; Reflections: integer;
ReflectionsDelay: single; Reverb: integer; ReverbDelay, Diffusion, Density,
HFReference: single): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetParamEQ: function(FXId: integer; Center, Bandwidth, Gain: single)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_FX_SetWavesReverb: function(FXId: integer;
InGain, ReverbMix, ReverbTime, HighFreqRTRatio: single): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ ========================= }
{ File Streaming functions. }
{ ========================= }
{
Note : Use FSOUND_LOADMEMORY flag with FSOUND_Stream_Open to stream from memory.
Use FSOUND_LOADRAW flag with FSOUND_Stream_Open to treat stream as raw pcm data.
Use FSOUND_MPEGACCURATE flag with FSOUND_Stream_Open to open mpegs in 'accurate mode' for settime/gettime/getlengthms.
Use FSOUND_FREE as the 'channel' variable, to let FMOD pick a free channel for you.
}
var
// call this before opening streams, not after
FSOUND_Stream_SetBufferSize: function(Ms: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Open: function(const name_or_data: PChar; Mode: cardinal;
Offset: integer; Length: integer): PFSoundStream;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Create: function(Callback: TFSoundStreamCallback;
Length: integer; Mode: cardinal; SampleRate: integer; UserData: integer)
: PFSoundStream;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Close: function(Stream: PFSoundStream): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Play: function(Channel: integer; Stream: PFSoundStream)
: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_PlayEx: function(Channel: integer; Stream: PFSoundStream;
Dsp: PFSoundDSPUnit; StartPaused: bytebool): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Stop: function(Stream: PFSoundStream): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetPosition: function(Stream: PFSoundStream; Position: cardinal)
: bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetPosition: function(Stream: PFSoundStream): cardinal;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetTime: function(Stream: PFSoundStream; Ms: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetTime: function(Stream: PFSoundStream): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetLength: function(Stream: PFSoundStream): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetLengthMs: function(Stream: PFSoundStream): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetMode: function(Stream: PFSoundStream; Mode: integer)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetMode: function(Stream: PFSoundStream): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetLoopPoints: function(Stream: PFSoundStream;
LoopStartPCM, LoopEndPCM: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetLoopCount: function(Stream: PFSoundStream; Count: integer)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetOpenState: function(Stream: PFSoundStream): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetSample: function(Stream: PFSoundStream): PFSoundSample;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ Every stream contains a sample to play back on }
FSOUND_Stream_CreateDSP: function(Stream: PFSoundStream;
Callback: TFSoundDSPCallback; Priority: integer; Param: integer)
: PFSoundDSPUnit;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetEndCallback: function(Stream: PFSoundStream;
Callback: TFSoundStreamCallback; UserData: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetSyncCallback: function(Stream: PFSoundStream;
Callback: TFSoundStreamCallback; UserData: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_AddSyncPoint: function(Stream: PFSoundStream;
PCMOffset: cardinal; Name: PChar): PFSyncPoint;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_DeleteSyncPoint: function(Point: PFSyncPoint): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetNumSyncPoints: function(Stream: PFSoundStream): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetSyncPoint: function(Stream: PFSoundStream; Index: integer)
: PFSyncPoint; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetSyncPointInfo: function(Point: PFSyncPoint;
var PCMOffset: cardinal): integer; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_Stream_SetSubStream: function(Stream: PFSoundStream; Index: integer)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetNumSubStreams: function(Stream: PFSoundStream): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_SetSubStreamSentence: function(Stream: PFSoundStream;
var sentencelist: cardinal; numitems: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetNumTagFields: function(Stream: PFSoundStream;
var Num: integer): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_GetTagField: function(Stream: PFSoundStream; Num: integer;
var _Type: TFSoundTagFieldType; var Name: PChar; var Value: Pointer;
var Length: integer): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_Stream_FindTagField: function(Stream: PFSoundStream;
_Type: TFSoundTagFieldType; Name: PChar; var Value: Pointer;
var Length: integer): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_Stream_Net_SetProxy: function(Proxy: PChar): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Net_GetLastServerStatus: function: PChar;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Net_SetBufferProperties: function(BufferSize: integer;
PreBuffer_Percent: integer; ReBuffer_Percent: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Net_GetBufferProperties: function(var BufferSize: integer;
var PreBuffer_Percent: integer; var ReBuffer_Percent: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Net_SetMetadataCallback: function(Stream: PFSoundStream;
Callback: TFMetaDataCallback; UserData: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Stream_Net_GetStatus: function(Stream: PFSoundStream;
var Status: TFSoundStreamNetStatus; var BufferPercentUsed: integer;
var BitRate: integer; var Flags: cardinal): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ =================== }
{ CD audio functions. }
{ =================== }
{
Note : 0 = default cdrom. Otherwise specify the drive letter, for example. 'D'.
}
var
FSOUND_CD_Play: function(Drive: byte; Track: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_SetPlayMode: procedure(Drive: byte; Mode: integer);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_Stop: function(Drive: byte): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_SetPaused: function(Drive: byte; Paused: bytebool): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_SetVolume: function(Drive: byte; Volume: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_SetTrackTime: function(Drive: byte; Ms: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_OpenTray: function(Drive: byte; Open: byte): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
var
FSOUND_CD_GetPaused: function(Drive: byte): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_GetTrack: function(Drive: byte): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_GetNumTracks: function(Drive: byte): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_GetVolume: function(Drive: byte): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_GetTrackLength: function(Drive: byte; Track: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_CD_GetTrackTime: function(Drive: byte): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ ============== }
{ DSP functions. }
{ ============== }
{
DSP Unit control and information functions.
}
var
FSOUND_DSP_Create: function(Callback: TFSoundDSPCallback; Priority: integer;
Param: integer): PFSoundDSPUnit;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_Free: procedure(DSPUnit: PFSoundDSPUnit);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_SetPriority: procedure(DSPUnit: PFSoundDSPUnit; Priority: integer);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_GetPriority: function(DSPUnit: PFSoundDSPUnit): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_SetActive: procedure(DSPUnit: PFSoundDSPUnit; Active: bytebool);
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_GetActive: function(DSPUnit: PFSoundDSPUnit): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Functions to get hold of FSOUND 'system DSP unit' handles.
}
var
FSOUND_DSP_GetClearUnit: function: PFSoundDSPUnit;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_GetSFXUnit: function: PFSoundDSPUnit;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_GetMusicUnit: function: PFSoundDSPUnit;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_GetClipAndCopyUnit: function: PFSoundDSPUnit;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_GetFFTUnit: function: PFSoundDSPUnit;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Miscellaneous DSP functions
Note for the spectrum analysis function to work, you have to enable the FFT DSP unit with
the following code FSOUND_DSP_SetActive(FSOUND_DSP_GetFFTUnit(), TRUE);
It is off by default to save cpu usage.
}
var
FSOUND_DSP_MixBuffers: function(DestBuffer: Pointer; SrcBuffer: Pointer;
Len: integer; Freq: integer; Vol: integer; Pan: integer; Mode: cardinal)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_DSP_ClearMixBuffer: procedure; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_DSP_GetBufferLength: function: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF}; { Length of each DSP update }
FSOUND_DSP_GetBufferLengthTotal: function: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ Total buffer length due to FSOUND_SetBufferSize }
FSOUND_DSP_GetSpectrum: function: PSingle;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ Array of 512 floats - call FSOUND_DSP_SetActive(FSOUND_DSP_GetFFTUnit(), TRUE)) for this to work. }
{ ========================================================================== }
{ Reverb functions. (eax2/eax3 reverb) (NOT SUPPORTED IN LINUX/CE) }
{ ========================================================================== }
{
See structures above for definitions and information on the reverb parameters.
}
var
FSOUND_Reverb_SetProperties: function(const Prop: TFSoundReverbProperties)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Reverb_GetProperties: function(var Prop: TFSoundReverbProperties)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Reverb_SetChannelProperties: function(Channel: integer;
var Prop: TFSoundReverbChannelProperties): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Reverb_GetChannelProperties: function(Channel: integer;
var Prop: TFSoundReverbChannelProperties): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ ================================================ }
{ Recording functions (NOT SUPPORTED IN LINUX/MAC) }
{ ================================================ }
{
Recording initialization functions
}
var
FSOUND_Record_SetDriver: function(OutputType: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Record_GetNumDrivers: function: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Record_GetDriverName: function(Id: integer): PChar;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Record_GetDriver: function: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Recording functionality. Only one recording session will work at a time.
}
var
FSOUND_Record_StartSample: function(Sptr: PFSoundSample; Loop: bytebool)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FSOUND_Record_Stop: function: bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FSOUND_Record_GetPosition: function: integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{ ============================================================================================= }
{ FMUSIC API (MOD,S3M,XM,IT,MIDI PLAYBACK) }
{ ============================================================================================= }
{
Song management / playback functions.
}
var
FMUSIC_LoadSong: function(const Name: PChar): PFMusicModule;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_LoadSongEx: function(name_or_data: Pointer; Offset: integer;
Length: integer; Mode: cardinal; var SampleList: integer;
SampleListNum: integer): PFMusicModule; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FMUSIC_GetOpenState: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_FreeSong: function(Module: PFMusicModule): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_PlaySong: function(Module: PFMusicModule): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_StopSong: function(Module: PFMusicModule): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_StopAllSongs: procedure; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
var
FMUSIC_SetZxxCallback: function(Module: PFMusicModule;
Callback: TFMusicCallback): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FMUSIC_SetRowCallback: function(Module: PFMusicModule;
Callback: TFMusicCallback; RowStep: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetOrderCallback: function(Module: PFMusicModule;
Callback: TFMusicCallback; OrderStep: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetInstCallback: function(Module: PFMusicModule;
Callback: TFMusicCallback; Instrument: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
var
FMUSIC_SetSample: function(Module: PFMusicModule; SampNo: integer;
Sptr: PFSoundSample): bytebool; {$IFDEF UNIX} cdecl {$ELSE} stdcall
{$ENDIF};
FMUSIC_SetUserData: function(Module: PFMusicModule; UserData: integer)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_OptimizeChannels: function(Module: PFMusicModule; MaxChannels: integer;
MinVolume: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Runtime song functions.
}
var
FMUSIC_SetReverb: function(Reverb: bytebool): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetLooping: function(Module: PFMusicModule; Looping: bytebool)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetOrder: function(Module: PFMusicModule; Order: integer): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetPaused: function(Module: PFMusicModule; Pause: bytebool): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetMasterVolume: function(Module: PFMusicModule; Volume: integer)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetMasterSpeed: function(Module: PFMusicModule; Speed: single)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_SetPanSeperation: function(Module: PFMusicModule; PanSep: single)
: bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Static song information functions.
}
var
FMUSIC_GetName: function(Module: PFMusicModule): PChar;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetType: function(Module: PFMusicModule): TFMusicTypes;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetNumOrders: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetNumPatterns: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetNumInstruments: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetNumSamples: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetNumChannels: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetSample: function(Module: PFMusicModule; SampNo: integer)
: PFSoundSample;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetPatternLength: function(Module: PFMusicModule;
OrderNo: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
Runtime song information.
}
var
FMUSIC_IsFinished: function(Module: PFMusicModule): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_IsPlaying: function(Module: PFMusicModule): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetMasterVolume: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetGlobalVolume: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetOrder: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetPattern: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetSpeed: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetBPM: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetRow: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetPaused: function(Module: PFMusicModule): bytebool;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetTime: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetRealChannel: function(Module: PFMusicModule;
ModChannel: integer): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
FMUSIC_GetUserData: function(Module: PFMusicModule): integer;
{$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
implementation
uses
{$IFDEF UNIX}
{$IFDEF LINUX}
Libc,
{$ENDIF}
dynlibs,
{$ENDIF}
GLSLog;
const
{$IFDEF LINUX}
FMOD_DLL = 'libfmod.so';
{$ELSE}
{$IFDEF MSWINDOWS}
FMOD_DLL = 'fmod.dll';
{$ENDIF}
{$IFDEF DARWIN}
FMOD_DLL = 'fmod.dylib';
{$ENDIF}
{$ENDIF}
type
{$IFDEF UNIX}
TFMODModuleHandle = TLibHandle;
{$ELSE}
TFMODModuleHandle = HINST;
{$ENDIF}
const
INVALID_MODULEHANDLE_VALUE = TFMODModuleHandle(0);
var
FMODHandle: TFMODModuleHandle;
function GetAddress(Handle: TFMODModuleHandle; FuncName: PChar): Pointer;
begin
Result := GetProcAddress(Handle, FuncName);
if not Assigned(Result) then
GLSLogger.LogErrorFmt('Failed to find "%s" in "%s"', [FuncName, FMOD_DLL]);
end;
function FMOD_Load(LibName: PChar): boolean;
begin
Result := False;
{ Make sure the previous library is unloaded }
FMOD_Unload;
{ If no library name given, use the default library names }
if LibName = nil then
LibName := FMOD_DLL;
{ Load the library }
FMODHandle := INVALID_MODULEHANDLE_VALUE;
FMODHandle := LoadLibrary(LibName);
if FMODHandle = INVALID_MODULEHANDLE_VALUE then
Exit;
{ Get all the function addresses from the library }
{$IFDEF MSWINDOWS}
FMUSIC_FreeSong := GetAddress(FMODHandle, '_FMUSIC_FreeSong@4');
FMUSIC_GetBPM := GetAddress(FMODHandle, '_FMUSIC_GetBPM@4');
FMUSIC_GetGlobalVolume := GetAddress(FMODHandle, '_FMUSIC_GetGlobalVolume@4');
FMUSIC_GetMasterVolume := GetAddress(FMODHandle, '_FMUSIC_GetMasterVolume@4');
FMUSIC_GetName := GetAddress(FMODHandle, '_FMUSIC_GetName@4');
FMUSIC_GetNumChannels := GetAddress(FMODHandle, '_FMUSIC_GetNumChannels@4');
FMUSIC_GetNumInstruments := GetAddress(FMODHandle,
'_FMUSIC_GetNumInstruments@4');
FMUSIC_GetNumOrders := GetAddress(FMODHandle, '_FMUSIC_GetNumOrders@4');
FMUSIC_GetNumPatterns := GetAddress(FMODHandle, '_FMUSIC_GetNumPatterns@4');
FMUSIC_GetNumSamples := GetAddress(FMODHandle, '_FMUSIC_GetNumSamples@4');
FMUSIC_GetOpenState := GetAddress(FMODHandle, '_FMUSIC_GetOpenState@4');
FMUSIC_GetOrder := GetAddress(FMODHandle, '_FMUSIC_GetOrder@4');
FMUSIC_GetPattern := GetAddress(FMODHandle, '_FMUSIC_GetPattern@4');
FMUSIC_GetPatternLength := GetAddress(FMODHandle,
'_FMUSIC_GetPatternLength@8');
FMUSIC_GetPaused := GetAddress(FMODHandle, '_FMUSIC_GetPaused@4');
FMUSIC_GetRealChannel := GetAddress(FMODHandle, '_FMUSIC_GetRealChannel@8');
FMUSIC_GetRow := GetAddress(FMODHandle, '_FMUSIC_GetRow@4');
FMUSIC_GetSample := GetAddress(FMODHandle, '_FMUSIC_GetSample@8');
FMUSIC_GetSpeed := GetAddress(FMODHandle, '_FMUSIC_GetSpeed@4');
FMUSIC_GetTime := GetAddress(FMODHandle, '_FMUSIC_GetTime@4');
FMUSIC_GetType := GetAddress(FMODHandle, '_FMUSIC_GetType@4');
FMUSIC_GetUserData := GetAddress(FMODHandle, '_FMUSIC_GetUserData@4');
FMUSIC_IsFinished := GetAddress(FMODHandle, '_FMUSIC_IsFinished@4');
FMUSIC_IsPlaying := GetAddress(FMODHandle, '_FMUSIC_IsPlaying@4');
FMUSIC_LoadSong := GetAddress(FMODHandle, '_FMUSIC_LoadSong@4');
FMUSIC_LoadSongEx := GetAddress(FMODHandle, '_FMUSIC_LoadSongEx@24');
FMUSIC_OptimizeChannels := GetAddress(FMODHandle,
'_FMUSIC_OptimizeChannels@12');
FMUSIC_PlaySong := GetAddress(FMODHandle, '_FMUSIC_PlaySong@4');
FMUSIC_SetInstCallback := GetAddress(FMODHandle,
'_FMUSIC_SetInstCallback@12');
FMUSIC_SetLooping := GetAddress(FMODHandle, '_FMUSIC_SetLooping@8');
FMUSIC_SetMasterSpeed := GetAddress(FMODHandle, '_FMUSIC_SetMasterSpeed@8');
FMUSIC_SetMasterVolume := GetAddress(FMODHandle, '_FMUSIC_SetMasterVolume@8');
FMUSIC_SetOrder := GetAddress(FMODHandle, '_FMUSIC_SetOrder@8');
FMUSIC_SetOrderCallback := GetAddress(FMODHandle,
'_FMUSIC_SetOrderCallback@12');
FMUSIC_SetPanSeperation := GetAddress(FMODHandle,
'_FMUSIC_SetPanSeperation@8');
FMUSIC_SetPaused := GetAddress(FMODHandle, '_FMUSIC_SetPaused@8');
FMUSIC_SetReverb := GetAddress(FMODHandle, '_FMUSIC_SetReverb@4');
FMUSIC_SetRowCallback := GetAddress(FMODHandle, '_FMUSIC_SetRowCallback@12');
FMUSIC_SetSample := GetAddress(FMODHandle, '_FMUSIC_SetSample@12');
FMUSIC_SetUserData := GetAddress(FMODHandle, '_FMUSIC_SetUserData@8');
FMUSIC_SetZxxCallback := GetAddress(FMODHandle, '_FMUSIC_SetZxxCallback@8');
FMUSIC_StopAllSongs := GetAddress(FMODHandle, '_FMUSIC_StopAllSongs@0');
FMUSIC_StopSong := GetAddress(FMODHandle, '_FMUSIC_StopSong@4');
FSOUND_3D_GetAttributes := GetAddress(FMODHandle,
'_FSOUND_3D_GetAttributes@12');
FSOUND_3D_GetMinMaxDistance := GetAddress(FMODHandle,
'_FSOUND_3D_GetMinMaxDistance@12');
FSOUND_3D_Listener_GetAttributes := GetAddress(FMODHandle,
'_FSOUND_3D_Listener_GetAttributes@32');
FSOUND_3D_Listener_SetAttributes := GetAddress(FMODHandle,
'_FSOUND_3D_Listener_SetAttributes@32');
FSOUND_3D_Listener_SetCurrent := GetAddress(FMODHandle,
'_FSOUND_3D_Listener_SetCurrent@8');
FSOUND_3D_SetAttributes := GetAddress(FMODHandle,
'_FSOUND_3D_SetAttributes@12');
FSOUND_3D_SetDistanceFactor := GetAddress(FMODHandle,
'_FSOUND_3D_SetDistanceFactor@4');
FSOUND_3D_SetDopplerFactor := GetAddress(FMODHandle,
'_FSOUND_3D_SetDopplerFactor@4');
FSOUND_3D_SetMinMaxDistance := GetAddress(FMODHandle,
'_FSOUND_3D_SetMinMaxDistance@12');
FSOUND_3D_SetRolloffFactor := GetAddress(FMODHandle,
'_FSOUND_3D_SetRolloffFactor@4');
// FSOUND_CD_Eject := GetAddress(FMODHandle,'_FSOUND_CD_Eject@4');
FSOUND_CD_GetNumTracks := GetAddress(FMODHandle, '_FSOUND_CD_GetNumTracks@4');
FSOUND_CD_GetPaused := GetAddress(FMODHandle, '_FSOUND_CD_GetPaused@4');
FSOUND_CD_GetTrack := GetAddress(FMODHandle, '_FSOUND_CD_GetTrack@4');
FSOUND_CD_GetTrackLength := GetAddress(FMODHandle,
'_FSOUND_CD_GetTrackLength@8');
FSOUND_CD_GetTrackTime := GetAddress(FMODHandle, '_FSOUND_CD_GetTrackTime@4');
FSOUND_CD_GetVolume := GetAddress(FMODHandle, '_FSOUND_CD_GetVolume@4');
FSOUND_CD_OpenTray := GetAddress(FMODHandle, '_FSOUND_CD_OpenTray@8');
FSOUND_CD_Play := GetAddress(FMODHandle, '_FSOUND_CD_Play@8');
FSOUND_CD_SetPaused := GetAddress(FMODHandle, '_FSOUND_CD_SetPaused@8');
FSOUND_CD_SetPlayMode := GetAddress(FMODHandle, '_FSOUND_CD_SetPlayMode@8');
FSOUND_CD_SetTrackTime := GetAddress(FMODHandle, '_FSOUND_CD_SetTrackTime@8');
FSOUND_CD_SetVolume := GetAddress(FMODHandle, '_FSOUND_CD_SetVolume@8');
FSOUND_CD_Stop := GetAddress(FMODHandle, '_FSOUND_CD_Stop@4');
FSOUND_Close := GetAddress(FMODHandle, '_FSOUND_Close@0');
FSOUND_DSP_ClearMixBuffer := GetAddress(FMODHandle,
'_FSOUND_DSP_ClearMixBuffer@0');
FSOUND_DSP_Create := GetAddress(FMODHandle, '_FSOUND_DSP_Create@12');
FSOUND_DSP_Free := GetAddress(FMODHandle, '_FSOUND_DSP_Free@4');
FSOUND_DSP_GetActive := GetAddress(FMODHandle, '_FSOUND_DSP_GetActive@4');
FSOUND_DSP_GetBufferLength := GetAddress(FMODHandle,
'_FSOUND_DSP_GetBufferLength@0');
FSOUND_DSP_GetBufferLengthTotal := GetAddress(FMODHandle,
'_FSOUND_DSP_GetBufferLengthTotal@0');
FSOUND_DSP_GetClearUnit := GetAddress(FMODHandle,
'_FSOUND_DSP_GetClearUnit@0');
FSOUND_DSP_GetClipAndCopyUnit := GetAddress(FMODHandle,
'_FSOUND_DSP_GetClipAndCopyUnit@0');
FSOUND_DSP_GetFFTUnit := GetAddress(FMODHandle, '_FSOUND_DSP_GetFFTUnit@0');
FSOUND_DSP_GetMusicUnit := GetAddress(FMODHandle,
'_FSOUND_DSP_GetMusicUnit@0');
FSOUND_DSP_GetPriority := GetAddress(FMODHandle, '_FSOUND_DSP_GetPriority@4');
FSOUND_DSP_GetSFXUnit := GetAddress(FMODHandle, '_FSOUND_DSP_GetSFXUnit@0');
FSOUND_DSP_GetSpectrum := GetAddress(FMODHandle, '_FSOUND_DSP_GetSpectrum@0');
FSOUND_DSP_MixBuffers := GetAddress(FMODHandle, '_FSOUND_DSP_MixBuffers@28');
FSOUND_DSP_SetActive := GetAddress(FMODHandle, '_FSOUND_DSP_SetActive@8');
FSOUND_DSP_SetPriority := GetAddress(FMODHandle, '_FSOUND_DSP_SetPriority@8');
FSOUND_File_SetCallbacks := GetAddress(FMODHandle,
'_FSOUND_File_SetCallbacks@20');
FSOUND_FX_Disable := GetAddress(FMODHandle, '_FSOUND_FX_Disable@4');
FSOUND_FX_Enable := GetAddress(FMODHandle, '_FSOUND_FX_Enable@8');
FSOUND_FX_SetChorus := GetAddress(FMODHandle, '_FSOUND_FX_SetChorus@32');
FSOUND_FX_SetCompressor := GetAddress(FMODHandle,
'_FSOUND_FX_SetCompressor@28');
FSOUND_FX_SetDistortion := GetAddress(FMODHandle,
'_FSOUND_FX_SetDistortion@24');
FSOUND_FX_SetEcho := GetAddress(FMODHandle, '_FSOUND_FX_SetEcho@24');
FSOUND_FX_SetFlanger := GetAddress(FMODHandle, '_FSOUND_FX_SetFlanger@32');
FSOUND_FX_SetGargle := GetAddress(FMODHandle, '_FSOUND_FX_SetGargle@12');
FSOUND_FX_SetI3DL2Reverb := GetAddress(FMODHandle,
'_FSOUND_FX_SetI3DL2Reverb@52');
FSOUND_FX_SetParamEQ := GetAddress(FMODHandle, '_FSOUND_FX_SetParamEQ@16');
FSOUND_FX_SetWavesReverb := GetAddress(FMODHandle,
'_FSOUND_FX_SetWavesReverb@20');
FSOUND_GetAmplitude := GetAddress(FMODHandle, '_FSOUND_GetAmplitude@4');
FSOUND_GetChannelsPlaying := GetAddress(FMODHandle,
'_FSOUND_GetChannelsPlaying@0');
FSOUND_GetCPUUsage := GetAddress(FMODHandle, '_FSOUND_GetCPUUsage@0');
FSOUND_GetCurrentLevels := GetAddress(FMODHandle,
'_FSOUND_GetCurrentLevels@12');
FSOUND_GetCurrentPosition := GetAddress(FMODHandle,
'_FSOUND_GetCurrentPosition@4');
FSOUND_GetCurrentSample := GetAddress(FMODHandle,
'_FSOUND_GetCurrentSample@4');
FSOUND_GetDriver := GetAddress(FMODHandle, '_FSOUND_GetDriver@0');
FSOUND_GetDriverCaps := GetAddress(FMODHandle, '_FSOUND_GetDriverCaps@8');
FSOUND_GetDriverName := GetAddress(FMODHandle, '_FSOUND_GetDriverName@4');
FSOUND_GetError := GetAddress(FMODHandle, '_FSOUND_GetError@0');
FSOUND_GetFrequency := GetAddress(FMODHandle, '_FSOUND_GetFrequency@4');
FSOUND_GetLoopMode := GetAddress(FMODHandle, '_FSOUND_GetLoopMode@4');
FSOUND_GetMaxChannels := GetAddress(FMODHandle, '_FSOUND_GetMaxChannels@0');
FSOUND_GetMaxSamples := GetAddress(FMODHandle, '_FSOUND_GetMaxSamples@0');
FSOUND_GetMemoryStats := GetAddress(FMODHandle, '_FSOUND_GetMemoryStats@8');
FSOUND_GetMixer := GetAddress(FMODHandle, '_FSOUND_GetMixer@0');
FSOUND_GetMute := GetAddress(FMODHandle, '_FSOUND_GetMute@4');
FSOUND_GetNumDrivers := GetAddress(FMODHandle, '_FSOUND_GetNumDrivers@0');
// FSOUND_GetNumHardwareChannels := GetAddress(FMODHandle,'_FSOUND_GetNumHardwareChannels@0');
FSOUND_GetNumHWChannels := GetAddress(FMODHandle,
'_FSOUND_GetNumHWChannels@12');
FSOUND_GetNumSubChannels := GetAddress(FMODHandle,
'_FSOUND_GetNumSubChannels@4');
FSOUND_GetOutput := GetAddress(FMODHandle, '_FSOUND_GetOutput@0');
FSOUND_GetOutputHandle := GetAddress(FMODHandle, '_FSOUND_GetOutputHandle@0');
FSOUND_GetOutputRate := GetAddress(FMODHandle, '_FSOUND_GetOutputRate@0');
FSOUND_GetPan := GetAddress(FMODHandle, '_FSOUND_GetPan@4');
FSOUND_GetPaused := GetAddress(FMODHandle, '_FSOUND_GetPaused@4');
FSOUND_GetPriority := GetAddress(FMODHandle, '_FSOUND_GetPriority@4');
FSOUND_GetReserved := GetAddress(FMODHandle, '_FSOUND_GetReserved@4');
FSOUND_GetSFXMasterVolume := GetAddress(FMODHandle,
'_FSOUND_GetSFXMasterVolume@0');
FSOUND_GetSpeakerMode := GetAddress(FMODHandle, '_FSOUND_GetSpeakerMode@0');
FSOUND_GetSubChannel := GetAddress(FMODHandle, '_FSOUND_GetSubChannel@8');
FSOUND_GetSurround := GetAddress(FMODHandle, '_FSOUND_GetSurround@4');
FSOUND_GetVersion := GetAddress(FMODHandle, '_FSOUND_GetVersion@0');
FSOUND_GetVolume := GetAddress(FMODHandle, '_FSOUND_GetVolume@4');
FSOUND_Init := GetAddress(FMODHandle, '_FSOUND_Init@12');
FSOUND_IsPlaying := GetAddress(FMODHandle, '_FSOUND_IsPlaying@4');
FSOUND_PlaySound := GetAddress(FMODHandle, '_FSOUND_PlaySound@8');
FSOUND_PlaySoundEx := GetAddress(FMODHandle, '_FSOUND_PlaySoundEx@16');
FSOUND_Record_GetDriver := GetAddress(FMODHandle,
'_FSOUND_Record_GetDriver@0');
FSOUND_Record_GetDriverName := GetAddress(FMODHandle,
'_FSOUND_Record_GetDriverName@4');
FSOUND_Record_GetNumDrivers := GetAddress(FMODHandle,
'_FSOUND_Record_GetNumDrivers@0');
FSOUND_Record_GetPosition := GetAddress(FMODHandle,
'_FSOUND_Record_GetPosition@0');
FSOUND_Record_SetDriver := GetAddress(FMODHandle,
'_FSOUND_Record_SetDriver@4');
FSOUND_Record_StartSample := GetAddress(FMODHandle,
'_FSOUND_Record_StartSample@8');
FSOUND_Record_Stop := GetAddress(FMODHandle, '_FSOUND_Record_Stop@0');
FSOUND_Reverb_GetChannelProperties :=
GetAddress(FMODHandle, '_FSOUND_Reverb_GetChannelProperties@8');
FSOUND_Reverb_GetProperties := GetAddress(FMODHandle,
'_FSOUND_Reverb_GetProperties@4');
FSOUND_Reverb_SetChannelProperties :=
GetAddress(FMODHandle, '_FSOUND_Reverb_SetChannelProperties@8');
FSOUND_Reverb_SetProperties := GetAddress(FMODHandle,
'_FSOUND_Reverb_SetProperties@4');
FSOUND_Sample_Alloc := GetAddress(FMODHandle, '_FSOUND_Sample_Alloc@28');
FSOUND_Sample_Free := GetAddress(FMODHandle, '_FSOUND_Sample_Free@4');
FSOUND_Sample_Get := GetAddress(FMODHandle, '_FSOUND_Sample_Get@4');
FSOUND_Sample_GetDefaults := GetAddress(FMODHandle,
'_FSOUND_Sample_GetDefaults@20');
FSOUND_Sample_GetDefaultsEx := GetAddress(FMODHandle,
'_FSOUND_Sample_GetDefaultsEx@32');
FSOUND_Sample_GetLength := GetAddress(FMODHandle,
'_FSOUND_Sample_GetLength@4');
FSOUND_Sample_GetLoopPoints := GetAddress(FMODHandle,
'_FSOUND_Sample_GetLoopPoints@12');
FSOUND_Sample_GetMinMaxDistance := GetAddress(FMODHandle,
'_FSOUND_Sample_GetMinMaxDistance@12');
FSOUND_Sample_GetMode := GetAddress(FMODHandle, '_FSOUND_Sample_GetMode@4');
FSOUND_Sample_GetName := GetAddress(FMODHandle, '_FSOUND_Sample_GetName@4');
FSOUND_Sample_Load := GetAddress(FMODHandle, '_FSOUND_Sample_Load@20');
FSOUND_Sample_Lock := GetAddress(FMODHandle, '_FSOUND_Sample_Lock@28');
FSOUND_Sample_SetDefaults := GetAddress(FMODHandle,
'_FSOUND_Sample_SetDefaults@20');
FSOUND_Sample_SetDefaultsEx := GetAddress(FMODHandle,
'_FSOUND_Sample_SetDefaultsEx@32');
FSOUND_Sample_SetLoopPoints := GetAddress(FMODHandle,
'_FSOUND_Sample_SetLoopPoints@12');
FSOUND_Sample_SetMaxPlaybacks := GetAddress(FMODHandle,
'_FSOUND_Sample_SetMaxPlaybacks@8');
FSOUND_Sample_SetMinMaxDistance := GetAddress(FMODHandle,
'_FSOUND_Sample_SetMinMaxDistance@12');
FSOUND_Sample_SetMode := GetAddress(FMODHandle, '_FSOUND_Sample_SetMode@8');
FSOUND_Sample_Unlock := GetAddress(FMODHandle, '_FSOUND_Sample_Unlock@20');
FSOUND_Sample_Upload := GetAddress(FMODHandle, '_FSOUND_Sample_Upload@12');
FSOUND_SetBufferSize := GetAddress(FMODHandle, '_FSOUND_SetBufferSize@4');
FSOUND_SetCurrentPosition := GetAddress(FMODHandle,
'_FSOUND_SetCurrentPosition@8');
FSOUND_SetDriver := GetAddress(FMODHandle, '_FSOUND_SetDriver@4');
FSOUND_SetFrequency := GetAddress(FMODHandle, '_FSOUND_SetFrequency@8');
// FSOUND_SetFrequencyEx := GetAddress(FMODHandle,'_FSOUND_SetFrequencyEx@8');
FSOUND_SetHWND := GetAddress(FMODHandle, '_FSOUND_SetHWND@4');
FSOUND_SetLoopMode := GetAddress(FMODHandle, '_FSOUND_SetLoopMode@8');
FSOUND_SetMaxHardwareChannels := GetAddress(FMODHandle,
'_FSOUND_SetMaxHardwareChannels@4');
FSOUND_SetMemorySystem := GetAddress(FMODHandle,
'_FSOUND_SetMemorySystem@20');
FSOUND_SetMinHardwareChannels := GetAddress(FMODHandle,
'_FSOUND_SetMinHardwareChannels@4');
FSOUND_SetMixer := GetAddress(FMODHandle, '_FSOUND_SetMixer@4');
FSOUND_SetMute := GetAddress(FMODHandle, '_FSOUND_SetMute@8');
FSOUND_SetOutput := GetAddress(FMODHandle, '_FSOUND_SetOutput@4');
FSOUND_SetPan := GetAddress(FMODHandle, '_FSOUND_SetPan@8');
FSOUND_SetPanSeperation := GetAddress(FMODHandle,
'_FSOUND_SetPanSeperation@4');
FSOUND_SetPaused := GetAddress(FMODHandle, '_FSOUND_SetPaused@8');
FSOUND_SetPriority := GetAddress(FMODHandle, '_FSOUND_SetPriority@8');
FSOUND_SetReserved := GetAddress(FMODHandle, '_FSOUND_SetReserved@8');
FSOUND_SetSFXMasterVolume := GetAddress(FMODHandle,
'_FSOUND_SetSFXMasterVolume@4');
FSOUND_SetSpeakerMode := GetAddress(FMODHandle, '_FSOUND_SetSpeakerMode@4');
FSOUND_SetSurround := GetAddress(FMODHandle, '_FSOUND_SetSurround@8');
FSOUND_SetVolume := GetAddress(FMODHandle, '_FSOUND_SetVolume@8');
FSOUND_SetVolumeAbsolute := GetAddress(FMODHandle,
'_FSOUND_SetVolumeAbsolute@8');
FSOUND_StopSound := GetAddress(FMODHandle, '_FSOUND_StopSound@4');
FSOUND_Stream_AddSyncPoint := GetAddress(FMODHandle,
'_FSOUND_Stream_AddSyncPoint@12');
FSOUND_Stream_Close := GetAddress(FMODHandle, '_FSOUND_Stream_Close@4');
FSOUND_Stream_Create := GetAddress(FMODHandle, '_FSOUND_Stream_Create@20');
FSOUND_Stream_CreateDSP := GetAddress(FMODHandle,
'_FSOUND_Stream_CreateDSP@16');
FSOUND_Stream_DeleteSyncPoint := GetAddress(FMODHandle,
'_FSOUND_Stream_DeleteSyncPoint@4');
FSOUND_Stream_FindTagField := GetAddress(FMODHandle,
'_FSOUND_Stream_FindTagField@20');
FSOUND_Stream_GetLength := GetAddress(FMODHandle,
'_FSOUND_Stream_GetLength@4');
FSOUND_Stream_GetLengthMs := GetAddress(FMODHandle,
'_FSOUND_Stream_GetLengthMs@4');
FSOUND_Stream_GetMode := GetAddress(FMODHandle, '_FSOUND_Stream_GetMode@4');
FSOUND_Stream_GetNumSubStreams := GetAddress(FMODHandle,
'_FSOUND_Stream_GetNumSubStreams@4');
FSOUND_Stream_GetNumSyncPoints := GetAddress(FMODHandle,
'_FSOUND_Stream_GetNumSyncPoints@4');
FSOUND_Stream_GetNumTagFields := GetAddress(FMODHandle,
'_FSOUND_Stream_GetNumTagFields@8');
FSOUND_Stream_GetOpenState := GetAddress(FMODHandle,
'_FSOUND_Stream_GetOpenState@4');
FSOUND_Stream_GetPosition := GetAddress(FMODHandle,
'_FSOUND_Stream_GetPosition@4');
FSOUND_Stream_GetSample := GetAddress(FMODHandle,
'_FSOUND_Stream_GetSample@4');
FSOUND_Stream_GetSyncPoint := GetAddress(FMODHandle,
'_FSOUND_Stream_GetSyncPoint@8');
FSOUND_Stream_GetSyncPointInfo := GetAddress(FMODHandle,
'_FSOUND_Stream_GetSyncPointInfo@8');
FSOUND_Stream_GetTagField := GetAddress(FMODHandle,
'_FSOUND_Stream_GetTagField@24');
FSOUND_Stream_GetTime := GetAddress(FMODHandle, '_FSOUND_Stream_GetTime@4');
FSOUND_Stream_Net_GetBufferProperties :=
GetAddress(FMODHandle, '_FSOUND_Stream_Net_GetBufferProperties@12');
FSOUND_Stream_Net_GetLastServerStatus :=
GetAddress(FMODHandle, '_FSOUND_Stream_Net_GetLastServerStatus@0');
FSOUND_Stream_Net_GetStatus := GetAddress(FMODHandle,
'_FSOUND_Stream_Net_GetStatus@20');
FSOUND_Stream_Net_SetBufferProperties :=
GetAddress(FMODHandle, '_FSOUND_Stream_Net_SetBufferProperties@12');
FSOUND_Stream_Net_SetMetadataCallback :=
GetAddress(FMODHandle, '_FSOUND_Stream_Net_SetMetadataCallback@12');
// FSOUND_Stream_Net_SetNetDataCallback := GetAddress(FMODHandle,'_FSOUND_Stream_Net_SetNetDataCallback@8');
FSOUND_Stream_Net_SetProxy := GetAddress(FMODHandle,
'_FSOUND_Stream_Net_SetProxy@4');
// FSOUND_Stream_Net_SetTimeout := GetAddress(FMODHandle,'_FSOUND_Stream_Net_SetTimeout@4');
FSOUND_Stream_Open := GetAddress(FMODHandle, '_FSOUND_Stream_Open@16');
FSOUND_Stream_Play := GetAddress(FMODHandle, '_FSOUND_Stream_Play@8');
FSOUND_Stream_PlayEx := GetAddress(FMODHandle, '_FSOUND_Stream_PlayEx@16');
FSOUND_Stream_SetBufferSize := GetAddress(FMODHandle,
'_FSOUND_Stream_SetBufferSize@4');
FSOUND_Stream_SetEndCallback := GetAddress(FMODHandle,
'_FSOUND_Stream_SetEndCallback@12');
FSOUND_Stream_SetLoopCount := GetAddress(FMODHandle,
'_FSOUND_Stream_SetLoopCount@8');
FSOUND_Stream_SetLoopPoints := GetAddress(FMODHandle,
'_FSOUND_Stream_SetLoopPoints@12');
FSOUND_Stream_SetMode := GetAddress(FMODHandle, '_FSOUND_Stream_SetMode@8');
// FSOUND_Stream_SetPCM := GetAddress(FMODHandle,'_FSOUND_Stream_SetPCM@8');
FSOUND_Stream_SetPosition := GetAddress(FMODHandle,
'_FSOUND_Stream_SetPosition@8');
FSOUND_Stream_SetSubStream := GetAddress(FMODHandle,
'_FSOUND_Stream_SetSubStream@8');
FSOUND_Stream_SetSubStreamSentence :=
GetAddress(FMODHandle, '_FSOUND_Stream_SetSubStreamSentence@12');
FSOUND_Stream_SetSyncCallback := GetAddress(FMODHandle,
'_FSOUND_Stream_SetSyncCallback@12');
FSOUND_Stream_SetTime := GetAddress(FMODHandle, '_FSOUND_Stream_SetTime@8');
FSOUND_Stream_Stop := GetAddress(FMODHandle, '_FSOUND_Stream_Stop@4');
FSOUND_Update := GetAddress(FMODHandle, '_FSOUND_Update@0');
{$ELSE}
FSOUND_SetOutput := GetAddress(FMODHandle, 'FSOUND_SetOutput');
FSOUND_SetDriver := GetAddress(FMODHandle, 'FSOUND_SetDriver');
FSOUND_SetMixer := GetAddress(FMODHandle, 'FSOUND_SetMixer');
FSOUND_SetBufferSize := GetAddress(FMODHandle, 'FSOUND_SetBufferSize');
FSOUND_SetHWND := GetAddress(FMODHandle, 'FSOUND_SetHWND');
FSOUND_SetMinHardwareChannels := GetAddress(FMODHandle,
'FSOUND_SetMinHardwareChannels');
FSOUND_SetMaxHardwareChannels := GetAddress(FMODHandle,
'FSOUND_SetMaxHardwareChannels');
FSOUND_SetMemorySystem := GetAddress(FMODHandle, 'FSOUND_SetMemorySystem');
FSOUND_Init := GetAddress(FMODHandle, 'FSOUND_Init');
FSOUND_Close := GetAddress(FMODHandle, 'FSOUND_Close');
FSOUND_Update := GetAddress(FMODHandle, 'FSOUND_Update');
FSOUND_SetSpeakerMode := GetAddress(FMODHandle, 'FSOUND_SetSpeakerMode');
FSOUND_SetSFXMasterVolume := GetAddress(FMODHandle,
'FSOUND_SetSFXMasterVolume');
FSOUND_SetPanSeperation := GetAddress(FMODHandle, 'FSOUND_SetPanSeperation');
FSOUND_GetError := GetAddress(FMODHandle, 'FSOUND_GetError');
FSOUND_GetVersion := GetAddress(FMODHandle, 'FSOUND_GetVersion');
FSOUND_GetOutput := GetAddress(FMODHandle, 'FSOUND_GetOutput');
FSOUND_GetOutputHandle := GetAddress(FMODHandle, 'FSOUND_GetOutputHandle');
FSOUND_GetDriver := GetAddress(FMODHandle, 'FSOUND_GetDriver');
FSOUND_GetMixer := GetAddress(FMODHandle, 'FSOUND_GetMixer');
FSOUND_GetNumDrivers := GetAddress(FMODHandle, 'FSOUND_GetNumDrivers');
FSOUND_GetDriverName := GetAddress(FMODHandle, 'FSOUND_GetDriverName');
FSOUND_GetDriverCaps := GetAddress(FMODHandle, 'FSOUND_GetDriverCaps');
FSOUND_GetOutputRate := GetAddress(FMODHandle, 'FSOUND_GetOutputRate');
FSOUND_GetMaxChannels := GetAddress(FMODHandle, 'FSOUND_GetMaxChannels');
FSOUND_GetMaxSamples := GetAddress(FMODHandle, 'FSOUND_GetMaxSamples');
FSOUND_GetSpeakerMode := GetAddress(FMODHandle, 'FSOUND_GetSpeakerMode');
FSOUND_GetSFXMasterVolume := GetAddress(FMODHandle,
'FSOUND_GetSFXMasterVolume');
FSOUND_GetNumHWChannels := GetAddress(FMODHandle, 'FSOUND_GetNumHWChannels');
FSOUND_GetChannelsPlaying := GetAddress(FMODHandle,
'FSOUND_GetChannelsPlaying');
FSOUND_GetCPUUsage := GetAddress(FMODHandle, 'FSOUND_GetCPUUsage');
FSOUND_GetMemoryStats := GetAddress(FMODHandle, 'FSOUND_GetMemoryStats');
FSOUND_Sample_Load := GetAddress(FMODHandle, 'FSOUND_Sample_Load');
FSOUND_Sample_Alloc := GetAddress(FMODHandle, 'FSOUND_Sample_Alloc');
FSOUND_Sample_Free := GetAddress(FMODHandle, 'FSOUND_Sample_Free');
FSOUND_Sample_Upload := GetAddress(FMODHandle, 'FSOUND_Sample_Upload');
FSOUND_Sample_Lock := GetAddress(FMODHandle, 'FSOUND_Sample_Lock');
FSOUND_Sample_Unlock := GetAddress(FMODHandle, 'FSOUND_Sample_Unlock');
FSOUND_Sample_SetMode := GetAddress(FMODHandle, 'FSOUND_Sample_SetMode');
FSOUND_Sample_SetLoopPoints := GetAddress(FMODHandle,
'FSOUND_Sample_SetLoopPoints');
FSOUND_Sample_SetDefaults := GetAddress(FMODHandle,
'FSOUND_Sample_SetDefaults');
FSOUND_Sample_SetDefaultsEx := GetAddress(FMODHandle,
'FSOUND_Sample_SetDefaultsEx');
FSOUND_Sample_SetMinMaxDistance := GetAddress(FMODHandle,
'FSOUND_Sample_SetMinMaxDistance');
FSOUND_Sample_SetMaxPlaybacks := GetAddress(FMODHandle,
'FSOUND_Sample_SetMaxPlaybacks');
FSOUND_Sample_Get := GetAddress(FMODHandle, 'FSOUND_Sample_Get');
FSOUND_Sample_GetName := GetAddress(FMODHandle, 'FSOUND_Sample_GetName');
FSOUND_Sample_GetLength := GetAddress(FMODHandle, 'FSOUND_Sample_GetLength');
FSOUND_Sample_GetLoopPoints := GetAddress(FMODHandle,
'FSOUND_Sample_GetLoopPoints');
FSOUND_Sample_GetDefaults := GetAddress(FMODHandle,
'FSOUND_Sample_GetDefaults');
FSOUND_Sample_GetDefaultsEx := GetAddress(FMODHandle,
'FSOUND_Sample_GetDefaultsEx');
FSOUND_Sample_GetMode := GetAddress(FMODHandle, 'FSOUND_Sample_GetMode');
FSOUND_Sample_GetMinMaxDistance := GetAddress(FMODHandle,
'FSOUND_Sample_GetMinMaxDistance');
FSOUND_PlaySound := GetAddress(FMODHandle, 'FSOUND_PlaySound');
FSOUND_PlaySoundEx := GetAddress(FMODHandle, 'FSOUND_PlaySoundEx');
FSOUND_StopSound := GetAddress(FMODHandle, 'FSOUND_StopSound');
FSOUND_SetFrequency := GetAddress(FMODHandle, 'FSOUND_SetFrequency');
FSOUND_SetVolume := GetAddress(FMODHandle, 'FSOUND_SetVolume');
FSOUND_SetVolumeAbsolute := GetAddress(FMODHandle,
'FSOUND_SetVolumeAbsolute');
FSOUND_SetPan := GetAddress(FMODHandle, 'FSOUND_SetPan');
FSOUND_SetSurround := GetAddress(FMODHandle, 'FSOUND_SetSurround');
FSOUND_SetMute := GetAddress(FMODHandle, 'FSOUND_SetMute');
FSOUND_SetPriority := GetAddress(FMODHandle, 'FSOUND_SetPriority');
FSOUND_SetReserved := GetAddress(FMODHandle, 'FSOUND_SetReserved');
FSOUND_SetPaused := GetAddress(FMODHandle, 'FSOUND_SetPaused');
FSOUND_SetLoopMode := GetAddress(FMODHandle, 'FSOUND_SetLoopMode');
FSOUND_SetCurrentPosition := GetAddress(FMODHandle,
'FSOUND_SetCurrentPosition');
FSOUND_3D_SetAttributes := GetAddress(FMODHandle, 'FSOUND_3D_SetAttributes');
FSOUND_3D_SetMinMaxDistance := GetAddress(FMODHandle,
'FSOUND_3D_SetMinMaxDistance');
FSOUND_IsPlaying := GetAddress(FMODHandle, 'FSOUND_IsPlaying');
FSOUND_GetFrequency := GetAddress(FMODHandle, 'FSOUND_GetFrequency');
FSOUND_GetVolume := GetAddress(FMODHandle, 'FSOUND_GetVolume');
FSOUND_GetAmplitude := GetAddress(FMODHandle, 'FSOUND_GetAmplitude');
FSOUND_GetPan := GetAddress(FMODHandle, 'FSOUND_GetPan');
FSOUND_GetSurround := GetAddress(FMODHandle, 'FSOUND_GetSurround');
FSOUND_GetMute := GetAddress(FMODHandle, 'FSOUND_GetMute');
FSOUND_GetPriority := GetAddress(FMODHandle, 'FSOUND_GetPriority');
FSOUND_GetReserved := GetAddress(FMODHandle, 'FSOUND_GetReserved');
FSOUND_GetPaused := GetAddress(FMODHandle, 'FSOUND_GetPaused');
FSOUND_GetLoopMode := GetAddress(FMODHandle, 'FSOUND_GetLoopMode');
FSOUND_GetCurrentPosition := GetAddress(FMODHandle,
'FSOUND_GetCurrentPosition');
FSOUND_GetCurrentSample := GetAddress(FMODHandle, 'FSOUND_GetCurrentSample');
FSOUND_GetCurrentLevels := GetAddress(FMODHandle, 'FSOUND_GetCurrentLevels');
FSOUND_GetNumSubChannels := GetAddress(FMODHandle,
'FSOUND_GetNumSubChannels');
FSOUND_GetSubChannel := GetAddress(FMODHandle, 'FSOUND_GetSubChannel');
FSOUND_3D_GetAttributes := GetAddress(FMODHandle, 'FSOUND_3D_GetAttributes');
FSOUND_3D_GetMinMaxDistance := GetAddress(FMODHandle,
'FSOUND_3D_GetMinMaxDistance');
FSOUND_3D_Listener_SetCurrent := GetAddress(FMODHandle,
'FSOUND_3D_Listener_SetCurrent');
FSOUND_3D_Listener_SetAttributes := GetAddress(FMODHandle,
'FSOUND_3D_Listener_SetAttributes');
FSOUND_3D_Listener_GetAttributes := GetAddress(FMODHandle,
'FSOUND_3D_Listener_GetAttributes');
FSOUND_3D_SetDopplerFactor := GetAddress(FMODHandle,
'FSOUND_3D_SetDopplerFactor');
FSOUND_3D_SetDistanceFactor := GetAddress(FMODHandle,
'FSOUND_3D_SetDistanceFactor');
FSOUND_3D_SetRolloffFactor := GetAddress(FMODHandle,
'FSOUND_3D_SetRolloffFactor');
FSOUND_FX_Enable := GetAddress(FMODHandle, 'FSOUND_FX_Enable');
FSOUND_FX_SetChorus := GetAddress(FMODHandle, 'FSOUND_FX_SetChorus');
FSOUND_FX_SetCompressor := GetAddress(FMODHandle, 'FSOUND_FX_SetCompressor');
FSOUND_FX_SetDistortion := GetAddress(FMODHandle, 'FSOUND_FX_SetDistortion');
FSOUND_FX_SetEcho := GetAddress(FMODHandle, 'FSOUND_FX_SetEcho');
FSOUND_FX_SetFlanger := GetAddress(FMODHandle, 'FSOUND_FX_SetFlanger');
FSOUND_FX_SetGargle := GetAddress(FMODHandle, 'FSOUND_FX_SetGargle');
FSOUND_FX_SetI3DL2Reverb := GetAddress(FMODHandle,
'FSOUND_FX_SetI3DL2Reverb');
FSOUND_FX_SetParamEQ := GetAddress(FMODHandle, 'FSOUND_FX_SetParamEQ');
FSOUND_FX_SetWavesReverb := GetAddress(FMODHandle,
'FSOUND_FX_SetWavesReverb');
FSOUND_Stream_Open := GetAddress(FMODHandle, 'FSOUND_Stream_Open');
FSOUND_Stream_Create := GetAddress(FMODHandle, 'FSOUND_Stream_Create');
FSOUND_Stream_Close := GetAddress(FMODHandle, 'FSOUND_Stream_Close');
FSOUND_Stream_Play := GetAddress(FMODHandle, 'FSOUND_Stream_Play');
FSOUND_Stream_PlayEx := GetAddress(FMODHandle, 'FSOUND_Stream_PlayEx');
FSOUND_Stream_Stop := GetAddress(FMODHandle, 'FSOUND_Stream_Stop');
FSOUND_Stream_SetEndCallback := GetAddress(FMODHandle,
'FSOUND_Stream_SetEndCallback');
FSOUND_Stream_SetSyncCallback := GetAddress(FMODHandle,
'FSOUND_Stream_SetSyncCallback');
FSOUND_Stream_GetSample := GetAddress(FMODHandle, 'FSOUND_Stream_GetSample');
FSOUND_Stream_CreateDSP := GetAddress(FMODHandle, 'FSOUND_Stream_CreateDSP');
FSOUND_Stream_SetBufferSize := GetAddress(FMODHandle,
'FSOUND_Stream_SetBufferSize');
FSOUND_Stream_SetPosition := GetAddress(FMODHandle,
'FSOUND_Stream_SetPosition');
FSOUND_Stream_GetPosition := GetAddress(FMODHandle,
'FSOUND_Stream_GetPosition');
FSOUND_Stream_SetTime := GetAddress(FMODHandle, 'FSOUND_Stream_SetTime');
FSOUND_Stream_GetTime := GetAddress(FMODHandle, 'FSOUND_Stream_GetTime');
FSOUND_Stream_GetLength := GetAddress(FMODHandle, 'FSOUND_Stream_GetLength');
FSOUND_Stream_GetLengthMs := GetAddress(FMODHandle,
'FSOUND_Stream_GetLengthMs');
FSOUND_Stream_SetMode := GetAddress(FMODHandle, 'FSOUND_Stream_SetMode');
FSOUND_Stream_GetMode := GetAddress(FMODHandle, 'FSOUND_Stream_GetMode');
FSOUND_Stream_SetLoopPoints := GetAddress(FMODHandle,
'FSOUND_Stream_SetLoopPoints');
FSOUND_Stream_SetLoopCount := GetAddress(FMODHandle,
'FSOUND_Stream_SetLoopCount');
FSOUND_Stream_GetOpenState := GetAddress(FMODHandle,
'FSOUND_Stream_GetOpenState');
FSOUND_Stream_AddSyncPoint := GetAddress(FMODHandle,
'FSOUND_Stream_AddSyncPoint');
FSOUND_Stream_DeleteSyncPoint := GetAddress(FMODHandle,
'FSOUND_Stream_DeleteSyncPoint');
FSOUND_Stream_GetNumSyncPoints := GetAddress(FMODHandle,
'FSOUND_Stream_GetNumSyncPoints');
FSOUND_Stream_GetSyncPoint := GetAddress(FMODHandle,
'FSOUND_Stream_GetSyncPoint');
FSOUND_Stream_GetSyncPointInfo := GetAddress(FMODHandle,
'FSOUND_Stream_GetSyncPointInfo');
FSOUND_Stream_SetSubStream := GetAddress(FMODHandle,
'FSOUND_Stream_SetSubStream');
FSOUND_Stream_GetNumSubStreams := GetAddress(FMODHandle,
'FSOUND_Stream_GetNumSubStreams');
FSOUND_Stream_SetSubStreamSentence :=
GetAddress(FMODHandle, 'FSOUND_Stream_SetSubStreamSentence');
FSOUND_Stream_GetNumTagFields := GetAddress(FMODHandle,
'FSOUND_Stream_GetNumTagFields');
FSOUND_Stream_GetTagField := GetAddress(FMODHandle,
'FSOUND_Stream_GetTagField');
FSOUND_Stream_FindTagField := GetAddress(FMODHandle,
'FSOUND_Stream_FindTagField');
FSOUND_Stream_Net_SetProxy := GetAddress(FMODHandle,
'FSOUND_Stream_Net_SetProxy');
FSOUND_Stream_Net_GetLastServerStatus :=
GetAddress(FMODHandle, 'FSOUND_Stream_Net_GetLastServerStatus');
FSOUND_Stream_Net_SetBufferProperties :=
GetAddress(FMODHandle, 'FSOUND_Stream_Net_SetBufferProperties');
FSOUND_Stream_Net_GetBufferProperties :=
GetAddress(FMODHandle, 'FSOUND_Stream_Net_GetBufferProperties');
FSOUND_Stream_Net_SetMetadataCallback :=
GetAddress(FMODHandle, 'FSOUND_Stream_Net_SetMetadataCallback');
FSOUND_Stream_Net_GetStatus := GetAddress(FMODHandle,
'FSOUND_Stream_Net_GetStatus');
FSOUND_CD_Play := GetAddress(FMODHandle, 'FSOUND_CD_Play');
FSOUND_CD_SetPlayMode := GetAddress(FMODHandle, 'FSOUND_CD_SetPlayMode');
FSOUND_CD_Stop := GetAddress(FMODHandle, 'FSOUND_CD_Stop');
FSOUND_CD_SetPaused := GetAddress(FMODHandle, 'FSOUND_CD_SetPaused');
FSOUND_CD_SetVolume := GetAddress(FMODHandle, 'FSOUND_CD_SetVolume');
FSOUND_CD_SetTrackTime := GetAddress(FMODHandle, 'FSOUND_CD_SetTrackTime');
FSOUND_CD_OpenTray := GetAddress(FMODHandle, 'FSOUND_CD_OpenTray');
FSOUND_CD_GetPaused := GetAddress(FMODHandle, 'FSOUND_CD_GetPaused');
FSOUND_CD_GetTrack := GetAddress(FMODHandle, 'FSOUND_CD_GetTrack');
FSOUND_CD_GetNumTracks := GetAddress(FMODHandle, 'FSOUND_CD_GetNumTracks');
FSOUND_CD_GetVolume := GetAddress(FMODHandle, 'FSOUND_CD_GetVolume');
FSOUND_CD_GetTrackLength := GetAddress(FMODHandle,
'FSOUND_CD_GetTrackLength');
FSOUND_CD_GetTrackTime := GetAddress(FMODHandle, 'FSOUND_CD_GetTrackTime');
FSOUND_DSP_Create := GetAddress(FMODHandle, 'FSOUND_DSP_Create');
FSOUND_DSP_Free := GetAddress(FMODHandle, 'FSOUND_DSP_Free');
FSOUND_DSP_SetPriority := GetAddress(FMODHandle, 'FSOUND_DSP_SetPriority');
FSOUND_DSP_GetPriority := GetAddress(FMODHandle, 'FSOUND_DSP_GetPriority');
FSOUND_DSP_SetActive := GetAddress(FMODHandle, 'FSOUND_DSP_SetActive');
FSOUND_DSP_GetActive := GetAddress(FMODHandle, 'FSOUND_DSP_GetActive');
FSOUND_DSP_GetClearUnit := GetAddress(FMODHandle, 'FSOUND_DSP_GetClearUnit');
FSOUND_DSP_GetSFXUnit := GetAddress(FMODHandle, 'FSOUND_DSP_GetSFXUnit');
FSOUND_DSP_GetMusicUnit := GetAddress(FMODHandle, 'FSOUND_DSP_GetMusicUnit');
FSOUND_DSP_GetClipAndCopyUnit := GetAddress(FMODHandle,
'FSOUND_DSP_GetClipAndCopyUnit');
FSOUND_DSP_GetFFTUnit := GetAddress(FMODHandle, 'FSOUND_DSP_GetFFTUnit');
FSOUND_DSP_MixBuffers := GetAddress(FMODHandle, 'FSOUND_DSP_MixBuffers');
FSOUND_DSP_ClearMixBuffer := GetAddress(FMODHandle,
'FSOUND_DSP_ClearMixBuffer');
FSOUND_DSP_GetBufferLength := GetAddress(FMODHandle,
'FSOUND_DSP_GetBufferLength');
FSOUND_DSP_GetBufferLengthTotal := GetAddress(FMODHandle,
'FSOUND_DSP_GetBufferLengthTotal');
FSOUND_DSP_GetSpectrum := GetAddress(FMODHandle, 'FSOUND_DSP_GetSpectrum');
FSOUND_Reverb_SetProperties := GetAddress(FMODHandle,
'FSOUND_Reverb_SetProperties');
FSOUND_Reverb_GetProperties := GetAddress(FMODHandle,
'FSOUND_Reverb_GetProperties');
FSOUND_Reverb_SetChannelProperties :=
GetAddress(FMODHandle, 'FSOUND_Reverb_SetChannelProperties');
FSOUND_Reverb_GetChannelProperties :=
GetAddress(FMODHandle, 'FSOUND_Reverb_GetChannelProperties');
FSOUND_Record_SetDriver := GetAddress(FMODHandle, 'FSOUND_Record_SetDriver');
FSOUND_Record_GetNumDrivers := GetAddress(FMODHandle,
'FSOUND_Record_GetNumDrivers');
FSOUND_Record_GetDriverName := GetAddress(FMODHandle,
'FSOUND_Record_GetDriverName');
FSOUND_Record_GetDriver := GetAddress(FMODHandle, 'FSOUND_Record_GetDriver');
FSOUND_Record_StartSample := GetAddress(FMODHandle,
'FSOUND_Record_StartSample');
FSOUND_Record_Stop := GetAddress(FMODHandle, 'FSOUND_Record_Stop');
FSOUND_Record_GetPosition := GetAddress(FMODHandle,
'FSOUND_Record_GetPosition');
FSOUND_File_SetCallbacks := GetAddress(FMODHandle,
'FSOUND_File_SetCallbacks');
FMUSIC_LoadSong := GetAddress(FMODHandle, 'FMUSIC_LoadSong');
FMUSIC_LoadSongEx := GetAddress(FMODHandle, 'FMUSIC_LoadSongEx');
FMUSIC_GetOpenState := GetAddress(FMODHandle, 'FMUSIC_GetOpenState');
FMUSIC_FreeSong := GetAddress(FMODHandle, 'FMUSIC_FreeSong');
FMUSIC_PlaySong := GetAddress(FMODHandle, 'FMUSIC_PlaySong');
FMUSIC_StopSong := GetAddress(FMODHandle, 'FMUSIC_StopSong');
FMUSIC_StopAllSongs := GetAddress(FMODHandle, 'FMUSIC_StopAllSongs');
FMUSIC_SetZxxCallback := GetAddress(FMODHandle, 'FMUSIC_SetZxxCallback');
FMUSIC_SetRowCallback := GetAddress(FMODHandle, 'FMUSIC_SetRowCallback');
FMUSIC_SetOrderCallback := GetAddress(FMODHandle, 'FMUSIC_SetOrderCallback');
FMUSIC_SetInstCallback := GetAddress(FMODHandle, 'FMUSIC_SetInstCallback');
FMUSIC_SetSample := GetAddress(FMODHandle, 'FMUSIC_SetSample');
FMUSIC_SetUserData := GetAddress(FMODHandle, 'FMUSIC_SetUserData');
FMUSIC_OptimizeChannels := GetAddress(FMODHandle, 'FMUSIC_OptimizeChannels');
FMUSIC_SetReverb := GetAddress(FMODHandle, 'FMUSIC_SetReverb');
FMUSIC_SetLooping := GetAddress(FMODHandle, 'FMUSIC_SetLooping');
FMUSIC_SetOrder := GetAddress(FMODHandle, 'FMUSIC_SetOrder');
FMUSIC_SetPaused := GetAddress(FMODHandle, 'FMUSIC_SetPaused');
FMUSIC_SetMasterVolume := GetAddress(FMODHandle, 'FMUSIC_SetMasterVolume');
FMUSIC_SetMasterSpeed := GetAddress(FMODHandle, 'FMUSIC_SetMasterSpeed');
FMUSIC_SetPanSeperation := GetAddress(FMODHandle, 'FMUSIC_SetPanSeperation');
FMUSIC_GetName := GetAddress(FMODHandle, 'FMUSIC_GetName');
FMUSIC_GetType := GetAddress(FMODHandle, 'FMUSIC_GetType');
FMUSIC_GetNumOrders := GetAddress(FMODHandle, 'FMUSIC_GetNumOrders');
FMUSIC_GetNumPatterns := GetAddress(FMODHandle, 'FMUSIC_GetNumPatterns');
FMUSIC_GetNumInstruments := GetAddress(FMODHandle,
'FMUSIC_GetNumInstruments');
FMUSIC_GetNumSamples := GetAddress(FMODHandle, 'FMUSIC_GetNumSamples');
FMUSIC_GetNumChannels := GetAddress(FMODHandle, 'FMUSIC_GetNumChannels');
FMUSIC_GetSample := GetAddress(FMODHandle, 'FMUSIC_GetSample');
FMUSIC_GetPatternLength := GetAddress(FMODHandle, 'FMUSIC_GetPatternLength');
FMUSIC_IsFinished := GetAddress(FMODHandle, 'FMUSIC_IsFinished');
FMUSIC_IsPlaying := GetAddress(FMODHandle, 'FMUSIC_IsPlaying');
FMUSIC_GetMasterVolume := GetAddress(FMODHandle, 'FMUSIC_GetMasterVolume');
FMUSIC_GetGlobalVolume := GetAddress(FMODHandle, 'FMUSIC_GetGlobalVolume');
FMUSIC_GetOrder := GetAddress(FMODHandle, 'FMUSIC_GetOrder');
FMUSIC_GetPattern := GetAddress(FMODHandle, 'FMUSIC_GetPattern');
FMUSIC_GetSpeed := GetAddress(FMODHandle, 'FMUSIC_GetSpeed');
FMUSIC_GetBPM := GetAddress(FMODHandle, 'FMUSIC_GetBPM');
FMUSIC_GetRow := GetAddress(FMODHandle, 'FMUSIC_GetRow');
FMUSIC_GetPaused := GetAddress(FMODHandle, 'FMUSIC_GetPaused');
FMUSIC_GetTime := GetAddress(FMODHandle, 'FMUSIC_GetTime');
FMUSIC_GetRealChannel := GetAddress(FMODHandle, 'FMUSIC_GetRealChannel');
FMUSIC_GetUserData := GetAddress(FMODHandle, 'FMUSIC_GetUserData');
{$ENDIF}
Result := True;
end;
procedure FMOD_Unload;
begin
{ Only free the library if it was already loaded }
if FMODHandle <> INVALID_MODULEHANDLE_VALUE then
FreeLibrary(FMODHandle);
FMODHandle := INVALID_MODULEHANDLE_VALUE;
end;
var
Saved8087CW: word;
initialization
{ Save the current FPU state and then disable FPU exceptions }
Saved8087CW := Default8087CW;
Set8087CW($133F); { Disable all fpu exceptions }
finalization
{ Make sure the library is unloaded }
FMOD_Unload;
{ Reset the FPU to the previous state }
Set8087CW(Saved8087CW);
end.
|
unit Quick.RTTI.Utils;
interface
uses
SysUtils,
Rtti;
type
TRTTI = class
private class var
fCtx : TRttiContext;
public
//class function GetProperties();
class function GetField(aInstance : TObject; const aFieldName : string) : TRttiField; overload;
class function GetField(aTypeInfo : Pointer; const aFieldName : string) : TRttiField; overload;
class function FieldExists(aTypeInfo : Pointer; const aFieldName : string) : Boolean;
class function GetFieldValue(aInstance : TObject; const aFieldName : string) : TValue; overload;
class function GetFieldValue(aTypeInfo : Pointer; const aFieldName: string) : TValue; overload;
class function GetProperty(aInstance : TObject; const aPropertyName : string) : TRttiProperty; overload;
class function GetProperty(aTypeInfo : Pointer; const aPropertyName : string) : TRttiProperty; overload;
class function PropertyExists(aTypeInfo : Pointer; const aPropertyName : string) : Boolean;
class function GetPropertyValue(aInstance : TObject; const aPropertyName : string) : TValue; overload;
class function GetPropertyValue(aTypeInfo : Pointer; const aPropertyName : string) : TValue; overload;
end;
ERTTIError = class(Exception);
implementation
{ TRTTIUtils }
class function TRTTI.FieldExists(aTypeInfo: Pointer; const aFieldName: string): Boolean;
var
rtype : TRttiType;
begin
rtype := fCtx.GetType(aTypeInfo);
Result := rtype.GetField(aFieldName) <> nil;
end;
class function TRTTI.GetField(aInstance: TObject; const aFieldName: string): TRttiField;
var
rtype : TRttiType;
begin
rtype := fCtx.GetType(aInstance.ClassInfo);
if rtype <> nil then
begin
Result := rtype.GetField(aFieldName);
end;
end;
class function TRTTI.GetField(aTypeInfo: Pointer; const aFieldName: string): TRttiField;
var
rtype : TRttiType;
begin
rtype := fCtx.GetType(aTypeInfo);
if rtype <> nil then
begin
Result := rtype.GetField(aFieldName);
end;
end;
class function TRTTI.GetFieldValue(aInstance : TObject; const aFieldName: string): TValue;
var
rfield: TRttiField;
begin
rfield := GetField(aInstance,aFieldName);
if rfield <> nil then Result := rfield.GetValue(aInstance);
end;
class function TRTTI.GetFieldValue(aTypeInfo : Pointer; const aFieldName: string): TValue;
var
rfield: TRttiField;
begin
rfield := GetField(aTypeInfo,aFieldName);
if rfield <> nil then rfield.GetValue(aTypeInfo);
end;
class function TRTTI.GetProperty(aInstance: TObject; const aPropertyName: string): TRttiProperty;
var
rtype : TRttiType;
begin
rtype := fCtx.GetType(aInstance.ClassInfo);
if rtype <> nil then Result := rtype.GetProperty(aPropertyName);
end;
class function TRTTI.GetProperty(aTypeInfo: Pointer; const aPropertyName: string): TRttiProperty;
var
rtype : TRttiType;
begin
rtype := fCtx.GetType(aTypeInfo);
if rtype <> nil then Result := rtype.GetProperty(aPropertyName);
end;
class function TRTTI.GetPropertyValue(aInstance: TObject; const aPropertyName: string): TValue;
var
rprop : TRttiProperty;
begin
rprop := GetProperty(aInstance,aPropertyName);
if rprop <> nil then Result := rprop.GetValue(aInstance);
end;
class function TRTTI.GetPropertyValue(aTypeInfo: Pointer; const aPropertyName: string): TValue;
var
rprop : TRttiProperty;
begin
rprop := GetProperty(aTypeInfo,aPropertyName);
if rprop <> nil then Result := rprop.GetValue(aTypeInfo);
end;
class function TRTTI.PropertyExists(aTypeInfo: Pointer; const aPropertyName: string): Boolean;
begin
Result := fCtx.GetType(aTypeInfo).GetProperty(aPropertyName) <> nil;
end;
end.
|
unit fFocusedControls;
{==============================================================================}
{ Focused Control Dialog }
{------------------------------------------------------------------------------}
{ This dialog handles displaying focus changes during the normal operation }
{ of the application. It uses the internal Delphi message CMFocusChanged }
{ to populate the list. }
{ }
{ ShowFocusedControlDialog is a global variable indicating this dialog }
{ should be shown, and the globals DestinationControl and Previous Control }
{ are used to track and report the position of the current focus. }
{ }
{ The dialog is a singleton, meaning only one exists at a given time, and it }
{ should only be accessed through the GetInstance function. }
{==============================================================================}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls;
type
// Indicates which tab key is used, if any
TTabKeyUsed = (tkuTab, tkuShiftTab, tkuNone);
// Focus Dialog
TdlgFocusedControls = class(TForm)
sbar: TStatusBar;
lv: TListView;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
Count: integer; // used for line numbering
public
class function GetInstance: TdlgFocusedControls; // Singleton access. Also shows dialog if it isn't already visible.
procedure AddFocusChange(const ASource, ADestination, ADirection: string); // Called to add an entry to the dialog
end;
var
ShowFocusedControlDialog: boolean; // Toggle used to determine if the dialog should show.
DestinationControl: TWinControl; // Global used to change the focus inside the parent form, in conjunction with CMFocusChange window message
PreviousControl: TWinControl; // Global used for focus changes
const
TabKeyUsedStr: array[TTabKeyUsed] of string = ('Tab', 'Shift Tab', 'None'); // used to display tab states in diagnostics
implementation
{$R *.dfm}
uses fFrame;
var
dlgFocusedControls: TdlgFocusedControls; // put down here because the dialog is a singleton.
{ TdlgFocusedControls }
{-----------------------------------------------------------------------------------}
{ AddFocusChange - called to add a line to the list }
{ ASource: Name of the source control of the focus change (From) }
{ ADestination: Name of the destination control of the focus change (To) }
{ ADirection: Indicates which direction the focus is coming from (Tab State) }
{-----------------------------------------------------------------------------------}
procedure TdlgFocusedControls.AddFocusChange(const ASource, ADestination, ADirection: string);
var
li: TListItem;
begin
if not Visible then Show; // make sure the form is showing, as it may have been closed previously.
inc(Count);
li := lv.Items.Add;
li.Caption := IntToStr(Count); // line number
li.SubItems.Add(ASource); // From
li.SubItems.Add(ADestination); // To
li.SubItems.Add(ADirection); // Which way
Repaint;
end;
{----------------------------------}
{ FormClose - closing the dialog }
{----------------------------------}
procedure TdlgFocusedControls.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
// make sure the menu item and the toggle are set back to false
ShowFocusedControlDialog := False;
frmFrame.mnuFocusChanges.Checked := False;
end;
{------------------------------------}
{ FormCreate - starting the dialog }
{------------------------------------}
procedure TdlgFocusedControls.FormCreate(Sender: TObject);
begin
Count := 0; // line number
lv.Clear; // make sure test form data is cleared
end;
{----------------------------------------------------------------------}
{ GetInstance - Handles calling the singleton instance of the dialog }
{ In other words, making sure there is only one. }
{----------------------------------------------------------------------}
class function TdlgFocusedControls.GetInstance: TdlgFocusedControls;
begin
if not assigned(dlgFocusedControls) then begin // Create if it doesn't exist
dlgFocusedControls := TdlgFocusedControls.Create(nil);
end;
Result := dlgFocusedControls;
end;
initialization
ShowFocusedControlDialog := False; // default to False
finalization
if assigned(dlgFocusedControls) then // clean up singleton, not destroyed by application automatically
dlgFocusedControls.Free;
end.
|
unit uIRCColors;
interface
uses Graphics;
const
ColorChar = '';
BoldChar = '';
ClearChar = '';
ItalicChar = #$1D;
UnderlineChar = #$1F;
IrcColors: array[0..15] of TColor = (
clWhite,
clBlack,
clNavy,
clGreen,
clRed,
clMaroon,
clPurple,
clOlive,
clYellow,
clLime,
clTeal,
clAqua,
clBlue,
clFuchsia,
clGray,
clLtGray
);
type
TIRCTextStyle = record
CharCode: Char;
FontStyle: TFontStyle;
end;
const
IRCTextStyles: array[0..2] of TIRCTextStyle = (
(CharCode: BoldChar; FontStyle: fsBold),
(CharCode: ItalicChar; FontStyle: fsItalic),
(CharCode: UnderlineChar; FontStyle: fsUnderline)
);
function StripBackgroundColors(const AText: string): string;
function StripForegroundColors(const AText: string): string;
function StripSpecialChars(const AText: string): string;
implementation
uses SysUtils;
function StripSpecialChars(const AText: string): string;
var
I: Integer;
begin
Result := StringReplace(AText, ClearChar, '', [rfReplaceAll]);
Result := StringReplace(Result, ColorChar, '', [rfReplaceAll]);
for I := Low(IRCTextStyles) to High(IRCTextStyles) do
Result := StringReplace(Result, IRCTextStyles[I].CharCode, '', [rfReplaceAll]);
end;
function StripBackgroundColors(const AText: string): string;
var
I, J: Integer;
begin
Result := AText;
for I := High(IrcColors) downto Low(IrcColors) do
begin
for J := High(IrcColors) downto Low(IrcColors) do
begin
Result := StringReplace(Result, Format(ColorChar + '%s,%s', [Format('%.*d', [2, I]), Format('%.*d', [2, J])]), '', [rfReplaceAll]);
Result := StringReplace(Result, Format(ColorChar + '%d,%d', [I, J]), '', [rfReplaceAll]);
end;
end;
end;
function StripForegroundColors(const AText: string): string;
var
I: Integer;
begin
Result := AText;
for I := High(IrcColors) downto Low(IrcColors) do
begin
Result := StringReplace(Result, Format(ColorChar + '%s', [Format('%.*d', [2, I])]), '', [rfReplaceAll]);
Result := StringReplace(Result, Format(ColorChar + '%d', [I]), '', [rfReplaceAll]);
end;
end;
end.
|
unit for_in_generic_1;
interface
implementation
function Iterate<T>(const Arr: array of T; const Proc: procedure (const Item: T; out BreakIterate: Boolean)): Integer;
begin
var Br := False;
for var Item in Arr do
begin
Proc(Item, Br);
if Br then
Exit;
end;
end;
var A: array of Int32;
G: Integer = 0;
procedure Test;
begin
A := [1, 2, 3, 4, 5];
Iterate<Int32>(A, procedure (const Item: Int32; out BreakIterate: Boolean)
begin
G := G + Item;
end);
end;
initialization
Test();
finalization
Assert(G = 15);
end. |
unit uSaveFileDialog;
//The following code example illustrates creating a SaveFileDialog, setting members,
//calling the dialog box using the ShowDialog method, and saving the current file.
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Control.Base, CNClrLib.Component.SaveFileDialog;
type
TForm17 = class(TForm)
Button1: TButton;
CnSaveFileDialog1: TCnSaveFileDialog;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form17: TForm17;
implementation
{$R *.dfm}
uses CNClrLib.Core;
procedure TForm17.Button1Click(Sender: TObject);
var
myStream: _Stream;
begin
CnSaveFileDialog1.Filter := 'txt files (*.txt)|*.txt|All files (*.*)|*.*';
CnSaveFileDialog1.FilterIndex := 2;
CnSaveFileDialog1.RestoreDirectory := True;
if CnSaveFileDialog1.ShowDialog = TDialogResult.drOK then
begin
myStream := CnSaveFileDialog1.OpenFile;
if myStream <> nil then
begin
// Code to write the stream goes here.
myStream.Close();
end;
end;
end;
end.
|
PROGRAM Hello(INPUT, OUTPUT);
BEGIN
WRITELN('Hello world!');
END;
PROGRAM Hello(INPUT, OUTPUT);
BEGIN
WRITELN('Hello world!');
END;
PROGRAM Hello(INPUT, OUTPUT);
BEGIN
WRITELN('Hello world!');
END;
PROGRAM Hello(INPUT, OUTPUT);
BEGIN
WRITELN('Hello world!');
END;
PROGRAM Hello(INPUT, OUTPUT);
BEGIN
WRITELN('Hello world!');
END |
unit fTemplateImport;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Gauges, StdCtrls, ComCtrls, fBase508Form, VA508AccessibilityManager;
type
TfrmTemplateImport = class(TfrmBase508Form)
animImport: TAnimate;
btnCancel: TButton;
lblImporting: TStaticText;
gaugeImport: TGauge;
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure StartImportMessage(AFileName: string; MaxCount: integer);
function UpdateImportMessage(CurrentCount: integer): boolean;
procedure StopImportMessage;
implementation
{$R *.DFM}
uses
ORFn;
var
frmTemplateImport: TfrmTemplateImport = nil;
procedure StartImportMessage(AFileName: string; MaxCount: integer);
begin
if not assigned(frmTemplateImport) then
begin
frmTemplateImport := TfrmTemplateImport.Create(Application);
ResizeAnchoredFormToFont(frmTemplateImport);
with frmTemplateImport do
begin
lblImporting.Caption := lblImporting.Caption + AFileName;
lblImporting.Hint := lblImporting.Caption;
gaugeImport.MaxValue := MaxCount;
Show;
Application.ProcessMessages;
end;
end;
end;
function UpdateImportMessage(CurrentCount: integer): boolean;
begin
if assigned(frmTemplateImport) then
begin
Result := (not frmTemplateImport.btnCancel.Enabled);
if not Result then
begin
frmTemplateImport.gaugeImport.Progress := CurrentCount;
Application.ProcessMessages;
end;
end
else
Result := TRUE;
end;
procedure StopImportMessage;
begin
if assigned(frmTemplateImport) then
FreeAndNil(frmTemplateImport);
end;
procedure TfrmTemplateImport.btnCancelClick(Sender: TObject);
begin
lblImporting.Caption := 'Canceling...';
btnCancel.Enabled := FALSE;
Application.ProcessMessages;
end;
end.
|
unit umain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, DividerBevel, usplashabout, uPoweredby, Forms,
Controls, Graphics, Dialogs, StdCtrls, Grids, ExtCtrls, Buttons, Menus,
IniFiles, strutils;
type
{ TfrmMain }
TfrmMain = class(TForm)
btnAdd: TButton;
btnQuit: TButton;
btnDelete: TButton;
btnEnterFilePath: TButton;
btnEnterDirPath: TButton;
btnCreateTmpl: TButton;
btnLoadTmpl: TButton;
btnSetMagicalString: TButton;
DividerBevel1: TDividerBevel;
edtSection: TEdit;
GroupBox1: TGroupBox;
Label1: TLabel;
findFile: TOpenDialog;
Label2: TLabel;
MenuItem1: TMenuItem;
miClearAll: TMenuItem;
miReindexing: TMenuItem;
appendToFile: TOpenDialog;
openTmpl: TOpenDialog;
pmStringGrid: TPopupMenu;
Poweredby1: TPoweredby;
rgSaveAs: TRadioGroup;
saveToIniFile: TSaveDialog;
saveTmpl: TSaveDialog;
selectDir: TSelectDirectoryDialog;
sgValues: TStringGrid;
sbSaveAsNew: TSpeedButton;
Shape1: TShape;
sbAppendIni: TSpeedButton;
SplashAbout1: TSplashAbout;
procedure btnAddClick(Sender: TObject);
procedure btnCreateTmplClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnEnterDirPathClick(Sender: TObject);
procedure btnEnterFilePathClick(Sender: TObject);
procedure btnLoadTmplClick(Sender: TObject);
procedure btnQuitClick(Sender: TObject);
procedure btnSetMagicalStringClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure miClearAllClick(Sender: TObject);
procedure miReindexingClick(Sender: TObject);
procedure sbAppendIniClick(Sender: TObject);
procedure sbSaveAsNewClick(Sender: TObject);
private
{ private declarations }
encryptionString : String; {default MAGICAL_STRING}
procedure setColWidth;
procedure saveConfAsTxt(const lastIndex : Integer; const filePath : String; const currSection : String);
procedure saveConfEncrypted(const lastIndex : Integer; const filePath : String; const currSection : String);
procedure appendConfAsTxt(const lastIndex : Integer; const filePath : String; const currSection : String);
procedure appendConfEncrypted(const lastIndex : Integer; const filePath : String; const currSection : String);
public
{ public declarations }
end;
var
frmMain: TfrmMain;
const
SUCCESS_MSG : String = 'Success!';
ROW_INDEX_ERROR : String = 'Row index error.';
HASH_ERROR : String = 'Hash error.';
NO_SECTION_ERROR : String = 'There is no section(error).';
implementation
uses
uexdatis, uinputstring, uerrordlg;
{$R *.lfm}
{ TfrmMain }
procedure TfrmMain.btnQuitClick(Sender: TObject);
begin
Close;
Application.Terminate;
end;
procedure TfrmMain.btnSetMagicalStringClick(Sender: TObject);
const
STRING_ERROR : String = 'Length of the string is not appropriate.';
SAME_STRING : String = 'The same string.';
var
showSuccessMsg : Boolean = False;
tempString : String;
errorDlg : TfrmErrorDlg;
begin
{create dialog}
dlgInputString:= TdlgInputString.Create(frmMain);
{show current string}
dlgInputString.edtCurrString.Text:= encryptionString;
{show dialog}
if(dlgInputString.ShowModal = mrOK) then
begin
tempString:= dlgInputString.getNewString;
{ the same string?}
if(tempString = encryptionString) then
begin
{free dialog}
dlgInputString.Free;
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(SAME_STRING);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{good enough?}
if(Length(tempString) > 2) then
begin
showSuccessMsg:= True;
encryptionString:= tempString;
end
else
begin
{free dialog}
dlgInputString.Free;
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(STRING_ERROR);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
end;
{free dialog}
dlgInputString.Free;
{*****************************************************************************
-debug msg
ShowMessage(encryptionString);
*****************************************************************************}
if(showSuccessMsg) then
ShowMessage(SUCCESS_MSG);
end;
procedure TfrmMain.btnAddClick(Sender: TObject);
var
currRows : Integer;
begin
{number of rows}
currRows:= sgValues.RowCount;
{add row}
sgValues.RowCount:= currRows + 1;
sgValues.Cells[0, currRows]:= IntToStr(currRows);
{set focus}
sgValues.Row:= currRows;
sgValues.Col:= 1;
sgValues.SetFocus;
Application.ProcessMessages;
end;
procedure TfrmMain.btnCreateTmplClick(Sender: TObject);
var
numOfRows : Integer;
csvPath : String;
errorDlg : TfrmErrorDlg;
begin
{Check number of rows}
numOfRows:= sgValues.RowCount;
if(numOfRows < 2) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(HASH_ERROR);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{save to csv file}
if(saveTmpl.Execute) then
begin
csvPath:= saveTmpl.FileName;
try
sgValues.SaveToCSVFile(csvPath,';');
except
on e : Exception do
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(e.Message);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
end;
end;
{success msg}
ShowMessage(SUCCESS_MSG);
end;
procedure TfrmMain.btnDeleteClick(Sender: TObject);
var
currRow : Integer;
errorDlg : TfrmErrorDlg;
begin
{count rows}
if(sgValues.RowCount < 2) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(ROW_INDEX_ERROR);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{selected}
currRow:= sgValues.Row;
sgValues.DeleteRow(currRow);
Application.ProcessMessages;
end;
procedure TfrmMain.btnEnterDirPathClick(Sender: TObject);
var
currPath : String = '';
currRow, currCol : Integer; {cells}
errorDlg : TfrmErrorDlg;
begin
{number of rows}
if(sgValues.RowCount < 2) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(ROW_INDEX_ERROR );
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{selectDir(SelectDirectoryDialog) run}
if(selectDir.Execute) then
currPath:= selectDir.FileName;
{find position}
currRow:= sgValues.Row;
currCol:= sgValues.Col;
sgValues.Cells[currCol, currRow]:= currPath;
Application.ProcessMessages;
end;
procedure TfrmMain.btnEnterFilePathClick(Sender: TObject);
var
currPath : String = '';
currRow, currCol : Integer; {cells}
errorDlg : TfrmErrorDlg;
begin
{number of rows}
if(sgValues.RowCount < 2) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(ROW_INDEX_ERROR );
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{findFile(OpenDialog) run}
if(findFile.Execute) then
currPath:= findFile.FileName;
{find position}
currRow:= sgValues.Row;
currCol:= sgValues.Col;
sgValues.Cells[currCol, currRow]:= currPath;
Application.ProcessMessages;
end;
procedure TfrmMain.btnLoadTmplClick(Sender: TObject);
var
tmplPath : String = '';
begin
{find template(csv)}
if(openTmpl.Execute) then
tmplPath:= openTmpl.FileName;
{load from csv}
if(FileExistsUTF8(tmplPath)) then
begin
sgValues.Clear;
sgValues.LoadFromCSVFile(tmplPath, ';');
{set cols width}
setColWidth;
Application.ProcessMessages;
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
{stringGrid captions}
sgValues.Cells[0,0]:= 'Rb';
sgValues.Cells[1,0]:= 'Name';
sgValues.Cells[2,0]:= 'Value';
{set cols width}
setColWidth;
{set magical string}
encryptionString:= MAGICAL_STRING;{default}
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
{splash}
Poweredby1.ShowPoweredByForm;
SplashAbout1.ShowSplash;
end;
procedure TfrmMain.miClearAllClick(Sender: TObject);
begin
{clear all}
sgValues.Clear;
{set captions}
sgValues.RowCount:= 1;
{stringGrid captions}
sgValues.Cells[0,0]:= 'Rb';
sgValues.Cells[1,0]:= 'Name';
sgValues.Cells[2,0]:= 'Value';
{set cols width}
setColWidth;
Application.ProcessMessages;
end;
procedure TfrmMain.miReindexingClick(Sender: TObject);
var
i, numOfRows : Integer; {counter}
begin
numOfRows:= sgValues.RowCount;
if(numOfRows < 2) then
Exit;{nothing to do}
{reindexing}
for i := 1 to numOfRows - 1 do
sgValues.Cells[0, i]:= IntToStr(i);
Application.ProcessMessages;
end;
procedure TfrmMain.sbAppendIniClick(Sender: TObject);
var
numOfRows : Integer;
newIniFile : String = '';
currSection : String;
errorDlg : TfrmErrorDlg;
begin
{check section}
currSection:= edtSection.Text;
if(Length(currSection) < 1) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(NO_SECTION_ERROR);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{number of rows}
numOfRows:= sgValues.RowCount;
if(numOfRows < 2) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(HASH_ERROR);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{where to save (save dialog)}
if(appendToFile.Execute) then
newIniFile:= appendToFile.FileName;
{find lastIndex}
numOfRows:= numOfRows - 1;{last index}
{selected procedure}
case rgSaveAs.ItemIndex of
0: appendConfAsTxt(numOfRows, newIniFile, currSection);
1: appendConfEncrypted(numOfRows, newIniFile, currSection);
else appendConfAsTxt(numOfRows, newIniFile, currSection);
end;
end;
procedure TfrmMain.sbSaveAsNewClick(Sender: TObject);
const
CANCELED_PROCEDURE : String = 'Canceled procedure(by user).';
var
numOfRows : Integer;
newIniFile : String = '';
currSection : String;
errorDlg : TfrmErrorDlg;
begin
{check section}
currSection:= edtSection.Text;
if(Length(currSection) < 1) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(NO_SECTION_ERROR);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{number of rows}
numOfRows:= sgValues.RowCount;
if(numOfRows < 2) then
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(HASH_ERROR);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
{where to save (save dialog)}
if(saveToIniFile.Execute) then
newIniFile:= saveToIniFile.FileName;
{check file_name}
if(Length(newIniFile) < 5) then
begin
ShowMessage(CANCELED_PROCEDURE);
Exit;
end;
{find lastIndex}
numOfRows:= numOfRows - 1;{last index}
{selected procedure}
case rgSaveAs.ItemIndex of
0: saveConfAsTxt(numOfRows, newIniFile, currSection);
1: saveConfEncrypted(numOfRows, newIniFile, currSection);
else saveConfAsTxt(numOfRows, newIniFile, currSection);
end;
end;
procedure TfrmMain.setColWidth;
begin
sgValues.ColWidths[0]:= 35;
sgValues.ColWidths[1]:= 170;
sgValues.ColWidths[2]:= 170;
end;
procedure TfrmMain.saveConfAsTxt(const lastIndex: Integer;
const filePath: String; const currSection: String);
var
newIniFile : TIniFile;
i : Integer;
fileExist : Boolean = False;
existingSections : TStringList;
errorDlg : TfrmErrorDlg;
begin
{check file}
if(FileExistsUTF8(filePath)) then
fileExist:= True;
{try to create ini}
try
newIniFile:= TIniFile.Create(filePath);
except
on e : Exception do
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(e.Message);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
end;
{erase existing}
if(fileExist) then
begin
existingSections:= TStringList.Create;
newIniFile.ReadSections(existingSections);
if(existingSections.Count > 0) then
for i := 0 to existingSections.Count - 1 do
newIniFile.EraseSection(existingSections[i]);
{free TStrings(existingSections)}
existingSections.Free;
end;
{loop (write strings)}
for i := 1 to lastIndex do
if(sgValues.Cells[1, i] <> '') then
newIniFile.WriteString(currSection, sgValues.Cells[1, i], sgValues.Cells[2, i]);
{free ini}
newIniFile.Free;
{success msg}
ShowMessage(SUCCESS_MSG);
end;
procedure TfrmMain.saveConfEncrypted(const lastIndex: Integer;
const filePath: String; const currSection: String);
var
newIniFile : TIniFile;
i : Integer;
fileExist : Boolean = False;
existingSections : TStringList;
xorString : String; {encrypted}
errorDlg : TfrmErrorDlg;
begin
{check file}
if(FileExistsUTF8(filePath)) then
fileExist:= True;
{try to create ini}
try
newIniFile:= TIniFile.Create(filePath);
except
on e : Exception do
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(e.Message);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
end;
{erase existing}
if(fileExist) then
begin
existingSections:= TStringList.Create;
newIniFile.ReadSections(existingSections);
if(existingSections.Count > 0) then
for i := 0 to existingSections.Count - 1 do
newIniFile.EraseSection(existingSections[i]);
{free TStrings(existingSections)}
existingSections.Free;
end;
{loop (write strings)}
for i := 1 to lastIndex do
if(sgValues.Cells[1, i] <> '') then
begin
xorString:= XorEncode(encryptionString, sgValues.Cells[2, i]);
newIniFile.WriteString(currSection, sgValues.Cells[1, i], xorString);
end;
{free ini}
newIniFile.Free;
{success msg}
ShowMessage(SUCCESS_MSG);
end;
procedure TfrmMain.appendConfAsTxt(const lastIndex: Integer;
const filePath: String; const currSection: String);
var
newIniFile : TIniFile;
i : Integer;
errorDlg : TfrmErrorDlg;
begin
{try to create ini}
try
newIniFile:= TIniFile.Create(filePath);
except
on e : Exception do
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(e.Message);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
end;
{loop (write strings)}
for i := 1 to lastIndex do
if(sgValues.Cells[1, i] <> '') then
newIniFile.WriteString(currSection, sgValues.Cells[1, i], sgValues.Cells[2, i]);
{free ini}
newIniFile.Free;
{success msg}
ShowMessage(SUCCESS_MSG);
end;
procedure TfrmMain.appendConfEncrypted(const lastIndex: Integer;
const filePath: String; const currSection: String);
var
newIniFile : TIniFile;
i : Integer;
xorString : String;{enrypted}
errorDlg : TfrmErrorDlg;
begin
{try to create ini}
try
newIniFile:= TIniFile.Create(filePath);
except
on e : Exception do
begin
{error dialog}
errorDlg:= TfrmErrorDlg.Create(frmMain);
errorDlg.setErrorMsg(e.Message);
errorDlg.closeErrDetails;
errorDlg.ShowModal;
Exit;
end;
end;
{loop (write strings)}
for i := 1 to lastIndex do
if(sgValues.Cells[1, i] <> '') then
begin
xorString:= XorEncode(encryptionString, sgValues.Cells[2, i]);
newIniFile.WriteString(currSection, sgValues.Cells[1, i], xorString);
end;
{free ini}
newIniFile.Free;
{success msg}
ShowMessage(SUCCESS_MSG);
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Math.SIUnits;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.Math,
{$ELSE}
Classes, Math,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT.Intf;
{$I ADAPT_RTTI.inc}
type
{ Enum Types }
TADSIUnitNotation = (unShort, unLong);
TADSIMagnitude = (simYocto, simZepto, simAtto, simFemto, simPico, simNano, simMicro, simMilli, simCenti, simDeci,
simOne,
simDeca, simHecto, simKilo, simMega, simGiga, simTera, simPeta, simExa, simZetta, simYotta);
TADSIBaseUnitType = (sbtLength, sbtMass, sbtTime, sbtCurrent, sbtTemperature, sbtSubstance, sbtLuminousIntensity);
TADSIBaseUnits = (sbuMetre, sbuKilogram, sbuSecond, sbuAmpere, sbuKelvin, sbuMole, sbuCandela);
{ Array Types }
TADSIUnitNotations = Array[TADSIUnitNotation] of String;
/// <summary><c>Describes the "properties" of a Unit from the International System of Units.</c></summary>
TADSIUnit = record
Name: String;
Symbol: String;
BaseMagnitude: TADSIMagnitude;
Notations: TADSIUnitNotations;
UnitType: TADSIBaseUnitType;
end;
const
AD_UNIT_METRE: TADSIUnit = (
Name: 'metre';
Symbol: 'm';
BaseMagnitude: simOne;
Notations: ('m', 'metre');
UnitType: sbtLength;
);
AD_UNIT_GRAM: TADSIUnit = (
Name: 'gram';
Symbol: 'g';
BaseMagnitude: simKilo;
Notations: ('g', 'gram');
UnitType: sbtMass;
);
AD_UNIT_SECOND: TADSIUnit = (
Name: 'second';
Symbol: 's';
BaseMagnitude: simOne;
Notations: ('s', 'second');
UnitType: sbtTime;
);
AD_UNIT_AMPERE: TADSIUnit = (
Name: 'ampere';
Symbol: 'A';
BaseMagnitude: simOne;
Notations: ('A', 'ampere');
UnitType: sbtCurrent;
);
AD_UNIT_KELVIN: TADSIUnit = (
Name: 'kelvin';
Symbol: 'K';
BaseMagnitude: simOne;
Notations: ('K', 'kelvin');
UnitType: sbtTemperature;
);
AD_UNIT_MOLE: TADSIUnit = (
Name: 'mole';
Symbol: 'mol';
BaseMagnitude: simOne;
Notations: ('mol', 'mole');
UnitType: sbtSubstance;
);
AD_UNIT_CANDELA: TADSIUnit = (
Name: 'candela';
Symbol: 'cd';
BaseMagnitude: simOne;
Notations: ('cd', 'candela');
UnitType: sbtLuminousIntensity;
);
AD_UNIT_MAGNITUDE_NAMES_SI: Array[TADSIMagnitude, TADSIUnitNotation] of String = (
('y', 'Yocto'), ('z', 'Zepto'), ('a', 'Atto'), ('f', 'Femto'), ('p', 'Pico'), ('n', 'Nano'), ('µ', 'Micro'), ('m', 'Milli'), ('c', 'Centi'), ('d', 'Deci'),
('', ''),
('da', 'Deca'), ('h', 'Hecto'), ('k', 'Kilo'), ('M', 'Mega'), ('G', 'Giga'), ('T', 'Tera'), ('P', 'Peta'), ('E', 'Exa'), ('Z', 'Zetta'), ('Y', 'Yotta')
);
{$REGION 'Magnitude Conversion Table'}
AD_UNIT_MAGNITUDE_CONVERSIONTABLE_SI: Array[TADSIMagnitude, TADSIMagnitude] of ADFloat = (
// Yocto Zepto Atto Femto Pico Nano Micro Milli Centi Deci One Deca Hecto Kilo Mega Giga Tera Peta Exa Zetta Yotta
{Yocto} (1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-22, 1e-23, 1e-24, 1e-25, 1e-26, 1e-27, 1e-30, 1e-33, 1e-36, 1e-39, 1e-42, 1e-45, 1e-48),
{Zepto} (1e3, 1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-19, 1e-20, 1e-21, 1e-22, 1e-23, 1e-24, 1e-27, 1e-30, 1e-33, 1e-36, 1e-39, 1e-42, 1e-45),
{Atto} (1e6, 1e3, 1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-16, 1e-17, 1e-18, 1e-19, 1e-20, 1e-21, 1e-24, 1e-27, 1e-30, 1e-33, 1e-36, 1e-39, 1e-42),
{Femto} (1e9, 1e6, 1e3, 1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-13, 1e-14, 1e-15, 1e-16, 1e-17, 1e-18, 1e-21, 1e-24, 1e-27, 1e-30, 1e-33, 1e-36, 1e-39),
{Pico} (1e12, 1e9, 1e6, 1e3, 1, 1e-3, 1e-6, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15, 1e-18, 1e-21, 1e-24, 1e-27, 1e-30, 1e-33, 1e-36),
{Nano} (1e15, 1e12, 1e9, 1e6, 1e3, 1, 1e-3, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, 1e-27, 1e-30, 1e-33),
{Micro} (1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, 1e-27, 1e-30),
{Milli} (1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e1, 1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, 1e-27),
{Centi} (1e22, 1e19, 1e16, 1e13, 1e10, 1e7, 1e4, 1e1, 1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-8, 1e-11, 1e-14, 1e-17, 1e-20, 1e-23, 1e-26),
{Deci} (1e23, 1e20, 1e17, 1e14, 1e11, 1e8, 1e5, 1e2, 1e1, 1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-7, 1e-10, 1e-13, 1e-16, 1e-19, 1e-22, 1e-25),
{One} (1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1e1, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24),
{Deca} (1e25, 1e22, 1e19, 1e16, 1e13, 1e10, 1e7, 1e4, 1e3, 1e2, 1e1, 1, 1e-1, 1e-2, 1e-5, 1e-8, 1e-11, 1e-14, 1e-17, 1e-20, 1e-23),
{Hecto} (1e26, 1e23, 1e20, 1e17, 1e14, 1e11, 1e8, 1e5, 1e4, 1e3, 1e2, 1e1, 1, 1e-1, 1e-4, 1e-7, 1e-10, 1e-13, 1e-16, 1e-19, 1e-22),
{Kilo} (1e27, 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e5, 1e4, 1e3, 1e2, 1e1, 1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21),
{Mega} (1e30, 1e27, 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e8, 1e7, 1e6, 1e5, 1e4, 1e3, 1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18),
{Giga} (1e33, 1e30, 1e27, 1e24, 1e21, 1e18, 1e15, 1e12, 1e11, 1e10, 1e9, 1e8, 1e7, 1e6, 1e3, 1, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15),
{Tera} (1e36, 1e33, 1e30, 1e27, 1e24, 1e21, 1e18, 1e15, 1e14, 1e13, 1e12, 1e11, 1e10, 1e9, 1e6, 1e3, 1, 1e-3, 1e-6, 1e-9, 1e-12),
{Peta} (1e39, 1e36, 1e33, 1e30, 1e27, 1e24, 1e21, 1e18, 1e17, 1e16, 1e15, 1e14, 1e13, 1e12, 1e9, 1e6, 1e3, 1, 1e-3, 1e-6, 1e-9),
{Exa} (1e42, 1e39, 1e36, 1e33, 1e30, 1e27, 1e24, 1e21, 1e20, 1e19, 1e18, 1e17, 1e16, 1e15, 1e12, 1e9, 1e6, 1e3, 1, 1e-3, 1e-6),
{Zetta} (1e45, 1e42, 1e39, 1e36, 1e33, 1e30, 1e27, 1e24, 1e23, 1e22, 1e21, 1e20, 1e19, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1, 1e-3),
{Yotta} (1e48, 1e45, 1e42, 1e39, 1e36, 1e33, 1e30, 1e27, 1e26, 1e25, 1e24, 1e23, 1e22, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1)
);
{$ENDREGION}
function SIMagnitude(const ASourceValue: ADFloat): Integer;
function SIMagnitudeConvert(const ASourceValue: ADFloat; const AFromMagnitude, AToMagnitude: TADSIMagnitude): ADFloat; inline;
function SIMagnitudeGetNotationText(const AMagnitude: TADSIMagnitude; const ANotation: TADSIUnitNotation): String; inline;
procedure SIMagnitudeToBest(const AInValue: ADFloat; const AInMagnitude: TADSIMagnitude; var AOutValue: ADFloat; var AOutMagnitude: TADSIMagnitude); inline;
implementation
function SIMagnitude(const ASourceValue: ADFloat): Integer;
begin
if ASourceValue < 1 then
Result := 0
else
Result := Trunc(Log10(Abs(ASourceValue)));
end;
function SIMagnitudeConvert(const ASourceValue: ADFloat; const AFromMagnitude, AToMagnitude: TADSIMagnitude): ADFloat;
begin
Result := ASourceValue * AD_UNIT_MAGNITUDE_CONVERSIONTABLE_SI[AFromMagnitude, AToMagnitude];
end;
function SIMagnitudeGetNotationText(const AMagnitude: TADSIMagnitude; const ANotation: TADSIUnitNotation): String;
begin
Result := AD_UNIT_MAGNITUDE_NAMES_SI[AMagnitude, ANotation];
end;
procedure SIMagnitudeToBest(const AInValue: ADFloat; const AInMagnitude: TADSIMagnitude; var AOutValue: ADFloat; var AOutMagnitude: TADSIMagnitude);
var
LMagnitudeDifference: Integer;
begin
// Presume that no conversion is required.
AOutValue := AInValue;
AOutMagnitude := AInMagnitude;
{ TODO -oDaniel -cSI Units : Implement method to determine most appropriate Order of Magnitude to represent given value }
LMagnitudeDifference := SIMagnitude(AInValue);
if LMagnitudeDifference = 0 then
Exit
else if LMagnitudeDifference > 0 then
AOutMagnitude := TADSIMagnitude(Integer(AInMagnitude) + LMagnitudeDifference)
else if LMagnitudeDifference < 0 then
AOutMagnitude := TADSIMagnitude(Integer(AInMagnitude) - LMagnitudeDifference);
AOutValue := SIMagnitudeConvert(AInValue, AInMagnitude, AOutMagnitude);
end;
end.
|
{
/***************************************************************************
findreplacedialog.pp
--------------------
***************************************************************************/
Author: Mattias Gaertner
*****************************************************************************
* *
* See the file COPYING.modifiedLGPL, included in this distribution, *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
*****************************************************************************
Abstract:
Find and replace dialog form.
Usage:
Add to program
"Application.CreateForm(TLazFindReplaceDialog, FindReplaceDlg);"
Set the FindReplaceDlg.Options poperty
then do MResult:=FindReplaceDlg.ShowModal
ShowModal can have three possible results:
- mrOk for Find/Replace.
- mrAll for ReplaceAll
- mrCancel for Cancel
}
unit FindReplaceDialog;
{$mode objfpc}{$H+}
interface
uses
Classes, Math, SysUtils, LCLProc, LCLType, Controls, StdCtrls, Forms, Buttons,
ExtCtrls, LResources, Dialogs, SynEditTypes, RegExpr, SynEdit, LazUTF8,
IDEWindowIntf, LazarusIDEStrConsts, FileUtil;
type
TFindDlgComponent = (fdcText, fdcReplace);
TOnFindDlgKey = procedure(Sender: TObject; var Key: Word; Shift:TShiftState;
FindDlgComponent: TFindDlgComponent) of Object;
{ TLazFindReplaceDialog }
TLazFindReplaceDialog = class(TForm)
BackwardRadioButton: TRadioButton;
BtnPanel: TPanel;
ReplaceAllButton: TBitBtn;
CaseSensitiveCheckBox: TCheckBox;
EntireScopeRadioButton: TRadioButton;
ForwardRadioButton: TRadioButton;
FromCursorRadioButton: TRadioButton;
GlobalRadioButton: TRadioButton;
DirectionGroupBox: TGroupBox;
OriginGroupBox: TGroupBox;
ScopeGroupBox: TGroupBox;
OptionsGroupBox: TGroupBox;
MultiLineCheckBox: TCheckBox;
OKButton: TBitBtn;
PromptOnReplaceCheckBox: TCheckBox;
RegularExpressionsCheckBox: TCheckBox;
SelectedRadioButton: TRadioButton;
TextToFindLabel: TLabel;
ReplaceWithLabel: TLabel;
TextToFindComboBox: TComboBox;
ReplaceTextComboBox: TComboBox;
CancelButton: TBitBtn;
WholeWordsOnlyCheckBox: TCheckBox;
procedure FormChangeBounds(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure OptionsGroupBoxResize(Sender: TObject);
procedure TextToFindComboboxKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure OkButtonClick(Sender: TObject);
procedure ReplaceAllButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
FOnKey: TOnFindDlgKey;
fReplaceAllClickedLast: boolean;
RegExpr: TRegExpr;
function CheckInput: boolean;
function GetComponentText(c: TFindDlgComponent): string;
procedure SetComponentText(c: TFindDlgComponent; const AValue: string);
procedure SetOnKey(const AValue: TOnFindDlgKey);
procedure SetOptions(NewOptions: TSynSearchOptions);
function GetOptions: TSynSearchOptions;
function GetFindText: AnsiString;
procedure SetFindText(const NewFindText: AnsiString);
function GetReplaceText: AnsiString;
procedure SetReplaceText(const NewReplaceText: AnsiString);
procedure SetComboBoxText(AComboBox: TComboBox; const AText: AnsiString);
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
public
property Options: TSynSearchOptions read GetOptions write SetOptions;
property FindText:AnsiString read GetFindText write SetFindText;
property ReplaceText:AnsiString read GetReplaceText write SetReplaceText;
property OnKey: TOnFindDlgKey read FOnKey write SetOnKey;
property ComponentText[c: TFindDlgComponent]: string
read GetComponentText write SetComponentText;
end;
var
LazFindReplaceDialog: TLazFindReplaceDialog = nil;
implementation
{$R *.lfm}
{ TLazFindReplaceDialog }
constructor TLazFindReplaceDialog.Create(TheOwner:TComponent);
begin
inherited Create(TheOwner);
IDEDialogLayoutList.ApplyLayout(Self,420,350);
Caption:='';
TextToFindComboBox.Text:='';
TextToFindLabel.Caption:=SysToUTF8(dlgTextToFing);
ReplaceTextComboBox.Text:='';
ReplaceWithLabel.Caption:=SysToUTF8(dlgReplaceWith);
OptionsGroupBox.Caption:=SysToUTF8(dlgFROpts);
(*
with CaseSensitiveCheckBox do begin
Caption:=dlgCaseSensitive;
Hint:=lisDistinguishBigAndSmallLettersEGAAndA;
end;
with WholeWordsOnlyCheckBox do begin
Caption:=dlgWholeWordsOnly;
Hint:=lisOnlySearchForWholeWords;
end;
with RegularExpressionsCheckBox do begin
Caption:=dlgRegularExpressions;
Hint:=lisActivateRegularExpressionSyntaxForTextAndReplaceme;
end;
with MultiLineCheckBox do begin
Caption:=dlgMultiLine;
Hint:=lisAllowSearchingForMultipleLines;
end;
with PromptOnReplaceCheckBox do begin
Caption:=dlgPromptOnReplace;
Hint:=lisAskBeforeReplacingEachFoundText;
end;
OriginGroupBox.Caption:=dlgSROrigin;
FromCursorRadioButton.Caption := dlgFromCursor;
EntireScopeRadioButton.Caption := dlgEntireScope;
ScopeGroupBox.Caption:=dlgScope;
GlobalRadioButton.Caption := dlgGlobal;
SelectedRadioButton.Caption := dlgSelectedText;
DirectionGroupBox.Caption:=dlgDirection;
ForwardRadioButton.Caption := lisFRForwardSearch;
BackwardRadioButton.Caption := lisFRBackwardSearch;
*)
ReplaceAllButton.Caption:=SysToUTF8(dlgReplaceAll);
CancelButton.Caption:=SysToUTF8(dlgCancel);
fReplaceAllClickedLast:=false;
end;
destructor TLazFindReplaceDialog.Destroy;
begin
RegExpr.Free;
inherited Destroy;
if LazFindReplaceDialog=Self then
LazFindReplaceDialog:=nil;
end;
procedure TLazFindReplaceDialog.TextToFindComboBoxKeyDown(
Sender: TObject; var Key:Word; Shift:TShiftState);
var Component: TFindDlgComponent;
begin
//debugln('TLazFindReplaceDialog.TextToFindComboBoxKeyDown Key=',Key,' RETURN=',VK_RETURN,' TAB=',VK_TAB,' DOWN=',VK_DOWN,' UP=',VK_UP);
if Assigned(OnKey) then begin
if Sender=TextToFindComboBox then
Component:=fdcText
else
Component:=fdcReplace;
OnKey(Sender, Key, Shift, Component);
end;
end;
procedure TLazFindReplaceDialog.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
IDEDialogLayoutList.SaveLayout(Self);
end;
procedure TLazFindReplaceDialog.OptionsGroupBoxResize(Sender: TObject);
var
h: integer;
begin
DisableAlign;
h := (OptionsGroupBox.Height-12) div 3;
OriginGroupBox.Height := h;
ScopeGroupBox.Height := h;
DirectionGroupBox.Height := OptionsGroupBox.Height-2*h-12;
EnableAlign;
end;
procedure TLazFindReplaceDialog.FormChangeBounds(Sender: TObject);
var
w: integer;
begin
DisableAlign;
w := (ClientWidth - 18) div 2;
OptionsGroupBox.Width := w;
OriginGroupBox.Width := w;
ScopeGroupBox.Width := w;
DirectionGroupBox.Width := w;
EnableAlign;
end;
procedure TLazFindReplaceDialog.OkButtonClick(Sender:TObject);
begin
if not CheckInput then exit;
fReplaceAllClickedLast:=false;
ActiveControl:=TextToFindComboBox;
ModalResult:=mrOk;
end;
procedure TLazFindReplaceDialog.ReplaceAllButtonClick(Sender:TObject);
begin
if not CheckInput then exit;
fReplaceAllClickedLast:=true;
ActiveControl:=TextToFindComboBox;
ModalResult:=mrAll;
end;
procedure TLazFindReplaceDialog.CancelButtonClick(Sender:TObject);
begin
ActiveControl:=TextToFindComboBox;
end;
function TLazFindReplaceDialog.CheckInput: boolean;
begin
Result:=false;
if RegularExpressionsCheckBox.Checked then begin
if RegExpr=nil then RegExpr:=TRegExpr.Create;
try
RegExpr.Expression:=FindText;
RegExpr.Exec('test');
except
on E: ERegExpr do begin
MessageDlg(lisUEErrorInRegularExpression,
E.Message,mtError,[mbCancel],0);
exit;
end;
end;
if ReplaceTextComboBox.Enabled then begin
try
RegExpr.Substitute(ReplaceText);
except
on E: ERegExpr do begin
MessageDlg(lisUEErrorInRegularExpression,
E.Message,mtError,[mbCancel],0);
exit;
end;
end;
end;
end;
Result:=true;
end;
function TLazFindReplaceDialog.GetComponentText(c: TFindDlgComponent): string;
begin
case c of
fdcText: Result:=FindText;
else
Result:=Replacetext;
end;
end;
procedure TLazFindReplaceDialog.SetComponentText(c: TFindDlgComponent;
const AValue: string);
begin
case c of
fdcText: FindText:=AValue;
else
Replacetext:=AValue;
end;
end;
procedure TLazFindReplaceDialog.SetOnKey(const AValue: TOnFindDlgKey);
begin
FOnKey:=AValue;
end;
procedure TLazFindReplaceDialog.SetOptions(NewOptions:TSynSearchOptions);
begin
CaseSensitiveCheckBox.Checked:=ssoMatchCase in NewOptions;
WholeWordsOnlyCheckBox.Checked:=ssoWholeWord in NewOptions;
RegularExpressionsCheckBox.Checked:=ssoRegExpr in NewOptions;
MultiLineCheckBox.Checked:=ssoRegExprMultiLine in NewOptions;
PromptOnReplaceCheckBox.Checked:=ssoPrompt in NewOptions;
if ssoEntireScope in NewOptions
then EntireScopeRadioButton.Checked:=True
else FromCursorRadioButton.Checked:=True;
if ssoSelectedOnly in NewOptions
then SelectedRadioButton.Checked:=True
else GlobalRadioButton.Checked:=True;
if ssoBackwards in NewOptions
then BackwardRadioButton.Checked:=True
else ForwardRadioButton.Checked:=True;
ReplaceAllButton.Visible:=ssoReplace in NewOptions;
ReplaceTextComboBox.Enabled:=ReplaceAllButton.Visible;
ReplaceWithLabel.Enabled:=ReplaceAllButton.Visible;
PromptOnReplaceCheckBox.Enabled:=ReplaceAllButton.Visible;
if ssoReplace in NewOptions then begin
Caption:=SysToUTF8(lisMenuReplace);
OkButton.Caption:=SysToUTF8(lisMenuReplace);
end else begin
Caption:=SysToUTF8(lisMenuFind);
OkButton.Caption:=SysToUTF8(lisMenuFind);
end;
//DebugLn(['TLazFindReplaceDialog.SetOptions END ssoSelectedOnly=',ssoSelectedOnly in NewOptions,' SelectedRadioButton.Checked=',SelectedRadioButton.Checked]);
end;
function TLazFindReplaceDialog.GetOptions:TSynSearchOptions;
begin
Result:=[];
if CaseSensitiveCheckBox.Checked then Include(Result,ssoMatchCase);
if WholeWordsOnlyCheckBox.Checked then Include(Result,ssoWholeWord);
if RegularExpressionsCheckBox.Checked then Include(Result,ssoRegExpr);
if MultiLineCheckBox.Checked then Include(Result,ssoRegExprMultiLine);
if PromptOnReplaceCheckBox.Checked then Include(Result,ssoPrompt);
if EntireScopeRadioButton.Checked then Include(Result,ssoEntireScope);
if SelectedRadioButton.Checked then include(Result,ssoSelectedOnly);
if BackwardRadioButton.Checked then include(Result,ssoBackwards);
if ReplaceAllButton.Visible then include(Result,ssoReplace);
if fReplaceAllClickedLast then include(Result,ssoReplaceAll);
end;
function TLazFindReplaceDialog.GetFindText:AnsiString;
begin
Result:=TextToFindComboBox.Text;
end;
procedure TLazFindReplaceDialog.SetFindText(const NewFindText: AnsiString);
begin
// SetComboBoxText(TextToFindComboBox,NewFindText);
TextToFindComboBox.Text:=NewFindText;
TextToFindComboBox.SelectAll;
//debugln('TLazFindReplaceDialog.SetFindText A TextToFindComboBox.SelStart=',dbgs(TextToFindComboBox.SelStart),' TextToFindComboBox.SelLength=',dbgs(TextToFindComboBox.SelLength),' TextToFindComboBox.Text="',TextToFindComboBox.Text,'" NewFindText="',DbgStr(NewFindText),'"');
end;
function TLazFindReplaceDialog.GetReplaceText:AnsiString;
begin
Result:=ReplaceTextComboBox.Text;
end;
procedure TLazFindReplaceDialog.SetReplaceText(const NewReplaceText:AnsiString);
begin
SetComboBoxText(ReplaceTextComboBox,NewReplaceText);
end;
procedure TLazFindReplaceDialog.SetComboBoxText(AComboBox:TComboBox;
const AText:AnsiString);
var a:integer;
begin
a:=AComboBox.Items.IndexOf(AText);
//writeln('TLazFindReplaceDialog.SetComboBoxText ',AText,' ',a);
if a>=0 then
AComboBox.ItemIndex:=a
else begin
AComboBox.Items.Add(AText);
AComboBox.ItemIndex:=AComboBox.Items.IndexOf(AText);
end;
end;
initialization
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TfrmDialogDemo }
TfrmDialogDemo = class(TForm)
btnLoad: TButton;
btnSave: TButton;
btnFont: TButton;
btnClear: TButton;
fodFontDemo: TFontDialog;
memDemo: TMemo;
frmDialogDemo: TOpenDialog;
opdOpenDemo: TOpenDialog;
svdSaveDemo: TSaveDialog;
procedure btnClearClick(Sender: TObject);
procedure btnFontClick(Sender: TObject);
procedure btnLoadClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
frmDialogDemo: TfrmDialogDemo;
implementation
{$R *.lfm}
{ TfrmDialogDemo }
procedure TfrmDialogDemo.btnClearClick(Sender: TObject);
begin
memDemo.Clear;
end;
procedure TfrmDialogDemo.btnFontClick(Sender: TObject);
begin
if fodFontDemo.Execute then
memDemo.Font:=fodFontDemo.Font;
end;
procedure TfrmDialogDemo.btnLoadClick(Sender: TObject);
begin
if opdOpenDemo.Execute then
try
memDemo.Lines.LoadFromFile(opdOpenDemo.FileName);
except
ShowMessage('Error loading file ' + opdOpenDemo.FileName);
end;
end;
procedure TfrmDialogDemo.btnSaveClick(Sender: TObject);
begin
if svdSaveDemo.Execute then
try
memDemo.Lines.SaveToFile(svdSaveDemo.FileName);
except
ShowMessage('Error while writing to file ' + svdSaveDemo.FileName);
end;
end;
end.
|
unit FormMain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ComCtrls, ExtCtrls,
StdCtrls, Spin, PairSplitter, JSONPropStorage, syncobjs, fgl,
fpjson, Yeehaa;
type
TBulbMap = specialize TFPGMap<String,TBulbInfo>;
{ TMainForm }
TMainForm = class(TForm)
BRefresh: TButton;
BSelectAll: TButton;
BCopy: TButton;
BClear: TButton;
CBColor: TColorButton;
CBPoweredOn: TCheckBox;
EdModel: TEdit;
EdName: TEdit;
GBBulbList: TGroupBox;
GBBulbProps: TGroupBox;
GBOptions: TGroupBox;
GBTransitionDuration: TGroupBox;
GBLog: TGroupBox;
ConfigStorage: TJSONPropStorage;
LbTemperature: TLabel;
LbBrightness: TLabel;
LBBulbList: TListBox;
LbModel: TLabel;
LbName: TLabel;
LbPoweredOn: TLabel;
LbRGB: TLabel;
MemoLog: TMemo;
PMemoButtons: TPanel;
PSBulbLog: TPairSplitter;
PSBulbListProps: TPairSplitter;
PSBulbPropsOpts: TPairSplitter;
PairSplitterSide1: TPairSplitterSide;
PairSplitterSide2: TPairSplitterSide;
PairSplitterSide3: TPairSplitterSide;
PairSplitterSide4: TPairSplitterSide;
PairSplitterSide5: TPairSplitterSide;
PairSplitterSide6: TPairSplitterSide;
RGTransitionEffect: TRadioGroup;
SpEdBrightness: TSpinEdit;
SpEdTransitionDuration: TSpinEdit;
SpEdTemperature: TSpinEdit;
procedure BClearClick(Sender: TObject);
procedure BCopyClick(Sender: TObject);
procedure BSelectAllClick(Sender: TObject);
procedure CBColorColorChanged(Sender: TObject);
procedure CBPoweredOnChange(Sender: TObject);
procedure EdNameChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BRefreshClick(Sender: TObject);
procedure LBBulbListSelectionChange(Sender: TObject; User: boolean);
procedure SpEdBrightnessChange(Sender: TObject);
procedure SpEdTemperatureChange(Sender: TObject);
private
FYeeConn: TYeeConn;
FBulbMap: TBulbMap;
FSelectedBulb: TBulbInfo;
FCS: TCriticalSection;
FAutomaticStateChange: Boolean;
procedure InsertBulb(const ANewBulb: TBulbInfo);
procedure LogCommandResult(const AID: Integer; AResult, AError: TJSONData);
procedure LogConnectionError(const AMsg: String);
public
end;
var
MainForm: TMainForm;
implementation
{$R *.lfm}
const
ListenPort = 9999;
BroadcastIntervalMillisecond = 5000;
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
begin
FBulbMap := TBulbMap.Create;
FBulbMap.Sorted := true;
FYeeConn := TYeeConn.Create(ListenPort, BroadcastIntervalMillisecond);
FYeeConn.OnBulbFound := @InsertBulb;
FYeeConn.OnCommandResult := @LogCommandResult;
FYeeConn.OnConnectionError := @LogConnectionError;
FCS := TCriticalSection.Create;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FYeeConn.Free;
FBulbMap.Free;
FCS.Free;
end;
procedure TMainForm.CBPoweredOnChange(Sender: TObject);
var
LTransitionEffect: TTransitionEfect;
begin
if (LBBulbList.ItemIndex >= 0) and not FAutomaticStateChange then begin
case RGTransitionEffect.ItemIndex of
0: LTransitionEffect := teSudden;
otherwise LTransitionEffect := teSmooth;
end;
FYeeConn.SetPower(FSelectedBulb.IP,CBPoweredOn.Checked,LTransitionEffect,SpEdTransitionDuration.Value);
end;
end;
procedure TMainForm.BSelectAllClick(Sender: TObject);
begin
MemoLog.SelectAll;
end;
procedure TMainForm.CBColorColorChanged(Sender: TObject);
var
LTransitionEffect: TTransitionEfect;
begin
if (LBBulbList.ItemIndex >= 0) and not FAutomaticStateChange then begin
case RGTransitionEffect.ItemIndex of
0: LTransitionEffect := teSudden;
otherwise LTransitionEffect := teSmooth;
end;
FYeeConn.SetPower(FSelectedBulb.IP,true,LTransitionEffect,SpEdTransitionDuration.Value,pcmRGB);
FYeeConn.SetRGB(FSelectedBulb.IP,TRGBRange(CBColor.ButtonColor),LTransitionEffect,SpEdTransitionDuration.Value);
end;
end;
procedure TMainForm.BCopyClick(Sender: TObject);
begin
MemoLog.CopyToClipboard;
end;
procedure TMainForm.BClearClick(Sender: TObject);
begin
MemoLog.Clear;
end;
procedure TMainForm.EdNameChange(Sender: TObject);
begin
if (LBBulbList.ItemIndex >= 0) and not FAutomaticStateChange then begin
FYeeConn.SetName(FSelectedBulb.IP,EdName.Text);
end;
end;
procedure TMainForm.BRefreshClick(Sender: TObject);
begin
FCS.Enter;
try
FBulbMap.Clear;
LBBulbList.Clear;
finally
FCS.Leave;
end;
end;
procedure TMainForm.LBBulbListSelectionChange(Sender: TObject; User: boolean);
begin
GBBulbProps.Enabled := true;
try
FAutomaticStateChange := true;
try
FSelectedBulb := FBulbMap[LBBulbList.GetSelectedText];
EdModel.Text := FSelectedBulb.Model;
CBPoweredOn.Checked := FSelectedBulb.PoweredOn;
SpEdBrightness.Value := FSelectedBulb.BrightnessPercentage;
CBColor.ButtonColor := RGBToTColor(FSelectedBulb.RGB);
EdName.Text := FSelectedBulb.Name;
SpEdTemperature.Value := FSelectedBulb.CT;
finally
FAutomaticStateChange := false;
end;
except
on e: EListError do ; // intentionally ignored
end;
end;
procedure TMainForm.SpEdBrightnessChange(Sender: TObject);
var
LTransitionEffect: TTransitionEfect;
begin
if (LBBulbList.ItemIndex >= 0) and not FAutomaticStateChange then begin
case RGTransitionEffect.ItemIndex of
0: LTransitionEffect := teSudden;
otherwise LTransitionEffect := teSmooth;
end;
FYeeConn.SetBrightness(FSelectedBulb.IP,SpEdBrightness.Value,LTransitionEffect,SpEdTransitionDuration.Value);
end;
end;
procedure TMainForm.SpEdTemperatureChange(Sender: TObject);
var
LTransitionEffect: TTransitionEfect;
begin
if (LBBulbList.ItemIndex >= 0) and not FAutomaticStateChange then begin
case RGTransitionEffect.ItemIndex of
0: LTransitionEffect := teSudden;
otherwise LTransitionEffect := teSmooth;
end;
FYeeConn.SetPower(FSelectedBulb.IP,true,LTransitionEffect,SpEdTransitionDuration.Value,pcmCT);
FYeeConn.SetColorTemperature(FSelectedBulb.IP,SpEdTemperature.Value,LTransitionEffect,SpEdTransitionDuration.Value);
end;
end;
procedure TMainForm.InsertBulb(const ANewBulb: TBulbInfo);
begin
FCS.Enter;
try
if FBulbMap.IndexOf(ANewBulb.IP) < 0 then
LBBulbList.Items.Add(ANewBulb.IP);
FBulbMap[ANewBulb.IP] := ANewBulb;
finally
FCS.Leave;
end;
end;
procedure TMainForm.LogCommandResult(const AID: Integer; AResult,
AError: TJSONData);
begin
if Assigned(AResult) then MemoLog.Lines.Add('[Result] ' + AResult.AsJSON);
if Assigned(AError) then MemoLog.Lines.Add('[Error] ' + AError.AsJSON);
end;
procedure TMainForm.LogConnectionError(const AMsg: String);
begin
MemoLog.Lines.Add('[Connection error] ' + AMsg);
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_CrowdTool;
interface
uses
Classes, Controls, StdCtrls, Unit_FrameCrowdTool,
RN_Sample, RN_DetourNavMesh, RN_DetourNavMeshHelper, RN_DetourObstacleAvoidance, RN_ValueHistory, RN_DetourCrowd;
// Tool to create crowds.
type
PCrowdToolParams = ^TCrowdToolParams;
TCrowdToolParams = record
m_showCorners: Boolean;
m_showCollisionSegments: Boolean;
m_showPath: Boolean;
m_showVO: Boolean;
m_showOpt: Boolean;
m_showNeis: Boolean;
m_showLabels: Boolean;
m_showGrid: Boolean;
m_showNodes: Boolean;
m_showPerfGraph: Boolean;
m_showDetailAll: Boolean;
m_anticipateTurns: Boolean;
m_optimizeVis: Boolean;
m_optimizeTopo: Boolean;
m_obstacleAvoidance: Boolean;
m_obstacleAvoidanceType: Single;
m_separation: Boolean;
m_separationWeight: Single;
end;
TCrowdToolState = class (TSampleToolState)
private
m_sample: TSample;
m_nav: TdtNavMesh;
m_crowd: TdtCrowd;
m_targetPos: array [0..2] of Single;
m_targetRef: TdtPolyRef;
m_agentDebug: TdtCrowdAgentDebugInfo;
m_vod: TdtObstacleAvoidanceDebugData;
const AGENT_MAX_TRAIL = 64;
const MAX_AGENTS = 128;
type
PAgentTrail = ^TAgentTrail;
TAgentTrail = record
trail: array [0..AGENT_MAX_TRAIL*3-1] of Single;
htrail: Integer;
end;
var
m_trails: array [0..MAX_AGENTS-1] of TAgentTrail;
m_crowdTotalTime: TValueHistory;
m_crowdSampleCount: TValueHistory;
m_toolParams: TCrowdToolParams;
m_run: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure init(sample: TSample); override;
procedure reset; override;
procedure handleRender; override;
procedure handleRenderOverlay(proj, model: PDouble; view: PInteger); override;
procedure handleUpdate(dt: Single); override;
property isRunning: Boolean read m_run;
procedure setRunning(const s: Boolean); { m_run = s; }
procedure addAgent(const pos: PSingle);
procedure removeAgent(const idx: Integer);
procedure hilightAgent(const idx: Integer);
procedure updateAgentParams();
function hitTestAgents(const s, p: PSingle): Integer;
procedure setMoveTarget(const p: PSingle; adjust: Boolean);
procedure updateTick(const dt: Single);
function getToolParams: PCrowdToolParams; { return &m_toolParams; }
end;
TCrowdTool = class (TSampleTool)
private
fFrame: TFrameCrowdTool;
fUpdateUI: Boolean;
m_sample: TSample;
m_state: TCrowdToolState;
type TToolMode =
(
TOOLMODE_CREATE,
TOOLMODE_MOVE_TARGET,
TOOLMODE_SELECT,
TOOLMODE_TOGGLE_POLYS
);
var
m_mode: TToolMode;
public
constructor Create(aOwner: TWinControl);
destructor Destroy; override;
procedure init(sample: TSample); override;
procedure reset(); override;
procedure handleMenu(Sender: TObject); override;
procedure handleClick(s,p: PSingle; shift: Boolean); override;
procedure handleToggle(); override;
procedure handleStep(); override;
procedure handleUpdate(dt: Single); override;
procedure handleRender(); override;
procedure handleRenderOverlay(proj, model: PDouble; view: PInteger); override;
end;
implementation
uses Math,
RN_InputGeom, RN_SampleInterfaces, RN_DebugDraw, RN_PerfTimer,
RN_Recast, RN_RecastHelper, RN_RecastDebugDraw,
RN_DetourNavMeshBuilder, RN_DetourProximityGrid, RN_DetourNavMeshQuery, RN_DetourStatus, RN_DetourDebugDraw, RN_DetourCommon;
function isectSegAABB(const sp, sq, amin, amax: PSingle;
tmin, tmax: PSingle): Boolean;
const EPS = 0.000001;
var d: array [0..2] of Single; i: Integer; ood,t1,t2: Single;
begin
dtVsub(@d[0], sq, sp);
tmin^ := 0; // set to -FLT_MAX to get first hit on line
tmax^ := MaxSingle; // set to max distance ray can travel (for segment)
// For all three slabs
for i := 0 to 2 do
begin
if (Abs(d[i]) < EPS) then
begin
// Ray is parallel to slab. No hit if origin not within slab
if (sp[i] < amin[i]) or (sp[i] > amax[i]) then
Exit(false);
end
else
begin
// Compute intersection t value of ray with near and far plane of slab
ood := 1.0 / d[i];
t1 := (amin[i] - sp[i]) * ood;
t2 := (amax[i] - sp[i]) * ood;
// Make t1 be intersection with near plane, t2 with far plane
if (t1 > t2) then dtSwap(t1, t2);
// Compute the intersection of slab intersections intervals
if (t1 > tmin^) then tmin^ := t1;
if (t2 < tmax^) then tmax^ := t2;
// Exit with no collision as soon as slab intersection becomes empty
if (tmin^ > tmax^) then Exit(false);
end;
end;
Result := true;
end;
procedure getAgentBounds(const ag: PdtCrowdAgent; bmin, bmax: PSingle);
var p: PSingle; r, h: Single;
begin
p := @ag.npos[0];
r := ag.params.radius;
h := ag.params.height;
bmin[0] := p[0] - r;
bmin[1] := p[1];
bmin[2] := p[2] - r;
bmax[0] := p[0] + r;
bmax[1] := p[1] + h;
bmax[2] := p[2] + r;
end;
constructor TCrowdToolState.Create();
begin
inherited;
m_run := true;
m_toolParams.m_showCorners := false;
m_toolParams.m_showCollisionSegments := false;
m_toolParams.m_showPath := false;
m_toolParams.m_showVO := false;
m_toolParams.m_showOpt := false;
m_toolParams.m_showNeis := false;
m_toolParams.m_showLabels := false;
m_toolParams.m_showGrid := false;
m_toolParams.m_showNodes := false;
m_toolParams.m_showPerfGraph := false;
m_toolParams.m_showDetailAll := false;
m_toolParams.m_anticipateTurns := true;
m_toolParams.m_optimizeVis := true;
m_toolParams.m_optimizeTopo := true;
m_toolParams.m_obstacleAvoidance := true;
m_toolParams.m_obstacleAvoidanceType := 3.0;
m_toolParams.m_separation := false;
m_toolParams.m_separationWeight := 2.0;
FillChar(m_trails[0], sizeof(m_trails), 0);
m_vod := dtAllocObstacleAvoidanceDebugData();
m_vod.init(2048);
FillChar(m_agentDebug, sizeof(m_agentDebug), 0);
m_agentDebug.idx := -1;
m_agentDebug.vod := m_vod;
// Delphi: Assume C++ invokes constructor
m_crowdTotalTime := TValueHistory.Create;
m_crowdSampleCount := TValueHistory.Create;
end;
destructor TCrowdToolState.Destroy;
begin
dtFreeObstacleAvoidanceDebugData(m_vod);
// Delphi: Assume C++ invokes destructor
m_crowdTotalTime.Free;
m_crowdSampleCount.Free;
inherited;
end;
procedure TCrowdToolState.init(sample: TSample);
var nav: TdtNavMesh; crowd: TdtCrowd; params: TdtObstacleAvoidanceParams;
begin
if (m_sample <> sample) then
begin
m_sample := sample;
// m_oldFlags := m_sample.getNavMeshDrawFlags();
// m_sample.setNavMeshDrawFlags(m_oldFlags & ~DU_DRAWNAVMESH_CLOSEDLIST);
end;
nav := m_sample.getNavMesh;
crowd := m_sample.getCrowd;
if (nav <> nil) and (crowd <> nil) and ((m_nav <> nav) or (m_crowd <> crowd)) then
begin
m_nav := nav;
m_crowd := crowd;
crowd.init(MAX_AGENTS, m_sample.getAgentRadius, nav);
// Make polygons with 'disabled' flag invalid.
crowd.getEditableFilter(0).setExcludeFlags(SAMPLE_POLYFLAGS_DISABLED);
// Setup local avoidance params to different qualities.
// Use mostly default settings, copy from dtCrowd.
Move(crowd.getObstacleAvoidanceParams(0)^, params, sizeof(TdtObstacleAvoidanceParams));
// Low (11)
params.velBias := 0.5;
params.adaptiveDivs := 5;
params.adaptiveRings := 2;
params.adaptiveDepth := 1;
crowd.setObstacleAvoidanceParams(0, @params);
// Medium (22)
params.velBias := 0.5;
params.adaptiveDivs := 5;
params.adaptiveRings := 2;
params.adaptiveDepth := 2;
crowd.setObstacleAvoidanceParams(1, @params);
// Good (45)
params.velBias := 0.5;
params.adaptiveDivs := 7;
params.adaptiveRings := 2;
params.adaptiveDepth := 3;
crowd.setObstacleAvoidanceParams(2, @params);
// High (66)
params.velBias := 0.5;
params.adaptiveDivs := 7;
params.adaptiveRings := 3;
params.adaptiveDepth := 3;
crowd.setObstacleAvoidanceParams(3, @params);
end;
end;
procedure TCrowdToolState.reset();
begin
end;
procedure TCrowdToolState.handleRender();
var dd: TDebugDrawGL; rad: Single; nav: TdtNavMesh; crowd: TdtCrowd; navquery: TdtNavMeshQuery; i, j: Integer; ag: PdtCrowdAgent;
path: PdtPolyRef; npath: Integer; gridy, cs: Single; grid: TdtProximityGrid; pos, vel, dvel, v, p: PSingle; bounds: PInteger; x, y, count: Integer;
col: Cardinal; trail: PAgentTrail; prev: array [0..2] of Single; preva, a, radius, height: Single; idx: Integer; va, vb, center, s: PSingle;
nei: PdtCrowdAgent; vod: TdtObstacleAvoidanceDebugData; dx,dy,dz, sr, pen, pen2: Single;
begin
dd := TDebugDrawGL.Create;
rad := m_sample.getAgentRadius;
nav := m_sample.getNavMesh;
crowd := m_sample.getCrowd;
if (nav = nil) or (crowd = nil) then
Exit;
if (m_toolParams.m_showNodes and (crowd.getPathQueue <> nil)) then
begin
navquery := crowd.getPathQueue.getNavQuery();
if (navquery <> nil) then
duDebugDrawNavMeshNodes(dd, navquery);
end;
dd.depthMask(false);
// Draw paths
if (m_toolParams.m_showPath) then
begin
for i := 0 to crowd.getAgentCount - 1 do
begin
if (m_toolParams.m_showDetailAll = false) and (i <> m_agentDebug.idx) then
continue;
ag := crowd.getAgent(i);
if (not ag.active) then
continue;
path := ag.corridor.getPath();
npath := ag.corridor.getPathCount();
for j := 0 to npath - 1 do
duDebugDrawNavMeshPoly(dd, nav, path[j], duRGBA(255,255,255,24));
end;
end;
if (m_targetRef <> 0) then
duDebugDrawCross(dd, m_targetPos[0],m_targetPos[1]+0.1,m_targetPos[2], rad, duRGBA(255,255,255,192), 2.0);
// Occupancy grid.
if (m_toolParams.m_showGrid) then
begin
gridy := -MaxSingle;
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
pos := ag.corridor.getPos();
gridy := dtMax(gridy, pos[1]);
end;
gridy := gridy + 1.0;
dd.&begin(DU_DRAW_QUADS);
grid := crowd.getGrid;
bounds := grid.getBounds();
cs := grid.getCellSize();
for y := bounds[1] to bounds[3] do
begin
for x := bounds[0] to bounds[2] do
begin
count := grid.getItemCountAt(x,y);
if (count = 0) then continue;
col := duRGBA(128,0,0,dtMin(count*40,255));
dd.vertex(x*cs, gridy, y*cs, col);
dd.vertex(x*cs, gridy, y*cs+cs, col);
dd.vertex(x*cs+cs, gridy, y*cs+cs, col);
dd.vertex(x*cs+cs, gridy, y*cs, col);
end;
end;
dd.&end();
end;
// Trail
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
trail := @m_trails[i];
pos := @ag.npos[0];
dd.&begin(DU_DRAW_LINES,3.0);
preva := 1;
dtVcopy(@prev[0], pos);
for j := 0 to AGENT_MAX_TRAIL-1 - 1 do
begin
idx := (trail.htrail + AGENT_MAX_TRAIL-j) mod AGENT_MAX_TRAIL;
v := @trail.trail[idx*3];
a := 1 - j/AGENT_MAX_TRAIL;
dd.vertex(prev[0],prev[1]+0.1,prev[2], duRGBA(0,0,0,Trunc(128*preva)));
dd.vertex(v[0],v[1]+0.1,v[2], duRGBA(0,0,0,Trunc(128*a)));
preva := a;
dtVcopy(@prev[0], v);
end;
dd.&end();
end;
// Corners & co
for i := 0 to crowd.getAgentCount - 1 do
begin
if (m_toolParams.m_showDetailAll = false) and (i <> m_agentDebug.idx) then
continue;
ag := crowd.getAgent(i);
if (not ag.active) then
continue;
radius := ag.params.radius;
pos := @ag.npos[0];
if (m_toolParams.m_showCorners) then
begin
if (ag.ncorners <> 0) then
begin
dd.&begin(DU_DRAW_LINES, 2.0);
for j := 0 to ag.ncorners - 1 do
begin
if j = 0 then va := pos else va := @ag.cornerVerts[(j-1)*3];
vb := @ag.cornerVerts[j*3];
dd.vertex(va[0],va[1]+radius,va[2], duRGBA(128,0,0,192));
dd.vertex(vb[0],vb[1]+radius,vb[2], duRGBA(128,0,0,192));
end;
if (ag.ncorners <> 0) and ((ag.cornerFlags[ag.ncorners-1] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0) then
begin
v := @ag.cornerVerts[(ag.ncorners-1)*3];
dd.vertex(v[0],v[1],v[2], duRGBA(192,0,0,192));
dd.vertex(v[0],v[1]+radius*2,v[2], duRGBA(192,0,0,192));
end;
dd.&end();
if (m_toolParams.m_anticipateTurns) then
begin
(* float dvel[3], pos[3];
calcSmoothSteerDirection(ag.pos, ag.cornerVerts, ag.ncorners, dvel);
pos[0] := ag.pos[0] + dvel[0];
pos[1] := ag.pos[1] + dvel[1];
pos[2] := ag.pos[2] + dvel[2];
const float off := ag.radius+0.1f;
const float* tgt := &ag.cornerVerts[0];
const float y := ag.pos[1]+off;
dd.begin(DU_DRAW_LINES, 2.0f);
dd.vertex(ag.pos[0],y,ag.pos[2], duRGBA(255,0,0,192));
dd.vertex(pos[0],y,pos[2], duRGBA(255,0,0,192));
dd.vertex(pos[0],y,pos[2], duRGBA(255,0,0,192));
dd.vertex(tgt[0],y,tgt[2], duRGBA(255,0,0,192));
dd.end();*)
end;
end;
end;
if (m_toolParams.m_showCollisionSegments) then
begin
center := ag.boundary.getCenter();
duDebugDrawCross(dd, center[0],center[1]+radius,center[2], 0.2, duRGBA(192,0,128,255), 2.0);
duDebugDrawCircle(dd, center[0],center[1]+radius,center[2], ag.params.collisionQueryRange,
duRGBA(192,0,128,128), 2.0);
dd.&begin(DU_DRAW_LINES, 3.0);
for j := 0 to ag.boundary.getSegmentCount - 1 do
begin
s := ag.boundary.getSegment(j);
col := duRGBA(192,0,128,192);
if (dtTriArea2D(pos, s, s+3) < 0.0) then
col := duDarkenCol(col);
duAppendArrow(dd, s[0],s[1]+0.2,s[2], s[3],s[4]+0.2,s[5], 0.0, 0.3, col);
end;
dd.&end();
end;
if (m_toolParams.m_showNeis) then
begin
duDebugDrawCircle(dd, pos[0],pos[1]+radius,pos[2], ag.params.collisionQueryRange,
duRGBA(0,192,128,128), 2.0);
dd.&begin(DU_DRAW_LINES, 2.0);
for j := 0 to ag.nneis - 1 do
begin
// Get 'n'th active agent.
// TODO: fix this properly.
nei := crowd.getAgent(ag.neis[j].idx);
if (nei <> nil) then
begin
dd.vertex(pos[0],pos[1]+radius,pos[2], duRGBA(0,192,128,128));
dd.vertex(nei.npos[0],nei.npos[1]+radius,nei.npos[2], duRGBA(0,192,128,128));
end;
end;
dd.&end();
end;
if (m_toolParams.m_showOpt) then
begin
dd.&begin(DU_DRAW_LINES, 2.0);
dd.vertex(m_agentDebug.optStart[0],m_agentDebug.optStart[1]+0.3,m_agentDebug.optStart[2], duRGBA(0,128,0,192));
dd.vertex(m_agentDebug.optEnd[0],m_agentDebug.optEnd[1]+0.3,m_agentDebug.optEnd[2], duRGBA(0,128,0,192));
dd.&end();
end;
end;
// Agent cylinders.
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
radius := ag.params.radius;
pos := @ag.npos[0];
col := duRGBA(0,0,0,32);
if (m_agentDebug.idx = i) then
col := duRGBA(255,0,0,128);
duDebugDrawCircle(dd, pos[0], pos[1], pos[2], radius, col, 2.0);
end;
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
height := ag.params.height;
radius := ag.params.radius;
pos := @ag.npos[0];
col := duRGBA(220,220,220,128);
if (ag.targetState = DT_CROWDAGENT_TARGET_REQUESTING) or (ag.targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE) then
col := duLerpCol(col, duRGBA(128,0,255,128), 32)
else if (ag.targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_PATH) then
col := duLerpCol(col, duRGBA(128,0,255,128), 128)
else if (ag.targetState = DT_CROWDAGENT_TARGET_FAILED) then
col := duRGBA(255,32,16,128)
else if (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
col := duLerpCol(col, duRGBA(64,255,0,128), 128);
duDebugDrawCylinder(dd, pos[0]-radius, pos[1]+radius*0.1, pos[2]-radius,
pos[0]+radius, pos[1]+height, pos[2]+radius, col);
end;
if (m_toolParams.m_showVO) then
begin
for i := 0 to crowd.getAgentCount - 1 do
begin
if (m_toolParams.m_showDetailAll = false) and (i <> m_agentDebug.idx) then
continue;
ag := crowd.getAgent(i);
if (not ag.active) then
continue;
// Draw detail about agent sela
vod := m_agentDebug.vod;
dx := ag.npos[0];
dy := ag.npos[1]+ag.params.height;
dz := ag.npos[2];
duDebugDrawCircle(dd, dx,dy,dz, ag.params.maxSpeed, duRGBA(255,255,255,64), 2.0);
dd.&begin(DU_DRAW_QUADS);
for j := 0 to vod.getSampleCount - 1 do
begin
p := vod.getSampleVelocity(j);
sr := vod.getSampleSize(j);
pen := vod.getSamplePenalty(j);
pen2 := vod.getSamplePreferredSidePenalty(j);
col := duLerpCol(duRGBA(255,255,255,220), duRGBA(128,96,0,220), Round(pen*255));
col := duLerpCol(col, duRGBA(128,0,0,220), Round(pen2*128));
dd.vertex(dx+p[0]-sr, dy, dz+p[2]-sr, col);
dd.vertex(dx+p[0]-sr, dy, dz+p[2]+sr, col);
dd.vertex(dx+p[0]+sr, dy, dz+p[2]+sr, col);
dd.vertex(dx+p[0]+sr, dy, dz+p[2]-sr, col);
end;
dd.&end();
end;
end;
// Velocity stuff.
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
radius := ag.params.radius;
height := ag.params.height;
pos := @ag.npos[0];
vel := @ag.vel[0];
dvel := @ag.dvel[0];
col := duRGBA(220,220,220,192);
if (ag.targetState = DT_CROWDAGENT_TARGET_REQUESTING) or (ag.targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE) then
col := duLerpCol(col, duRGBA(128,0,255,192), 32)
else if (ag.targetState = DT_CROWDAGENT_TARGET_WAITING_FOR_PATH) then
col := duLerpCol(col, duRGBA(128,0,255,192), 128)
else if (ag.targetState = DT_CROWDAGENT_TARGET_FAILED) then
col := duRGBA(255,32,16,192)
else if (ag.targetState = DT_CROWDAGENT_TARGET_VELOCITY) then
col := duLerpCol(col, duRGBA(64,255,0,192), 128);
duDebugDrawCircle(dd, pos[0], pos[1]+height, pos[2], radius, col, 2.0);
duDebugDrawArrow(dd, pos[0],pos[1]+height,pos[2],
pos[0]+dvel[0],pos[1]+height+dvel[1],pos[2]+dvel[2],
0.0, 0.4, duRGBA(0,192,255,192), IfThen(m_agentDebug.idx = i, 2.0, 1.0));
duDebugDrawArrow(dd, pos[0],pos[1]+height,pos[2],
pos[0]+vel[0],pos[1]+height+vel[1],pos[2]+vel[2],
0.0, 0.4, duRGBA(0,0,0,160), 2.0);
end;
dd.depthMask(true);
dd.Free;
end;
procedure TCrowdToolState.handleRenderOverlay(proj, model: PDouble; view: PInteger);
//var crowd: TdtCrowd;
begin
{GLdouble x, y, z;
// Draw start and end point labels
if (m_targetRef && gluProject((GLdouble)m_targetPos[0], (GLdouble)m_targetPos[1], (GLdouble)m_targetPos[2],
model, proj, view, &x, &y, &z))
begin
imguiDrawText((int)x, (int)(y+25), IMGUI_ALIGN_CENTER, "TARGET", imguiRGBA(0,0,0,220));
end;
char label[32];
if (m_toolParams.m_showNodes)
begin
crowd := m_sample.getCrowd;
if (crowd && crowd.getPathQueue())
begin
const dtNavMeshQuery* navquery := crowd.getPathQueue().getNavQuery();
const dtNodePool* pool := navquery.getNodePool();
if (pool)
begin
const float off := 0.5f;
for (int i := 0; i < pool.getHashSize(); ++i)
begin
for (dtNodeIndex j := pool.getFirst(i); j != DT_NULL_IDX; j := pool.getNext(j))
begin
const dtNode* node := pool.getNodeAtIdx(j+1);
if (!node) continue;
if (gluProject((GLdouble)node.pos[0],(GLdouble)node.pos[1]+off,(GLdouble)node.pos[2],
model, proj, view, &x, &y, &z))
begin
const float heuristic := node.total;// - node.cost;
snprintf(label, 32, "%.2f", heuristic);
imguiDrawText((int)x, (int)y+15, IMGUI_ALIGN_CENTER, label, imguiRGBA(0,0,0,220));
end;
end;
end;
end;
end;
end;
if (m_toolParams.m_showLabels)
begin
crowd := m_sample.getCrowd;
if (crowd)
begin
for i := 0 to crowd.getAgentCount - 1 do
begin
const dtCrowdAgent* ag := crowd.getAgent(i);
if (not ag.active) then continue;
const float* pos := ag.npos;
const float h := ag.params.height;
if (gluProject((GLdouble)pos[0], (GLdouble)pos[1]+h, (GLdouble)pos[2],
model, proj, view, &x, &y, &z))
begin
snprintf(label, 32, "%d", i);
imguiDrawText((int)x, (int)y+15, IMGUI_ALIGN_CENTER, label, imguiRGBA(0,0,0,220));
end;
end;
end;
end;
if (m_agentDebug.idx <> -1)
begin
crowd := m_sample.getCrowd;
if (crowd)
begin
for i := 0 to crowd.getAgentCount - 1 do
begin
if (m_toolParams.m_showDetailAll = false) and (i <> m_agentDebug.idx) then
continue;
ag := crowd.getAgent(i);
if (not ag.active) then
continue;
radius := ag.params.radius;
if (m_toolParams.m_showNeis) then
begin
for j := 0 to ag.nneis - 1 do
begin
nei := crowd.getAgent(ag.neis[j].idx);
if (not nei.active) then continue;
if (gluProject((GLdouble)nei.npos[0], (GLdouble)nei.npos[1]+radius, (GLdouble)nei.npos[2],
model, proj, view, &x, &y, &z))
begin
snprintf(label, 32, '%.3f', ag.neis[j].dist);
imguiDrawText((int)x, (int)y+15, IMGUI_ALIGN_CENTER, label, imguiRGBA(255,255,255,220));
end;
end;
end;
end;
end;
end;
if (m_toolParams.m_showPerfGraph)
begin
GraphParams gp;
gp.setRect(300, 10, 500, 200, 8);
gp.setValueRange(0.0f, 2.0f, 4, "ms");
drawGraphBackground(&gp);
drawGraph(&gp, &m_crowdTotalTime, 1, "Total", duRGBA(255,128,0,255));
gp.setRect(300, 10, 500, 50, 8);
gp.setValueRange(0.0f, 2000.0f, 1, "");
drawGraph(&gp, &m_crowdSampleCount, 0, "Sample Count", duRGBA(96,96,96,128));
end;
}
end;
procedure TCrowdToolState.handleUpdate(dt: Single);
begin
if (m_run) then
updateTick(dt);
end;
procedure TCrowdToolState.addAgent(const pos: PSingle);
var crowd: TdtCrowd; ap: TdtCrowdAgentParams; idx, i: Integer; trail: PAgentTrail;
begin
if (m_sample = nil) then Exit;
crowd := m_sample.getCrowd;
FillChar(ap, sizeof(TdtCrowdAgentParams), 0);
ap.radius := m_sample.getAgentRadius;
ap.height := m_sample.getAgentHeight;
ap.maxAcceleration := 8.0;
ap.maxSpeed := 3.5;
ap.collisionQueryRange := ap.radius * 12.0;
ap.pathOptimizationRange := ap.radius * 30.0;
ap.updateFlags := 0;
if (m_toolParams.m_anticipateTurns) then
ap.updateFlags := ap.updateFlags or DT_CROWD_ANTICIPATE_TURNS;
if (m_toolParams.m_optimizeVis) then
ap.updateFlags := ap.updateFlags or DT_CROWD_OPTIMIZE_VIS;
if (m_toolParams.m_optimizeTopo) then
ap.updateFlags := ap.updateFlags or DT_CROWD_OPTIMIZE_TOPO;
if (m_toolParams.m_obstacleAvoidance) then
ap.updateFlags := ap.updateFlags or DT_CROWD_OBSTACLE_AVOIDANCE;
if (m_toolParams.m_separation) then
ap.updateFlags := ap.updateFlags or DT_CROWD_SEPARATION;
ap.obstacleAvoidanceType := Trunc(m_toolParams.m_obstacleAvoidanceType);
ap.separationWeight := m_toolParams.m_separationWeight;
idx := crowd.addAgent(pos, @ap);
if (idx <> -1) then
begin
if (m_targetRef <> 0) then
crowd.requestMoveTarget(idx, m_targetRef, @m_targetPos[0]);
// Init trail
trail := @m_trails[idx];
for i := 0 to AGENT_MAX_TRAIL - 1 do
dtVcopy(@trail.trail[i*3], pos);
trail.htrail := 0;
end;
end;
procedure TCrowdToolState.removeAgent(const idx: Integer);
var crowd: TdtCrowd;
begin
if (m_sample = nil) then Exit;
crowd := m_sample.getCrowd;
crowd.removeAgent(idx);
if (idx = m_agentDebug.idx) then
m_agentDebug.idx := -1;
end;
procedure TCrowdToolState.hilightAgent(const idx: Integer);
begin
m_agentDebug.idx := idx;
end;
procedure calcVel(vel, pos, tgt: PSingle; const speed: Single);
begin
dtVsub(vel, tgt, pos);
vel[1] := 0.0;
dtVnormalize(vel);
dtVscale(vel, vel, speed);
end;
procedure TCrowdToolState.setMoveTarget(const p: PSingle; adjust: Boolean);
var crowd: TdtCrowd; navquery: TdtNavMeshQuery; filter: TdtQueryFilter; ext: PSingle; vel: array [0..2] of Single;
ag: PdtCrowdAgent; i: Integer;
begin
if (m_sample = nil) then Exit;
// Find nearest point on navmesh and set move request to that location.
navquery := m_sample.getNavMeshQuery;
crowd := m_sample.getCrowd;
filter := crowd.getFilter(0);
ext := crowd.getQueryExtents();
if (adjust) then
begin
// Request velocity
if (m_agentDebug.idx <> -1) then
begin
ag := crowd.getAgent(m_agentDebug.idx);
if (ag <> nil) and ag.active then
begin
calcVel(@vel[0], @ag.npos[0], p, ag.params.maxSpeed);
crowd.requestMoveVelocity(m_agentDebug.idx, @vel[0]);
end;
end
else
begin
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
calcVel(@vel[0], @ag.npos[0], p, ag.params.maxSpeed);
crowd.requestMoveVelocity(i, @vel[0]);
end;
end;
end
else
begin
navquery.findNearestPoly(p, ext, filter, @m_targetRef, @m_targetPos[0]);
if (m_agentDebug.idx <> -1) then
begin
ag := crowd.getAgent(m_agentDebug.idx);
if (ag <> nil) and ag.active then
crowd.requestMoveTarget(m_agentDebug.idx, m_targetRef, @m_targetPos[0]);
end
else
begin
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
crowd.requestMoveTarget(i, m_targetRef, @m_targetPos[0]);
end;
end;
end;
end;
function TCrowdToolState.hitTestAgents(const s, p: PSingle): Integer;
var crowd: TdtCrowd; isel, i: Integer; tsel, tmin, tmax: Single; ag: PdtCrowdAgent; bmin, bmax: array [0..2] of Single;
begin
if (m_sample = nil) then Exit(-1);
crowd := m_sample.getCrowd;
isel := -1;
tsel := MaxSingle;
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
getAgentBounds(ag, @bmin[0], @bmax[0]);
if (isectSegAABB(s, p, @bmin[0],@bmax[0], @tmin, @tmax)) then
begin
if (tmin > 0) and (tmin < tsel) then
begin
isel := i;
tsel := tmin;
end;
end;
end;
Result := isel;
end;
procedure TCrowdToolState.updateAgentParams();
var crowd: TdtCrowd; updateFlags, obstacleAvoidanceType: Byte; params: TdtCrowdAgentParams; i: Integer; ag: PdtCrowdAgent;
begin
if (m_sample = nil) then Exit;
crowd := m_sample.getCrowd;
if (crowd = nil) then Exit;
updateFlags := 0;
obstacleAvoidanceType := 0;
if (m_toolParams.m_anticipateTurns) then
updateFlags := updateFlags or DT_CROWD_ANTICIPATE_TURNS;
if (m_toolParams.m_optimizeVis) then
updateFlags := updateFlags or DT_CROWD_OPTIMIZE_VIS;
if (m_toolParams.m_optimizeTopo) then
updateFlags := updateFlags or DT_CROWD_OPTIMIZE_TOPO;
if (m_toolParams.m_obstacleAvoidance) then
updateFlags := updateFlags or DT_CROWD_OBSTACLE_AVOIDANCE;
if (m_toolParams.m_separation) then
updateFlags := updateFlags or DT_CROWD_SEPARATION;
obstacleAvoidanceType := Trunc(m_toolParams.m_obstacleAvoidanceType);
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
if (not ag.active) then continue;
Move(ag.params, params, sizeof(TdtCrowdAgentParams));
params.updateFlags := updateFlags;
params.obstacleAvoidanceType := obstacleAvoidanceType;
params.separationWeight := m_toolParams.m_separationWeight;
crowd.updateAgentParameters(i, @params);
end;
end;
procedure TCrowdToolState.updateTick(const dt: Single);
var crowd: TdtCrowd; nav: TdtNavMesh; startTime, endTime: Int64; i: Integer; ag: PdtCrowdAgent; trail: PAgentTrail;
begin
if (m_sample = nil) then Exit;
nav := m_sample.getNavMesh;
crowd := m_sample.getCrowd;
if (nav = nil) or (crowd = nil) then Exit;
startTime := getPerfTime();
crowd.update(dt, @m_agentDebug);
endTime := getPerfTime();
// Update agent trails
for i := 0 to crowd.getAgentCount - 1 do
begin
ag := crowd.getAgent(i);
trail := @m_trails[i];
if (not ag.active) then
continue;
// Update agent movement trail.
trail.htrail := (trail.htrail + 1) mod AGENT_MAX_TRAIL;
dtVcopy(@trail.trail[trail.htrail*3], @ag.npos[0]);
end;
m_agentDebug.vod.normalizeSamples();
m_crowdSampleCount.addSample(crowd.getVelocitySampleCount);
m_crowdTotalTime.addSample(getPerfDeltaTimeUsec(startTime, endTime) / 1000.0);
end;
procedure TCrowdToolState.setRunning(const s: Boolean); begin m_run := s; end;
function TCrowdToolState.getToolParams: PCrowdToolParams; begin Result := @m_toolParams; end;
constructor TCrowdTool.Create(aOwner: TWinControl);
begin
inherited Create;
m_sample := nil;
m_state := nil;
m_mode := TOOLMODE_CREATE;
&type := TOOL_CROWD;
fFrame := TFrameCrowdTool.Create(aOwner);
fFrame.Align := alClient;
fFrame.Parent := aOwner;
fFrame.Visible := True;
fFrame.rgCrowdToolMode.OnClick := handleMenu;
fFrame.cbOptimizeVisibility.OnClick := handleMenu;
fFrame.cbOptimizeTopology.OnClick := handleMenu;
fFrame.cbAnticipateTurns.OnClick := handleMenu;
fFrame.cbObstacleAvoidance.OnClick := handleMenu;
fFrame.cbSeparation.OnClick := handleMenu;
end;
destructor TCrowdTool.Destroy;
begin
fFrame.Free;
m_state.Free;
inherited;
end;
procedure TCrowdTool.init(sample: TSample);
begin
if (m_sample <> sample) then
begin
m_sample := sample;
end;
if (sample = nil) then
Exit;
m_state := TCrowdToolState(sample.getToolState(&type));
if (m_state = nil) then
begin
m_state := TCrowdToolState.Create;
sample.setToolState(&type, m_state);
end;
m_state.init(sample);
end;
procedure TCrowdTool.reset();
begin
end;
procedure TCrowdTool.handleMenu(Sender: TObject);
var params: PCrowdToolParams;
begin
if fUpdateUI then Exit;
if (m_state = nil) then
Exit;
params := m_state.getToolParams;
// Delphi: When the Sender is NIL, we fill the controls with current state values
if Sender = nil then
begin
fUpdateUI := True;
fFrame.rgCrowdToolMode.ItemIndex := Byte(m_mode);
fFrame.cbOptimizeVisibility.Checked := params.m_optimizeVis;
fFrame.cbOptimizeTopology.Checked := params.m_optimizeTopo;
fFrame.cbAnticipateTurns.Checked := params.m_anticipateTurns;
fFrame.cbObstacleAvoidance.Checked := params.m_obstacleAvoidance;
fFrame.cbSeparation.Checked := params.m_separation;
fUpdateUI := False;
end;
if Sender = fFrame.rgCrowdToolMode then
begin
m_mode := TToolMode(fFrame.rgCrowdToolMode.ItemIndex);
params.m_optimizeVis := fFrame.cbOptimizeVisibility.Checked;
params.m_optimizeTopo := fFrame.cbOptimizeTopology.Checked;
params.m_anticipateTurns := fFrame.cbAnticipateTurns.Checked;
params.m_obstacleAvoidance := fFrame.cbObstacleAvoidance.Checked;
params.m_separation := fFrame.cbSeparation.Checked;
m_state.updateAgentParams();
end;
{
if (params.m_expandOptions)
begin
imguiIndent();
if (imguiCheck("Optimize Visibility", params.m_optimizeVis))
begin
params.m_optimizeVis := !params.m_optimizeVis;
m_state.updateAgentParams();
end;
if (imguiCheck("Optimize Topology", params.m_optimizeTopo))
begin
params.m_optimizeTopo := !params.m_optimizeTopo;
m_state.updateAgentParams();
end;
if (imguiCheck("Anticipate Turns", params.m_anticipateTurns))
begin
params.m_anticipateTurns := !params.m_anticipateTurns;
m_state.updateAgentParams();
end;
if (imguiCheck("Obstacle Avoidance", params.m_obstacleAvoidance))
begin
params.m_obstacleAvoidance := !params.m_obstacleAvoidance;
m_state.updateAgentParams();
end;
if (imguiSlider("Avoidance Quality", ¶ms.m_obstacleAvoidanceType, 0.0f, 3.0f, 1.0f))
begin
m_state.updateAgentParams();
end;
if (imguiCheck("Separation", params.m_separation))
begin
params.m_separation := !params.m_separation;
m_state.updateAgentParams();
end;
if (imguiSlider("Separation Weight", ¶ms.m_separationWeight, 0.0f, 20.0f, 0.01f))
begin
m_state.updateAgentParams();
end;
imguiUnindent();
end;
if (imguiCollapse("Selected Debug Draw", 0, params.m_expandSelectedDebugDraw))
params.m_expandSelectedDebugDraw := !params.m_expandSelectedDebugDraw;
if (params.m_expandSelectedDebugDraw)
begin
imguiIndent();
if (imguiCheck("Show Corners", params.m_showCorners))
params.m_showCorners := !params.m_showCorners;
if (imguiCheck("Show Collision Segs", params.m_showCollisionSegments))
params.m_showCollisionSegments := !params.m_showCollisionSegments;
if (imguiCheck("Show Path", params.m_showPath))
params.m_showPath := !params.m_showPath;
if (imguiCheck("Show VO", params.m_showVO))
params.m_showVO := !params.m_showVO;
if (imguiCheck("Show Path Optimization", params.m_showOpt))
params.m_showOpt := !params.m_showOpt;
if (imguiCheck("Show Neighbours", params.m_showNeis))
params.m_showNeis := !params.m_showNeis;
imguiUnindent();
end;
if (imguiCollapse("Debug Draw", 0, params.m_expandDebugDraw))
params.m_expandDebugDraw := !params.m_expandDebugDraw;
if (params.m_expandDebugDraw)
begin
imguiIndent();
if (imguiCheck("Show Labels", params.m_showLabels))
params.m_showLabels := !params.m_showLabels;
if (imguiCheck("Show Prox Grid", params.m_showGrid))
params.m_showGrid := !params.m_showGrid;
if (imguiCheck("Show Nodes", params.m_showNodes))
params.m_showNodes := !params.m_showNodes;
if (imguiCheck("Show Perf Graph", params.m_showPerfGraph))
params.m_showPerfGraph := !params.m_showPerfGraph;
if (imguiCheck("Show Detail All", params.m_showDetailAll))
params.m_showDetailAll := !params.m_showDetailAll;
imguiUnindent();
end;}
end;
procedure TCrowdTool.handleClick(s,p: PSingle; shift: Boolean);
var crowd: TdtCrowd; geom: TInputGeom; ahit: Integer; nav: TdtNavMesh; navquery: TdtNavMeshQuery; filter: TdtQueryFilter;
ext: PSingle; tgt: array [0..2] of Single; ref: TdtPolyRef; flags: Word;
begin
if (m_sample = nil) then Exit;
if (m_state = nil) then Exit;
geom := m_sample.getInputGeom;
if (geom = nil) then Exit;
crowd := m_sample.getCrowd;
if (crowd = nil) then Exit;
if (m_mode = TOOLMODE_CREATE) then
begin
if (shift) then
begin
// Delete
ahit := m_state.hitTestAgents(s,p);
if (ahit <> -1) then
m_state.removeAgent(ahit);
end
else
begin
// Add
m_state.addAgent(p);
end;
end
else if (m_mode = TOOLMODE_MOVE_TARGET) then
begin
m_state.setMoveTarget(p, shift);
end
else if (m_mode = TOOLMODE_SELECT) then
begin
// Highlight
ahit := m_state.hitTestAgents(s,p);
m_state.hilightAgent(ahit);
end
else if (m_mode = TOOLMODE_TOGGLE_POLYS) then
begin
nav := m_sample.getNavMesh;
navquery := m_sample.getNavMeshQuery;
if (nav <> nil) and (navquery <> nil) then
begin
filter := TdtQueryFilter.Create; // Delphi: Assume c++ creates a dummy here
ext := crowd.getQueryExtents();
navquery.findNearestPoly(p, ext, filter, @ref, @tgt[0]);
if (ref <> 0) then
begin
flags := 0;
if (dtStatusSucceed(nav.getPolyFlags(ref, @flags))) then
begin
flags := flags xor SAMPLE_POLYFLAGS_DISABLED;
nav.setPolyFlags(ref, flags);
end;
end;
filter.Free;
end;
end;
end;
procedure TCrowdTool.handleStep();
var dt: Single;
begin
if (m_state = nil) then Exit;
dt := 1.0/20.0;
m_state.updateTick(dt);
m_state.setRunning(false);
end;
procedure TCrowdTool.handleToggle();
begin
if (m_state = nil) then Exit;
m_state.setRunning(not m_state.isRunning);
end;
procedure TCrowdTool.handleUpdate(dt: Single);
begin
//rcIgnoreUnused(dt);
end;
procedure TCrowdTool.handleRender();
begin
end;
procedure TCrowdTool.handleRenderOverlay(proj, model: PDouble; view: PInteger);
begin
{ rcIgnoreUnused(model);
rcIgnoreUnused(proj);
// Tool help
const int h := view[3];
int ty := h-40;
if (m_mode == TOOLMODE_CREATE)
begin
imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "LMB: add agent. Shift+LMB: remove agent.", imguiRGBA(255,255,255,192));
end;
else if (m_mode == TOOLMODE_MOVE_TARGET)
begin
imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "LMB: set move target. Shift+LMB: adjust set velocity.", imguiRGBA(255,255,255,192));
ty -= 20;
imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "Setting velocity will move the agents without pathfinder.", imguiRGBA(255,255,255,192));
end;
else if (m_mode == TOOLMODE_SELECT)
begin
imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "LMB: select agent.", imguiRGBA(255,255,255,192));
end;
ty -= 20;
imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "SPACE: Run/Pause simulation. 1: Step simulation.", imguiRGBA(255,255,255,192));
ty -= 20;
if (m_state && m_state.isRunning())
imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "- RUNNING -", imguiRGBA(255,32,16,255));
else
imguiDrawText(280, ty, IMGUI_ALIGN_LEFT, "- PAUSED -", imguiRGBA(255,255,255,128)); }
end;
end. |
unit UContasReceber;
interface
uses SysUtils, Classes, UCliente, UFormaPagamento, UUsuario, UParcelas,
UCondicaoPagamento;
type ContasReceber = class
protected
numNota : Integer;
serieNota : string[2];
numParcela : Integer;
umCliente : Cliente;
umUsuario : Usuario;
umaFormaPagamento : FormaPagamento;
umaCondicaoPgto : CondicaoPagamento;
dataEmissao : TDateTime;
dataVencimento : TDateTime;
dataPagamento : TDateTime;
valor : Real;
multa : Real;
juros : Real;
desconto : Real;
TotalAux : Real;
status : string[15];
observacao : string[255];
umaParcela : Parcelas;
ListaParcelas : TList;
public
Constructor CrieObjeto;
Destructor Destrua_Se;
Procedure setNumNota (vNumNota : Integer);
Procedure setSerieNota (vSerieNota : string);
Procedure setNumParcela (vNumParcela : Integer);
Procedure setUmCliente (vCliente : Cliente);
Procedure setUmUsuario (vUsuario : Usuario);
Procedure setUmaFormaPagamento (vFormaPagamento : FormaPagamento);
Procedure setUmaCondicaoPagamento (vCondicaoPagamento : CondicaoPagamento);
Procedure setUmaParcelas (vParcelas : Parcelas);
Procedure setDataEmissao (vDataEmissao : TDateTime);
Procedure setDataVencimento (vDataVencimento : TDateTime);
Procedure setDataPagamento (vDataPagamento : TDateTime);
Procedure setValor (vValor : Real);
Procedure setMulta (vMulta : Real);
Procedure setJuros (vJuros : Real);
Procedure setDesconto (vDesconto : Real);
Procedure setTotalAux (vTotalAux : Real);
Procedure setStatus (vStatus : string);
Procedure setObservacao (vObservacao : string);
Function getNumNota : Integer;
Function getSerieNota : string;
Function getNumParcela : Integer;
Function getUmCliente : Cliente;
Function getUmUsuario : Usuario;
Function getUmaFormaPagamento : FormaPagamento;
Function getUmaCondicaoPagamento : CondicaoPagamento;
Function getUmaParcelas : Parcelas;
Function getDataEmissao : TDateTime;
Function getDataVencimento : TDateTime;
Function getDataPagamento : TDateTime;
Function getValor : Real;
Function getMulta : Real;
Function getJuros : Real;
Function getDesconto : Real;
Function getTotalAux : Real;
Function getStatus : string;
Function getObservacao : string;
//Parcelas
procedure CrieObjetoParcela;
procedure addParcelas(vParcelas : Parcelas);
procedure LimparListaParcelas;
function getParcelas(parcela:Integer):Parcelas;
function CountParcelas : Integer;
end;
implementation
{ ContasReceber }
constructor ContasReceber.CrieObjeto;
var dataAtual : TDateTime;
begin
dataAtual := Date;
numNota := 0;
serieNota := '';
numParcela := 0;
umCliente := Cliente.CrieObjeto;
umUsuario := Usuario.CrieObjeto;
umaFormaPagamento := FormaPagamento.CrieObjeto;
umaCondicaoPgto := CondicaoPagamento.CrieObjeto;
dataEmissao := dataAtual;
dataVencimento := dataAtual;
dataPagamento := dataAtual;
valor := 0.0;
multa := 0.0;
juros := 0.0;
desconto := 0.0;
TotalAux := 0.0;
status := '';
observacao := '';
ListaParcelas := TList.Create;
end;
destructor ContasReceber.Destrua_Se;
begin
ListaParcelas.Destroy;
end;
function ContasReceber.getDataEmissao: TDateTime;
begin
Result := dataEmissao;
end;
function ContasReceber.getDataPagamento: TDateTime;
begin
Result := dataPagamento;
end;
function ContasReceber.getDataVencimento: TDateTime;
begin
Result := dataVencimento;
end;
function ContasReceber.getDesconto: Real;
begin
Result := desconto;
end;
function ContasReceber.getJuros: Real;
begin
Result := juros;
end;
function ContasReceber.getMulta: Real;
begin
Result := multa;
end;
function ContasReceber.getNumNota: Integer;
begin
Result := numNota;
end;
function ContasReceber.getNumParcela: Integer;
begin
Result := numParcela;
end;
function ContasReceber.getObservacao: string;
begin
Result := observacao;
end;
function ContasReceber.getSerieNota: string;
begin
Result := serieNota;
end;
function ContasReceber.getStatus: string;
begin
Result := status;
end;
function ContasReceber.getTotalAux: Real;
begin
Result := TotalAux;
end;
function ContasReceber.getUmaCondicaoPagamento: CondicaoPagamento;
begin
Result := umaCondicaoPgto;
end;
function ContasReceber.getUmaFormaPagamento: FormaPagamento;
begin
Result := umaFormaPagamento;
end;
function ContasReceber.getUmaParcelas: Parcelas;
begin
Result := umaParcela;
end;
function ContasReceber.getUmCliente: Cliente;
begin
Result := umCliente;
end;
function ContasReceber.getUmUsuario: Usuario;
begin
Result := umUsuario;
end;
function ContasReceber.getValor: Real;
begin
Result := valor;
end;
procedure ContasReceber.setDataEmissao(vDataEmissao: TDateTime);
begin
dataEmissao := vDataEmissao;
end;
procedure ContasReceber.setDataPagamento(vDataPagamento: TDateTime);
begin
dataPagamento := vDataPagamento;
end;
procedure ContasReceber.setDataVencimento(vDataVencimento: TDateTime);
begin
dataVencimento:= vDataVencimento;
end;
procedure ContasReceber.setDesconto(vDesconto: Real);
begin
desconto := vDesconto;
end;
procedure ContasReceber.setJuros(vJuros: Real);
begin
juros := vJuros;
end;
procedure ContasReceber.setMulta(vMulta: Real);
begin
multa := vMulta;
end;
procedure ContasReceber.setNumNota(vNumNota: Integer);
begin
numNota := vNumNota;
end;
procedure ContasReceber.setNumParcela(vNumParcela: Integer);
begin
numParcela := vNumParcela;
end;
procedure ContasReceber.setObservacao(vObservacao: string);
begin
observacao := vObservacao;
end;
procedure ContasReceber.setSerieNota(vSerieNota: string);
begin
serieNota := vSerieNota;
end;
procedure ContasReceber.setStatus(vStatus: string);
begin
status := vStatus;
end;
procedure ContasReceber.setTotalAux(vTotalAux: Real);
begin
TotalAux := vTotalAux;
end;
procedure ContasReceber.setUmaCondicaoPagamento(vCondicaoPagamento: CondicaoPagamento);
begin
umaCondicaoPgto := vCondicaoPagamento;
end;
procedure ContasReceber.setUmaFormaPagamento(vFormaPagamento: FormaPagamento);
begin
umaFormaPagamento := vFormaPagamento;
end;
procedure ContasReceber.setUmaParcelas(vParcelas: Parcelas);
begin
umaParcela := vParcelas;
end;
procedure ContasReceber.setUmCliente(vCliente: Cliente);
begin
umCliente := vCliente;
end;
procedure ContasReceber.setUmUsuario(vUsuario: Usuario);
begin
umUsuario := vUsuario;
end;
procedure ContasReceber.setValor(vValor: Real);
begin
valor := vValor;
end;
//Parcelas
procedure ContasReceber.CrieObjetoParcela;
begin
umaParcela := Parcelas.CrieObjeto;
end;
procedure ContasReceber.addParcelas(vParcelas: Parcelas);
begin
ListaParcelas.Add(vParcelas);
end;
function ContasReceber.getParcelas(parcela: Integer): Parcelas;
begin
Result := ListaParcelas[parcela];
end;
function ContasReceber.CountParcelas: Integer;
begin
Result := ListaParcelas.Count;
end;
procedure ContasReceber.LimparListaParcelas;
var i : Integer;
begin
for i := 0 to ListaParcelas.Count -1 do
Parcelas(ListaParcelas[i]).Free;
ListaParcelas.Clear;
end;
end.
|
unit FMX.RESTLight.Types;
{
author: ZuBy
http://rzaripov.kz
2016
}
interface
type
// authorization response
TmyAuthToken = record
token: string;
user_id: string;
expires_in: Single;
end;
// app settings ( vk / facebook / instagram )
TmyAppSettings = record
ID: string;
Key: string;
OAuthURL: string;
RedirectURL: string;
BaseURL: string;
Scope: string;
APIVersion: string;
end;
// rest params
TmyRestParam = record
Key: string;
value: string;
is_file: boolean;
constructor Create(aKey, aValue: string; aIsFile: boolean);
end;
implementation
{ TmyRestParam }
constructor TmyRestParam.Create(aKey, aValue: string; aIsFile: boolean);
begin
Self.Key := aKey;
Self.value := aValue;
Self.is_file := aIsFile;
end;
end.
|
unit Ths.Erp.Database.Table.SysGridColColor;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TSysGridColColor = class(TTable)
private
FTableName: TFieldDB;
FColumnName: TFieldDB;
FMinValue: TFieldDB;
FMinColor: TFieldDB;
FMaxValue: TFieldDB;
FMaxColor: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property TableName1: TFieldDB read FTableName write FTableName;
Property ColumnName: TFieldDB read FColumnName write FColumnName;
property MinValue: TFieldDB read FMinValue write FMinValue;
property MinColor: TFieldDB read FMinColor write FMinColor;
property MaxValue: TFieldDB read FMaxValue write FMaxValue;
property MaxColor: TFieldDB read FMaxColor write FMaxColor;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TSysGridColColor.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'sys_grid_col_color';
SourceCode := '1';
FTableName := TFieldDB.Create('table_name', ftString, '');
FColumnName := TFieldDB.Create('column_name', ftString, '');
FMinValue := TFieldDB.Create('min_value', ftFloat, 0);
FMinColor := TFieldDB.Create('min_color', ftInteger, 0);
FMaxValue := TFieldDB.Create('max_value', ftFloat, 0);
FMaxColor := TFieldDB.Create('max_color', ftInteger, 0);
end;
procedure TSysGridColColor.SelectToDatasource(pFilter: string;
pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FTableName.FieldName,
TableName + '.' + FColumnName.FieldName,
TableName + '.' + FMinValue.FieldName,
TableName + '.' + FMinColor.FieldName,
TableName + '.' + FMaxValue.FieldName,
TableName + '.' + FMaxColor.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FTableName.FieldName).DisplayLabel := 'TABLE NAME';
Self.DataSource.DataSet.FindField(FColumnName.FieldName).DisplayLabel := 'COLUMN NAME';
Self.DataSource.DataSet.FindField(FMinValue.FieldName).DisplayLabel := 'MIN VALUE';
Self.DataSource.DataSet.FindField(FMinColor.FieldName).DisplayLabel := 'MIN COLOR';
Self.DataSource.DataSet.FindField(FMaxValue.FieldName).DisplayLabel := 'MAX VALUE';
Self.DataSource.DataSet.FindField(FMaxColor.FieldName).DisplayLabel := 'MAX COLOR';
end;
end;
end;
procedure TSysGridColColor.SelectToList(pFilter: string; pLock: Boolean;
pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FTableName.FieldName,
TableName + '.' + FColumnName.FieldName,
TableName + '.' + FMinValue.FieldName,
TableName + '.' + FMinColor.FieldName,
TableName + '.' + FMaxValue.FieldName,
TableName + '.' + FMaxColor.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FTableName.Value := FormatedVariantVal(FieldByName(FTableName.FieldName).DataType, FieldByName(FTableName.FieldName).Value);
FColumnName.Value := FormatedVariantVal(FieldByName(FColumnName.FieldName).DataType, FieldByName(FColumnName.FieldName).Value);
FMinValue.Value := FormatedVariantVal(FieldByName(FMinValue.FieldName).DataType, FieldByName(FMinValue.FieldName).Value);
FMinColor.Value := FormatedVariantVal(FieldByName(FMinColor.FieldName).DataType, FieldByName(FMinColor.FieldName).Value);
FMaxValue.Value := FormatedVariantVal(FieldByName(FMaxValue.FieldName).DataType, FieldByName(FMaxValue.FieldName).Value);
FMaxColor.Value := FormatedVariantVal(FieldByName(FMaxColor.FieldName).DataType, FieldByName(FMaxColor.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
EmptyDataSet;
Close;
end;
end;
end;
procedure TSysGridColColor.Insert(out pID: Integer;
pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FTableName.FieldName,
FColumnName.FieldName,
FMinValue.FieldName,
FMinColor.FieldName,
FMaxValue.FieldName,
FMaxColor.FieldName
]);
NewParamForQuery(QueryOfInsert, FTableName);
NewParamForQuery(QueryOfInsert, FColumnName);
NewParamForQuery(QueryOfInsert, FMinValue);
NewParamForQuery(QueryOfInsert, FMinColor);
NewParamForQuery(QueryOfInsert, FMaxValue);
NewParamForQuery(QueryOfInsert, FMaxColor);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TSysGridColColor.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FTableName.FieldName,
FColumnName.FieldName,
FMinValue.FieldName,
FMinColor.FieldName,
FMaxValue.FieldName,
FMaxColor.FieldName
]);
NewParamForQuery(QueryOfUpdate, FTableName);
NewParamForQuery(QueryOfUpdate, FColumnName);
NewParamForQuery(QueryOfUpdate, FMinValue);
NewParamForQuery(QueryOfUpdate, FMinColor);
NewParamForQuery(QueryOfUpdate, FMaxValue);
NewParamForQuery(QueryOfUpdate, FMaxColor);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TSysGridColColor.Clone():TTable;
begin
Result := TSysGridColColor.Create(Database);
Self.Id.Clone(TSysGridColColor(Result).Id);
FTableName.Clone(TSysGridColColor(Result).FTableName);
FColumnName.Clone(TSysGridColColor(Result).FColumnName);
FMinValue.Clone(TSysGridColColor(Result).FMinValue);
FMinColor.Clone(TSysGridColColor(Result).FMinColor);
FMaxValue.Clone(TSysGridColColor(Result).FMaxValue);
FMaxColor.Clone(TSysGridColColor(Result).FMaxColor);
end;
end.
|
unit U_WE_VECTOR_MAP;
{===============================================================================
Copyright(c) 2007-2009, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,向量图绘制单元
+ TWE_VECTOR_MAP 向量图绘制
+ TWE_VECTOR_MAP_COLOR 色彩索引
===============================================================================}
interface
uses SysUtils, Classes, Windows, Graphics, U_WE_EQUATION_DRAW, U_WE_EQUATION,
U_WIRING_ERROR, U_WE_EQUATION_MATH, U_WE_EXPRESSION, IniFiles, U_WE_ORGAN,
Math, Dialogs, Forms, U_WE_PHASE_MAP, System.Types,System.UITypes;
type
/// <summary>
/// 色彩索引
/// </summary>
TWE_VECTOR_MAP_COLOR = class(TPersistent)
private
FIniFile : string;
FPhaseLine: Integer;
FDotLine: Integer;
FBackground: Integer;
FPhaseB: Integer;
FPhaseC: Integer;
FPhaseA: Integer;
FPhaseCB: Integer;
FPhaseAB: Integer;
public
/// <summary>
/// 向量图 底色
/// </summary>
property Background : Integer read FBackground write FBackground;
/// <summary>
/// 向量图 虚轴颜色
/// </summary>
property DotLine : Integer read FDotLine write FDotLine;
/// <summary>
/// 向量图 三线 相线颜色
/// </summary>
property PhaseLine : Integer read FPhaseLine write FPhaseLine;
/// <summary>
/// 向量图 三线 第一元件
/// </summary>
property PhaseAB : Integer read FPhaseAB write FPhaseAB;
/// <summary>
/// 向量图 三线 第二元件
/// </summary>
property PhaseCB : Integer read FPhaseCB write FPhaseCB;
/// <summary>
/// 向量图 四线 第一元件
/// </summary>
property PhaseA : Integer read FPhaseA write FPhaseA;
/// <summary>
/// 向量图 四线 第二元件
/// </summary>
property PhaseB : Integer read FPhaseB write FPhaseB;
/// <summary>
/// 向量图 四线 第三元件
/// </summary>
property PhaseC : Integer read FPhaseC write FPhaseC;
procedure Assign(Source: TPersistent); override;
constructor Create(sIniFile : string);
destructor Destroy; override;
end;
/// <summary>
/// 获取两点之间的长度和角度 (入参为坐标点放大100倍的值)
/// </summary>
procedure GetLenAngle( dP1x, dP1y, dP2x, dP2y : Double;
var dLen:Double; var dAngle:Double );
type
/// <summary>
/// 向量图
/// </summary>
TWE_VECTOR_MAP = class( TComponent )
private
FMapCenter : TPoint;
FCanvas : TCanvas;
FRect : TRect;
FMapColor : TWE_VECTOR_MAP_COLOR;
FUnitStep : Integer;
FPenWidth : Integer;
FEquationDraw : TWE_EQUATION_DRAW;
FUIAngle: Double;
protected
/// <summary>
/// 画背景
/// </summary>
procedure DrawBackground( AHasCrossLine, AHasBorder : Boolean );
/// <summary>
/// 画矢量线
/// </summary>
procedure DrawLine( APen : TPen; APos : TPoint; ALen, AAngle : Double;
AHasArrow : Boolean; ASign : string );
/// <summary>
/// 画角度
/// </summary>
procedure DrawAngle( APen : TPen; APos : TPoint;
ARadius, AStartAngle, AEndAngle : Double; AHasArrow : Boolean; ASign : string );
/// <summary>
/// 画箭头
/// </summary>
procedure DrawArrow( APen : TPen; APos : TPoint; AAngle : Double );
protected
/// <summary>
/// 角度转换, 公式和画图的角度不同,需要转换
/// </summary>
function CovAngle( AValue : Double ) : Double;
/// <summary>
/// 画独立元件
/// </summary>
procedure DrawSingleEquation( AOrgan: TWE_ORGAN;
APen : TPen; APos : TPoint; AAngleRadius : Double );
/// <summary>
/// 画向量图
/// </summary>
procedure DrawPhase3Map( ROrgans: TStringList );
procedure DrawPhase4Map( ROrgans : TStringList );
published
/// <summary>
/// 画布
/// </summary>
property Canvas : TCanvas read FCanvas write FCanvas;
/// <summary>
/// 绘图的区域
/// </summary>
property Rect : TRect read FRect write FRect;
/// <summary>
/// 颜色索引
/// </summary>
property MapColor : TWE_VECTOR_MAP_COLOR read FMapColor write FMapColor;
/// <summary>
/// 单位长度
/// </summary>
property UnitStep : Integer read FUnitStep write FUnitStep;
/// <summary>
/// 画笔宽度
/// </summary>
property PenWidth : Integer read FPenWidth write FPenWidth;
/// <summary>
/// UI夹角(φ角)
/// </summary>
property UIAngle : Double read FUIAngle write FUIAngle;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// 绘制向量图
/// </summary>
procedure DrawPhaseMap( APhaseType: TWE_PHASE_TYPE; ROrgans: TStringList;
dUIAngle : Double; sCaption : string = '');
end;
implementation
{ TWE_VECTOR_MAP }
function TWE_VECTOR_MAP.CovAngle(AValue: Double): Double;
begin
if AValue >= -90 then
Result := (90 - AValue) / 180 * Pi
else
Result := (- AValue - 270) / 180 * Pi;
end;
constructor TWE_VECTOR_MAP.Create(AOwner: TComponent);
begin
inherited;
FEquationDraw := TWE_EQUATION_DRAW.Create( nil ); // 画公式
FMapColor := TWE_VECTOR_MAP_COLOR.Create(ChangeFileExt( Application.ExeName, '.ini' ));
FUIAngle := 20;
end;
destructor TWE_VECTOR_MAP.Destroy;
begin
FMapColor.Free;
FEquationDraw.Free;
inherited;
end;
procedure TWE_VECTOR_MAP.DrawAngle(APen: TPen; APos: TPoint; ARadius,
AStartAngle, AEndAngle: Double; AHasArrow: Boolean; ASign: string);
var
dAngle : Double;
pts: array[0..3] of TPoint;
dR : Double;
begin
if AStartAngle > AEndAngle then
begin
dAngle := AStartAngle;
AStartAngle := AEndAngle;
AEndAngle := dAngle;
end;
if Abs(AStartAngle - AEndAngle) > Pi then
begin
dAngle := AStartAngle;
AStartAngle := AEndAngle;
AEndAngle := dAngle;
end;
dR := ARadius* FUnitStep;
pts[0].X := Round(-dR) + FMapCenter.X;
pts[0].Y := Round(-dR)+ FMapCenter.Y;
pts[1].X := Round(dR)+ FMapCenter.X;
pts[1].Y := Round(dR)+ FMapCenter.Y;
pts[3].X := Round(dR*Cos(AStartAngle)+ FMapCenter.X);
pts[3].Y := Round(dR*Sin(AStartAngle)+ FMapCenter.Y);
pts[2].X := Round(dR*Cos(AEndAngle))+ FMapCenter.X;
pts[2].Y := Round(dR*Sin(AEndAngle))+ FMapCenter.Y;
FCanvas.Arc( pts[0].X,pts[0].Y,
pts[1].X,pts[1].Y,
pts[2].X,pts[2].Y,
pts[3].X,pts[3].Y);
// 画箭头
if AHasArrow and (Abs(AStartAngle - AEndAngle)>pi/6) then
begin
DrawArrow( APen, pts[3], pi/2 - AStartAngle);
DrawArrow( APen, pts[2], 2*pi - (AEndAngle+pi/2));
end;
end;
procedure TWE_VECTOR_MAP.DrawArrow(APen: TPen; APos: TPoint; AAngle: Double);
var
pArw : TPoint;
dPosX, dPosY : Double;
begin
with FCanvas do
begin
Pen := APen;
// 确定箭头大小
if FUnitStep / 30 > 2 then
dPosX := - FUnitStep / 30
else
dPosX := -2;
dPosY := dPosX * 2;
pArw.X := APos.X + Round(dPosY * Cos(AAngle) + dPosX * Sin(AAngle));
pArw.Y := APos.Y - Round(dPosY * Sin(AAngle) - dPosX * Cos(AAngle));
Polyline( [ APos, pArw ] );
dPosX := - dPosX;
pArw.X := APos.X + Round(dPosY * Cos(AAngle) + dPosX * Sin(AAngle));
pArw.Y := APos.Y - Round(dPosY * Sin(AAngle) - dPosX * Cos(AAngle));
Polyline( [ APos, pArw ] );
end;
end;
procedure TWE_VECTOR_MAP.DrawBackground(AHasCrossLine, AHasBorder: Boolean);
var
pO, pLen : TPoint;
begin
if not Assigned( FCanvas ) then
Exit;
with FCanvas do
begin
Brush.Color := FMapColor.Background;
Brush.Style := bsSolid;
FillRect( FRect );
// 画交叉坐标,田字格
if AHasCrossLine then
begin
Pen.Color := FMapColor.DotLine;
Pen.Style := psDot;
Pen.Width := FPenWidth;
pO.X := ( FRect.Right + FRect.Left ) div 2;
pO.Y := ( FRect.Bottom + FRect.Top ) div 2;
pLen := Point( Round( 0.9 * ( FRect.Right - FRect.Left ) / 2 ),
Round( 0.9 * ( FRect.Bottom - FRect.Top ) / 2 ) );
Rectangle( pO.X - pLen.X, pO.Y - pLen.Y, pO.X + pLen.X, pO.Y + pLen.Y );
MoveTo( pO.X - pLen.X, pO.Y );
LineTo( pO.X + pLen.X, pO.Y );
MoveTo( pO.X, pO.Y - pLen.Y );
LineTo( pO.X, pO.Y + pLen.Y );
end;
// 画边界
if AHasBorder then
begin
Pen.Color := FMapColor.DotLine;
Pen.Style := psSolid;
Pen.Width := FPenWidth;
Brush.Style := bsClear;
Rectangle( FRect );
end;
end;
end;
procedure TWE_VECTOR_MAP.DrawLine(APen: TPen; APos: TPoint; ALen, AAngle: Double;
AHasArrow: Boolean; ASign: string);
var
pEnd : TPoint;
pArw : TPoint;
begin
// 计算 终点 位置
pEnd.X := APos.X + Round( FUnitStep * ALen * Cos( AAngle ) );
pEnd.Y := APos.Y - Round( FUnitStep * ALen * Sin( AAngle ) );
// 画线
with FCanvas do
begin
Pen := APen;
Polyline( [ APos, pEnd ] );
// 画箭头
if AHasArrow then
DrawArrow( APen, pEnd, AAngle );
end;
if ASign <> '' then
begin
// pArw.X := pEnd.X + Round(Cos(AAngle) * FUnitStep/4);
// pArw.Y := pEnd.Y - Round(Sin(AAngle) * FUnitStep/4);
if AAngle > 3 * Pi / 2 then // 第四相线
begin
pArw.X := pEnd.X + FUnitStep div 10;
pArw.Y := pEnd.Y ;
end
else if AAngle > Pi + 0.02 then // 第三相线
begin
pArw.X := pEnd.X - FUnitStep div 4;
pArw.Y := pEnd.Y;
end
else if AAngle > Pi / 2 then // 第二相线
begin
pArw.X := pEnd.X - FUnitStep div 2;
pArw.Y := pEnd.Y - FUnitStep div 4;
end
else // 第一相线
begin
pArw.X := pEnd.X + FUnitStep div 20;
pArw.Y := pEnd.Y - FUnitStep div 3;
end;
// else if AAngle > 0 then
// begin
// pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 30 );
// pArw.Y := pEnd.Y - Round( FUnitStep / 3.5 );
// end
// else if AAngle > - Pi / 4 then
// begin
// pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 30 );
// pArw.Y := pEnd.Y - Round( FUnitStep / 3.5 );
// end
// else if AAngle > - Pi / 2.5 then
// begin
// pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
// pArw.Y := pEnd.Y - FUnitStep div 8;
// end
// else if AAngle > - Pi / 2 then
// begin
// pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
// pArw.Y := pEnd.Y - FUnitStep div 8;
// end
// else if AAngle > - 3 * Pi / 4 then
// begin
// pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
// pArw.Y := pEnd.Y - FUnitStep div 8;
// end
// else if AAngle > - Pi then
// begin
// pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
// pArw.Y := pEnd.Y + FUnitStep div 15;
// end;
FEquationDraw.DrawText( FCanvas, pArw, ASign, APen.Color,
FMapColor.Background, FUnitStep / 75 );
end;
end;
procedure TWE_VECTOR_MAP.DrawPhase3Map( ROrgans: TStringList );
var
AOrgan: TWE_ORGAN;
i: Integer;
begin
// 画 线电压
with FCanvas do
begin
Pen.Style := psSolid;
Pen.Color := FMapColor.PhaseLine;
Pen.Width := FPenWidth;
DrawLine( Pen, FMapCenter, 1, pi/2, True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_A ) );
DrawLine( Pen, FMapCenter, 1, DegToRad(330) , True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_B ) );
DrawLine( Pen, FMapCenter, 1, DegToRad(210), True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_C ) );
end;
for i := 0 to ROrgans.Count - 1 do
begin
case i of
0:FCanvas.Pen.Color := FMapColor.PhaseAB;
1:FCanvas.Pen.Color := FMapColor.PhaseCB;
end;
AOrgan := TWE_ORGAN(ROrgans.Objects[i]);
DrawSingleEquation( AOrgan, FCanvas.Pen, FMapCenter, 0.3 + 0.1*i );
end;
end;
procedure TWE_VECTOR_MAP.DrawPhase4Map( ROrgans : TStringList );
var
i : Integer;
AOrgan: TWE_ORGAN;
begin
FCanvas.Pen.Style := psSolid;
FCanvas.Pen.Width := FPenWidth;
with FCanvas do
begin
Pen.Style := psSolid;
Pen.Color := FMapColor.PhaseLine;
Pen.Width := FPenWidth;
DrawLine( Pen, FMapCenter, 1, pi/2, True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_A ) );
DrawLine( Pen, FMapCenter, 1, DegToRad(330) , True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_B ) );
DrawLine( Pen, FMapCenter, 1, DegToRad(210), True, DotVar( 'U' ) + SuffixVar( C_EQ_SIGN_C ) );
end;
for i := 0 to ROrgans.Count - 1 do
begin
case i of
0:FCanvas.Pen.Color := FMapColor.PhaseA;
1:FCanvas.Pen.Color := FMapColor.PhaseB;
2:FCanvas.Pen.Color := FMapColor.Phasec;
end;
AOrgan := TWE_ORGAN(ROrgans.Objects[i]);
DrawSingleEquation( AOrgan, FCanvas.Pen, FMapCenter, 0.3 + 0.1*i );
// Break;
end;
end;
procedure TWE_VECTOR_MAP.DrawPhaseMap(APhaseType: TWE_PHASE_TYPE;
ROrgans: TStringList; dUIAngle : Double; sCaption : string);
begin
FUIAngle := dUIAngle;
// 初始化变量
FMapCenter.X := ( FRect.Right + FRect.Left ) div 2;
FMapCenter.Y := ( FRect.Bottom + FRect.Top ) div 2;
FUnitStep := ( FRect.Right - FRect.Left ) div 5;
FPenWidth := FUnitStep div 100;
if FUnitStep = 0 then
Exit;
FMapColor.Background := PhaseMapColor.Background;
FMapColor.DotLine := PhaseMapColor.DotLine;
FMapColor.PhaseLine := PhaseMapColor.PhaseLine;
FMapColor.PhaseAB := PhaseMapColor.PhaseAB;
FMapColor.PhaseCB := PhaseMapColor.PhaseCB;
FMapColor.PhaseA := PhaseMapColor.PhaseA;
FMapColor.PhaseB := PhaseMapColor.PhaseB;
FMapColor.PhaseC := PhaseMapColor.PhaseC;
// 画背景及坐标
DrawBackground( True, False );
FCanvas.Font.Size := Round( FUnitStep /8 );
FCanvas.Font.Name := '宋体';
FCanvas.Font.Style := [];
FCanvas.Font.Color := clBlack;
FCanvas.TextOut(FRect.Right-90, FRect.Top+30, sCaption);
if APhaseType = ptThree then
DrawPhase3Map( ROrgans )
else
DrawPhase4Map( ROrgans );
end;
procedure TWE_VECTOR_MAP.DrawSingleEquation(AOrgan: TWE_ORGAN;
APen : TPen; APos: TPoint; AAngleRadius: Double);
var
dLen, dIAngle, dUAngle : Double;
AVectorIn, AVectorOut:TVECTOR_LINE;
dX, dY: Double;
dTemp, dTemp1 : Double;
bDraw : Boolean;
s : string;
begin
bDraw := True;
if not Assigned( AOrgan ) then
Exit;
if not Assigned( VectorLines ) then
Exit;
{电压线}
// 电压线终点
AVectorIn:=VectorLines.GetLine(AOrgan.UInType);
AVectorOut:= VectorLines.GetLine(AOrgan.UOutType);
if Assigned(AVectorIn) and Assigned(AVectorOut) then
begin
// AVectorIn.LineName := StringReplace(AVectorIn.LineName, '-', '',[]);
// AVectorOut.LineName := StringReplace(AVectorOut.LineName, '-', '',[]);
if AVectorIn.LineAngle = AVectorOut.LineAngle then
bDraw := False;
dTemp := DegToRad(AVectorIn.LineAngle);
dTemp1 := DegToRad(AVectorOut.LineAngle);
dX := Cos(dTemp)-Cos(dTemp1);
dY := Sin(dTemp)-Sin(dTemp1);
if (dX <> 0)or (dY<>0) then
begin
// 计算长度和角度
GetLenAngle(0,0,dX*100,dY*100, dLen, dUAngle);
dUAngle := dUAngle + DegToRad(30);
AOrgan.UAngle := RadToDeg(dUAngle);
dLen := dLen/100;
if AOrgan.UParam = pt1_2 then
dLen := dLen/2;
// 画线
s := '.'+AOrgan.UType;
if AOrgan.UParam = pt1_2 then
s := '{1,2}' + s;
DrawLine( APen, APos, dLen, dUAngle, True, s );
end;
end
else
begin
bDraw := False;
end;
{电流线}
AVectorIn:=VectorLines.GetLine(AOrgan.IInType);
AVectorOut:= VectorLines.GetLine(AOrgan.IOutType);
dLen := 1;
if Assigned(AVectorIn) then
AOrgan.IAngle := AVectorIn.LineAngle
else if Assigned(AVectorOut) then
AOrgan.IAngle := AVectorOut.LineAngle+180
else
AOrgan.IAngle := 90;
dIAngle := DegToRad(AOrgan.IAngle-FUIAngle);
// 画线
if Assigned(AVectorIn) or Assigned(AVectorOut) then
begin
s := AOrgan.IType;
Insert('.', s, Pos('-',s)+1);
DrawLine( APen, APos, dLen, dIAngle, True, s )
end
else
bDraw := False;
{画角度}
if bDraw then
DrawAngle( APen, APos, AAngleRadius, 2*pi-dUAngle, 2*pi-dIAngle, True, '' );
end;
procedure GetLenAngle(dP1x, dP1y, dP2x, dP2y : Double; var dLen,
dAngle: Double);
var
dTemp : Double;
begin
dLen := Sqrt(Sqr(dP2x-dP1x)+Sqr(dP2y-dP1y));
dTemp := ArcTan(Abs(dP2y-dP1y)/abs(dP2x-dP1x));
if dP2y >= dP1y then
begin
if dP2x >= dP1x then
dAngle := dTemp
else
dAngle := Pi-dTemp;
end
else
begin
if dP2x >= dP1x then
dAngle := 2*Pi-dTemp
else
dAngle := Pi+dTemp;
end;
// // 转换成角度
// dAngle := RadToDeg(dAngle);
end;
{ TWE_VECTOR_MAP_COLOR }
procedure TWE_VECTOR_MAP_COLOR.Assign(Source: TPersistent);
begin
inherited;
if Source is TWE_VECTOR_MAP_COLOR then
begin
FPhaseLine := TWE_VECTOR_MAP_COLOR(Source).PhaseLine;
FDotLine := TWE_VECTOR_MAP_COLOR(Source).DotLine;
FBackground := TWE_VECTOR_MAP_COLOR(Source).Background;
FPhaseB := TWE_VECTOR_MAP_COLOR(Source).PhaseB;
FPhaseC := TWE_VECTOR_MAP_COLOR(Source).PhaseC;
FPhaseA := TWE_VECTOR_MAP_COLOR(Source).PhaseA;
FPhaseCB := TWE_VECTOR_MAP_COLOR(Source).PhaseCB;
FPhaseAB := TWE_VECTOR_MAP_COLOR(Source).PhaseAB;
end;
end;
constructor TWE_VECTOR_MAP_COLOR.Create(sIniFile: string);
begin
FIniFile := sIniFile;
with TIniFile.Create(sIniFile) do
begin
FBackground := ReadInteger( 'PhaseMapColor', 'Background', clWhite );
FDotLine := ReadInteger( 'PhaseMapColor', 'DotLine', $00D1D1D1 );
FPhaseLine := ReadInteger( 'PhaseMapColor', 'PhaseLine', $005E5E5E );
FPhaseAB := ReadInteger( 'PhaseMapColor', 'PhaseAB', $003D9DFE );
FPhaseCB := ReadInteger( 'PhaseMapColor', 'PhaseCB', clRed );
FPhaseA := ReadInteger( 'PhaseMapColor', 'PhaseA', $003D9DFE );
FPhaseB := ReadInteger( 'PhaseMapColor', 'PhaseB', $00009700 );
FPhaseC := ReadInteger( 'PhaseMapColor', 'PhaseC', clRed );
Free;
end;
end;
destructor TWE_VECTOR_MAP_COLOR.Destroy;
begin
with TIniFile.Create(FIniFile) do
begin
WriteInteger('VectorMapColor', 'Background', FBackground);
WriteInteger('VectorMapColor', 'DotLine', FDotLine );
WriteInteger('VectorMapColor', 'PhaseLine', FPhaseLine );
WriteInteger('VectorMapColor', 'PhaseAB', FPhaseAB );
WriteInteger('VectorMapColor', 'PhaseCB', FPhaseCB );
WriteInteger('VectorMapColor', 'PhaseA', FPhaseA );
WriteInteger('VectorMapColor', 'PhaseB', FPhaseB );
WriteInteger('VectorMapColor', 'PhaseC', FPhaseC );
Free;
end;
inherited;
end;
end.
|
{===============================================================================
Copyright(c) 2007-2009, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,向量图绘制单元
+ TPOWER_PHASE_MAP 向量图绘制
+ TPOWER_PHASE_MAP_COLOR 色彩索引
===============================================================================}
unit U_POWER_PHASE_MAP;
interface
uses SysUtils, Classes, Windows, Graphics, U_WE_EQUATION_DRAW,
system.Types, system.UITypes, U_POWER_STATUS;
CONST
/// <summary>
/// 画图的最小值
/// </summary>
C_DRAW_VALUE_MIN = 0.1;
const
/// <summary>
/// 画图时的放大系数
/// </summary>
C_DRAW_U_SCALE_RATE = 1.5;
C_DRAW_I_SCALE_RATE = 1.2;
type
/// <summary>
/// 色彩索引
/// </summary>
TPOWER_PHASE_MAP_COLOR = record
Background : Integer; // 向量图 底色
DotLine : Integer; // 向量图 虚轴颜色
PhaseLine : Integer; // 向量图 三线 相线颜色
PhaseAB : Integer; // 向量图 三线 第一元件
PhaseCB : Integer; // 向量图 三线 第二元件
PhaseA : Integer; // 向量图 四线 第一元件
PhaseB : Integer; // 向量图 四线 第二元件
PhaseC : Integer; // 向量图 四线 第三元件
Font : Integer; // 字体颜色
end;
var
PowerPhaseMap : TPOWER_PHASE_MAP_COLOR;
type
/// <summary>
/// 向量图
/// </summary>
TPOWER_PHASE_MAP = class( TComponent )
private
FPowerStatus: TPOWER_STATUS;
FPower : TCKM_POWER;
FMapCenter : TPoint;
FCanvas : TCanvas;
FRect : TRect;
FMapColor : TPOWER_PHASE_MAP_COLOR;
FUnitStep : Integer;
FPenWidth : Integer;
FEquationDraw : TWE_EQUATION_DRAW;
FDefMapColor: TPOWER_PHASE_MAP_COLOR;
procedure SetDefMapColor(const Value: TPOWER_PHASE_MAP_COLOR);
protected
/// <summary>
/// 画背景
/// </summary>
procedure DrawBackground( AHasCrossLine, AHasBorder : Boolean );
/// <summary>
/// 画矢量线
/// </summary>
procedure DrawLine( APen : TPen; APos : TPoint; ALen, AAngle : Double;
AHasArrow : Boolean; ASign : string );
/// <summary>
/// 画角度
/// </summary>
procedure DrawAngle( APen : TPen; APos : TPoint;
ARadius, AStartAngle, AEndAngle : Double; AHasArrow : Boolean; ASign : string );
/// <summary>
/// 画箭头
/// </summary>
procedure DrawArrow( APen : TPen; APos : TPoint; AAngle : Double );
/// <summary>
/// 角度转换, 公式和画图的角度不同,需要转换
/// </summary>
function CovAngle( AValue : Double ) : Double;
/// <summary>
/// 画向量图
/// </summary>
procedure DrawPhase3Map;
procedure DrawPhase4Map;
/// <summary>
/// 修正电流值
/// </summary>
function FixedIValue( Value : Double ) : Double;
/// <summary>
/// 修正电压值
/// </summary>
function FixedUValue( Value : Double ) : Double;
public
/// <summary>
/// 画布
/// </summary>
property Canvas : TCanvas read FCanvas write FCanvas;
/// <summary>
/// 绘图的区域
/// </summary>
property Rect : TRect read FRect write FRect;
/// <summary>
/// 颜色索引
/// </summary>
property MapColor : TPOWER_PHASE_MAP_COLOR read FMapColor write FMapColor;
/// <summary>
/// 默认颜色索引
/// </summary>
property DefMapColor : TPOWER_PHASE_MAP_COLOR read FDefMapColor write SetDefMapColor;
/// <summary>
/// 单位长度
/// </summary>
property UnitStep : Integer read FUnitStep write FUnitStep;
/// <summary>
/// 画笔宽度
/// </summary>
property PenWidth : Integer read FPenWidth write FPenWidth;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// 绘制向量图
/// </summary>
procedure DrawPhaseMap( APowerStatus: TPOWER_STATUS; APower : TCKM_POWER );
end;
implementation
uses U_WE_POWER_ANALYSIS;
{ TPOWER_PHASE_MAP }
function TPOWER_PHASE_MAP.CovAngle(AValue: Double): Double;
begin
if AValue >= -90 then
Result := (90 - AValue) / 180 * Pi
else
Result := (- AValue - 270) / 180 * Pi;
end;
constructor TPOWER_PHASE_MAP.Create(AOwner: TComponent);
begin
inherited;
FEquationDraw := TWE_EQUATION_DRAW.Create( nil );
with FDefMapColor do
begin
Background := clWhite;
DotLine := $00D1D1D1;
PhaseLine := $005E5E5E;
PhaseAB := $003D9DFE;
PhaseCB := clRed ;
PhaseA := $003D9DFE;
PhaseB := $00009700;
PhaseC := clRed ;
Font := clBlack;
end;
FMapColor := FDefMapColor;
end;
destructor TPOWER_PHASE_MAP.Destroy;
begin
FEquationDraw.Free;
inherited;
end;
procedure TPOWER_PHASE_MAP.DrawAngle(APen: TPen; APos: TPoint; ARadius,
AStartAngle, AEndAngle: Double; AHasArrow: Boolean; ASign: string);
var
apPoint : array of TPoint;
dAngle : Double;
i : Integer;
pO : TPoint;
begin
if AStartAngle > AEndAngle then
begin
dAngle := AStartAngle;
AStartAngle := AEndAngle;
AEndAngle := dAngle;
end;
SetLength(apPoint, 0);
pO := APos;
if AEndAngle - AStartAngle < Pi then
begin
for i := Round(AStartAngle * 90) to Round(AEndAngle * 90) do
begin
SetLength(apPoint, Length(apPoint)+1);
apPoint[High(apPoint)].X := pO.X + Round(ARadius * FUnitStep * Sin(i / 90));
apPoint[High(apPoint)].Y := pO.Y - Round(ARadius * FUnitStep * Cos(i / 90));
end;
end
else
begin
for i := Round(AEndAngle * 90) to Round(Pi * 90) do
begin
SetLength(apPoint, Length(apPoint)+1);
apPoint[High(apPoint)].X := pO.X + Round(ARadius * FUnitStep * Sin(i / 90));
apPoint[High(apPoint)].Y := pO.Y - Round(ARadius * FUnitStep * Cos(i / 90));
end;
for i := Round(- Pi * 90) to Round(AStartAngle * 90) do
begin
SetLength(apPoint, Length(apPoint)+1);
apPoint[High(apPoint)].X := pO.X + Round(ARadius * FUnitStep * Sin(i / 90));
apPoint[High(apPoint)].Y := pO.Y - Round(ARadius * FUnitStep * Cos(i / 90));
end;
end;
// 画曲线
with FCanvas do
begin
Pen := APen;
Polyline(apPoint);
end;
// 画箭头
if AHasArrow then
begin
if AEndAngle - AStartAngle < Pi then
begin
if Length(apPoint) > 2000 / FUnitStep then
begin
DrawArrow( APen, apPoint[0], AStartAngle - Pi/2 );
DrawArrow( APen, apPoint[High(apPoint)], AEndAngle + Pi/2 );
end;
end
else
begin
if Length(apPoint) > 2000 / FUnitStep then
begin
DrawArrow( APen, apPoint[0], AEndAngle - Pi / 2 );
DrawArrow( APen, apPoint[High(apPoint)], AStartAngle + Pi/2 );
end;
end;
end;
end;
procedure TPOWER_PHASE_MAP.DrawArrow(APen: TPen; APos: TPoint; AAngle: Double);
var
pArw : TPoint;
dPosX, dPosY : Double;
begin
with FCanvas do
begin
Pen := APen;
// 确定箭头大小
if FUnitStep / 30 > 2 then
dPosX := - FUnitStep / 30
else
dPosX := -2;
dPosY := dPosX * 2;
pArw.X := APos.X + Round(dPosY * Sin(AAngle) + dPosX * Cos(AAngle));
pArw.Y := APos.Y - Round(dPosY * Cos(AAngle) - dPosX * Sin(AAngle));
Polyline( [ APos, pArw ] );
dPosX := - dPosX;
pArw.X := APos.X + Round(dPosY * Sin(AAngle) + dPosX * Cos(AAngle));
pArw.Y := APos.Y - Round(dPosY * Cos(AAngle) - dPosX * Sin(AAngle));
Polyline( [ APos, pArw ] );
end;
end;
procedure TPOWER_PHASE_MAP.DrawBackground(AHasCrossLine, AHasBorder: Boolean);
var
pO, pLen : TPoint;
begin
if not Assigned( FCanvas ) then
Exit;
with FCanvas do
begin
Brush.Color := FMapColor.Background;
Brush.Style := bsSolid;
FillRect( FRect );
// 画交叉坐标
if AHasCrossLine then
begin
Pen.Color := FMapColor.DotLine;
Pen.Style := psDot;
Pen.Width := FPenWidth;
pO.X := ( FRect.Right + FRect.Left ) div 2;
pO.Y := ( FRect.Bottom + FRect.Top ) div 2;
pLen := Point( Round( 0.9 * ( FRect.Right - FRect.Left ) / 2 ),
Round( 0.9 * ( FRect.Bottom - FRect.Top ) / 2 ) );
MoveTo( pO.X - pLen.X, pO.Y );
LineTo( pO.X + pLen.X, pO.Y );
MoveTo( pO.X, pO.Y - pLen.Y );
LineTo( pO.X, pO.Y + pLen.Y );
end;
// 画边界
if AHasBorder then
begin
Pen.Color := FMapColor.DotLine;
Pen.Style := psSolid;
Pen.Width := FPenWidth;
Brush.Style := bsClear;
Rectangle( FRect );
end;
end;
end;
procedure TPOWER_PHASE_MAP.DrawLine(APen: TPen; APos: TPoint; ALen, AAngle: Double;
AHasArrow: Boolean; ASign: string);
var
pEnd : TPoint;
pArw : TPoint;
begin
// 计算 终点 位置
pEnd.X := APos.X + Round( FUnitStep * ALen * Sin( AAngle ) );
pEnd.Y := APos.Y - Round( FUnitStep * ALen * Cos( AAngle ) );
// 画线
with FCanvas do
begin
Pen := APen;
Polyline( [ APos, pEnd ] );
// 画箭头
if AHasArrow then
DrawArrow( APen, pEnd, AAngle );
end;
if ASign <> '' then
begin
if AAngle > 3 * Pi / 4 then // 第四相线
begin
pArw.X := pEnd.X + FUnitStep div 15;
pArw.Y := pEnd.Y - FUnitStep div 10;
end
else if AAngle > Pi / 2 then
begin
pArw.X := pEnd.X + FUnitStep div 15;
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else if AAngle > Pi / 4 then // 第一相线
begin
pArw.X := pEnd.X + FUnitStep div 15;
pArw.Y := pEnd.Y - FUnitStep div 10;
end
else if AAngle > 0 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 30 );
pArw.Y := pEnd.Y - Round( FUnitStep / 3.5 );
end
else if AAngle > - Pi / 4 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 30 );
pArw.Y := pEnd.Y - Round( FUnitStep / 3.5 );
end
else if AAngle > - Pi / 2.5 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else if AAngle > - Pi / 2 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else if AAngle > - 3 * Pi / 4 then
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y - FUnitStep div 8;
end
else
begin
pArw.X := pEnd.X - Round( FUnitStep * Length( ASign ) / 15 );
pArw.Y := pEnd.Y + FUnitStep div 15;
end;
FEquationDraw.DrawText( FCanvas, pArw, ASign, APen.Color,
FMapColor.Background, FUnitStep / 75 );
end;
end;
procedure TPOWER_PHASE_MAP.DrawPhase3Map;
// U12是否反
function U12Reverse( dAngel : Double ) : Boolean;
begin
Result := Abs(dAngel - 120) > 6;
end;
function U23Reverse( dAngel : Double ) : Boolean;
begin
Result := Abs(dAngel + 180) > 6;
end;
var
dAngleU12 : Double;
PStatus : TWE_POWER_STATUS;
begin
// 画 线电压
with FCanvas do
begin
Pen.Style := psSolid;
Pen.Width := FPenWidth;
Pen.Color := FMapColor.PhaseLine;
DrawLine( Pen, FMapCenter, 1, CovAngle(90) , True, '.U_1' );
DrawLine( Pen, FMapCenter, 1, CovAngle(-30) , True, '.U_2' );
DrawLine( Pen, FMapCenter, 1, CovAngle(-150), True, '.U_3' );
end;
// 确定U12的电压位置
if Assigned( PowerAnalysis ) then
begin
PStatus.U := FPower.VoltagePercent / 100;
PStatus.I := FPower.CurrentPercent / 100;
PStatus.UIAngle := FPower.Angle;
PStatus.U1 := FPowerStatus.U1;
PStatus.I1 := FPowerStatus.I1;
PStatus.O1 := FPowerStatus.O1;
PStatus.U2 := FPowerStatus.U3;
PStatus.I2 := FPowerStatus.I3;
PStatus.O2 := FPowerStatus.O3;
PStatus.OU1U2 := FPowerStatus.OU1U3;
dAngleU12 := PowerAnalysis.GetUAngle( PStatus );
end
else
dAngleU12 := 120;
FCanvas.Pen.Color := FMapColor.PhaseAB;
with FCanvas do
begin
if FPowerStatus.U1 > C_DRAW_VALUE_MIN then
begin
if U12Reverse(dAngleU12) then
DrawLine( Pen, FMapCenter, FixedUValue( FPowerStatus.U1 ),
CovAngle( dAngleU12 ), True, '.U_2_1' )
else
DrawLine( Pen, FMapCenter, FixedUValue( FPowerStatus.U1 ),
CovAngle( dAngleU12 ), True, '.U_1_2' )
end;
if FPowerStatus.I1 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedIValue( FPowerStatus.I1 ),
CovAngle( dAngleU12 - FPowerStatus.O1 ), True, '.I_1' );
FCanvas.Pen.Color := FMapColor.PhaseCB;
if FPowerStatus.U3 > C_DRAW_VALUE_MIN then
begin
if U23Reverse(dAngleU12 - FPowerStatus.OU1U3) then
DrawLine( Pen, FMapCenter, FixedUValue( FPowerStatus.U3 ),
CovAngle( dAngleU12 - FPowerStatus.OU1U3 ), True, '.U_2_3' )
else
DrawLine( Pen, FMapCenter, FixedUValue( FPowerStatus.U3 ),
CovAngle( dAngleU12 - FPowerStatus.OU1U3 ), True, '.U_3_2' );
end;
if FPowerStatus.I3 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedIValue( FPowerStatus.I3 ),
CovAngle( dAngleU12 - FPowerStatus.OU1U3 - FPowerStatus.O3 ), True, '.I_3' );
end;
end;
procedure TPOWER_PHASE_MAP.DrawPhase4Map;
var
dAngleU1 : Double;
begin
FCanvas.Pen.Style := psSolid;
FCanvas.Pen.Width := FPenWidth;
dAngleU1 := 90;
with FCanvas do
begin
FCanvas.Pen.Color := FMapColor.PhaseA;
if FPowerStatus.U1 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedUValue( FPowerStatus.U1 ),
CovAngle( dAngleU1 ), True, '.U_1' );
if FPowerStatus.I1 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedIValue( FPowerStatus.I1 ),
CovAngle( dAngleU1 - FPowerStatus.O1 ), True, '.I_1' );
FCanvas.Pen.Color := FMapColor.PhaseB;
if FPowerStatus.U2 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedUValue( FPowerStatus.U2 ),
CovAngle( dAngleU1 - FPowerStatus.OU1U2 ), True, '.U_2' );
if FPowerStatus.I2 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedIValue( FPowerStatus.I2 ),
CovAngle( dAngleU1 - FPowerStatus.OU1U2 - FPowerStatus.O2 ), True, '.I_2' );
FCanvas.Pen.Color := FMapColor.PhaseC;
if FPowerStatus.U3 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedUValue( FPowerStatus.U3 ),
CovAngle( dAngleU1 - FPowerStatus.OU1U3 ), True, '.U_3' );
if FPowerStatus.I3 > C_DRAW_VALUE_MIN then
DrawLine( Pen, FMapCenter, FixedIValue( FPowerStatus.I3 ),
CovAngle( dAngleU1 - FPowerStatus.OU1U3 - FPowerStatus.O3 ), True, '.I_3' );
end;
end;
procedure TPOWER_PHASE_MAP.DrawPhaseMap(APowerStatus: TPOWER_STATUS; APower : TCKM_POWER);
begin
FPowerStatus := APowerStatus;
FPower := APower;
// 初始化变量
FMapCenter.X := ( FRect.Right + FRect.Left ) div 2;
FMapCenter.Y := ( FRect.Bottom + FRect.Top ) div 2;
FUnitStep := ( FRect.Right - FRect.Left ) div 5;
FPenWidth := FUnitStep div 100;
if FUnitStep = 0 then
Exit;
MapColor := PowerPhaseMap;
DrawBackground( True, True );
if Assigned( FPowerStatus ) then
if FPowerStatus.PowerType = ptThree then
DrawPhase3Map
else
DrawPhase4Map;
end;
function TPOWER_PHASE_MAP.FixedIValue(Value: Double): Double;
begin
// 使其均在0.4以上
Result := ( 0.4 + Value * 0.6 ) * C_DRAW_I_SCALE_RATE;
end;
function TPOWER_PHASE_MAP.FixedUValue(Value: Double): Double;
begin
Result := Value * C_DRAW_U_SCALE_RATE;
if Result > 2 then
Result := 2;
end;
procedure TPOWER_PHASE_MAP.SetDefMapColor(const Value: TPOWER_PHASE_MAP_COLOR);
begin
FDefMapColor := Value;
end;
end.
|
unit adot.Collections.Types;
interface
uses
System.Generics.Collections,
System.Generics.Defaults,
System.Classes,
System.SysUtils,
System.StrUtils,
System.Math;
type
TEnumerableExt<T> = class(TEnumerable<T>)
protected
class procedure DoSaveToStream(Src: TEnumerable<T>; Dst: TStream; Encoding: TEncoding = nil); static;
class procedure DoSaveToFile(Src: TEnumerable<T>; const FileName: string; Encoding: TEncoding = nil; MemStream: boolean = True); static;
class function ArrayToString(const Src: TArray<T>; Index,Count: integer): string; overload;
class function ArrayToString(const Src: TArray<T>): string; overload;
public
procedure SaveToStream(Dst: TStream; Encoding: TEncoding = nil);
procedure SaveToFile(const FileName: string; Encoding: TEncoding = nil; MemStream: boolean = True);
function ToString: string; override;
function ToText(const ValuesDelimiter: string = #13#10): string;
end;
implementation
uses
adot.Tools,
adot.Tools.RTTI;
{ TEnumerableExt<T> }
class procedure TEnumerableExt<T>.DoSaveToFile(Src: TEnumerable<T>; const FileName: string; Encoding: TEncoding; MemStream: boolean);
var
S: TStream;
begin
if MemStream
then S := TMemoryStream.Create
else S := TFileStream.Create(FileName, System.Classes.fmCreate);
try
DoSaveToStream(Src, S, Encoding);
if MemStream then
TMemoryStream(S).SaveToFile(FileName);
finally
Sys.FreeAndNil(S);
end;
end;
class procedure TEnumerableExt<T>.DoSaveToStream(Src: TEnumerable<T>; Dst: TStream; Encoding: TEncoding);
var
I: Integer;
S: string;
B: TArray<byte>;
V: T;
N: boolean;
begin
if Encoding = nil then
Encoding := TEncoding.UTF8;
B := Encoding.GetPreamble;
Dst.WriteBuffer(B, System.Length(B));
N := False;
for V in Src do
begin
S := IfThen(N,#13#10,'') + TRttiUtils.ValueAsString<T>(V);
B := Encoding.GetBytes(S);
Dst.WriteBuffer(B, System.Length(B));
N := True;
end;
end;
procedure TEnumerableExt<T>.SaveToFile(const FileName: string; Encoding: TEncoding; MemStream: boolean);
begin
DoSaveToFile(Self, Filename, Encoding, MemStream);
end;
procedure TEnumerableExt<T>.SaveToStream(Dst: TStream; Encoding: TEncoding);
begin
DoSaveTostream(Self, dst, Encoding);
end;
class function TEnumerableExt<T>.ArrayToString(const Src: TArray<T>): string;
begin
result := ArrayToString(Src, 0, Length(Src));
end;
class function TEnumerableExt<T>.ArrayToString(const Src: TArray<T>; Index, Count: integer): string;
var
Builder: TStringBuilder;
I: integer;
begin
Builder := TStringBuilder.Create;
try
for I := Index to Min(Index+Count-1, High(Src)) do
begin
if I > Index then
Builder.Append(#13#10);
Builder.Append(TRttiUtils.ValueAsString<T>(Src[I]));
end;
result := Builder.ToString;
finally
Builder.Free;
end;
end;
function TEnumerableExt<T>.ToString: string;
begin
result := ToText(' ');
end;
function TEnumerableExt<T>.ToText(const ValuesDelimiter: string = #13#10): string;
var
Builder: TStringBuilder;
V: T;
N: Boolean;
begin
Builder := TStringBuilder.Create;
try
N := False;
for V in Self do
begin
if N then
Builder.Append(ValuesDelimiter)
else
N := True;
Builder.Append(TRttiUtils.ValueAsString<T>(V));
end;
result := Builder.ToString;
finally
Builder.Free;
end;
end;
end.
|
unit TestCastSimple;
{ AFS 9 Jan 2000
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
This unit tests simple type casts
}
interface
uses Classes, StdCtrls;
var
lcStrings: TStringList;
lcObj: TObject;
lcButton: TButton;
implementation
procedure TestDot;
var
lc: TObject;
begin
//this works as qualified identifier in an expr
lc := lcButton.Owner;
// this doesn't
lc := (lcObj as TComponent).Owner;
end;
procedure Test1;
begin
(lcButton as TObject).Free;
(lcObj as TStringList).Free;
(lcStrings as TObject).Free;
end;
procedure TestSurplusBrackets;
begin
// surplus brackets in casts
((lcButton as TObject)).Free;
(((lcObj as TStringList))).Free;
((((lcStrings as TObject)))).Free;
end;
procedure TestSurplusBrackets2;
begin
// just brackets, no casts
lcButton.Parent.Parent.Owner.Free;
(lcButton.Parent.Parent).Owner.Free;
((lcButton.Parent).Parent).Owner.Free;
(((lcButton).Parent).Parent).Owner.Free;
((((lcButton).Parent).Parent).Owner).Free;
end;
procedure Test2;
var
lc: TObject;
begin
lc := (lcButton as TObject);
lc := (lcObj as TStringList);
lc := (lcStrings as TObject);
lc := (lcStrings);
end;
procedure Test3;
begin
if lcObj is TStrings then
(lcObj as TStrings).ClassName;
if lcObj is TStrings then
begin
((lcObj as TStrings)).ClassName;
end;
end;
procedure Test4;
var
lc: TObject;
begin
// left recursive it is
lc := (lcObj as TComponent).Owner;
lc := ((lcObj as TComponent).Owner as TButton);
lc := (((lcObj as TComponent).Owner as TButton).Owner as TButton);
lc := ((((lcObj as TComponent).Owner as TButton).Owner as TButton).Owner as TButton);
// nested it is
lc := ((lcObj as TObject) as TComponent);
lc := (((lcObj as TButton) as TObject) as TComponent);
// both
lc := ((lcObj as TComponent).Owner as TComponent);
lc := (((lcObj as TButton) as TComponent).Owner as TComponent);
// surplus brackets
lc := ((((((lcObj as TButton)) as TComponent)).Owner as TComponent));
// complex on the left
lc := (lcButton.Parent as TComponent).Owner;
lc := (lcButton.Parent.Parent as TComponent).Owner;
// just brackets
lc := (lcButton.Parent.Parent).Owner;
lc := ((lcButton.Parent).Parent).Owner;
lc := (((lcButton).Parent).Parent).Owner;
lc := ((((lcButton).Parent).Parent).Owner);
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// 本单元是提供数据连接的单元(两层架),只输出一个有效的ADOConnection
//
//主要实现:
// 1、读取Ini配置文件信息
//-----------------------------------------------------------------------------}
unit untEasyUtilRWIni;
interface
uses
SysUtils, Classes, Windows, IniFiles;
type
{ TEasyStreamIniFile }
TEasyStreamIniFile = class (TMemIniFile)
{* 支持流操作的 IniFile 类,提供了 LoadFromStream、SaveToStream 允许从流中读取
Ini 数据。 }
private
FFileName: string;
public
constructor Create(const FileName: string = '');
destructor Destroy; override;
function LoadFromFile(const FileName: string): Boolean;
function LoadFromStream(Stream: TStream): Boolean; virtual;
function SaveToFile(const FileName: string): Boolean;
function SaveToStream(Stream: TStream): Boolean; virtual;
procedure UpdateFile; override;
property FileName: string read FFileName;
end;
{ TEasyXorIniFile }
TEasyXorIniFile = class (TEasyStreamIniFile)
{* 支持内容 Xor 加密及流操作的 IniFile 类,允许对 INI 数据进行 Xor 加密。 }
private
FXorStr: string;
protected
public
constructor Create(const FileName: string; const XorStr: string);
{* 类构造器。
|<PRE>
FileName: string - INI 文件名,如果文件存在将自动加载
XorStr: string - 用于 Xor 操作的字符串
|</PRE>}
function LoadFromStream(Stream: TStream): Boolean; override;
{* 从流中装载 INI 数据,流中的数据将用 Xor 解密 }
function SaveToStream(Stream: TStream): Boolean; override;
{* 保存 INI 数据到流,流中的数据将用 Xor 加密 }
end;
TEasyRWIni = class(TComponent)
private
FIniFile: TIniFile;
public
//读INI取值
function ReadValueString(ASection, AIdent, ADefault: string): string; overload;
function ReadValueBoolean(ASection, AIdent: string; ADefault: Boolean): Boolean; overload;
function ReadValueInteger(ASection, AIdent: string; ADefault: Integer): Integer; overload;
function ReadValueDateTime(ASection, AIdent: string; ADefault: TDateTime): TDateTime; overload;
function ReadValueDouble(ASection, AIdent: string; ADefault: Double): Double; overload;
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; IniPath: string); reintroduce; overload;
destructor Destroy; override;
end;
implementation
uses untEasyUtilStream;
{ TEasyRWIni }
constructor TEasyRWIni.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
constructor TEasyRWIni.Create(AOwner: TComponent; IniPath: string);
begin
inherited Create(AOwner);
FIniFile := TIniFile.Create(IniPath);
end;
destructor TEasyRWIni.Destroy;
begin
if FIniFile <> nil then
FreeAndNil(FIniFile);
inherited;
end;
function TEasyRWIni.ReadValueBoolean(ASection, AIdent: string; ADefault: Boolean): Boolean;
begin
Result := FIniFile.ReadBool(ASection, AIdent, ADefault);
end;
function TEasyRWIni.ReadValueDateTime(ASection, AIdent: string; ADefault: TDateTime): TDateTime;
begin
Result := FIniFile.ReadDateTime(ASection, AIdent, ADefault);
end;
function TEasyRWIni.ReadValueDouble(ASection, AIdent: string; ADefault: Double): Double;
begin
Result := FIniFile.ReadFloat(ASection, AIdent, ADefault);
end;
function TEasyRWIni.ReadValueInteger(ASection, AIdent: string; ADefault: Integer): Integer;
begin
Result := FIniFile.ReadInteger(ASection, AIdent, ADefault);
end;
function TEasyRWIni.ReadValueString(ASection, AIdent, ADefault: string): string;
begin
Result := FIniFile.ReadString(ASection, AIdent, ADefault);
end;
{ TEasyStreamIniFile }
constructor TEasyStreamIniFile.Create(const FileName: string);
begin
inherited Create('');
FFileName := FileName;
if FileExists(FFileName) then
LoadFromFile(FFileName);
end;
destructor TEasyStreamIniFile.Destroy;
begin
UpdateFile;
inherited;
end;
function TEasyStreamIniFile.LoadFromFile(const FileName: string): Boolean;
var
Stream: TFileStream;
begin
try
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := LoadFromStream(Stream);
finally
Stream.Free;
end;
except
Result := False;
end;
end;
function TEasyStreamIniFile.LoadFromStream(Stream: TStream): Boolean;
var
Strings: TStrings;
begin
try
Strings := TStringList.Create;
try
Strings.LoadFromStream(Stream);
SetStrings(Strings);
finally
Strings.Free;
end;
Result := True;
except
Result := False;
end;
end;
function TEasyStreamIniFile.SaveToFile(const FileName: string): Boolean;
var
Stream: TFileStream;
begin
try
Stream := TFileStream.Create(FileName, fmCreate);
try
Stream.Size := 0;
Result := SaveToStream(Stream);
finally
Stream.Free;
end;
except
Result := False;
end;
end;
function TEasyStreamIniFile.SaveToStream(Stream: TStream): Boolean;
var
Strings: TStrings;
begin
try
Strings := TStringList.Create;
try
GetStrings(Strings);
Strings.SaveToStream(Stream);
finally
Strings.Free;
end;
Result := True;
except
Result := False;
end;
end;
procedure TEasyStreamIniFile.UpdateFile;
begin
if FileExists(FFileName) then
SaveToFile(FFileName);
end;
{ TEasyXorIniFile }
constructor TEasyXorIniFile.Create(const FileName, XorStr: string);
begin
FXorStr := XorStr;
inherited Create(FileName);
end;
function TEasyXorIniFile.LoadFromStream(Stream: TStream): Boolean;
var
XorStream: TEasyXorStream;
begin
XorStream := TEasyXorStream.Create(Stream, AnsiString(FXorStr));
try
Result := inherited LoadFromStream(XorStream);
finally
XorStream.Free;
end;
end;
function TEasyXorIniFile.SaveToStream(Stream: TStream): Boolean;
var
XorStream: TEasyXorStream;
begin
XorStream := TEasyXorStream.Create(Stream, AnsiString(FXorStr));
try
Result := inherited SaveToStream(XorStream);
finally
XorStream.Free;
end;
end;
end.
|
unit JvSpecialImageDemoForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls,
Spin, JvSpecialImage;
type
{ TForm1 }
TForm1 = class(TForm)
btnFadeIn: TButton;
btnFadeOut: TButton;
cbFlipped: TCheckBox;
cbMirrored: TCheckBox;
cbInverted: TCheckBox;
JvSpecialImage1: TJvSpecialImage;
lblFadingSpeed: TLabel;
lblBrightness: TLabel;
Panel1: TPanel;
rbFadeBlack: TRadioButton;
rbFadeWhite: TRadioButton;
sbBrightness: TScrollBar;
seFadingSpeed: TSpinEdit;
procedure btnFadeInClick(Sender: TObject);
procedure btnFadeOutClick(Sender: TObject);
procedure cbFlippedChange(Sender: TObject);
procedure cbInvertedChange(Sender: TObject);
procedure cbMirroredChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure JvSpecialImage1FadingComplete(Sender: TObject);
procedure rbFadeBlackChange(Sender: TObject);
procedure rbFadeWhiteChange(Sender: TObject);
procedure sbBrightnessChange(Sender: TObject);
procedure seFadingSpeedChange(Sender: TObject);
private
FStartTime: TDateTime;
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.btnFadeInClick(Sender: TObject);
begin
Caption := 'Fading in...';
(*
sbBrightness.OnChange := nil;
sbBrightness.Position := 0;
lblBrightness.Caption := 'Brightness ' + IntToStr(sbBrightness.Position);
sbBrightness.OnChange := @sbBrightnessChange;
*)
FStartTime := Now;
JvSpecialImage1.FadeIn;
btnFadeOut.Enabled := true;
btnFadeIn.Enabled := false;
sbBrightness.Enabled := btnFadeOut.Enabled;
end;
procedure TForm1.btnFadeOutClick(Sender: TObject);
begin
Caption := 'Fading out...';
FStartTime := Now;
JvSpecialImage1.FadeOut;
btnFadeOut.Enabled := false;
btnFadeIn.Enabled := true;
sbBrightness.Enabled := btnFadeOut.Enabled;
end;
procedure TForm1.cbFlippedChange(Sender: TObject);
begin
JvSpecialImage1.Flipped := cbFlipped.Checked;
end;
procedure TForm1.cbInvertedChange(Sender: TObject);
begin
JvSpecialImage1.Inverted := cbInverted.Checked;
end;
procedure TForm1.cbMirroredChange(Sender: TObject);
begin
JvSpecialImage1.Mirrored := cbMirrored.Checked;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
sbBrightness.Position := JvSpecialImage1.Brightness;
end;
procedure TForm1.JvSpecialImage1FadingComplete(Sender: TObject);
begin
Caption := 'Time for fading: ' + IntToStr(Round((Now - FStartTime)*24*60*60*1000)) + 'ms';
end;
procedure TForm1.rbFadeBlackChange(Sender: TObject);
begin
if rbFadeBlack.Checked then JvSpecialImage1.FadingEnd := feBlack;
end;
procedure TForm1.rbFadeWhiteChange(Sender: TObject);
begin
if rbFadeWhite.Checked then JvSpecialImage1.FadingEnd := feWhite;
end;
procedure TForm1.sbBrightnessChange(Sender: TObject);
begin
JvSpecialImage1.Brightness := sbBrightness.Position;
lblBrightness.caption := Format('Brightness: %d', [JvSpecialImage1.Brightness]);
end;
procedure TForm1.seFadingSpeedChange(Sender: TObject);
begin
JvSpecialImage1.FadingSpeed := seFadingSpeed.Value;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Notification Center implementation for Windows }
{ }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Win.Notification;
interface
{$SCOPEDENUMS ON}
uses
System.Notification;
/// <summary>Common ancestor used to instantiate platform implementation</summary>
type TPlatformNotificationCenter = class(TBaseNotificationCenter)
protected
class function GetInstance: TBaseNotificationCenter; override;
end;
implementation
uses
System.SysUtils,
System.Messaging,
System.Generics.Collections,
System.Hash,
System.Win.Registry,
Winapi.Windows,
Winapi.ActiveX,
Winapi.KnownFolders,
Winapi.ShlObj,
Winapi.PropKey,
Winapi.PropSys,
System.Win.WinRT,
Winapi.WinRT,
Winapi.CommonTypes,
Winapi.DataRT,
Winapi.Storage,
Winapi.Foundation,
Winapi.UI.Notifications,
Winapi.Foundation.Types;
type
TNotificationCenterWinRT = class;
TNotificationCenterDelegateActivated = class;
TNotificationCenterDelegateDismiss = class;
TNotificationCenterDelegateFailed = class;
{ TNotificationCenterWindows }
TNotificationWinRT = class
private
FToast: IToastNotification;
FDelegateActivatedToken: EventRegistrationToken;
FDelegateDismissToken: EventRegistrationToken;
FDelegateFailedToken: EventRegistrationToken;
public
constructor Create(const ANotificationCenter: TNotificationCenterWinRT; const ANotification: TNotification);
destructor Destroy; override;
/// <summary>Reference to native Windows RT toast notification</summary>
property Toast: IToastNotification read FToast;
end;
TNotificationCenterWinRT = class(TPlatformNotificationCenter)
private class var
FSingleton: TNotificationCenterWinRT;
FAvailable: Boolean;
private
class constructor Create;
class destructor Destroy;
class function GetNotificationCenter: TNotificationCenterWinRT; static;
private const
AppId = 'Embarcadero.DesktopToasts.';
private
FNotifications: TDictionary<string, TNotificationWinRT>;
FToastNotifier: IToastNotifier;
class function GetAppNotificationKey: string; static;
class function CreateShortcut: Boolean; static;
public
constructor Create;
destructor Destroy; override;
procedure DoScheduleNotification(const ANotification: TNotification); override;
procedure DoPresentNotification(const ANotification: TNotification); override;
procedure DoCancelNotification(const AName: string); overload; override;
procedure DoCancelNotification(const ANotification: TNotification); overload; override;
procedure DoCancelAllNotifications; override;
procedure DoCreateOrUpdateChannel(const AChannel: TChannel); override;
procedure DoDeleteChannel(const AChannelId: string); override;
procedure DoGetAllChannels(const AChannels: TChannels); override;
procedure DoSetIconBadgeNumber(const ACount: Integer); override;
function DoGetIconBadgeNumber: Integer; override;
procedure DoResetIconBadgeNumber; override;
class property NotificationCenter: TNotificationCenterWinRT read GetNotificationCenter;
end;
{ TNotificationCenterDelegateActivated }
TNotificationCenterDelegateActivated = class(TInspectableObject, TypedEventHandler_2__IToastNotification__IInspectable,
TypedEventHandler_2__IToastNotification__IInspectable_Delegate_Base)
private
FNotification: TNotification;
public
constructor Create(const ANotification: TNotification);
destructor Destroy; override;
procedure Invoke(sender: IToastNotification; args: IInspectable); safecall;
end;
{ TNotificationCenterDelegateDismiss }
TNotificationCenterDelegateDismiss = class(TInspectableObject, TypedEventHandler_2__IToastNotification__IToastDismissedEventArgs,
TypedEventHandler_2__IToastNotification__IToastDismissedEventArgs_Delegate_Base)
private
FName: string;
[Weak] FNotificationCenter: TNotificationCenterWinRT;
public
constructor Create(const ANotificationCenter: TNotificationCenterWinRT; const ANotificationName: string);
procedure Invoke(sender: IToastNotification; args: IToastDismissedEventArgs); safecall;
end;
{ TNotificationCenterDelegateFailed }
TNotificationCenterDelegateFailed = class(TInspectableObject, TypedEventHandler_2__IToastNotification__IToastFailedEventArgs,
TypedEventHandler_2__IToastNotification__IToastFailedEventArgs_Delegate_Base)
private
FName: string;
[Weak] FNotificationCenter: TNotificationCenterWinRT;
public
constructor Create(const ANotificationCenter: TNotificationCenterWinRT; const ANotificationName: string);
procedure Invoke(sender: IToastNotification; args: IToastFailedEventArgs); safecall;
end;
{ TToastTemplateGenerator }
TToastTemplateGenerator = class abstract
private
{ Helpers for working with XML Template }
class function TryGetNodes(const ATemplate: Xml_Dom_IXmlDocument; const ANodeName: string; out ANodes: Xml_Dom_IXmlNodeList): Boolean; static;
class function SelectSingleNode(const ATemplate: Xml_Dom_IXmlDocument; const ANodeName: string; out ANode: Xml_Dom_IXmlElement): Boolean; static;
public
class function GetXMLDoc(const ANotification: TNotification): Xml_Dom_IXmlDocument; static;
end;
{ TNotificationCenterWindows }
class constructor TNotificationCenterWinRT.Create;
begin
FAvailable := True;
end;
class destructor TNotificationCenterWinRT.Destroy;
begin
FSingleton.Free;
end;
constructor TNotificationCenterWinRT.Create;
var
LWSAppID: TWindowsString;
begin
inherited;
FNotifications := TObjectDictionary<string, TNotificationWinRT>.Create([doOwnsValues]);
LWSAppID := TWindowsString.Create(GetAppNotificationKey);
FToastNotifier := TToastNotificationManager.Statics.CreateToastNotifier(LWSAppID);
end;
destructor TNotificationCenterWinRT.Destroy;
begin
FNotifications.Free;
inherited;
end;
class function TNotificationCenterWinRT.GetAppNotificationKey: string;
begin
Result := TNotificationCenterWinRT.AppId + THashBobJenkins.GetHashString(ParamStr(0));
end;
class function TNotificationCenterWinRT.CreateShortcut: Boolean;
const
CNotificationsKey: string = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings';
CShowInCenterName: string = 'ShowInActionCenter';
var
LReg: TRegistry;
LKey: string;
Path: PWideChar;
LBufferPath: array [0..MAX_PATH] of Char;
ShortcutPath: string;
LShellLink: IShellLink;
LPropertyStore: Winapi.PropSys.IPropertyStore;
LAppIdPropVar: PROPVARIANT;
LSaveLink: Boolean;
LFindData: TWin32FindDataW;
begin
LReg := TRegistry.Create;
try
LReg.RootKey := HKEY_CURRENT_USER;
LKey := CNotificationsKey + '\' + GetAppNotificationKey;
if not LReg.OpenKey(LKey, False) then
begin
if not LReg.OpenKey(LKey, True) then
Exit(False);
LReg.WriteInteger(CShowInCenterName, 1);
end;
finally
LReg.Free;
end;
Result := False;
if Succeeded(SHGetKnownFolderPath(FOLDERID_Programs, 0, 0, Path)) then
begin
ShortcutPath := string(Path) + '\' + ChangeFileExt(ExtractFileName(ParamStr(0)), '.lnk');
if FileExists(ShortcutPath) and Succeeded(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, LShellLink)) and
Succeeded((LShellLink as IPersistFile).Load(PWideChar(ShortcutPath), 0)) and
Succeeded(LShellLink.GetPath(LBufferPath, MAX_PATH, LFindData, 0)) and (LBufferPath = ParamStr(0)) then
Result := True
else
if Succeeded(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLink, LShellLink)) then
begin
LShellLink.SetPath(PChar(ParamStr(0)));
LShellLink.SetWorkingDirectory(PChar(ExtractFilePath(ParamStr(0))));
LPropertyStore := LShellLink as Winapi.PropSys.IPropertyStore;
ZeroMemory(@LAppIdPropVar,SizeOf(LAppIdPropVar));
if Succeeded(InitPropVariantFromString(PWideChar(GetAppNotificationKey), LAppIdPropVar)) then
try
if Succeeded(LPropertyStore.SetValue(PKEY_AppUserModel_ID, LAppIdPropVar)) and
Succeeded(LPropertyStore.Commit) then
begin
LSaveLink := True;
if FileExists(ShortcutPath) then
LSaveLink := System.SysUtils.DeleteFile(ShortcutPath);
if LSaveLink then
Result := Succeeded((LShellLink as IPersistFile).Save(PChar(ShortcutPath), True));
end;
finally
PropVariantClear(LAppIdPropVar);
end;
end;
end;
end;
procedure TNotificationCenterWinRT.DoCancelAllNotifications;
var
ToastNotification: TNotificationWinRT;
begin
inherited;
TMonitor.Enter(FNotifications);
try
for ToastNotification in FNotifications.Values do
FToastNotifier.Hide(ToastNotification.Toast);
FNotifications.Clear;
finally
TMonitor.Exit(FNotifications);
end;
end;
procedure TNotificationCenterWinRT.DoCancelNotification(const AName: string);
var
ToastNotification: TNotificationWinRT;
begin
inherited;
TMonitor.Enter(FNotifications);
try
if FNotifications.TryGetValue(AName, ToastNotification) then
begin
FToastNotifier.Hide(ToastNotification.Toast);
FNotifications.Remove(AName);
end;
finally
TMonitor.Exit(FNotifications);
end;
end;
procedure TNotificationCenterWinRT.DoCancelNotification(const ANotification: TNotification);
begin
inherited;
DoCancelNotification(ANotification.Name);
end;
procedure TNotificationCenterWinRT.DoCreateOrUpdateChannel(const AChannel: TChannel);
begin
// Relevant only for Android
end;
procedure TNotificationCenterWinRT.DoDeleteChannel(const AChannelId: string);
begin
// Relevant only for Android
end;
procedure TNotificationCenterWinRT.DoPresentNotification(const ANotification: TNotification);
var
ToastNotification: TNotificationWinRT;
begin
inherited;
if CreateShortcut then
begin
DoCancelNotification(ANotification);
ToastNotification := TNotificationWinRT.Create(Self, ANotification);
TMonitor.Enter(FNotifications);
try
FNotifications.AddOrSetValue(ANotification.Name, ToastNotification);
finally
TMonitor.Exit(FNotifications);
end;
FToastNotifier.Show(ToastNotification.Toast);
end;
end;
procedure TNotificationCenterWinRT.DoScheduleNotification(const ANotification: TNotification);
begin
inherited;
end;
procedure TNotificationCenterWinRT.DoSetIconBadgeNumber(const ACount: Integer);
begin
inherited;
end;
procedure TNotificationCenterWinRT.DoGetAllChannels(const AChannels: TChannels);
begin
// Relevant only for Android
end;
function TNotificationCenterWinRT.DoGetIconBadgeNumber: Integer;
begin
inherited;
Result := 0;
end;
procedure TNotificationCenterWinRT.DoResetIconBadgeNumber;
begin
inherited;
end;
class function TNotificationCenterWinRT.GetNotificationCenter: TNotificationCenterWinRT;
begin
if (FSingleton = nil) and FAvailable then
try
FSingleton := TNotificationCenterWinRT.Create;
except
// Exception will be raised when Notification Center services (WpnXxxx) are stopped
FAvailable := False;
FreeAndNil(FSingleton);
end;
Result := FSingleton;
end;
{ TPlatformNotificationCenter }
class function TPlatformNotificationCenter.GetInstance: TBaseNotificationCenter;
begin
if TOSVersion.Check(6, 2) then // Windows 8
Result := TBaseNotificationCenter(TNotificationCenterWinRT.NotificationCenter)
else
Result := nil;
end;
{ TToastTemplateGenerator }
class function TToastTemplateGenerator.GetXMLDoc(const ANotification: TNotification): Xml_Dom_IXmlDocument;
function SelectTemplate: ToastTemplateType;
begin
if (ANotification.Title <> '') and (ANotification.AlertBody <> '') then
Result := ToastTemplateType.ToastText02
else
Result := ToastTemplateType.ToastText01;
end;
var
LToastsTextElements: Xml_Dom_IXmlNodeList;
LWSTitleString: TWindowsString;
LWSBodyString: TWindowsString;
LTemplateType: ToastTemplateType;
LToastNode: Xml_Dom_IXmlElement;
LStr1, LStr2: TWindowsString;
LAudioNode: Xml_Dom_IXmlElement;
begin
LTemplateType := SelectTemplate;
Result := TToastNotificationManager.Statics.GetTemplateContent(LTemplateType);
if SelectSingleNode(Result, '/toast', LToastNode) then
begin
LStr1 := TWindowsString.Create('duration');
LStr2 := TWindowsString.Create('short');
LToastNode.SetAttribute(LStr1, LStr2);
end;
LStr1 := TWindowsString.Create('audio');
LAudioNode := Result.CreateElement(LStr1);
if not ANotification.EnableSound then
begin
LStr1 := TWindowsString.Create('silent');
LStr2 := TWindowsString.Create('true');
LAudioNode.SetAttribute(LStr1, LStr2);
end;
case LTemplateType of
ToastTemplateType.ToastText01:
begin
if TryGetNodes(Result, 'text', LToastsTextElements) and (LToastsTextElements.Length > 0) then
begin
LWSTitleString := TWindowsString.Create(ANotification.Title + ANotification.AlertBody);
(LToastsTextElements.Item(0) as Xml_Dom_IXmlNodeSerializer).InnerText := LWSTitleString;
end;
end;
ToastTemplateType.ToastText02:
begin
if TryGetNodes(Result, 'text', LToastsTextElements) and (LToastsTextElements.Length >= 2) then
begin
LWSTitleString := TWindowsString.Create(ANotification.Title);
(LToastsTextElements.Item(0) as Xml_Dom_IXmlNodeSerializer).InnerText := LWSTitleString;
LWSBodyString := TWindowsString.Create(ANotification.AlertBody);
(LToastsTextElements.Item(1) as Xml_Dom_IXmlNodeSerializer).InnerText := LWSBodyString;
end;
end;
end;
end;
class function TToastTemplateGenerator.SelectSingleNode(const ATemplate: Xml_Dom_IXmlDocument; const ANodeName: string;
out ANode: Xml_Dom_IXmlElement): Boolean;
var
LNodeNameString: TWindowsString;
begin
ANode := nil;
LNodeNameString := TWindowsString.Create(ANodeName);
ANode := (ATemplate as Xml_Dom_IXmlNodeSelector).SelectSingleNode(LNodeNameString) as Xml_Dom_IXmlElement;
Result := ANode <> nil;
end;
class function TToastTemplateGenerator.TryGetNodes(const ATemplate: Xml_Dom_IXmlDocument; const ANodeName: string;
out ANodes: Xml_Dom_IXmlNodeList): Boolean;
var
LNodeNameString: TWindowsString;
begin
ANodes := nil;
LNodeNameString := TWindowsString.Create(ANodeName);
ANodes := ATemplate.GetElementsByTagName(LNodeNameString);
Result := ANodes <> nil;
end;
{ TNotificationCenterDelegateActivated }
constructor TNotificationCenterDelegateActivated.Create(const ANotification: TNotification);
begin
inherited Create;
FNotification := TNotification.Create;
FNotification.Assign(ANotification);
end;
destructor TNotificationCenterDelegateActivated.Destroy;
begin
FNotification.Free;
inherited;
end;
procedure TNotificationCenterDelegateActivated.Invoke(sender: IToastNotification; args: IInspectable);
begin
TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(FNotification));
end;
{ TNotificationCenterDelegateDismiss }
constructor TNotificationCenterDelegateDismiss.Create(const ANotificationCenter: TNotificationCenterWinRT; const ANotificationName: string);
begin
inherited Create;
FName := ANotificationName;
FNotificationCenter := ANotificationCenter;
end;
procedure TNotificationCenterDelegateDismiss.Invoke(sender: IToastNotification; args: IToastDismissedEventArgs);
begin
TMonitor.Enter(FNotificationCenter.FNotifications);
try
FNotificationCenter.FNotifications.Remove(FName);
finally
TMonitor.Exit(FNotificationCenter.FNotifications);
end;
end;
{ TNotificationCenterDelegateFailed }
constructor TNotificationCenterDelegateFailed.Create(const ANotificationCenter: TNotificationCenterWinRT;
const ANotificationName: string);
begin
inherited Create;
FName := ANotificationName;
FNotificationCenter := ANotificationCenter;
end;
procedure TNotificationCenterDelegateFailed.Invoke(sender: IToastNotification; args: IToastFailedEventArgs);
begin
TMonitor.Enter(FNotificationCenter.FNotifications);
try
FNotificationCenter.FNotifications.Remove(FName);
finally
TMonitor.Exit(FNotificationCenter.FNotifications);
end;
end;
{ TToastNotificationWrapper }
constructor TNotificationWinRT.Create(const ANotificationCenter: TNotificationCenterWinRT;
const ANotification: TNotification);
var
DeleateActivate: TNotificationCenterDelegateActivated;
DelegateDismiss: TNotificationCenterDelegateDismiss;
DelegateFailed: TNotificationCenterDelegateFailed;
begin
FToast := TToastNotification.Factory.CreateToastNotification(TToastTemplateGenerator.GetXMLDoc(ANotification));
DeleateActivate := TNotificationCenterDelegateActivated.Create(ANotification);
FDelegateActivatedToken := FToast.add_Activated(DeleateActivate);
DelegateDismiss := TNotificationCenterDelegateDismiss.Create(ANotificationCenter, ANotification.Name);
FDelegateDismissToken := FToast.add_Dismissed(DelegateDismiss);
DelegateFailed := TNotificationCenterDelegateFailed.Create(ANotificationCenter, ANotification.Name);
FDelegateFailedToken := FToast.add_Failed(DelegateFailed);
end;
destructor TNotificationWinRT.Destroy;
begin
FToast.remove_Dismissed(FDelegateDismissToken);
FToast.remove_Activated(FDelegateActivatedToken);
FToast.remove_Failed(FDelegateFailedToken);
inherited;
end;
end.
|
unit uGCodeHL;
(*
uGCodeHL based on simlehl.pas included as an example highlighter found in
..\lazarus\examples\SynEdit\NewHighlighterTutorial
See comments below and http://wiki.lazarus.freepascal.org/SynEdit_Highlighter
How it works:
- Creation
The Highlighter creates Attributes that it can return the Words and Spaces.
- SetLine
Is called by SynEdit before a line gets painted (or before highlight info is needed)
This is also called, each time the text changes fol *all* changed lines
and may even be called for all lines after the change up to the end of text.
After SetLine was called "GetToken*" should return information about the
first token on the line.
Note: Spaces are token too.
- Next
Scan to the next token, on the line that was set by "SetLine"
"GetToken*" should return info about that next token.
- GetEOL
Returns True, if "Next" was called while on the last token of the line.
- GetTokenEx, GetTokenAttribute
Provide info about the token found by "Next"
- Next, GetEOL. GetToken*
Are used by SynEdit to iterate over the Line.
Important: The tokens returned for each line, must represent the original
line-text (mothing added, nothing left out), and be returned in the correct order.
They are called very often and should perform ath high speed.
- GetToken, GetTokenPos, GetTokenKind
SynEdit uses them e.g for finding matching brackets. If GetTokenKind returns different values per Attribute,
then brackets only match, if they are of the same kind
(e.g, if there was a string attribute, brackets outside a string would not match brackets inside a string)
*)
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, SynEditTypes, SynEditHighlighter;
type
{ TGCodeHl }
// TGCodeHl = class(TSynCustomHighlighter)
TGCodeHl = class(TSynCustomHighlighter)
private
fSpecialAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
//
// setup gcodes we are going to highlight
// G1 G2 G3
// G other
// M
// O
// T
// Z
fG123Attri: TSynHighlighterAttributes;
fGAttri: TSynHighlighterAttributes;
fMAttri: TSynHighlighterAttributes;
fOAttri: TSynHighlighterAttributes;
fTAttri: TSynHighlighterAttributes;
fZAttri: TSynHighlighterAttributes;
procedure SetIdentifierAttri(AValue: TSynHighlighterAttributes);
procedure SetSpaceAttri(AValue: TSynHighlighterAttributes);
procedure SetSpecialAttri(AValue: TSynHighlighterAttributes);
procedure SetG123Attri(AValue: TSynHighlighterAttributes);
procedure SetGAttri(AValue: TSynHighlighterAttributes);
procedure SetMAttri(AValue: TSynHighlighterAttributes);
procedure SetOAttri(AValue: TSynHighlighterAttributes);
procedure SetTAttri(AValue: TSynHighlighterAttributes);
procedure SetZAttri(AValue: TSynHighlighterAttributes);
protected
// accesible for the other examples
FTokenPos, FTokenEnd: integer;
FLineText: string;
public
procedure SetLine(const NewValue: string; LineNumber: integer); override;
procedure Next; override;
function GetEol: boolean; override;
procedure GetTokenEx(out TokenStart: PChar; out TokenLength: integer); override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
public
function GetToken: string; override;
function GetTokenPos: integer; override;
function GetTokenKind: integer; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override;
constructor Create(AOwner: TComponent); override;
published
(* Define 4 Attributes, for the different highlights. *)
property SpecialAttri: TSynHighlighterAttributes
read fSpecialAttri write SetSpecialAttri;
property IdentifierAttri: TSynHighlighterAttributes
read fIdentifierAttri write SetIdentifierAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write SetSpaceAttri;
property G123Attri: TSynHighlighterAttributes read fG123Attri write SetG123Attri;
property GAttri: TSynHighlighterAttributes read fGAttri write SetGAttri;
property MAttri: TSynHighlighterAttributes read fMAttri write SetMAttri;
property OAttri: TSynHighlighterAttributes read fOAttri write SetOAttri;
property TAttri: TSynHighlighterAttributes read fTAttri write SetTAttri;
property ZAttri: TSynHighlighterAttributes read fZAttri write SetZAttri;
end;
implementation
constructor TGCodeHl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
(* Create and initialize the attributes *)
fSpecialAttri := TSynHighlighterAttributes.Create('special', 'special');
AddAttribute(fSpecialAttri);
// fSpecialAttri.Style := [fsBold];
fSpecialAttri.Background := clLtGray;
fIdentifierAttri := TSynHighlighterAttributes.Create('ident', 'ident');
AddAttribute(fIdentifierAttri);
fSpaceAttri := TSynHighlighterAttributes.Create('space', 'space');
AddAttribute(fSpaceAttri);
//fSpaceAttri.FrameColor := clSilver;
//fSpaceAttri.FrameEdges := sfeAround;
// g code G1 G2 G3
fG123Attri := TSynHighlighterAttributes.Create('G123', 'G123');
AddAttribute(fG123Attri);
// fG123Attri.Style := [fsBold];
fG123Attri.Background := clTeal ;
// g codes G other
fGAttri := TSynHighlighterAttributes.Create('Gblocks', 'Gblocks');
AddAttribute(fGAttri);
// fGAttri.Style := [fsBold];
fGAttri.Background := clLime;
// g codes M
fMAttri := TSynHighlighterAttributes.Create('Mblocks', 'Mblocks');
AddAttribute(fMAttri);
// fMAttri.Style := [fsBold];
fMAttri.Background := clYellow;
// gcodes O
fOAttri := TSynHighlighterAttributes.Create('Oblocks', 'Oblocks');
AddAttribute(fOAttri);
// fOAttri.Style := [fsBold];
fOAttri.Background := clAqua;
// g codes T
fTAttri := TSynHighlighterAttributes.Create('Tblocks', 'Tblocks');
AddAttribute(fTAttri);
// fTAttri.Style := [fsBold];
fTAttri.Background := clRed;
// gcodes Z
fZAttri := TSynHighlighterAttributes.Create('Zblocks', 'Zblocks');
AddAttribute(fZAttri);
// fOAttri.Style := [fsBold];
fZAttri.Background :=clSilver ;
// Ensure the HL reacts to changes in the attributes. Do this once, if all attributes are created
SetAttributesOnChange(@DefHighlightChange);
end;
(* Setters for attributes / This allows using in Object inspector*)
procedure TGCodeHl.SetIdentifierAttri(AValue: TSynHighlighterAttributes);
begin
fIdentifierAttri.Assign(AValue);
end;
procedure TGCodeHl.SetG123Attri(AValue: TSynHighlighterAttributes);
begin
fG123Attri.Assign(AValue);
end;
procedure TGCodeHl.SetGAttri(AValue: TSynHighlighterAttributes);
begin
fGAttri.Assign(AValue);
end;
procedure TGCodeHl.SetMAttri(AValue: TSynHighlighterAttributes);
begin
fMAttri.Assign(AValue);
end;
procedure TGCodeHl.SetOAttri(AValue: TSynHighlighterAttributes);
begin
fOAttri.Assign(AValue);
end;
procedure TGCodeHl.SetZAttri(AValue: TSynHighlighterAttributes);
begin
fZAttri.Assign(AValue);
end;
procedure TGCodeHl.SetTAttri(AValue: TSynHighlighterAttributes);
begin
fTAttri.Assign(AValue);
end;
procedure TGCodeHl.SetSpaceAttri(AValue: TSynHighlighterAttributes);
begin
fSpaceAttri.Assign(AValue);
end;
procedure TGCodeHl.SetSpecialAttri(AValue: TSynHighlighterAttributes);
begin
fSpecialAttri.Assign(AValue);
end;
procedure TGCodeHl.SetLine(const NewValue: string; LineNumber: integer);
begin
inherited;
FLineText := NewValue;
// Next will start at "FTokenEnd", so set this to 1
FTokenEnd := 1;
Next;
end;
procedure TGCodeHl.Next;
var
lineLen: integer;
begin
// FTokenEnd should be at the start of the next Token (which is the Token we want)
FTokenPos := FTokenEnd;
// assume empty, will only happen for EOL
FTokenEnd := FTokenPos;
// Scan forward
// FTokenEnd will be set 1 after the last char. That is:
// - The first char of the next token
// - or past the end of line (which allows GetEOL to work)
// I think this is the code that we need to modify to get out g code tokens defined!
// ie what starts a token [A..Z] and what ends a token (either Space, eol or [A..Z]
// rem to force text to upper case
lineLen := length(FLineText);
if FTokenPos > lineLen then
// At line end
exit
else
if FLineText[FTokenEnd] in [#9, ' '] then
// At Space? Find end of spaces
while (FTokenEnd <= lineLen) and (FLineText[FTokenEnd] in [#0..#32]) do
Inc(FTokenEnd)
else
if FLineText[FTokenEnd] = '(' then // start of comment, parse until end
begin
while True do
begin
if (FTokenEnd > lineLen) then
Exit;
if FLineText[FTokenEnd] = ')' then
begin
inc(FTokenEnd);
Exit;
end;
Inc(FTokenEnd);
end;
end
else
// Find end of G Code Address Block (either a space or another G code)
begin
if FTokenPos = FTokenEnd then
Inc(FTokenEnd);
while True do
begin
if (FTokenEnd > lineLen) then
Exit;
if upCase(FLineText[FTokenEnd]) in ['A'..'Z',' ','('] then
Exit;
Inc(FTokenEnd);
end;
end;
end;
function TGCodeHl.GetEol: boolean;
begin
Result := FTokenPos > length(FLineText);
end;
procedure TGCodeHl.GetTokenEx(out TokenStart: PChar; out TokenLength: integer);
begin
TokenStart := @FLineText[FTokenPos];
TokenLength := FTokenEnd - FTokenPos;
end;
function TGCodeHl.GetTokenAttribute: TSynHighlighterAttributes;
var
Gcode : String;
begin
// Match the text, specified by FTokenPos and FTokenEnd
if FLineText[FTokenPos] in [#9, ' '] then
Result := SpaceAttri
else
if FLineText[FTokenPos] = '(' then // start of G Code comment
Result := SpecialAttri
else
Begin
Gcode := upCase(Copy(FLineText,FTokenPos,(FTokenEnd - FTokenPos)));
if (Gcode = 'G1') or (Gcode = 'G2') or (Gcode = 'G3') then
Result := G123Attri
else
if (Gcode = 'G01') or (Gcode = 'G02') or (Gcode = 'G03') then // catch other valid style
Result := G123Attri
else
if upCase(FLineText[FTokenPos]) = 'G' then
Result := GAttri
else
if upCase(FLineText[FTokenPos]) = 'M' then
Result := MAttri
else
if upCase(FLineText[FTokenPos]) = 'O' then
Result := OAttri
else
if upCase(FLineText[FTokenPos]) = 'T' then
Result := TAttri
else
if upCase(FLineText[FTokenPos]) = 'Z' then
Result := ZAttri
else
Result := IdentifierAttri;
END;
end;
function TGCodeHl.GetToken: string;
begin
Result := copy(FLineText, FTokenPos, FTokenEnd - FTokenPos);
end;
function TGCodeHl.GetTokenPos: integer;
begin
Result := FTokenPos - 1;
end;
function TGCodeHl.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
// Some default attributes
case Index of
SYN_ATTR_COMMENT: Result := fSpecialAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
else
Result := nil;
end;
end;
function TGCodeHl.GetTokenKind: integer;
var
a: TSynHighlighterAttributes;
begin
// Map Attribute into a unique number
a := GetTokenAttribute;
Result := 0;
if a = fSpaceAttri then
Result := 1
else
if a = fSpecialAttri then
Result := 2
else
if a = fIdentifierAttri then
Result := 3
else
if a = fG123Attri then
Result := 4
else
if a = fGAttri then
Result := 5
else
if a = fMAttri then
Result := 6
else
if a = fOAttri then
Result := 7
else
if a = fTAttri then
Result := 8
else
if a = fZAttri then
Result := 9;
end;
end.
|
unit uSchach;
interface
uses Graphics, Classes, SysUtils, Dialogs;
type
TZug = String;
TPosition = record
x,y:Integer;
end;
TFarbe = (schwarz, weiss);
TTyp = (Bauer,Laeufer,Springer,Turm,Dame,Koenig);
TSchachFigur = class
Position: TPosition;
Farbe:TFarbe;
aktiv:Boolean;
Typ:TTyp;
BildIndex:Integer; {in der Bilder-Liste}
constructor Create;
destructor Destroy; override;
procedure Zeichnen;
function KannZiehen(P:TPosition; MitSP:Boolean):Boolean; virtual; {Nachfolger (Figuren) Also AbgeleiteteKlassen erben und können dies verändern!(per override) dann "Result:=inherited KannZiehen(P);"}
procedure MoveTo(P:TPosition); virtual;
function Schachprobe(P:TPosition):Boolean;
procedure AppendZugListe(var L:TStringList); virtual;
end;
var Brett : Array[1..8,1..8] of TSchachFigur;
Spieler,Max,Min : TFarbe;
RochadeWK,RochadeWQ,RochadeSK,RochadeSQ : Boolean;
enpassantPos:TPosition;
AnzahlFiguren : Array[schwarz..weiss,Bauer..Koenig] of Integer;
KoenigsPosition : Array[schwarz..weiss] of TPosition;
startPos:TPosition;
gameOver:Boolean;
function Gegenfarbe(F:TFarbe):TFarbe;
function Abstand(p1,p2:TPosition):Integer;
function IstFrei(P:TPosition) : Boolean;
function ImBrett(P:TPosition) : Boolean;
function GleichP(P1,P2:TPosition):Boolean;
function PosToStr(P:TPosition) : String;
function StrToPos(S:String) : TPosition;
function ColToStr(c:TFarbe) : String;
procedure Execute(Zug:String);
function ZugListeVon(Farbe:TFarbe):TStringList;
function ImSchach(F:TFarbe):Boolean;
function IstMatt(Farbe:TFarbe; var IstPatt:Boolean):Boolean;
implementation
uses uFEN;
constructor TSchachFigur.Create;
begin
inherited Create;
Position.x:=0; {muss noch gesetzt werden}
Position.y:=0;
Farbe:=weiss;
aktiv:=true;
Typ:=Bauer;
end;
destructor TSchachFigur.Destroy;
begin
inherited destroy;
end;
procedure TSchachFigur.Zeichnen;
begin
end;
function TSchachFigur.KannZiehen(P:TPosition; MitSP:Boolean):Boolean;
begin
Result:=false;
end;
{Ben,Marlon}
procedure TSchachFigur.MoveTo(P:TPosition); //KannZiehen muss vorher geprüft werden
var T:TTyp;
F:TFarbe;
begin
if Brett[P.x,p.y]<>nil then
begin {schlagen}
T:=Brett[P.x,P.y].Typ;
F:=Brett[P.x,P.y].Farbe;
{Anton:}
if (T=Turm) and (F=Weiss) then
begin
if (P.x=8) and (P.y=1) then RochadeWK:=false;
if (P.x=1) and (P.y=1) then RochadeWQ:=false;
end;
if (T=Turm) and (F=Schwarz) then
begin
if (P.x=8) and (P.y=8) then RochadeSK:=false;
if (P.x=1) and (P.y=8) then RochadeSQ:=false;
end;
Dec(AnzahlFiguren[F,T]);
Brett[P.x,P.y].Destroy;
Brett[P.x,P.y]:=nil;
end;
Brett[Position.x,Position.y]:= nil;
Position:=P;
Brett[P.x,P.y]:=self;
enpassantPos.x:=0;
enpassantPos.y:=0;
end;
function TSchachFigur.SchachProbe(P:TPosition):Boolean;
{prüft, ob man nach dem Zug nach P nicht im Schach stünde}
var F,FE:TSchachFigur;
P0,KP0:TPosition;
begin
{merken}
F:=Brett[P.x,P.y];
P0:=Position;
KP0:=KoenigsPosition[Farbe];
{einfaches Probeziehen ohne Move}
Brett[P0.x,P0.y]:=nil;
Brett[P.x,P.y]:=self;
Position:=P;
if (Typ=Bauer) and (F=nil) and (P0.x<>P.x)
then FE:=Brett[P.x,P0.y] {Enpassant-Schlag: geschlagener Bauer}
else FE:=nil;
if Typ=Koenig then KoenigsPosition[Farbe]:=P;
{nicht im Schach?}
Result:=not ImSchach(Farbe);
{zurückziehen}
Position:=P0;
Brett[P0.x,P0.y]:=self;
Brett[P.x,P.y]:=F;
if (Typ=Bauer) and (F=nil) and (P0.x<>P.x)
then Brett[P.x,P0.y]:=FE;
if Typ=Koenig then KoenigsPosition[Farbe]:=P0;
end;
{Jakob,Alexander}
procedure TSchachFigur.AppendZugListe(var L:TStringList);
var x1,y1:Integer;
P:TPosition;
begin
for x1:=1 to 8 do
for y1:=1 to 8 do
begin
P.x:=x1;
P.y:=y1;
if KannZiehen(P,true) then
L.add(PosToStr(Position)+'-'+PosToStr(P)); {Muss optimiert werden}
end;
end;
{*****************************************************************}
function Gegenfarbe(F:TFarbe):TFarbe;
begin
if F = weiss then
result := schwarz
else
result := weiss;
end;
function Abstand(p1,p2:TPosition):Integer;
var x,y:Integer;
begin
x := abs(p1.x - p2.x);
y := abs(p1.y - p2.y);
if x<y then result := y
else result := x;
end;
function IstFrei(P:TPosition) : Boolean;
begin
Result:=(Brett[P.x,P.y]=nil);
end;
function ImBrett(P:TPosition) : Boolean;
begin
Result:=(P.x in [1..8]) and (P.y in [1..8]);
end;
{Carlos}
function PosToStr(P:TPosition) : String;
begin
Result := StrFromColumn(P.x) + IntToStr(P.y);
end;
{Erik, Dario}
function ColToStr(c:TFarbe) : String;
begin
if c = weiss then Result := 'Weiß'
else Result := 'Schwarz';
end;
{Carlos}
function StrToPos(S:String) : TPosition;
var ersterTeil, zweiterTeil : char;
begin
ersterTeil := S[1];
zweiterTeil := S[2];
Result.x := ColumnFromString(ersterTeil);
Result.y := StrToInt(zweiterTeil);
end;
function GleichP(P1,P2:TPosition):Boolean;
begin
Result:=(P1.x=P2.x) and (P1.y=P2.y);
end;
procedure Execute(Zug:String);
var StartPos, ZielPos : TPosition;
begin
StartPos := StrToPos(Zug[1]+Zug[2]);
ZielPos := StrToPos(Zug[4] + Zug[5]);
Brett[StartPos.x, StartPos.y].MoveTo(ZielPos);
end;
{Jakob, Alexander}
function ZugListeVon(Farbe:TFarbe):TStringList;
var x1,y1:Integer;
L:TStringList;
F:TSchachFigur;
begin
L:=TStringList.Create;
for x1:=1 to 8 do
for y1:=1 to 8 do
begin
F:= Brett[x1,y1];
if (F<>nil) and (F.Farbe = Farbe) then
F.AppendZugListe(L);
end;
Result:=L;
end;
{***************************************************************************}
{Anton und Philipp}
function ImSchach(F:TFarbe):Boolean;
var x,y:Integer;
begin
Result:=false;
x:=1;
while (x<=8) and not Result do
begin
y:=1;
while (y<=8) and not Result do
begin
if (Brett[x,y]<>nil) and (Brett[x,y].Farbe<>F) and
Brett[x,y].Kannziehen(Koenigsposition[F],false) {ohne Schachprobe!}
then Result:=true;
inc(y);
end;
inc(x);
end;
end;
{Anton}
function IstMatt(Farbe:TFarbe; var IstPatt:Boolean):Boolean;
var i:Integer;
L:TStringList;
Zug,fen:String;
begin
L:=ZugListeVon(Farbe);
Result:=ImSchach(Farbe);
i:=0;
while Result and (i<L.Count) do {!!!}
begin
Zug:=L.Strings[i];
Fen:=FenfromBoard;
Execute(Zug);
if not ImSchach(Farbe) then Result:=false;
inc(i);
BoardfromFen(Fen);
end;
IstPatt:=not Result and (L.Count = 0);
L.Clear;
L.Destroy;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{:
<b>History : </b><font size=-1><ul>
<li>04/06/10 - Yar - Added to GLScene
(Created by Rustam Asmandiarov aka Predator)
</ul></font>
}
unit GLSArchiveManager;
{$I GLScene.inc}
interface
uses
Classes, SysUtils,
//GLS
GLPersistentClasses, GLApplicationFileIO;
Type
TCompressionLevel = (
clNone,
clFastest,
clDefault,
clMax,
clLevel1,
clLevel2,
clLevel3,
clLevel4,
clLevel5,
clLevel6,
clLevel7,
clLevel8,
clLevel9
);
//****************************************************************************
//Базовый класс для архиваторов
{ TBaseArchive }
TBaseArchive= class(TDataFile)
protected
FFileName: string;
FContentList: TStrings;
FCompressionLevel: TCompressionLevel;
Procedure SetCompressionLevel(aValue: TCompressionLevel); Virtual;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
property ContentList: TStrings read FContentList;
property CompressionLevel: TCompressionLevel
read FCompressionLevel
write SetCompressionLevel default clNone;
procedure Clear; virtual;abstract;
function ContentExists(ContentName: string): boolean;virtual;abstract;
function GetContent(Stream: TStream; index: integer): TStream; overload;virtual;abstract;
function GetContent(ContentName: string): TStream; overload;virtual;abstract;
function GetContent(index: integer): TStream; overload;virtual;abstract;
function GetContentSize(index: integer): integer; overload;virtual;abstract;
function GetContentSize(ContentName: string): integer; overload;virtual;abstract;
procedure AddFromStream(ContentName, Path: string; FS: TStream);virtual;abstract;
procedure AddFromFile(FileName, Path: string);virtual;abstract;
procedure RemoveContent(index: integer); overload;virtual;abstract;
procedure RemoveContent(ContentName: string); overload;virtual;abstract;
procedure Extract(index: integer; NewName: string); overload; virtual;abstract;
procedure Extract(ContentName, NewName: string); overload; virtual;abstract;
end;
TBaseArchiveClass = class of TBaseArchive;
//****************************************************************************
//Классы регистрации архивов, для того что бы по расшырениям архива можно было
//использовать соответсвующий архиватор. Например: GLFilePak,GLFileZLib
{TArchiveFileFormat}
{Запись для зарегестрированного класса}
TArchiveFileFormat = class
public
BaseArchiveClass: TBaseArchiveClass;
Extension: string;
Description: string;
DescResID: Integer;
end;
{TArchiveFileFormatsList}
{Список зарегестрированных классов}
TArchiveFileFormatsList = class(TPersistentObjectList)
public
{ Public Declarations }
destructor Destroy; override;
procedure Add(const Ext, Desc: string; DescID: Integer; AClass:
TBaseArchiveClass);
function FindExt(ext: string): TBaseArchiveClass;
function FindFromFileName(const fileName: string): TBaseArchiveClass;
procedure Remove(AClass: TBaseArchiveClass);
end;
//*****************************************************************************
//Для одновременной работы с несколькими архивами ввел коллекции
{ TLibArchive }
{Итем для работы с одним архивом}
TLibArchive = class(TCollectionItem)
private
{ Private Declarations }
vArchive: TBaseArchive;
ArcClass: TBaseArchiveClass;
FFileName: string;
FName: string;
procedure SetCompressionLevel(aValue: TCompressionLevel);
function GetCompressionLevel: TCompressionLevel;
function GetContentList: TStrings;
procedure SetName(const val: string);
protected
{ Protected Declarations }
function GetDisplayName: string; override;
public
{ Public Declarations }
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
property CompressionLevel: TCompressionLevel
read GetCompressionLevel
write SetCompressionLevel default clDefault;
procedure CreateArchive(FileName: string;
OverwriteExistingFile: boolean = False);
property ContentList: TStrings read GetContentList;
procedure LoadFromFile(aFileName: string); overload;
procedure LoadFromFile(aFileName, aAchiverType: string); overload;
procedure Clear;
function ContentExists(aContentName: string): boolean;
property FileName: string read FFileName;
function GetContent(aindex: integer): TStream; overload;
function GetContent(aContentName: string): TStream; overload;
function GetContentSize(aindex: integer): integer; overload;
function GetContentSize(aContentName: string): integer; overload;
procedure AddFromStream(aContentName, aPath: string; aF: TStream); overload;
procedure AddFromStream(aContentName: string; aF: TStream); overload;
procedure AddFromFile(aFileName, aPath: string); overload;
procedure AddFromFile(aFileName: string); overload;
procedure RemoveContent(aindex: integer); overload;
procedure RemoveContent(aContentName: string); overload;
procedure Extract(aindex: integer; aNewName: string); overload;
procedure Extract(aContentName, aNewName: string); overload;
published
property Name: string read FName write SetName;
end;
{ TLibArchives }
TLibArchives = class(TOwnedCollection)
protected
{ Protected Declarations }
procedure SetItems(index: Integer; const val: TLibArchive);
function GetItems(index: Integer): TLibArchive;
public
{ Public Declarations }
constructor Create(AOwner: TComponent);
function Owner: TPersistent;
function IndexOf(const Item: TLibArchive) : Integer;
function Add: TLibArchive;
function FindItemID(ID: Integer) : TLibArchive;
property Items[index: Integer]: TLibArchive read GetItems
write SetItems; default;
//Ищем архиватор по именыи открытого архива
function GetArchiveByFileName(const AName: string) : TLibArchive;
function GetFileNameOfArchive(aValue: TLibArchive) : string;
//ищем нужный итем
function MakeUniqueName(const nameRoot: string) : string;
function GetLibArchiveByName(const AName: string) : TLibArchive;
function GetNameOfLibArchive(const Archive: TLibArchive) : string;
end;
//*****************************************************************************
//Компонента VCL для работы с архивами.
{ TGLSArchiveManager }
TGLSArchiveManager = class(TComponent)
Private
FArchives: TLibArchives;
Procedure SetArchives(aValue: TLibArchives);
Public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetArchiveByFileName(const aName: string): TLibArchive;
function GetFileNameOfArchive(const aArchive: TLibArchive): string;
function GetContent(aContentName: string): TStream;
function ContentExists(aContentName: string): boolean;
function OpenArchive(aFileName: string): TLibArchive; overload;
function OpenArchive(aFileName, aAchiverType: string): TLibArchive; overload;
procedure CloseArchive(aArchive: TLibArchive);
Published
property Archives: TLibArchives read FArchives write SetArchives;
end;
//****************************************************************************
//Другое
EInvalidArchiveFile = class(Exception);
//Получение класса доступных архиваторов
function GetArchiveFileFormats: TArchiveFileFormatsList;
//Регистрация архиватора.
procedure RegisterArchiveFormat(const AExtension, ADescription: string;
AClass: TBaseArchiveClass);
procedure UnregisterArchiveFormat(AClass: TBaseArchiveClass);
//Получение активного менеджера архивов
//Внимание!!! Работает только для одного Менеджера Архивов
function GetArchiveManager: TGLSArchiveManager;
// GLApplicationFileIO
//Эти функции служат для автоматизации загрузки
//Пользователь вводит LoadFromFile а через эти функции получает результат.
function ArcCreateFileStream(const fileName: string; mode: word): TStream;
function ArcFileStreamExists(const fileName: string): boolean;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
Uses
GLStrings;
var
vArchiveFileFormats: TArchiveFileFormatsList;
vArchiveManager: TGLSArchiveManager;
function GetArchiveFileFormats: TArchiveFileFormatsList;
begin
if not Assigned(vArchiveFileFormats) then
vArchiveFileFormats := TArchiveFileFormatsList.Create;
Result := vArchiveFileFormats;
end;
procedure RegisterArchiveFormat(const AExtension, ADescription: string;
AClass: TBaseArchiveClass);
begin
RegisterClass(AClass);
GetArchiveFileFormats.Add(AExtension, ADescription, 0, AClass);
end;
procedure UnregisterArchiveFormat(AClass: TBaseArchiveClass);
begin
if Assigned(vArchiveFileFormats) then
vArchiveFileFormats.Remove(AClass);
end;
function GetArchiveManager: TGLSArchiveManager;
begin
Result := vArchiveManager;
end;
function ArcCreateFileStream(const fileName: string; mode: word): TStream;
begin
If GetArchiveManager <> nil then
with GetArchiveManager do
if ContentExists(fileName) then
begin
Result := GetContent(fileName);
Exit;
end;
if SysUtils.FileExists(fileName) then begin
Result := TFileStream.Create(FileName, mode);
Exit;
//????
//Не пойму зачем создавать файловый поток когда файл не найден
{ end
else begin
Result := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite);
Exit; }
end;
Result:=nil;
end;
function ArcFileStreamExists(const fileName: string): boolean;
begin
If GetArchiveManager <> nil then
with GetArchiveManager do
if ContentExists(fileName) then
begin
Result:=True;
Exit;
end;
Result := SysUtils.FileExists(fileName);
end;
//******************************************************************************
{ TLibArchive }
constructor TLibArchive.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
FName := TLibArchives(ACollection).MakeUniqueName('LibArchive');
end;
destructor TLibArchive.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TLibArchive.SetCompressionLevel(aValue: TCompressionLevel);
begin
if vArchive = nil then Exit;
vArchive.CompressionLevel := aValue;
end;
function TLibArchive.GetCompressionLevel: TCompressionLevel;
begin
Result := clDefault;
if vArchive = nil then Exit;
Result := vArchive.CompressionLevel;
end;
procedure TLibArchive.CreateArchive(FileName: string;
OverwriteExistingFile: boolean = False);
var
fFile: TFileStream;
begin
if OverwriteExistingFile or not SysUtils.FileExists(FileName) then
begin
fFile := TFileStream.Create(FileName, fmCreate);
fFile.Free;
end;
end;
procedure TLibArchive.LoadFromFile(aFileName: string);
var
ext: string;
begin
ext := LowerCase(ExtractFileExt(aFileName));
Delete(ext,1,1);
LoadFromFile(aFileName, ext);
end;
procedure TLibArchive.LoadFromFile(aFileName, aAchiverType: string);
begin
if not SysUtils.FileExists(aFileName) then
Exit;
ArcClass := GetArchiveFileFormats.FindExt(aAchiverType);
If ArcClass=nil then
begin
raise Exception.Create(ClassName+': Unable to find module archiver to expand '+ aAchiverType);
exit;
end;
vArchive := ArcClass.Create(nil);
vArchive .LoadFromFile(aFileName);
FFileName := aFileName;
end;
procedure TLibArchive.Clear;
begin
if vArchive=nil then Exit;
vArchive.Clear;
vArchive.Free;
ArcClass :=nil;
FFileName := '';
end;
function TLibArchive.ContentExists(aContentName: string): boolean;
begin
Result := false;
if vArchive=nil then Exit;
Result := vArchive.ContentExists(aContentName)
end;
function TLibArchive.GetContent(aindex: integer): TStream;
begin
Result := nil;
if vArchive=nil then Exit;
Result := vArchive.GetContent(aindex)
end;
function TLibArchive.GetContent(aContentName: string): TStream;
begin
Result := nil;
if vArchive=nil then Exit;
Result := vArchive.GetContent(aContentName)
end;
function TLibArchive.GetContentSize(aindex: integer): integer;
begin
Result := -1;
if vArchive=nil then Exit;
Result := vArchive.GetContentSize(aindex)
end;
function TLibArchive.GetContentSize(aContentName: string): integer;
begin
Result := -1;
if vArchive=nil then Exit;
Result := vArchive.GetContentSize(aContentName)
end;
procedure TLibArchive.AddFromStream(aContentName, aPath: string; aF: TStream);
begin
if vArchive=nil then Exit;
vArchive.AddFromStream(aContentName, aPath, aF)
end;
procedure TLibArchive.AddFromStream(aContentName: string; aF: TStream);
begin
if vArchive=nil then Exit;
vArchive.AddFromStream(aContentName, '', aF)
end;
procedure TLibArchive.AddFromFile(aFileName, aPath: string);
begin
if vArchive=nil then Exit;
vArchive.AddFromFile(aFileName, aPath)
end;
procedure TLibArchive.AddFromFile(aFileName: string);
begin
if vArchive=nil then Exit;
vArchive.AddFromFile(aFileName, '')
end;
procedure TLibArchive.RemoveContent(aindex: integer);
begin
if vArchive=nil then Exit;
vArchive.RemoveContent(aindex)
end;
procedure TLibArchive.RemoveContent(aContentName: string);
begin
if vArchive=nil then Exit;
vArchive.RemoveContent(aContentName)
end;
procedure TLibArchive.Extract(aindex: integer; aNewName: string);
begin
if vArchive=nil then Exit;
vArchive.Extract(aindex, aNewName)
end;
procedure TLibArchive.Extract(aContentName, aNewName: string);
begin
if vArchive=nil then Exit;
vArchive.Extract(aContentName, aNewName)
end;
function TLibArchive.GetContentList: TStrings;
begin
Result := nil;
if vArchive=nil then Exit;
Result := vArchive.ContentList;
end;
procedure TLibArchive.SetName(const val: string);
begin
if val <> FName then
begin
if not (csLoading in
TComponent(TLibArchives(Collection).GetOwner).ComponentState) then
begin
if TLibArchives(Collection).GetLibArchiveByName(val) <> Self then
FName := TLibArchives(Collection).MakeUniqueName(val)
else
FName := val;
end
else
FName := val;
end;
end;
function TLibArchive.GetDisplayName: string;
begin
Result := Name;
end;
{ TLibArchives }
procedure TLibArchives.SetItems(index: Integer; const val: TLibArchive);
begin
GetItems(Index).Assign(Val);
end;
function TLibArchives.GetItems(index: Integer): TLibArchive;
begin
Result := TLibArchive(inherited GetItem(Index));
end;
constructor TLibArchives.Create(AOwner: TComponent);
begin
inherited Create(AOwner, TLibArchive);
end;
function TLibArchives.Owner: TPersistent;
begin
Result := GetOwner;
end;
function TLibArchives.IndexOf(const Item: TLibArchive): Integer;
var
I: Integer;
begin
Result := -1;
if Count <> 0 then
for I := 0 to Count - 1 do
if GetItems(I) = Item then
begin
Result := I;
Exit;
end;
end;
function TLibArchives.Add: TLibArchive;
begin
Result := (inherited Add) as TLibArchive;
end;
function TLibArchives.FindItemID(ID: Integer): TLibArchive;
begin
Result := (inherited FindItemID(ID)) as TLibArchive;
end;
function TLibArchives.GetArchiveByFileName(const AName: string): TLibArchive;
var
i: Integer;
Arc: TLibArchive;
begin
for i := 0 to Count - 1 do
begin
Arc := TLibArchive(inherited Items[i]);
if Arc.FileName = AName then
begin
Result := Arc;
Exit;
end;
end;
Result := nil;
end;
function TLibArchives.GetFileNameOfArchive(aValue: TLibArchive): string;
var
ArcIndex: Integer;
begin
ArcIndex := IndexOf(aValue);
if ArcIndex <> -1 then
Result := GetItems(ArcIndex).FileName
else
Result := '';
end;
function TLibArchives.MakeUniqueName(const nameRoot: string): string;
var
i: Integer;
begin
Result := nameRoot;
i := 1;
while GetLibArchiveByName(Result) <> nil do
begin
Result := nameRoot + IntToStr(i);
Inc(i);
end;
end;
function TLibArchives.GetLibArchiveByName(const AName: string): TLibArchive;
var
i: Integer;
Arc: TLibArchive;
begin
for i := 0 to Count - 1 do
begin
Arc := TLibArchive(inherited Items[i]);
if (Arc.Name = AName) then
begin
Result := Arc;
Exit;
end;
end;
Result := nil;
end;
function TLibArchives.GetNameOfLibArchive(const Archive: TLibArchive): string;
var
MatIndex: Integer;
begin
MatIndex := IndexOf(Archive);
if MatIndex <> -1 then
Result := GetItems(MatIndex).Name
else
Result := '';
end;
{ TArchiveFileFormatsList }
//******************************************************************************
destructor TArchiveFileFormatsList.Destroy;
begin
Clean;
inherited Destroy;
end;
procedure TArchiveFileFormatsList.Add(const Ext, Desc: string; DescID: Integer;
AClass: TBaseArchiveClass);
var
newRec: TArchiveFileFormat;
begin
newRec := TArchiveFileFormat.Create;
with newRec do
begin
Extension := AnsiLowerCase(Ext);
BaseArchiveClass := AClass;
Description := Desc;
DescResID := DescID;
end;
inherited Add(newRec);
end;
function TArchiveFileFormatsList.FindExt(ext: string): TBaseArchiveClass;
var
i: Integer;
begin
ext := AnsiLowerCase(ext);
for i := Count - 1 downto 0 do
with TArchiveFileFormat(Items[I]) do
begin
if Extension = ext then
begin
Result := BaseArchiveClass;
Exit;
end;
end;
Result := nil;
end;
function TArchiveFileFormatsList.FindFromFileName(const fileName: string
): TBaseArchiveClass;
var
ext: string;
begin
ext := ExtractFileExt(Filename);
System.Delete(ext, 1, 1);
Result := FindExt(ext);
if not Assigned(Result) then
raise EInvalidArchiveFile.CreateFmt(glsUnknownExtension,
[ext, 'GLFile' + UpperCase(ext)]);
end;
procedure TArchiveFileFormatsList.Remove(AClass: TBaseArchiveClass);
var
i: Integer;
begin
for i := Count - 1 downto 0 do
begin
if TArchiveFileFormat(Items[i]).BaseArchiveClass.InheritsFrom(AClass) then
DeleteAndFree(i);
end;
end;
//******************************************************************************
{ TBaseArchive }
procedure TBaseArchive.SetCompressionLevel(aValue: TCompressionLevel);
begin
if FCompressionLevel <> aValue then
FCompressionLevel := aValue;
end;
constructor TBaseArchive.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FContentList := TStringList.Create;
FCompressionLevel := clDefault;
end;
destructor TBaseArchive.Destroy;
begin
FContentList.Free;
inherited Destroy;
end;
//******************************************************************************
{ TGLSArchiveManager }
constructor TGLSArchiveManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FArchives := TLibArchives.Create(self);
vArchiveManager := Self;
vAFIOCreateFileStream := ArcCreateFileStream;
vAFIOFileStreamExists := ArcFileStreamExists;
end;
destructor TGLSArchiveManager.Destroy;
begin
vArchiveManager := nil;
FArchives.Free;
inherited Destroy;
end;
procedure TGLSArchiveManager.SetArchives(aValue: TLibArchives);
begin
FArchives.Assign(aValue);
end;
function TGLSArchiveManager.GetArchiveByFileName(const aName: string): TLibArchive;
begin
Result := FArchives.GetArchiveByFileName(AName);
end;
function TGLSArchiveManager.GetFileNameOfArchive(const aArchive: TLibArchive): string;
begin
Result := FArchives.GetFileNameOfArchive(aArchive)
end;
function TGLSArchiveManager.GetContent(aContentName: string): TStream;
var
i: integer;
begin
Result := nil;
With FArchives do
for i:=0 to Count-1 do
if Items[i].ContentExists(aContentName) then
begin
Result := Items[i].GetContent(aContentName);
Exit;
end;
end;
function TGLSArchiveManager.ContentExists(aContentName: string): boolean;
var
i: integer;
begin
Result := false;
With FArchives do
for i:=0 to Count-1 do
if Items[i].ContentExists(aContentName) then
begin
Result := Items[i].ContentExists(aContentName);
Exit;
end;
end;
function TGLSArchiveManager.OpenArchive(aFileName: string): TLibArchive;
begin
Result := FArchives.Add;
Result.LoadFromFile(aFileName);
end;
function TGLSArchiveManager.OpenArchive(aFileName, aAchiverType: string
): TLibArchive;
begin
Result := FArchives.Add;
Result.LoadFromFile(aFileName, aAchiverType);
end;
procedure TGLSArchiveManager.CloseArchive(aArchive: TLibArchive);
begin
FArchives.Delete(FArchives.IndexOf(aArchive));
end;
initialization
RegisterClasses([TGLSArchiveManager, TLibArchives]);
finalization
FreeAndNil(vArchiveFileFormats);
end.
|
unit Player.AudioOutput.PCM;
interface
uses Windows,SysUtils,Classes,Player.AudioOutput.Base,MediaProcessing.Definitions;
type
TAudioOutputDecoder_PCM = class (TAudioOutputDecoder)
public
function DecodeToPCM(
const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal;
out aPcmFormat: TPCMFormat;
out aPcmData: pointer; out aPcmDataSize: cardinal):boolean; override;
end;
TPlayerAudioOutput_PCM = class (TPlayerAudioOutputWaveOut)
public
constructor Create; override;
end;
implementation
{ THHAudioOutputDirectX }
function TAudioOutputDecoder_PCM.DecodeToPCM(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal;out aPcmFormat: TPCMFormat; out aPcmData: pointer; out aPcmDataSize: cardinal):boolean;
begin
aPcmData:=aData;
aPcmDataSize:=aDataSize;
aPcmFormat.Channels:=aFormat.AudioChannels;
aPcmFormat.BitsPerSample:=aFormat.AudioBitsPerSample;
aPcmFormat.SamplesPerSec:=aFormat.AudioSamplesPerSec;
result:=true;
end;
{ TPlayerAudioOutput_PCM }
constructor TPlayerAudioOutput_PCM.Create;
begin
inherited Create;
RegisterDecoderClass(stPCM,TAudioOutputDecoder_PCM);
SetStreamType(stPCM);
end;
end.
|
{*******************************************************}
{ }
{ Midas RemoteDataModule Pooler Demo }
{ }
{*******************************************************}
unit pooler;
interface
uses
ComObj, ActiveX, Server_TLB, Classes, SyncObjs, Windows;
type
{
This is the pooler class. It is responsible for managing the pooled RDMs.
It implements the same interface as the RDM does, and each call will get an
unused RDM and use it for the call.
}
TPooler = class(TAutoObject, IPooledRDM)
private
function LockRDM: IPooledRDM;
procedure UnlockRDM(Value: IPooledRDM);
protected
{ IAppServer }
function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall;
function AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer;
Options: Integer; const CommandText: WideString;
var Params: OleVariant; var OwnerData: OleVariant): OleVariant; safecall;
function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall;
function AS_GetProviderNames: OleVariant; safecall;
function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall;
function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer;
var OwnerData: OleVariant): OleVariant; safecall;
procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString;
var Params: OleVariant; var OwnerData: OleVariant); safecall;
end;
{
The pool manager is responsible for keeping a list of RDMs that are being
pooled and for giving out unused RDMs.
}
TPoolManager = class(TObject)
private
FRDMList: TList;
FMaxCount: Integer;
FTimeout: Integer;
FCriticalSection: TCriticalSection;
FSemaphore: THandle;
function GetLock(Index: Integer): Boolean;
procedure ReleaseLock(Index: Integer; var Value: IPooledRDM);
function CreateNewInstance: IPooledRDM;
public
constructor Create;
destructor Destroy; override;
function LockRDM: IPooledRDM;
procedure UnlockRDM(var Value: IPooledRDM);
property Timeout: Integer read FTimeout;
property MaxCount: Integer read FMaxCount;
end;
PRDM = ^TRDM;
TRDM = record
Intf: IPooledRDM;
InUse: Boolean;
end;
var
PoolManager: TPoolManager;
implementation
uses ComServ, srvrdm, SysUtils;
constructor TPoolManager.Create;
begin
FRDMList := TList.Create;
FCriticalSection := TCriticalSection.Create;
FTimeout := 5000;
FMaxCount := 15;
FSemaphore := CreateSemaphore(nil, FMaxCount, FMaxCount, nil);
end;
destructor TPoolManager.Destroy;
var
i: Integer;
begin
FCriticalSection.Free;
for i := 0 to FRDMList.Count - 1 do
begin
PRDM(FRDMList[i]).Intf := nil;
FreeMem(PRDM(FRDMList[i]));
end;
FRDMList.Free;
CloseHandle(FSemaphore);
inherited Destroy;
end;
function TPoolManager.GetLock(Index: Integer): Boolean;
begin
FCriticalSection.Enter;
try
Result := not PRDM(FRDMList[Index]).InUse;
if Result then
PRDM(FRDMList[Index]).InUse := True;
finally
FCriticalSection.Leave;
end;
end;
procedure TPoolManager.ReleaseLock(Index: Integer; var Value: IPooledRDM);
begin
FCriticalSection.Enter;
try
PRDM(FRDMList[Index]).InUse := False;
Value := nil;
ReleaseSemaphore(FSemaphore, 1, nil);
finally
FCriticalSection.Leave;
end;
end;
function TPoolManager.CreateNewInstance: IPooledRDM;
var
p: PRDM;
begin
FCriticalSection.Enter;
try
New(p);
p.Intf := RDMFactory.CreateComObject(nil) as IPooledRDM;
p.InUse := True;
FRDMList.Add(p);
Result := p.Intf;
finally
FCriticalSection.Leave;
end;
end;
function TPoolManager.LockRDM: IPooledRDM;
var
i: Integer;
begin
Result := nil;
if WaitForSingleObject(FSemaphore, Timeout) = WAIT_FAILED then
raise Exception.Create('Server too busy');
for i := 0 to FRDMList.Count - 1 do
begin
if GetLock(i) then
begin
Result := PRDM(FRDMList[i]).Intf;
Exit;
end;
end;
if FRDMList.Count < MaxCount then
Result := CreateNewInstance;
if Result = nil then { This shouldn't happen because of the sempahore locks }
raise Exception.Create('Unable to lock RDM');
end;
procedure TPoolManager.UnlockRDM(var Value: IPooledRDM);
var
i: Integer;
begin
for i := 0 to FRDMList.Count - 1 do
begin
if Value = PRDM(FRDMList[i]).Intf then
begin
ReleaseLock(i, Value);
break;
end;
end;
end;
{
Each call for the server is wrapped in a call to retrieve the RDM, and then
when it is finished it releases the RDM.
}
function TPooler.LockRDM: IPooledRDM;
begin
Result := PoolManager.LockRDM;
end;
procedure TPooler.UnlockRDM(Value: IPooledRDM);
begin
PoolManager.UnlockRDM(Value);
end;
function TPooler.AS_ApplyUpdates(const ProviderName: WideString;
Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer;
var OwnerData: OleVariant): OleVariant;
var
RDM: IPooledRDM;
begin
RDM := LockRDM;
try
Result := RDM.AS_ApplyUpdates(ProviderName, Delta, MaxErrors, ErrorCount, OwnerData);
finally
UnlockRDM(RDM);
end;
end;
function TPooler.AS_DataRequest(const ProviderName: WideString;
Data: OleVariant): OleVariant;
var
RDM: IPooledRDM;
begin
RDM := LockRDM;
try
Result := RDM.AS_DataRequest(ProviderName, Data);
finally
UnlockRDM(RDM);
end;
end;
procedure TPooler.AS_Execute(const ProviderName, CommandText: WideString;
var Params, OwnerData: OleVariant);
var
RDM: IPooledRDM;
begin
RDM := LockRDM;
try
RDM.AS_Execute(ProviderName, CommandText, Params, OwnerData);
finally
UnlockRDM(RDM);
end;
end;
function TPooler.AS_GetParams(const ProviderName: WideString;
var OwnerData: OleVariant): OleVariant;
var
RDM: IPooledRDM;
begin
RDM := LockRDM;
try
Result := RDM.AS_GetParams(ProviderName, OwnerData);
finally
UnlockRDM(RDM);
end;
end;
function TPooler.AS_GetProviderNames: OleVariant;
var
RDM: IPooledRDM;
begin
RDM := LockRDM;
try
Result := RDM.AS_GetProviderNames;
finally
UnlockRDM(RDM);
end;
end;
function TPooler.AS_GetRecords(const ProviderName: WideString;
Count: Integer; out RecsOut: Integer; Options: Integer;
const CommandText: WideString; var Params,
OwnerData: OleVariant): OleVariant;
var
RDM: IPooledRDM;
begin
RDM := LockRDM;
try
Result := RDM.AS_GetRecords(ProviderName, Count, RecsOut, Options,
CommandText, Params, OwnerData);
finally
UnlockRDM(RDM);
end;
end;
function TPooler.AS_RowRequest(const ProviderName: WideString;
Row: OleVariant; RequestType: Integer;
var OwnerData: OleVariant): OleVariant;
var
RDM: IPooledRDM;
begin
RDM := LockRDM;
try
Result := RDM.AS_RowRequest(ProviderName, Row, RequestType, OwnerData);
finally
UnlockRDM(RDM);
end;
end;
initialization
PoolManager := TPoolManager.Create;
TAutoObjectFactory.Create(ComServer, TPooler, Class_Pooler, ciMultiInstance, tmFree);
finalization
PoolManager.Free;
end.
|
{ **********************************************************************}
{ }
{ DeskMetrics DLL - dskMetricsCommon.pas }
{ Copyright (c) 2010-2011 DeskMetrics Limited }
{ }
{ http://deskmetrics.com }
{ http://support.deskmetrics.com }
{ }
{ support@deskmetrics.com }
{ }
{ This code is provided under the DeskMetrics Modified BSD License }
{ A copy of this license has been distributed in a file called }
{ LICENSE with this source code. }
{ }
{ **********************************************************************}
unit dskMetricsCommon;
interface
uses
Windows, SysUtils;
{ Windows API Functions }
function _LoadKernelFunc(const FFuncName: string): Pointer;
{ Strings Functions }
function _GetLongPath(FPath: string): string;
{ Executable Version }
function _GetExecutableVersion(const FFilePath: string): string;
implementation
uses
dskMetricsConsts;
function _LoadKernelFunc(const FFuncName: string): Pointer;
begin
try
{$IFDEF WARNDIRS}{$WARN UNSAFE_TYPE OFF}{$ENDIF}
Result := GetProcAddress(GetModuleHandle('kernel32.dll'), PChar(FFuncName));
{$IFDEF WARNDIRS}{$WARN UNSAFE_TYPE ON}{$ENDIF}
except
Result := nil;
end;
end;
function _GetLongPath(FPath: string): string;
var
nPos:Integer;
hSearch:THandle;
w32FindData:TWin32FindData;
bIsBackSlash:Boolean;
begin
try
FPath := ExpandFileName(FPath);
Result := ExtractFileDrive(FPath);
nPos := Length(Result);
if Length(FPath) <= nPos then
Exit;
if FPath[nPos+1]= '\' then
begin
Result := Result+'\';
Inc(nPos);
end;
Delete(FPath,1,nPos);
repeat
nPos := Pos('\',FPath);
bIsBackSlash := nPos > 0;
if not(bIsBackSlash) then
nPos := Length(FPath)+1;
hSearch := FindFirstFile(PChar(Result+Copy(FPath,1,nPos-1)),w32FindData);
if hSearch<>INVALID_HANDLE_VALUE then
begin
try
Result := Result+w32FindData.cFileName;
if bIsBackSlash then
Result := Result+'\';
finally
Windows.FindClose(hSearch);
end;
end
else
begin
Result := Result+FPath;
Break;
end;
Delete(FPath,1,nPos);
until Length(FPath)=0;
except
Result := '';
end;
end;
function _GetExecutableVersion(const FFilePath: string): string;
var
InfoSize, Wnd: DWORD;
VerBuf: Pointer;
FI: PVSFixedFileInfo;
VerSize: DWORD;
begin
Result := NULL_STR;
try
InfoSize := GetFileVersionInfoSize(PChar(FFilePath), Wnd);
if InfoSize <> 0 then
begin
VerBuf := AllocMem(InfoSize);
try
if GetFileVersionInfo(PChar(FFilePath), Wnd, InfoSize, VerBuf) then
begin
if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then
Result := Format('%d.%d',[FI.dwFileVersionMS shr 16 and $0000FFFF, FI.dwFileVersionMS and $0000FFFF])
end;
finally
FreeMem(VerBuf);
end;
end;
except
Result := NULL_STR;
end;
end;
end.
|
unit ColorClass;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types,
FMX.Objects, FMX.StdCtrls, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math,
System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects;
const
SOLID_PRIMARY_COLOR: TAlphaColor = ($FF1867C0);
SOLID_ERROR_COLOR: TAlphaColor = ($FFFF5252);
SOLID_NORMAL_COLOR: TAlphaColor = ($FFF5F5F5);
SOLID_SECONDARY_COLOR: TAlphaColor = ($FF5CBBF6);
SOLID_WARNING_COLOR: TAlphaColor = ($FFFB8C00);
SOLID_SUCCESS_COLOR: TAlphaColor = ($FF4CAF50);
TRANSPARENT_PRIMARY_COLOR: TAlphaColor = ($1E1867C0);
TRANSPARENT_ERROR_COLOR: TAlphaColor = ($1EFF5252);
TRANSPARENT_NORMAL_COLOR: TAlphaColor = ($1E323232);
TRANSPARENT_SECONDARY_COLOR: TAlphaColor = ($1E5CBBF6);
TRANSPARENT_WARNING_COLOR: TAlphaColor = ($1EFB8C00);
TRANSPARENT_SUCCESS_COLOR: TAlphaColor = ($1E4CAF50);
SOLID_BLACK : TAlphaColor = ($FF323232);
SOLID_WHITE : TAlphaColor = ($FFFFFFFF);
TRANSPARENT_BLACK : TAlphaColor = ($1E323232);
TRANSPARENT_WHITE : TAlphaColor = ($1EFFFFFF);
type
TColorClass = (Primary, Error, Normal, Secondary, Warning, Success, Custom);
implementation
end.
|
unit slmlog;
interface
function SaveToLogFile(const ALogFile, ALog : string; AFlag: byte = 0): boolean;
implementation
uses SysUtils, Windows;
var
cs : TRTLCriticalSection;
function SaveToLogFile(const ALogFile, ALog : string; AFlag: byte = 0): boolean;
var
F : TextFile;
begin
result := false;
EnterCriticalSection(cs); //关键代码段
try try
AssignFile(F, ALogFile);
if FileExists(ALogFile) then Append(F) else ReWrite(F);
case AFlag of
1: begin
WriteLn(F, ''); //换行
Write(F, Format('%s %-16s %s', [FormatDateTime('yyyy-MM-dd hh:mm:ss.zzz', now), ChangeFileExt(ExtractFileName(GetModuleName(hInstance)), ''), ALog])); //一行的开始
end;
2: Write(F, Format(' %s', [ALog])); //一行的中间内容
3: WriteLn(F, Format(' %s', [ALog])); //一行的结束
else
WriteLn(F, Format('%s %-16s %s', [FormatDateTime('yyyy-MM-dd hh:mm:ss.zzz', now), //单独一行
ChangeFileExt(ExtractFileName(GetModuleName(hInstance)), ''),
ALog]));
end;
CloseFile(F);
result := true;
except
end;
finally
LeaveCriticalSection(cs);
end;
end;
initialization
InitializeCriticalSection(cs);
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DSAzDlgPageBlob;
interface
uses
Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, System.Generics.Collections, Vcl.Graphics,
Vcl.Grids, Vcl.StdCtrls, Vcl.ValEdit;
type
TAzPageBlob = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
lblBlobName: TLabel;
edtBlobName: TEdit;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
edtContentType: TEdit;
edtLanguage: TEdit;
edtMD5: TEdit;
edtEncoding: TEdit;
vleMeta: TValueListEditor;
btnAddMetadata: TButton;
btnDelMetadata: TButton;
lblContentLength: TLabel;
edtContentLength: TEdit;
cbUnit: TComboBox;
Label5: TLabel;
edtSequence: TEdit;
procedure btnAddMetadataClick(Sender: TObject);
procedure btnDelMetadataClick(Sender: TObject);
procedure edtBlobNameChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function GetBlobName: String;
function GetContentType: String;
function GetContentLanguage: String;
function GetContentMD5: String;
function GetContentEncoding: String;
function GetContentLength: Int64;
function GetSequenceNumber: Int64;
procedure AssignMetadata(const meta: TDictionary<String, String>);
procedure PopulateWithMetadata(const meta: TDictionary<String, String>);
function RawMetadata: TStrings;
end;
implementation
uses Vcl.Dialogs, System.SysUtils;
{$R *.dfm}
procedure TAzPageBlob.AssignMetadata(
const meta: TDictionary<String, String>);
var
I, Count: Integer;
key, value: String;
begin
meta.Clear;
Count := vleMeta.Strings.Count;
for I := 0 to Count - 1 do
begin
key := vleMeta.Strings.Names[I];
value := vleMeta.Strings.ValueFromIndex[I];
if (Length(key) > 0) and (Length(value) > 0) then
meta.Add(key, value);
end;
end;
procedure TAzPageBlob.btnAddMetadataClick(Sender: TObject);
begin
vleMeta.InsertRow('', '', true);
vleMeta.SetFocus;
end;
procedure TAzPageBlob.btnDelMetadataClick(Sender: TObject);
var
row: Integer;
begin
row := vleMeta.Row;
if (row > 0) and (row < vleMeta.RowCount) then
vleMeta.DeleteRow(row);
end;
procedure TAzPageBlob.edtBlobNameChange(Sender: TObject);
begin
OKBtn.Enabled := Length(edtBlobName.Text) > 0;
end;
function TAzPageBlob.GetBlobName: String;
begin
Result := edtBlobName.Text;
end;
function TAzPageBlob.GetContentEncoding: String;
begin
Result := edtEncoding.Text;
end;
function TAzPageBlob.GetContentLanguage: String;
begin
Result := edtLanguage.Text;
end;
function TAzPageBlob.GetContentLength: Int64;
begin
Result := StrToInt64(edtContentLength.Text);
case cbUnit.ItemIndex of
1: Result := Result * 1024;
2: Result := Result * 1024 * 1024;
3: Result := Result * 1024 * 1024 * 1024;
end;
end;
function TAzPageBlob.GetContentMD5: String;
begin
Result := edtMD5.Text;
end;
function TAzPageBlob.GetContentType: String;
begin
Result := edtContentType.Text;
end;
function TAzPageBlob.GetSequenceNumber: Int64;
begin
Result := StrToInt64(edtSequence.Text);
end;
procedure TAzPageBlob.PopulateWithMetadata(
const meta: TDictionary<String, String>);
var
keys: TArray<String>;
I, Count: Integer;
begin
vleMeta.Strings.Clear;
keys := meta.Keys.ToArray;
Count := meta.Keys.Count;
for I := 0 to Count - 1 do
vleMeta.Values[keys[I]] := meta.Items[keys[I]];
end;
function TAzPageBlob.RawMetadata: TStrings;
begin
Result := vleMeta.Strings
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.ComStrs;
interface
resourcestring
sTabFailClear = 'Failed to clear tab control';
sTabFailDelete = 'Failed to delete tab at index %d';
sTabFailRetrieve = 'Failed to retrieve tab at index %d';
sTabFailGetObject = 'Failed to get object at index %d';
sTabFailSet = 'Failed to set tab "%s" at index %d';
sTabFailSetObject = 'Failed to set object at index %d';
sTabMustBeMultiLine = 'MultiLine must be True when TabPosition is tpLeft or tpRight';
sInvalidLevel = 'Invalid item level assignment';
sInvalidLevelEx = 'Invalid level (%d) for item "%s"';
sInvalidIndex = 'Invalid index';
sInsertError = 'Unable to insert an item';
sInvalidOwner = 'Invalid owner';
sUnableToCreateColumn = 'Unable to create new column';
sUnableToCreateItem = 'Unable to create new item';
sRichEditInsertError = 'RichEdit line insertion error';
sRichEditLoadFail = 'Failed to Load Stream';
sRichEditSaveFail = 'Failed to Save Stream';
sTooManyPanels = 'StatusBar cannot have more than 64 panels';
sHKError = 'Error assigning Hot-Key to %s. %s';
sHKInvalid = 'Hot-Key is invalid';
sHKInvalidWindow = 'Window is invalid or a child window';
sHKAssigned = 'Hot-Key is assigned to another window';
sUDAssociated = '%s is already associated with %s';
sPageIndexError = '%d is an invalid PageIndex value. PageIndex must be ' +
'between 0 and %d';
sInvalidComCtl32 = 'This control requires version 4.70 or greater of COMCTL32.DLL';
sDateTimeMax = 'Date exceeds maximum of %s';
sDateTimeMin = 'Date is less than minimum of %s';
sNeedAllowNone = 'You must be in ShowCheckbox mode to set to this date';
sFailSetCalDateTime = 'Failed to set calendar date or time';
sFailSetCalMaxSelRange = 'Failed to set maximum selection range';
sFailSetCalMinMaxRange = 'Failed to set calendar min/max range';
sCalRangeNeedsMultiSelect = 'Date range can only be used in multiselect mode';
sFailsetCalSelRange = 'Failed to set calendar selected range';
implementation
end.
|
unit PluginTypes;
interface
Uses Windows, Classes, Graphics;
Type
TGetStreamFunc = function (FName:ShortString): TStream;
TStreamExistsFunc = function (FName:ShortString): Boolean;
TGetProcFunc = function (FuncName:ShortString): Pointer;
TDecompressFunc = function (Src:TMemoryStream): TMemoryStream;
TCompressFunc = function (Src:TStream): TMemoryStream;
TTextInfoRec = packed record
Factor, Offset, Size, Start, FileOffset: Integer;
UsedScriptOffset: Boolean;
end;
TErrorMessageFunc = procedure (Msg:String);
TCosmoPlugin = packed record
MainWindow: THandle;
FF7Path: Shortstring;
CurFile: Shortstring;
InputStream: TGetStreamFunc;
LZS_Decompress: TDecompressFunc;
LZS_Compress: TCompressFunc;
Log: TErrorMessageFunc;
InputExists: TStreamExistsFunc;
GetProcedure: TGetProcFunc;
end;
TExtractTextFunc = function (Src:TMemoryStream;var Table:TList;var Info:TTextInfoRec): TMemoryStream;
TDecodeTextFunc = function (Src:TStream): String;
TEncodeTextFunc = function (Src:String): TMemoryStream;
TGetBackgroundFunc = function (Src:TMemoryStream): TBitmap;
TLGPRepairFunc = procedure (FName:ShortString);
TLGPCreateFunc = procedure (SrcFolder,OutputFile:ShortString;DeleteOriginal,UseErrorCheck:Boolean);
TLGPPackFunc = procedure (FName:ShortString);
TGetPluginFunc = procedure (Functions:TStringList);
TPluginFunc = function (Data:TCosmoPlugin): Integer;
TCombinerFunc = function(Original:TMemoryStream;NewForeground,NewBackground:TBitmap):TMemoryStream;
Const
PLUG_SUCCESS = $1;
PLUG_CLOSEFILE = $2;
PLUG_LOADFILE = $4;
implementation
end.
|
{******************************************}
{ TeeChart Delphi Component Library }
{ SQL Query Chart Demo }
{ Copyright (c) 1995-2001 by David Berneda }
{ All rights reserved }
{******************************************}
unit sqlbars;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids, DB,
DBTables, Chart, Series, DbChart, Teengine, TeeProcs;
type
TSQLBarsForm = class(TForm)
DBChart1: TDBChart;
DataSource1: TDataSource;
Panel1: TPanel;
BitBtn1: TBitBtn;
BarSeries1: TBarSeries;
Query1: TQuery;
Panel2: TPanel;
Memo1: TMemo;
BitBtn2: TBitBtn;
ComboBox1: TComboBox;
Label1: TLabel;
CBRandomBar: TCheckBox;
Panel3: TPanel;
DBGrid1: TDBGrid;
Label2: TLabel;
procedure BitBtn2Click(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DBChart1ClickLegend(Sender: TCustomChart;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure BarSeries1Click(Sender: TChartSeries; ValueIndex: Integer;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure BarSeries1GetBarStyle(Sender: TCustomBarSeries;
ValueIndex: Longint; var TheBarStyle: TBarStyle);
procedure CBRandomBarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
Uses UDemUtil;
procedure TSQLBarsForm.BitBtn2Click(Sender: TObject);
begin { rerun the SQL query }
Screen.Cursor:=crHourGlass;
try
Query1.Close;
Query1.Sql:=Memo1.Lines;
Query1.Open;
finally
Screen.Cursor:=crDefault;
end;
end;
procedure TSQLBarsForm.ComboBox1Change(Sender: TObject);
begin
if BarSeries1 is TCustomBarSeries then
BarSeries1.BarStyle:=TBarStyle(ComboBox1.ItemIndex); { <-- change bar style }
end;
procedure TSQLBarsForm.FormCreate(Sender: TObject);
begin
ComboBox1.ItemIndex:=Ord(BarSeries1.BarStyle); { <-- set combobox1 }
end;
procedure TSQLBarsForm.DBChart1ClickLegend(Sender: TCustomChart;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
With DBChart1.Legend do Color:=EditColor(Self,Color);
end;
procedure TSQLBarsForm.BarSeries1Click(Sender: TChartSeries;
ValueIndex: Integer; Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
With BarSeries1 do
ValueColor[ValueIndex]:=EditColor(Self,ValueColor[ValueIndex]);
end;
procedure TSQLBarsForm.BarSeries1GetBarStyle(Sender: TCustomBarSeries;
ValueIndex: Longint; var TheBarStyle: TBarStyle);
begin
if CBRandomBar.Checked then
TheBarStyle:=TBarStyle(Random(1+Ord(High(TBarStyle))));
end;
procedure TSQLBarsForm.CBRandomBarClick(Sender: TObject);
begin
ComboBox1.Enabled:=not CBRandomBar.Checked;
DBChart1.Repaint;
end;
end.
|
unit Controller.Register.ToFuel;
interface
uses
Model.Register.ToFuel, View.List.ToFuel, View.Register.ToFuel,
Controller.Register.Base, View.Report.ToFuel, System.Classes;
type
TToFuel = class(TRegister<TToFuel, TdtmdlToFuel, TfrmListToFuel,
TfrmRegisterToFuel>)
private
FViewReport: TfrmReportToFuel;
procedure ShowReport;
protected
procedure AssignPointer; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{ TToFuel }
procedure TToFuel.AssignPointer;
begin
inherited;
List.OnShowReport := Self.ShowReport;
end;
constructor TToFuel.Create(AOwner: TComponent);
begin
inherited;
FViewReport := TfrmReportToFuel.Create(Self);
end;
destructor TToFuel.Destroy;
begin
FViewReport.DisposeOf;
inherited;
end;
procedure TToFuel.ShowReport;
begin
Model.OpenReport;
FViewReport.ShowReport;
end;
end.
|
unit oPKIEncryptionEngine;
interface
uses
System.Classes,
System.SysUtils,
System.Win.Registry,
Winapi.Windows,
wcrypt2,
WinSCard,
oPKIEncryption,
oPKIEncryptionEx,
TRPCB;
type
TPKIEncryptionEngine = class(TInterfacedObject, IPKIEncryptionEngine, IPKIEncryptionEngineEx)
private
fCSPName: string;
fHashAlgorithm: TPKIHashAlgorithm;
fProviderHandle: HCRYPTPROV; // Provider handle - retrieved once on Create
fRPCBroker: TRPCBroker; // So we can do method calls to VistA as current signed on user
fCurrentPIN: string; // Updated everytime ValidatePIN is called so SignData can reuse it
fOnLogEvent: TPKIEncryptionLogEvent; // Built in generic logging capability - See property OnLogEvent in IPKIEncryptionEngine
procedure fLogEvent(const aMessage: string);
procedure setOnLogEvent(const aOnLogEvent: TPKIEncryptionLogEvent);
// Internal methods
procedure checkSignature(aDataString, aSignatureString: string; aDataTimeSigned: PFileTime = nil);
procedure checkCertChain(aPCertContext: PCCERT_CONTEXT);
procedure checkCertRevocation(aPCertContext: PCCERT_CONTEXT);
procedure hashBuffer(aBuffer: string; var aHashText: AnsiString; var aHashValue: AnsiString; var aHashHex: AnsiString);
procedure setVistASAN(aNewSAN: string);
procedure setCSPName(const aValue: string);
procedure setHashAlgorithm(const aValue: string);
procedure setupCryptoServiceProvider;
function getCertContext: PCCERT_CONTEXT;
function getIsValidPIN(const aPKIPIN: string; var aMessage: string): boolean;
// Methods for the IPKIEncryptionEngine interface properties
function getIsCardReaderReady: boolean;
function getSANFromCard: string;
function getSANFromVistA: string;
function getVistAUserName: string;
function getSANLink: TPKISANLink;
function getEngineVersion: string;
function getCSPName: string;
function getHashAlgorithm: string;
procedure DisplayProviders;
procedure GetCertificates(aList: TStrings);
procedure SignData(aPKIEncryptionData: IPKIEncryptionData);
procedure HashData(aPKIEncryptionData: IPKIEncryptionData);
procedure ValidateSignature(aPKIEncryptionSignature: IPKIEncryptionSignature);
procedure SaveSignature(aPKIEncryptionData: IPKIEncryptionData);
procedure LinkSANtoVistA;
procedure ClearPIN;
public
constructor Create(aRPCBroker: TRPCBroker);
destructor Destroy; override;
end;
implementation
uses
XLFMime,
StrUtils,
oPKIEncryptionData,
oPKIEncryptionCertificate;
{ TPKIEncryption }
constructor TPKIEncryptionEngine.Create(aRPCBroker: TRPCBroker);
begin
inherited Create;
fRPCBroker := aRPCBroker;
fOnLogEvent := fLogEvent;
fCurrentPIN := '';
setupCryptoServiceProvider; // Gets info from registry
if not CryptAcquireContextA(@fProviderHandle, nil, nil, PKI_PROVIDER_TYPE, 0) then
// This tries again but will create the missing key set if that's the problem
if not CryptAcquireContextA(@fProviderHandle, nil, nil, PKI_PROVIDER_TYPE, CRYPT_NEWKEYSET) then
// We've got bigger issues, let's not dork around
raise EPKIEncryptionError.Create(getLastSystemError);
end;
destructor TPKIEncryptionEngine.Destroy;
begin
if fProviderHandle <> 0 then
CryptReleaseContext(fProviderHandle, 0);
inherited;
end;
procedure TPKIEncryptionEngine.fLogEvent(const aMessage: string);
begin
// Prevents nil pointer when not using logging
end;
procedure TPKIEncryptionEngine.setupCryptoServiceProvider;
var
aRegistry: TRegistry;
const
KEY_32 = '\SOFTWARE\vista\PKIEngine';
KEY_64 = '\SOFTWARE\Wow6432Node\vista\PKIEngine';
begin
aRegistry := TRegistry.Create(KEY_READ);
try
aRegistry.RootKey := HKEY_LOCAL_MACHINE;
try
if aRegistry.KeyExists(KEY_32) then
begin
aRegistry.OpenKeyReadOnly(KEY_32);
setCSPName(aRegistry.ReadString('CSPName'));
setHashAlgorithm(aRegistry.ReadString('HashAlgorithm'));
end
else if aRegistry.KeyExists(KEY_64) then
begin
aRegistry.OpenKeyReadOnly(KEY_64);
setCSPName(aRegistry.ReadString('CSPName'));
setHashAlgorithm(aRegistry.ReadString('HashAlgorithm'));
end
else
begin
setCSPName('ActivClient Cryptographic Service Provider');
setHashAlgorithm('SHA1RSA');
end;
except
raise EPKIEncryptionError.Create('Unable to properly setup the Crypto Service Provider (CSP)');
end;
finally
aRegistry.CloseKey;
aRegistry.Free;
end;
end;
procedure TPKIEncryptionEngine.setCSPName(const aValue: string);
begin
fCSPName := aValue;
end;
procedure TPKIEncryptionEngine.setHashAlgorithm(const aValue: string);
var
aNewAlgorithm: TPKIHashAlgorithm;
begin
for aNewAlgorithm := Low(TPKIHashAlgorithm) to High(TPKIHashAlgorithm) do
if CompareText(PKI_HASH_ALGORITHM[aNewAlgorithm], aValue) = 0 then
begin
fHashAlgorithm := aNewAlgorithm;
Exit;
end;
raise EPKIEncryptionError.CreateFmt('Invalid Hash Algorithm ''%s''', [aValue]);
end;
procedure TPKIEncryptionEngine.setOnLogEvent(const aOnLogEvent: TPKIEncryptionLogEvent);
begin
if Assigned(aOnLogEvent) then
begin
fOnLogEvent := aOnLogEvent;
fOnLogEvent(Format('%s logging started', [ClassName]));
fOnLogEvent(Format('%s version: %s', [ClassName, getEngineVersion]));
end
else
begin
fOnLogEvent(Format('%s logging stopped', [ClassName]));
fOnLogEvent := fLogEvent; // aka the bit bucket
end;
end;
procedure TPKIEncryptionEngine.setVistASAN(aNewSAN: string);
begin
fRPCBroker.RemoteProcedure := 'XUS PKI SET UPN';
fRPCBroker.Param[0].PType := literal;
fRPCBroker.Param[0].value := aNewSAN;
fRPCBroker.Call;
if fRPCBroker.Results.Count = 0 then
raise EPKIEncryptionError.Create(DLG_89802049);
if StrToIntDef(fRPCBroker.Results[0], 0) <> 1 then
raise EPKIEncryptionError.Create(DLG_89802049);
end;
procedure TPKIEncryptionEngine.checkCertChain(aPCertContext: PCCERT_CONTEXT);
var
aChainEngine: HCERTCHAINENGINE;
aChainContext: PCCERT_CHAIN_CONTEXT;
aEnhkeyUsage: CERT_ENHKEY_USAGE;
aCertUsage: CERT_USAGE_MATCH;
aChainPara: CERT_CHAIN_PARA;
aChainConfig: CERT_CHAIN_ENGINE_CONFIG;
i: integer;
begin
try
try
aEnhkeyUsage.CUsageIdentifier := 0;
aEnhkeyUsage.RgpszUsageIdentifier := nil;
aCertUsage.DwType := USAGE_MATCH_TYPE_AND;
aCertUsage.Usage := aEnhkeyUsage;
aChainPara.CbSize := Sizeof(aChainPara);
aChainPara.RequestedUsage := aCertUsage;
aChainConfig.CbSize := Sizeof(CERT_CHAIN_ENGINE_CONFIG);
aChainConfig.HRestrictedRoot := nil;
aChainConfig.HRestrictedTrust := nil;
aChainConfig.HRestrictedOther := nil;
aChainConfig.CAdditionalStore := 0;
aChainConfig.RghAdditionalStore := nil;
aChainConfig.DwFlags := CERT_CHAIN_REVOCATION_CHECK_CHAIN;
aChainConfig.DwUrlRetrievalTimeout := 30000;
aChainConfig.MaximumCachedCertificates := 0;
aChainConfig.CycleDetectionModulus := 0;
// Create the nondefault certificate chain engine
if CertCreateCertificateChainEngine(@aChainConfig, aChainEngine) then
fOnLogEvent('Chain Engine Created')
else
raise EPKIEncryptionError.Create(getLastSystemError);
// Build a chain using CertGetCertificateChain and the certificate retrieved
if CertGetCertificateChain(aChainEngine, aPCertContext, nil, nil, @aChainPara, CERT_CHAIN_REVOCATION_CHECK_CHAIN, nil, aChainContext) then
fOnLogEvent('The Chain Context has been created')
else
raise EPKIEncryptionError.Create(getLastSystemError);
// Display some of the contents of the chain
fOnLogEvent('The size of the chain context is ' + IntToStr(aChainContext.CbSize));
fOnLogEvent(IntToStr(aChainContext.CChain) + ' simple chains found.');
i := aChainContext.TrustStatus.DwErrorStatus;
fOnLogEvent('Error status for the chain: ' + IntToStr(i));
case i of
CERT_TRUST_NO_ERROR:
fOnLogEvent('No error found for this certificate or chain');
CERT_TRUST_IS_NOT_TIME_VALID:
raise EPKIEncryptionError.Create(DLG_89802020); // 'This certificate or one of the certificates in the certificate chain is not time-valid ');
CERT_TRUST_IS_NOT_TIME_NESTED:
raise EPKIEncryptionError.Create(DLG_89802023); // 'Certificates in the chain are not properly time - nested');
CERT_TRUST_IS_REVOKED:
raise EPKIEncryptionError.Create(DLG_89802032); // 'Trust for this certificate or one of the certificates in the certificate chain has been revoked');
CERT_TRUST_IS_NOT_SIGNATURE_VALID:
raise EPKIEncryptionError.Create(DLG_89802029); // 'The certificate or one of the certificates in the certificate chain does not have a valid signature');
CERT_TRUST_IS_NOT_VALID_FOR_USAGE:
raise EPKIEncryptionError.Create(DLG_89802030); // 'The certificate or certificate chain is not valid in its proposed usage');
CERT_TRUST_IS_UNTRUSTED_ROOT:
raise EPKIEncryptionError.Create(DLG_89802025); // 'The certificate or certificate chain is based on an untrusted root');
CERT_TRUST_REVOCATION_STATUS_UNKNOWN:
raise EPKIEncryptionError.Create(DLG_89802026); // 'The revocation status of the certificate or one of the certificates in the certificate chain is unknown');
CERT_TRUST_IS_CYCLIC:
raise EPKIEncryptionError.Create(DLG_89802027); // 'One of the certificates in the chain was issued by a certification authority that the original certificate had certified');
CERT_TRUST_IS_PARTIAL_CHAIN:
raise EPKIEncryptionError.Create(DLG_89802028); // 'The certificate chain is not complete');
CERT_TRUST_CTL_IS_NOT_TIME_VALID:
raise EPKIEncryptionError.Create(DLG_89802020); // 'A CTL used to create this chain was not time-valid');
CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID:
raise EPKIEncryptionError.Create(DLG_89802029); // 'A CTL used to create this chain did not have a valid signature');
CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE:
raise EPKIEncryptionError.Create(DLG_89802030); // 'A CTL used to create this chain is not valid for this usage');
else
raise EPKIEncryptionError.CreateFmt(DLG_89802010 + 'An unknown error code returned from PChainContext.TrustStatus.DwErrorStatus [%d]', [i]);
end;
i := aChainContext.TrustStatus.DwInfoStatus;
fOnLogEvent('Info status for the chain: ' + IntToStr(i));
if (i and CERT_TRUST_HAS_EXACT_MATCH_ISSUER) = CERT_TRUST_HAS_EXACT_MATCH_ISSUER then
fOnLogEvent('An exact match issuer certificate has been found for this certificate.');
if (i and CERT_TRUST_HAS_KEY_MATCH_ISSUER) = CERT_TRUST_HAS_KEY_MATCH_ISSUER then
fOnLogEvent('A key match issuer certificate has been found for this certificate.');
if (i and CERT_TRUST_HAS_NAME_MATCH_ISSUER) = CERT_TRUST_HAS_NAME_MATCH_ISSUER then
fOnLogEvent('A name match issuer certificate has been found for this certificate.');
if (i and CERT_TRUST_IS_SELF_SIGNED) = CERT_TRUST_IS_SELF_SIGNED then
fOnLogEvent('This certificate is self-signed.');
if (i and CERT_TRUST_HAS_PREFERRED_ISSUER) = CERT_TRUST_HAS_PREFERRED_ISSUER then
fOnLogEvent('This certificate has a preferred issuer.');
if (i and CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY) = CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY then
fOnLogEvent('An Issuance Chain Policy exists.');
if (i and CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS) = CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS then
fOnLogEvent('A valid name contraints for all namespaces, including UPN.');
if (i and CERT_TRUST_IS_COMPLEX_CHAIN) = CERT_TRUST_IS_COMPLEX_CHAIN then
fOnLogEvent('The certificate chain created is a complex chain.');
fOnLogEvent('Certificate Chain Check OK');
except
on E: Exception do
begin
fOnLogEvent('Certificate Chain Check Failure');
fOnLogEvent(E.Message);
raise;
end;
end;
finally
if aChainEngine <> 0 then
CertFreeCertificateChainEngine(aChainEngine);
if aChainContext <> nil then
CertFreeCertificateChain(aChainContext);
end;
end;
procedure TPKIEncryptionEngine.checkCertRevocation(aPCertContext: PCCERT_CONTEXT);
var
aRevStatus: CERT_REVOCATION_STATUS;
argpvContext: array [0 .. 3] of pointer;
i: integer;
begin
try
aRevStatus.CbSize := Sizeof(aRevStatus);
aRevStatus.dwIndex := 0;
aRevStatus.dwError := 0;
for i := 0 to 3 do
argpvContext[i] := nil;
argpvContext[0] := aPCertContext;
if CertVerifyRevocation(PKI_ENCODING_TYPE, CERT_CONTEXT_REVOCATION_TYPE, 1, @argpvContext[0], CERT_VERIFY_REV_SERVER_OCSP_FLAG, nil, @aRevStatus) then
fOnLogEvent('OCSP - PASS')
else
begin
fOnLogEvent('OCSP - FAIL');
raise EPKIEncryptionError.Create(getLastSystemError);
end;
except
raise;
end;
end;
procedure TPKIEncryptionEngine.checkSignature(aDataString, aSignatureString: string;
aDataTimeSigned:
PFileTime = nil);
var
i: integer;
aPKIEncryptionData: IPKIEncryptionData;
aSignature: AnsiString;
aMessageHandle: HCRYPTMSG;
aCert: PCCERT_CONTEXT;
aCertStore: HCERTSTORE;
aContent: AnsiString;
aContentSize: DWORD;
aSignerCert: array of DWORD;
aSignerCertSize: DWORD;
aNameString: string;
aNameStringSize: DWORD;
begin
aMessageHandle := nil;
aCert := nil;
aCertStore := nil;
try
try
fOnLogEvent('********************************* VALIDATING SIGNATURE ************************');
NewPKIEncryptionData(aPKIEncryptionData);
aPKIEncryptionData.Buffer := aDataString;
HashData(aPKIEncryptionData);
fOnLogEvent('Data Hash Value: ' + string(aPKIEncryptionData.getHashValue));
fOnLogEvent('Data Hash Text: ' + string(aPKIEncryptionData.HashText));
aSignature := MimeDecodeString(AnsiString(aSignatureString));
// Open a msg
aMessageHandle := CryptMsgOpenToDecode(PKI_ENCODING_TYPE, 0, 0, 0, nil, nil);
if aMessageHandle = nil then
raise EPKIEncryptionError.Create(getLastSystemError)
else
fOnLogEvent('Successfully retrieved a new Message Handle');
// Add the signature
if CryptMsgUpdate(aMessageHandle, pointer(aSignature), Length(aSignature) + 1, True) then // Handle to the message
fOnLogEvent('The encoded blob has been added to the message')
else
raise EPKIEncryptionError.Create(DLG_89802015);
// Get the number of bytes needed for the content
if CryptMsgGetParam(aMessageHandle, CMSG_CONTENT_PARAM, 0, nil, @aContentSize) then
fOnLogEvent('Hash value size as been retrieved at ' + IntToStr(aContentSize))
else
raise EPKIEncryptionError.Create(getLastSystemError);
// Allocate memory and get the content
SetLength(aContent, aContentSize + 1);
if CryptMsgGetParam(aMessageHandle, CMSG_CONTENT_PARAM, 0, pointer(aContent), @aContentSize) then
fOnLogEvent('Content has been retrieved')
else
raise EPKIEncryptionError.Create(getLastSystemError);
fOnLogEvent('Hash Value From The Message: ' + string(aContent));
fOnLogEvent('Hash Value From Message as MIME: ' + string(MimeEncodeString(aContent)));
fOnLogEvent('Hash Value From The Data: ' + string(aPKIEncryptionData.getHashValue));
if AnsiCompareStr(string(aContent), string(aPKIEncryptionData.getHashValue)) = 0 then
fOnLogEvent('Hash Values Match')
else
raise EPKIEncryptionError.Create(DLG_89802016);
// Verify the signature
if CryptMsgGetParam(aMessageHandle, CMSG_SIGNER_CERT_INFO_PARAM, 0, nil, @aSignerCertSize) then
fOnLogEvent('Retrieved length of SignerCert: ' + IntToStr(aSignerCertSize))
else
raise EPKIEncryptionError.Create(getLastSystemError);
// Allocate Memory and get the signers CERT_INFO
SetLength(aSignerCert, aSignerCertSize + 1);
if CryptMsgGetParam(aMessageHandle, CMSG_SIGNER_CERT_INFO_PARAM, 0, pointer(aSignerCert), @aSignerCertSize) then
fOnLogEvent('Cert Info retrieved')
else
raise EPKIEncryptionError.Create(getLastSystemError);
// Open a certificate store in memory using CERT_STORE_PROV_MSG which initializes it with the certificates from the MSG
aCertStore := CertOpenStore(CERT_STORE_PROV_MSG, PKI_ENCODING_TYPE, 0, 0, aMessageHandle);
if aCertStore = nil then
raise EPKIEncryptionError.Create(getLastSystemError);
// Find the signer's cert in the store
aCert := CertGetSubjectCertificateFromStore(aCertStore, PKI_ENCODING_TYPE, pointer(aSignerCert));
if aCert = nil then
raise EPKIEncryptionError.Create(getLastSystemError);
// Get the name size and allocate for it - includes null terminator here
// aNameStringSize := CertGetNameStringA(aCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, nil, 0);
aNameStringSize := CertGetNameString(aCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, nil, 0);
if aNameStringSize = 0 then
raise EPKIEncryptionError.Create(getLastSystemError)
else
SetLength(aNameString, aNameStringSize);
// Get the Cert Name
// if CertGetNameStringA(aCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, pointer(aNameString), aNameStringSize) = 0 then
if CertGetNameString(aCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, PWideChar(aNameString), aNameStringSize) = 0 then
raise EPKIEncryptionError.Create(DLG_89802033) // 'Error getting name value')
else
fOnLogEvent('Got the name from the cert: ' + string(aNameString) + ' <<<<<<==================');
// Use the CERT_INFO from the signer Cert to Verify the signature
if CryptMsgControl(aMessageHandle, 0, CMSG_CTRL_VERIFY_SIGNATURE, aCert.pCertInfo) then
fOnLogEvent('Digital signature verified')
else
raise EPKIEncryptionError.Create(getLastSystemError);
// Verify the date/time signed
i := CertVerifyTimeValidity(nil, aCert.pCertInfo);
case i of
- 1:
raise EPKIEncryptionError.Create(DLG_89802019); // 'Before certificate effective date');
1:
raise EPKIEncryptionError.Create(DLG_89802020); // 'Certificate is expired');
else
fOnLogEvent('Certificate Time Validty - PASS');
end;
fOnLogEvent('Checking Certificate Chain');
checkCertChain(aCert);
fOnLogEvent('Checking Certificate for OCSP Revocation');
checkCertRevocation(aCert);
except
raise;
end;
finally
if aMessageHandle <> nil then
CryptMsgClose(aMessageHandle);
if aCert <> nil then
CertFreeCertificateContext(aCert);
if assigned(aCertStore) then
CertCloseStore(aCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
end;
end;
function TPKIEncryptionEngine.getIsCardReaderReady: boolean;
var
aActiveProtocol: DWORD;
aCardName: AnsiString;
aFHCard: LongInt;
aReaders: AnsiString;
aSCardContext: LongInt;
aSize: LongInt;
begin
try
fOnLogEvent('Establishing Context with the Card Reader');
if SCardEstablishContext(SCARD_SCOPE_USER, nil, nil, @aSCardContext) <> PKI_SCARD_S_SUCCESS then
raise EPKIEncryptionError.Create(DLG_89802034); // 'No Context');
// Get the size needed for the card readers
fOnLogEvent('Getting proper buffer size');
SCardListReadersA(aSCardContext, nil, nil, aSize);
SetLength(aReaders, aSize);
// Get the card readers in aReaders
fOnLogEvent('Getting Card Readers');
if SCardListReadersA(aSCardContext, nil, PAnsiChar(aReaders), aSize) <> PKI_SCARD_S_SUCCESS then
raise EPKIEncryptionError.Create(DLG_89802006); // 'Unable to access card reader');
// Walk the list of readers and grab the first one that is valid
while Length(aReaders) > 1 do
begin
aCardName := AnsiString(Copy(aReaders, 1, Pos(#0, string(aReaders))));
fOnLogEvent('Got Card Reader: ' + string(aCardName));
aReaders := Copy(aReaders, Length(aCardName) + 1, Length(aReaders));
if SCardConnectA(aSCardContext, PAnsiChar(aCardName), SCARD_SHARE_SHARED, 3, aFHCard, @aActiveProtocol) = PKI_SCARD_S_SUCCESS then
begin
fOnLogEvent('Successfully established context with Card Reader: ' + string(aCardName));
Result := True;
Exit;
end
else
fOnLogEvent('Unable to establish context with Card Reader: ' + string(aCardName));
end;
Result := False;
except
on EPKIEncryptionError do
raise;
on E: Exception do
raise EPKIEncryptionError.Create(DLG_89802010 + E.Message);
end;
end;
function TPKIEncryptionEngine.getCertContext: PCCERT_CONTEXT;
var
i: integer;
isFound: boolean;
aDWord: DWORD;
aByte: Byte;
aPByte: PByte;
aPBArray: PByteArray;
aHCertStore: HCERTSTORE;
aPCertContext: PCCERT_CONTEXT;
aCertNameLength: DWORD;
aCertSerialNumber: string;
aCertDisplayName: string;
aCertEMailName: string;
isCertSigning: boolean;
isDisplayNameCorrect: boolean;
aVistAUserName: string;
aVistASAN: string;
begin
Result := nil;
aHCertStore := CertOpenSystemStoreA(0, PAnsiChar('MY'));
if aHCertStore = nil then
raise EPKIEncryptionError.Create(DLG_89802010 + 'Could not open the ''MY'' Cert Store');
aVistAUserName := getVistAUserName; { This method checks for existence of fRPCBroker }
if aVistAUserName = '' then
raise EPKIEncryptionError.Create(DLG_89802010 + 'Unable to get certificate without VistA User Name');
{ If this exists, the cert must have it in the EMAIL name,
otherwise, it tries to find it via the users last name }
aVistASAN := getSANFromVistA;
aPCertContext := CertEnumCertificatesInStore(aHCertStore, nil);
isFound := False;
while (aPCertContext <> nil) and (not isFound) do
try
fOnLogEvent('--------------------------------------------------------------------------');
if aVistASAN = '' then
begin
fOnLogEvent('No SAN passed in, trying to match on ' + getVistAUserName);
aCertNameLength := CertGetNameString(aPCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, nil, 0);
SetLength(aCertDisplayName, aCertNameLength);
if (CertGetNameString(aPCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, 0, PWideChar(aCertDisplayName), aCertNameLength) > 1) then
while Copy(aCertDisplayName, Length(aCertDisplayName), 1) = #0 do
aCertDisplayName := Copy(aCertDisplayName, 1, Length(aCertDisplayName) - 1)
else
raise Exception.Create('Error in CertGetNameString');
fOnLogEvent(Format('CERT_NAME_SIMPLE_DISPLAY_TYPE = %s', [aCertDisplayName]));
fOnLogEvent('VistA Name = ' + getVistAUserName);
isDisplayNameCorrect := (Pos(UpperCase(Copy(aCertDisplayName, 1, 1)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') > 0) and // Starts with a character
(Pos(Copy(aCertDisplayName, Length(aCertDisplayName), 1), '0123456789)') > 0) and // Ends with a number or paren
(Pos(UpperCase(Copy(aVistAUserName, 1, Pos(',', aVistAUserName) - 1)), UpperCase(aCertDisplayName)) > 0); // Contains the users last name from VistA - Not the best but oh well :(
if not isDisplayNameCorrect then
begin
fOnLogEvent('Invalid Display Name');
Continue;
end
else
begin
fOnLogEvent('Name match successful');
end
end
else { We have a SAN, we must match it exactly }
begin
fOnLogEvent('VistA SAN exists, trying to match on ' + aVistASAN);
aCertEMailName := '';
aCertNameLength := CertGetNameString(aPCertContext, CERT_NAME_EMAIL_TYPE, 0, 0, nil, 0);
SetLength(aCertEMailName, aCertNameLength);
CertGetNameString(aPCertContext, CERT_NAME_EMAIL_TYPE, 0, 0, PWideChar(aCertEMailName), aCertNameLength);
while Copy(aCertEMailName, Length(aCertEMailName), 1) = #0 do
aCertEMailName := Copy(aCertEMailName, 1, Length(aCertEMailName) - 1);
fOnLogEvent(Format('CERT_NAME_EMAIL_TYPE = %s', [aCertEMailName]));
if aCertEMailName = '' then
begin
fOnLogEvent('Blank CERT_NAME_EMAIL_TYPE');
Continue;
end
else
begin
if CompareText(aVistASAN, aCertEMailName) <> 0 then
begin
fOnLogEvent('SAN Mismatch on certificate');
Continue;
end;
end;
end;
// Get the Cert serialNumber and convert to Hex
aDWord := aPCertContext.pCertInfo.SerialNumber.CbData;
aPBArray := PByteArray(aPCertContext.pCertInfo.SerialNumber.PbData);
aCertSerialNumber := '';
for i := aDWord - 1 downto 0 do
begin
aCertSerialNumber := aCertSerialNumber + IntToHex(Byte(aPBArray[i]), 2);
if i > 0 then
aCertSerialNumber := aCertSerialNumber + ' ';
end;
fOnLogEvent(Format('CertSerialNum: %s', [aCertSerialNumber]));
aPByte := @aByte;
if CertGetIntendedKeyUsage(PKI_ENCODING_TYPE, aPCertContext.pCertInfo, aPByte, 1) then
i := aByte
else
i := 0;
fOnLogEvent(Format('Required Intended Purposes: %d', [i]));
// CERT_DIGITAL_SIGNATURE_KEY_USAGE = $80;
fOnLogEvent(
Format('CERT_DIGITAL_SIGNATURE_KEY_USAGE = %s',
[BoolToStr(((i and CERT_DIGITAL_SIGNATURE_KEY_USAGE) = CERT_DIGITAL_SIGNATURE_KEY_USAGE), True)]));
// CERT_NON_REPUDIATION_KEY_USAGE = // $40;
fOnLogEvent(
Format('CERT_NON_REPUDIATION_KEY_USAGE = %s',
[BoolToStr(((i and CERT_NON_REPUDIATION_KEY_USAGE) = CERT_NON_REPUDIATION_KEY_USAGE), True)]));
isCertSigning :=
((i and CERT_DIGITAL_SIGNATURE_KEY_USAGE) = CERT_DIGITAL_SIGNATURE_KEY_USAGE) and
((i and CERT_NON_REPUDIATION_KEY_USAGE) = CERT_NON_REPUDIATION_KEY_USAGE); // then // Official and correct
if not isCertSigning then
begin
fOnLogEvent('Cannot digitally sign with non-repudiation with this one');
Continue;
end;
if not(CertVerifyTimeValidity(nil, aPCertContext.pCertInfo) = 0) then
begin
fOnLogEvent('CertVerifyTimeValidity has failed');
Continue;
end;
// We have a valid candidate check the chain and the revocation
try
checkCertChain(aPCertContext);
checkCertRevocation(aPCertContext);
isFound := True;
Result := aPCertContext;
fOnLogEvent('This is the cert!');
except
on E: Exception do
fOnLogEvent(E.Message);
end;
finally
// Continue will ALWAYS take us here and then back into the loop - Gets next cert only if not found
if not isFound then
aPCertContext := CertEnumCertificatesInStore(aHCertStore, aPCertContext);
end;
end;
procedure TPKIEncryptionEngine.GetCertificates(aList: TStrings);
var
aProvider: PHCRYPTPROV;
aHCertStore: HCERTSTORE;
aPCertContext: PCCERT_CONTEXT;
aPKICertificate: TPKIEncryptionCertificate;
begin
aList.Clear;
if not CryptAcquireContextA(@aProvider, nil, nil, PKI_ACTIVE_CLIENT_TYPE, 0) then
raise Exception.Create('Cannot get context.');
aHCertStore := CertOpenSystemStoreA(0, PAnsiChar('MY'));
if aHCertStore = nil then
raise EPKIEncryptionError.Create(DLG_89802010 + 'Could not open the ''MY'' Cert Store');
aPCertContext := CertEnumCertificatesInStore(aHCertStore, nil);
while (aPCertContext <> nil) do
try
aPKICertificate := TPKIEncryptionCertificate.Create(aPCertContext);
aList.AddObject(aPKICertificate.CertFriendlyName, aPKICertificate);
finally
aPCertContext := CertEnumCertificatesInStore(aHCertStore, aPCertContext);
end;
if assigned(aHCertStore) then
CertCloseStore(aHCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
end;
function TPKIEncryptionEngine.getCSPName: string;
begin
Result := fCSPName;
end;
function TPKIEncryptionEngine.getEngineVersion: string;
begin
Result := PKI_ENGINE_VERSION;
end;
function TPKIEncryptionEngine.getHashAlgorithm: string;
begin
Result := PKI_HASH_ALGORITHM[fHashAlgorithm];
end;
function TPKIEncryptionEngine.getSANFromCard: string;
var
aPCertContext: PCCERT_CONTEXT;
aCertEMailName: string;
aCertNameLength: DWORD;
begin
fOnLogEvent('TPKIEncryption.GetSANFromCard');
aPCertContext := getCertContext;
if aPCertContext = nil then
raise EPKIEncryptionError.Create(DLG_89802004); // 'Unable to get Certificate');
aCertEMailName := '';
aCertNameLength := CertGetNameString(aPCertContext, CERT_NAME_EMAIL_TYPE, 0, 0, nil, 0);
SetLength(aCertEMailName, aCertNameLength);
CertGetNameString(aPCertContext, CERT_NAME_EMAIL_TYPE, 0, 0, PWideChar(aCertEMailName), aCertNameLength);
while Copy(aCertEMailName, Length(aCertEMailName), 1) = #0 do
aCertEMailName := Copy(aCertEMailName, 1, Length(aCertEMailName) - 1);
fOnLogEvent(Format('CERT_NAME_EMAIL_TYPE = %s', [aCertEMailName]));
Result := string(aCertEMailName);
end;
function TPKIEncryptionEngine.getSANFromVistA: string;
begin
fRPCBroker.RemoteProcedure := 'XUS PKI GET UPN';
fRPCBroker.Call;
if fRPCBroker.Results.Count > 0 then
Result := fRPCBroker.Results[0]
else
Result := '';
end;
function TPKIEncryptionEngine.getVistAUserName: string;
begin
if Assigned(fRPCBroker) then
Result := fRPCBroker.User.Name
else
Result := '';
end;
(*
This is the internal private method accessible only from within this object.
Any errors that we know about will be raised as an EPKIEncryptionError
*)
procedure TPKIEncryptionEngine.hashBuffer(aBuffer: string;
var
aHashText: AnsiString;
var
aHashValue: AnsiString;
var
aHashHex: AnsiString);
var
i: integer;
aHashData: AnsiString;
aHashLength: DWORD;
aHashHandle: HCRYPTHASH;
function ByteToHex(InByte: Byte): ShortString;
const
Digits: array [0 .. 15] of char = '0123456789ABCDEF';
begin
Result := ShortString(Digits[InByte shr 4]) + ShortString(Digits[InByte and $0F]);
end;
begin
try
fOnLogEvent('Calling CryptCreateHash');
if (not CryptCreateHash(fProviderHandle, CALG_SHA_256, 0, 0, @aHashHandle)) then
begin
i := GetLastError;
fOnLogEvent(Format('%d: %s', [i, SysErrorMessage(i)]));
raise EPKIEncryptionError.Create(getLastSystemError);
end
else
fOnLogEvent('Successfully created hash object in CryptCreateHash');
// Actually do the hashing
fOnLogEvent('Hashing: ' + aBuffer);
aHashData := AnsiString(aBuffer);
if not CryptHashData(aHashHandle, PByte(aHashData), Length(aHashData), 0) then
raise EPKIEncryptionError.Create(getLastSystemError);
// See how big the hash value is
fOnLogEvent('Going to Get Hash Value Length');
if CryptGetHashParam(aHashHandle, HP_HASHVAL, nil, @aHashLength, 0) <> True then
begin
i := GetLastError;
fOnLogEvent(Format('%d: %s', [i, SysErrorMessage(i)]));
raise EPKIEncryptionError.Create(getLastSystemError);
end;
// Retrieve the hash value - Note MUST BE PByte()
fOnLogEvent('Going to Get Hash Value Data');
SetLength(aHashValue, aHashLength);
if CryptGetHashParam(aHashHandle, HP_HASHVAL, PByte(aHashValue), @aHashLength, 0) <> True then
begin
i := GetLastError;
fOnLogEvent(Format('%d: %s', [i, SysErrorMessage(i)]));
raise EPKIEncryptionError.Create(getLastSystemError);
end;
aHashHex := '';
for i := 0 to Length(aHashValue) do
aHashHex := aHashHex + ByteToHex(Byte(aHashValue[i]));
aHashText := '';
SetLength(aHashText, MimeEncodedSize(aHashLength));
aHashText := MimeEncodeString(aHashValue);
CryptDestroyHash(aHashHandle);
except
if aHashHandle <> 0 then
CryptDestroyHash(aHashHandle);
raise;
end;
end;
function TPKIEncryptionEngine.getSANLink: TPKISANLink;
var
aVistASAN: string;
aPIVCardSAN: string;
begin
try
aVistASAN := getSANFromVistA;
aPIVCardSAN := getSANFromCard;
fOnLogEvent(Format('Comparing the following values ''%s'' and ''%s''', [aVistASAN, aPIVCardSAN]));
if CompareText(aPIVCardSAN, '') = 0 then
Result := slNoCertFound
else if CompareText(aVistASAN, '') = 0 then
Result := slBlankVistA
else if CompareText(aPIVCardSAN, aVistASAN) <> 0 then
Result := slMisMatch
else
Result := slOK;
except
on EBrokerError do
Result := slVistAError;
on EPKIEncryptionError do
Result := slNoCertFound;
on Exception do
Result := slError;
end;
end;
procedure TPKIEncryptionEngine.ClearPIN;
begin
fCurrentPIN := '';
end;
procedure TPKIEncryptionEngine.ValidateSignature(aPKIEncryptionSignature: IPKIEncryptionSignature);
begin
try
checkSignature(aPKIEncryptionSignature.DataString, aPKIEncryptionSignature.Signature, nil);
except
raise;
end;
end;
procedure TPKIEncryptionEngine.SignData(aPKIEncryptionData: IPKIEncryptionData);
var
// aSignatureSuccess: boolean;
RgpbToBeSigned: array [0 .. 0] of PByte;
RgcbToBeSigned: array [0 .. 0] of PDWORD;
// aPByte: PByte;
// aMessage: string;
aHashValue: AnsiString;
aHashValueLength: DWORD;
aSignature: AnsiString;
aSignatureLength: DWORD;
aSignatureStr: string;
aSignMsgParam: CRYPT_SIGN_MESSAGE_PARA;
aPKIEncryptionDataEx: IPKIEncryptionDataEx;
aPCertContext: PCCERT_CONTEXT;
begin
try
// This will check to see if the current PIN has already been entered for this object lifecycle
{
if fCurrentPIN = '' then
raise EPKIEncryptionError.Create(DLG_89802014)
else if not getIsValidPIN(fCurrentPIN, aMessage) then
raise EPKIEncryptionError.Create(DLG_89802014);
}
fOnLogEvent('Signing data: ' + aPKIEncryptionData.Buffer);
aPKIEncryptionData.Validate; // virtual methods shall raise exception if not valid for signing
HashData(aPKIEncryptionData); // Hashes data from getBuffer
fOnLogEvent('We have hashed the data successfully');
if aPKIEncryptionData.QueryInterface(IPKIEncryptionDataEx, aPKIEncryptionDataEx) <> 0 then
raise EPKIEncryptionError.Create(DLG_89802031);
if getSANFromVistA = '' then
raise EPKIEncryptionError.Create(DLG_89802048)
else
aPCertContext := getCertContext;
if aPCertContext = nil then
raise EPKIEncryptionError.Create(DLG_89802004)
else
fOnLogEvent('Got the CertContext Successfully');
aSignMsgParam.CbSize := Sizeof(CRYPT_SIGN_MESSAGE_PARA);
aSignMsgParam.PvHashAuxInfo := nil;
aSignMsgParam.cMsgCert := 0;
aSignMsgParam.RgpMsgCert := nil;
aSignMsgParam.CMsgCrl := 0;
aSignMsgParam.RgpMsgCrl := nil;
aSignMsgParam.CAuthAttr := 0;
aSignMsgParam.RgAuthAttr := nil;
aSignMsgParam.CUnauthAttr := 0;
aSignMsgParam.RgUnauthAttr := nil;
aSignMsgParam.DwFlags := 0;
aSignMsgParam.DwInnerContentType := 0;
aSignMsgParam.PSigningCert := aPCertContext;
aSignMsgParam.DwMsgEncodingType := PKI_ENCODING_TYPE;
case fHashAlgorithm of
ha128:
aSignMsgParam.HashAlgorithm.PszObjId := szOID_RSA_SHA1RSA;
ha256:
aSignMsgParam.HashAlgorithm.PszObjId := szOID_RSA_SHA256RSA;
ha384:
aSignMsgParam.HashAlgorithm.PszObjId := szOID_RSA_SHA384RSA;
ha512:
aSignMsgParam.HashAlgorithm.PszObjId := szOID_RSA_SHA512RSA;
else
aSignMsgParam.HashAlgorithm.PszObjId := szOID_RSA_SHA1RSA;
end;
aSignMsgParam.HashAlgorithm.Parameters.CbData := 0;
// The Signing Cert
aSignMsgParam.cMsgCert := 1;
aSignMsgParam.RgpMsgCert := @aPCertContext;
// The data to be signed and its length
aHashValue := aPKIEncryptionDataEx.getHashValue;
aHashValueLength := Length(aHashValue);
RgpbToBeSigned[0] := @aHashValue;
RgcbToBeSigned[0] := @aHashValueLength;
aSignatureLength := 0;
{ Get the size of the signature first }
if CryptSignMessage(@aSignMsgParam, False, 1, RgpbToBeSigned[0], RgcbToBeSigned[0], nil, @aSignatureLength) then
fOnLogEvent('Successfully retrieved the required size of the signature: ' + IntToStr(aSignatureLength))
else
raise EPKIEncryptionError.Create(getLastSystemError);
SetLength(aSignature, aSignatureLength + 1);
if CryptSignMessage(@aSignMsgParam, False, 1, RgpbToBeSigned[0], RgcbToBeSigned[0], PByte(aSignature), @aSignatureLength) then
fOnLogEvent('Successfully signed the message.')
else
raise EPKIEncryptionError.Create(getLastSystemError);
SetLength(aSignatureStr, MimeEncodedSize(Length(aSignature)));
aSignatureStr := string(MimeEncodeString(aSignature));
fOnLogEvent('Signature Data: ' + aPKIEncryptionData.Buffer);
fOnLogEvent('Signature HashText: ' + aPKIEncryptionData.HashText);
fOnLogEvent('Signature Data as MIME: ' + aSignatureStr);
aPKIEncryptionDataEx.setSignature(aSignatureStr); // String(MimeEncodeString(aSignature)));
aPKIEncryptionDataEx.setDateTimeSigned(Now);
{ debug - Uncomment the lines below to immediately pass back the signature string for validation
fOnLogEvent('checking the signature as is');
checkSignature(aPKIEncryptionData.Buffer, aSignatureStr);
fOnLogEvent('we are back from checking the signature');
debug }
except
on E: EPKIEncryptionError do
raise;
on E: Exception do
raise EPKIEncryptionError.Create(DLG_89802010 + E.Message);
end;
end;
procedure TPKIEncryptionEngine.HashData(aPKIEncryptionData: IPKIEncryptionData);
(*
This is the public method that calls the internal method for actual hashing and
then updates the values in the IPKIEncryptionData object.
All known errors are raised as EPKIEncryptionErrors.
*)
var
aHashText: AnsiString;
aHashValue: AnsiString;
aHashHexValue: AnsiString;
aPKIEncryptionDataEx: IPKIEncryptionDataEx;
begin
fOnLogEvent('Entered TPKIEncryption.HashData(aPKIEncryptionData: IPKIEncryptionData);');
try
hashBuffer(aPKIEncryptionData.Buffer, aHashText, aHashValue, aHashHexValue);
if aPKIEncryptionData.QueryInterface(IPKIEncryptionDataEx, aPKIEncryptionDataEx) = 0 then
begin
aPKIEncryptionDataEx.setHashValue(aHashValue);
aPKIEncryptionDataEx.setHashText(aHashText);
aPKIEncryptionDataEx.setHashHex(aHashHexValue);
end;
except
raise;
end;
end;
procedure TPKIEncryptionEngine.LinkSANtoVistA;
var
aPIVCardSAN: string;
begin
try
fOnLogEvent(Format('Linking PIV Card SAN to VistA Account ''%s (DUZ:%s)''', [fRPCBroker.User.Name, fRPCBroker.User.DUZ]));
aPIVCardSAN := getSANFromCard;
if CompareText(aPIVCardSAN, '') = 0 then
raise EPKIEncryptionError.Create(DLG_89802041);
setVistASAN(aPIVCardSAN);
except
on EBrokerError do
raise EPKIEncryptionError.Create(DLG_89802047); // Lets user know the broker copped a 'tude
else
raise;
end;
end;
procedure TPKIEncryptionEngine.SaveSignature(aPKIEncryptionData: IPKIEncryptionData);
begin
// Future development - Need to save the signature so other clients don't have to bang on the PKI files
end;
procedure TPKIEncryptionEngine.DisplayProviders; // Requires a valid fOnLogEvent
var
dwIndex: DWORD;
DwType: DWORD;
dwName: DWORD;
DwFlags: DWORD;
aName: AnsiString;
PbData: array [0 .. 1024] of Byte;
CbData: DWORD;
aiAlgid: ALG_ID;
paiAlgid: ^ALG_ID;
aAlgType: string;
dwBits: DWORD;
pdwBits: ^DWORD;
dwNameLen: DWORD;
pdwNameLen: ^DWORD;
i, j: integer;
begin
fOnLogEvent('DISPLAY PROVIDERS - START');
fOnLogEvent('');
fOnLogEvent('Provider Types');
fOnLogEvent('--------------');
dwIndex := 0;
while CryptEnumProviderTypesA(dwIndex, nil, 0, @DwType, nil, @dwName) do
begin
SetLength(aName, dwName);
if CryptEnumProviderTypesA(dwIndex, nil, 0, @DwType, PAnsiChar(aName), @dwName) then
fOnLogEvent(Format('%0.4d: %s', [DwType, string(aName)]));
inc(dwIndex);
end;
fOnLogEvent('');
fOnLogEvent('Providers');
fOnLogEvent('---------');
dwIndex := 0;
while CryptEnumProvidersA(dwIndex, nil, 0, @DwType, nil, @dwName) = True do
begin
SetLength(aName, dwName);
if CryptEnumProvidersA(dwIndex, nil, 0, @DwType, PAnsiChar(aName), @dwName) then
fOnLogEvent(Format('%0.4d: %s', [DwType, string(aName)]));
inc(dwIndex);
end;
fOnLogEvent('');
fOnLogEvent('Default Provider for PKI Operations');
fOnLogEvent('-----------------------------------');
if CryptGetDefaultProviderA(PKI_PROVIDER_TYPE, 0, CRYPT_MACHINE_DEFAULT, nil, @dwName) then
begin
SetLength(aName, dwName);
CryptGetDefaultProviderA(PKI_PROVIDER_TYPE, 0, CRYPT_MACHINE_DEFAULT, PAnsiChar(aName), @dwName);
fOnLogEvent(Format('%s', [string(aName)]));
end;
fOnLogEvent('');
fOnLogEvent('Supported Algorithms');
fOnLogEvent(Format('%-8s %4s %-15s %s', ['ID', 'Bits', 'Type', 'Name']));
fOnLogEvent('-----------------------------------------------------------------');
CbData := 1024;
for i := 0 to 1023 do
PbData[i] := 0;
DwFlags := CRYPT_FIRST;
while CryptGetProvParam(fProviderHandle, PP_ENUMALGS, @PbData[0], @CbData, DwFlags) do
begin
DwFlags := CRYPT_NEXT;
i := 0;
paiAlgid := @PbData[i];
aiAlgid := paiAlgid^;
inc(i, Sizeof(aiAlgid));
pdwBits := @PbData[i];
dwBits := pdwBits^;
inc(i, Sizeof(dwBits));
pdwNameLen := @PbData[i];
dwNameLen := pdwNameLen^;
inc(i, Sizeof(dwNameLen));
SetLength(aName, dwNameLen);
for j := 0 to dwNameLen - 1 do
aName[j + 1] := AnsiChar(PbData[i + j]);
case GET_ALG_CLASS(aiAlgid) of
ALG_CLASS_ANY:
aAlgType := 'Any';
ALG_CLASS_SIGNATURE:
aAlgType := 'Signature';
ALG_CLASS_MSG_ENCRYPT:
aAlgType := 'Message Encrypt';
ALG_CLASS_DATA_ENCRYPT:
aAlgType := 'Data Encrypt';
ALG_CLASS_HASH:
aAlgType := 'Hash';
ALG_CLASS_KEY_EXCHANGE:
aAlgType := 'Exchange';
else
aAlgType := 'Unknown';
end;
fOnLogEvent(Format('%.8x %4d %-15s %s', [aiAlgid, dwBits, string(aAlgType), string(aName)]));
end;
fOnLogEvent('DISPLAY PROVIDERS - END');
end;
function TPKIEncryptionEngine.getIsValidPIN(const aPKIPIN: string;
var
aMessage:
string): boolean;
var
aHandle: DWORD;
aPinValue: AnsiString;
aCSPName: AnsiString;
begin
try
Result := False;
aCSPName := AnsiString(fCSPName);
fOnLogEvent('Checking Card Reader Status');
if not getIsCardReaderReady then
raise EPKIEncryptionError.Create(DLG_89802035);
fOnLogEvent('Acquiring Context for ' + fCSPName);
if CryptAcquireContextA(@aHandle, PAnsiChar(''), PAnsiChar(aCSPName), PKI_ACTIVE_CLIENT_TYPE, 0) then
try
// Store this internally so it can be present multiple times for multiple signing or until cleared
fCurrentPIN := aPKIPIN;
// Get an AnsiString copy for the DLL
aPinValue := AnsiString(aPKIPIN);
fOnLogEvent('Setting Provider Parameter');
if CryptSetProvParam(aHandle, PP_SIGNATURE_PIN, PByte(aPinValue), 0) then
begin
aMessage := 'PIN Verified';
fOnLogEvent(aMessage);
Result := True;
end
else
raise EPKIEncryptionError.Create(getLastSystemError);
except
on E: Exception do
begin
fCurrentPIN := '';
aMessage := E.Message;
fOnLogEvent(aMessage);
Result := False;
end;
end
else
begin
fCurrentPIN := '';
aMessage := SysErrorMessage(GetLastError);
fOnLogEvent(aMessage);
Result := False;
end;
finally
if aHandle <> 0 then
CryptReleaseContext(aHandle, 0);
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.DAO.Query
Description : DAODatabase Query
Author : Kike Pérez
Version : 1.1
Created : 31/08/2018
Modified : 07/04/2020
This file is part of QuickDAO: https://github.com/exilon/QuickDAO
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.DAO.Query;
{$i QuickDAO.inc}
interface
uses
Classes,
RTTI,
{$IFNDEF FPC}
System.SysUtils,
System.TypInfo,
Json,
System.Variants,
System.Generics.Collections,
System.Generics.Defaults,
{$ELSE}
SysUtils,
TypInfo,
Generics.Collections,
Generics.Defaults,
Variants,
Quick.Json.fpc.Compatibility,
Quick.Rtti.fpc.Compatibility,
{$ENDIF}
Quick.Commons,
Quick.RTTI.Utils,
Quick.Json.Serializer,
Quick.DAO,
Quick.DAO.Database;
type
TDAOQuery<T : class, constructor> = class(TInterfacedObject,IDAOQuery<T>,IDAOLinqQuery<T>)
private
fWhereClause : string;
fOrderClause : string;
fOrderAsc : Boolean;
fSelectedFields : TArray<string>;
function FormatParams(const aWhereClause : string; aWhereParams : array of const) : string;
protected
fDAODataBase : TDAODataBase;
fModel : TDAOModel;
fQueryGenerator : IDAOQueryGenerator;
fHasResults : Boolean;
fFirstIteration : Boolean;
function MoveNext : Boolean; virtual; abstract;
function GetCurrent : T; virtual; abstract;
function GetFieldValue(const aName : string) : Variant; virtual; abstract;
function GetFieldValues(aDAORecord : TDAORecord; aExcludeAutoIDFields : Boolean) : TStringList;
procedure FillRecordFromDB(aDAORecord : T);
function GetDBFieldValue(const aFieldName : string; aValue : TValue): TValue;
function GetFieldsPairs(aDAORecord : TDAORecord): string; overload;
function GetFieldsPairs(const aFieldNames : string; aFieldValues : array of const; aIsTimeStamped : Boolean): string; overload;
function GetRecordValue(const aFieldName : string; aValue : TValue) : string;
function GetModel : TDAOModel;
function OpenQuery(const aQuery : string) : Integer; virtual; abstract;
function ExecuteQuery(const aQuery : string) : Boolean; virtual; abstract;
public
constructor Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator); virtual;
property Model : TDAOModel read fModel write fModel;
property HasResults : Boolean read fHasResults write fHasResults;
function Eof : Boolean; virtual; abstract;
function AddOrUpdate(aDAORecord : TDAORecord) : Boolean; virtual;
function Add(aDAORecord : TDAORecord) : Boolean; virtual;
function CountResults : Integer; virtual; abstract;
function Update(aDAORecord : TDAORecord) : Boolean; overload; virtual;
function Delete(aDAORecord : TDAORecord) : Boolean; overload; virtual;
function Delete(const aWhere : string) : Boolean; overload; virtual;
//LINQ queries
function Where(const aFormatSQLWhere: string; const aValuesSQLWhere: array of const) : IDAOLinqQuery<T>; overload;
function Where(const aWhereClause : string) : IDAOLinqQuery<T>; overload;
function SelectFirst : T;
function SelectLast : T;
function Select : IDAOResult<T>; overload;
function Select(const aFieldNames : string) : IDAOResult<T>; overload;
function SelectTop(aNumber : Integer) : IDAOResult<T>;
function Sum(const aFieldName : string) : Int64;
function Count : Int64;
function Update(const aFieldNames : string; const aFieldValues : array of const) : Boolean; overload;
function Delete : Boolean; overload;
function OrderBy(const aFieldValues : string) : IDAOLinqQuery<T>;
function OrderByDescending(const aFieldValues : string) : IDAOLinqQuery<T>;
end;
implementation
{ TDAOQuery }
constructor TDAOQuery<T>.Create(aDAODataBase : TDAODataBase; aModel : TDAOModel; aQueryGenerator : IDAOQueryGenerator);
begin
fFirstIteration := True;
fDAODataBase := aDAODataBase;
fModel := aModel;
fWhereClause := '1=1';
fSelectedFields := [];
fQueryGenerator := aQueryGenerator;
fHasResults := False;
end;
function TDAOQuery<T>.GetFieldValues(aDAORecord : TDAORecord; aExcludeAutoIDFields : Boolean) : TStringList;
var
ctx: TRttiContext;
{$IFNDEF FPC}
attr : TCustomAttribute;
{$ENDIF}
rType: TRttiType;
rProp: TRttiProperty;
propertyname : string;
propvalue : TValue;
skip : Boolean;
begin
Result := TStringList.Create;
Result.Delimiter := ',';
Result.StrictDelimiter := True;
try
rType := ctx.GetType(aDAORecord.ClassInfo);
try
for rProp in TRTTI.GetProperties(rType,roFirstBase) do
begin
propertyname := rProp.Name;
if IsPublishedProp(aDAORecord,propertyname) then
begin
{$IFNDEF FPC}
for attr in rProp.GetAttributes do
begin
if attr is TMapField then propertyname := TMapField(attr).Name;
end;
{$ENDIF}
skip := False;
propvalue := rProp.GetValue(aDAORecord);
if CompareText(rProp.Name,fModel.PrimaryKey.Name) = 0 then
begin
if not aExcludeAutoIDFields then
begin
if (rProp.PropertyType.Name = 'TAutoID') and ((propvalue.IsEmpty) or (propvalue.AsInt64 = 0)) then skip := True;
end
else skip := True;
end;
if not skip then Result.Add(GetRecordValue(propertyname,propvalue));
end;
end;
finally
ctx.Free;
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error getting field values "%s" : %s',[Self.ClassName,e.Message]);
end;
end;
end;
function TDAOQuery<T>.GetModel: TDAOModel;
begin
Result := fModel;
end;
function TDAOQuery<T>.GetRecordValue(const aFieldName: string; aValue: TValue): string;
var
rttijson : TRTTIJson;
jpair : TJsonPair;
//a : TTypeKind;
begin
//a := aValue.Kind;
case aValue.Kind of
tkDynArray :
begin
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
jpair := TJSONPair.Create(aFieldName,rttijson.SerializeValue(aValue));
try
{$IFNDEF FPC}
Result := QuotedStr(jpair.JsonValue.ToJson);
{$ELSE}
Result := QuotedStr(jpair.JsonValue.AsJson);
{$ENDIF}
finally
jpair.Free;
end;
finally
rttijson.Free;
end;
end;
tkString, tkLString, tkWString, tkUString{$IFDEF FPC}, tkAnsiString{$ENDIF} : Result := QuotedStr(aValue.AsString);
tkInteger : Result := aValue.AsInteger.ToString;
tkInt64 : Result := aValue.AsInt64.ToString;
{$IFDEF FPC}
tkBool : Result := aValue.AsBoolean.ToString;
{$ENDIF}
tkFloat :
begin
if ((aValue.TypeInfo = TypeInfo(TDateTime)) or
(aValue.TypeInfo = TypeInfo(TCreationDate)) or
(aValue.TypeInfo = TypeInfo(TModifiedDate))) then
begin
if aValue.AsExtended = 0.0 then Result := 'null'
else Result := QuotedStr(fQueryGenerator.DateTimeToDBField(aValue.AsExtended));
end
else if aValue.TypeInfo = TypeInfo(TDate) then
begin
Result := QuotedStr(aValue.AsExtended.ToString);
end
else if aValue.TypeInfo = TypeInfo(TTime) then
begin
Result := QuotedStr(aValue.AsExtended.ToString);
end
else Result := StringReplace(string(aValue.AsVariant),',','.',[]);
end;
tkEnumeration :
begin
if (aValue.TypeInfo = System.TypeInfo(Boolean)) then
begin
if CompareText(string(aValue.AsVariant),'true') = 0 then Result := '1'
else Result := '0';
end
else
begin
//value := value;
end;
end;
tkRecord, tkClass :
begin
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
jpair := TJSONPair.Create(aFieldName,rttijson.SerializeRecord(aValue));
try
Result := QuotedStr(jpair.{$IFNDEF FPC}ToJSON{$ELSE}JsonString{$ENDIF});
finally
jpair.Free;
end;
finally
rttijson.Free;
end;
end;
else Result := 'null';
end;
end;
function TDAOQuery<T>.GetFieldsPairs(aDAORecord : TDAORecord): string;
var
ctx: TRttiContext;
{$IFNDEF FPC}
attr : TCustomAttribute;
{$ENDIF}
rType: TRttiType;
rProp: TRttiProperty;
propertyname : string;
propvalue : TValue;
value : string;
begin
Result := '';
try
rType := ctx.GetType(fModel.Table);
try
for rProp in TRTTI.GetProperties(rType,roFirstBase) do
begin
propertyname := rProp.Name;
if IsPublishedProp(aDAORecord,propertyname) then
begin
{$IFNDEF FPC}
for attr in rProp.GetAttributes do
begin
if attr is TMapField then propertyname := TMapField(attr).Name;
end;
{$ENDIF}
propvalue := rProp.GetValue(aDAORecord);
value := GetRecordValue(propertyname,propvalue);
if not ((CompareText(propertyname,fModel.PrimaryKey.Name) = 0) and (rProp.PropertyType.Name = 'TAutoID')) then Result := Result + Format('[%s]=%s,',[propertyname,value])
else if propvalue.TypeInfo = TypeInfo(TModifiedDate) then value := fQueryGenerator.DateTimeToDBField(Now());
//rProp.SetValue(Self,GetDBFieldValue(propertyname,rProp.GetValue(Self)));
end;
end;
Result := RemoveLastChar(Result);
finally
ctx.Free;
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error getting fields "%s" : %s',[aDAORecord.ClassName,e.Message]);
end;
end;
end;
function TDAOQuery<T>.GetFieldsPairs(const aFieldNames : string; aFieldValues : array of const; aIsTimeStamped : Boolean): string;
var
fieldname : string;
value : string;
i : Integer;
begin
if aIsTimeStamped then Result := 'ModifiedDate = ' + fQueryGenerator.DateTimeToDBField(Now()) + ',';
i := 0;
for fieldname in aFieldNames.Split([',']) do
begin
case aFieldValues[i].VType of
vtInteger : value := IntToStr(aFieldValues[i].VInteger);
vtInt64 : value := IntToStr(aFieldValues[i].VInt64^);
vtExtended : value := FloatToStr(aFieldValues[i].VExtended^);
vtBoolean : value := BoolToStr(aFieldValues[i].VBoolean);
vtWideString : value := DbQuotedStr(string(aFieldValues[i].VWideString^));
{$IFNDEF NEXTGEN}
vtAnsiString : value := DbQuotedStr(AnsiString(aFieldValues[i].VAnsiString));
vtString : value := DbQuotedStr(aFieldValues[i].VString^);
{$ENDIF}
vtChar : value := DbQuotedStr(aFieldValues[i].VChar);
vtPChar : value := string(aFieldValues[i].VPChar).QuotedString;
else value := DbQuotedStr(string(aFieldValues[i].VUnicodeString));
end;
Result := Result + fieldname + '=' + value + ',';
Inc(i);
end;
RemoveLastChar(Result);
end;
procedure TDAOQuery<T>.FillRecordFromDB(aDAORecord : T);
var
ctx: TRttiContext;
{$IFNDEF FPC}
attr : TCustomAttribute;
{$ENDIF}
rType: TRttiType;
rProp: TRttiProperty;
propertyname : string;
rvalue : TValue;
dbfield : TDBField;
IsFilterSelect : Boolean;
skip : Boolean;
begin
try
IsFilterSelect := not IsEmptyArray(fSelectedFields);
rType := ctx.GetType(fModel.Table);
try
for rProp in TRTTI.GetProperties(rType,roFirstBase) do
begin
propertyname := rProp.Name;
if IsPublishedProp(aDAORecord,propertyname) then
begin
{$IFNDEF FPC}
for attr in rProp.GetAttributes do
begin
if attr is TMapField then propertyname := TMapField(attr).Name;
end;
{$ENDIF}
skip := False;
if (IsFilterSelect) and (not StrInArray(propertyname,fSelectedFields)) then skip := True;
if not skip then rvalue := GetDBFieldValue(propertyname,rProp.GetValue(TDAORecord(aDAORecord)))
else rvalue := nil;
if CompareText(propertyname,fModel.PrimaryKey.Name) = 0 then
begin
if not rvalue.IsEmpty then
begin
dbfield.FieldName := fModel.PrimaryKey.Name;
dbfield.Value := rValue.AsVariant;
TDAORecord(aDAORecord).PrimaryKey := dbfield;
end;
end;
if not rvalue.IsEmpty then rProp.SetValue(TDAORecord(aDAORecord),rvalue);
end;
end;
finally
ctx.Free;
end;
except
on E : Exception do
begin
raise Exception.CreateFmt('Error filling record "%s" field : %s',[fModel.TableName,e.Message]);
end;
end;
end;
function TDAOQuery<T>.GetDBFieldValue(const aFieldName : string; aValue : TValue): TValue;
var
IsNull : Boolean;
fieldvalue : variant;
rttijson : TRTTIJson;
json : TJsonObject;
jArray : TJSONArray;
//a : TTypeKind;
begin
fieldvalue := GetFieldValue(aFieldName);
IsNull := IsEmptyOrNull(fieldvalue);
//a := aValue.Kind;
try
case aValue.Kind of
tkDynArray :
begin
if IsNull then Exit(nil);
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
jArray := TJSONObject.ParseJSONValue(fieldvalue) as TJSONArray;
try
{$IFNDEF FPC}
Result := rttijson.DeserializeDynArray(aValue.TypeInfo,Self,jArray);
{$ELSE}
rttijson.DeserializeDynArray(aValue.TypeInfo,aFieldName,aValue.AsObject,jArray);
{$ENDIF}
finally
jArray.Free;
end;
finally
rttijson.Free;
end;
end;
tkClass :
begin
if IsNull then Exit(nil);
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
json := TJSONObject.ParseJSONValue('{'+fieldvalue+'}') as TJSONObject;
try
Result := rttijson.DeserializeObject(Self,json.GetValue(aFieldName) as TJSONObject);
finally
json.Free;
end;
finally
rttijson.Free;
end;
end;
tkString, tkLString, tkWString, tkUString{$IFDEF FPC}, tkAnsiString{$ENDIF} :
begin
if not IsNull then Result := string(fieldvalue)
else Result := '';
end;
tkChar, tkWChar :
begin
if not IsNull then Result := string(fieldvalue)
else Result := '';
end;
tkInteger :
begin
if not IsNull then Result := Integer(fieldvalue)
else Result := 0;
end;
tkInt64 :
begin
if not IsNull then Result := Int64(fieldvalue)
else Result := 0;
end;
{$IFDEF FPC}
tkBool :
begin
if not IsNull then Result := Boolean(fieldvalue)
else Result := False;
end;
{$ENDIF}
tkFloat :
begin
if ((aValue.TypeInfo = TypeInfo(TDateTime)) or
(aValue.TypeInfo = TypeInfo(TCreationDate)) or
(aValue.TypeInfo = TypeInfo(TModifiedDate))) then
begin
if not IsNull then
begin
{$IFNDEF FPC}
if not Self.ClassName.StartsWith('TDAOQueryFireDAC') then Result := fQueryGenerator.DBFieldToDateTime(fieldvalue)
{$ELSE}
if not string(Self.ClassName).StartsWith('TDAOQueryFireDAC') then Result := fQueryGenerator.DBFieldToDateTime(fieldvalue)
{$ENDIF}
else Result := StrToDateTime(fieldvalue);
end
else Result := 0;
end
else if aValue.TypeInfo = TypeInfo(TDate) then
begin
if not IsNull then Result := {$IFNDEF FPC}TDate{$ELSE}VarToDateTime{$ENDIF}(fieldvalue)
else Result := 0;
end
else if aValue.TypeInfo = TypeInfo(TTime) then
begin
if not IsNull then Result := {$IFNDEF FPC}TTime{$ELSE}VarToDateTime{$ENDIF}(fieldvalue)
else Result := 0;
end
else if not IsNull then Result := Extended(fieldvalue)
else Result := 0;
end;
tkEnumeration :
begin
if (aValue.TypeInfo = System.TypeInfo(Boolean)) then
begin
if not IsNull then Result := Boolean(fieldvalue)
else Result := False;
end
else
begin
if not IsNull then TValue.Make({$IFDEF FPC}@{$ENDIF}fieldvalue,aValue.TypeInfo,Result)
else TValue.Make(0,aValue.TypeInfo, Result);
end;
end;
tkSet :
begin
//Result.JsonValue := TJSONString.Create(aValue.ToString);
end;
tkRecord :
begin
if IsNull then Exit(nil);
{$IFNDEF FPC}
rttijson := TRTTIJson.Create(TSerializeLevel.slPublishedProperty);
try
json := TJSONObject.ParseJSONValue('{'+fieldvalue+'}') as TJSONObject;
try
Result := rttijson.DeserializeRecord(aValue,Self,json.GetValue(aFieldName) as TJSONObject);
finally
json.Free;
end;
finally
rttijson.Free;
end;
{$ENDIF}
end;
tkMethod, tkPointer, tkClassRef ,tkInterface, tkProcedure :
begin
//skip these properties
end
else
begin
{$IFNDEF FPC}
raise Exception.Create(Format('Error %s %s',[aFieldName,GetTypeName(aValue.TypeInfo)]));
{$ELSE}
Exit(nil);
raise Exception.CreateFmt('Error getting DB field "%s"',[aFieldName]);
{$ENDIF}
end;
end;
except
on E : Exception do
begin
if aValue.Kind = tkClass then raise Exception.CreateFmt('Serialize error class "%s.%s" : %s',[aFieldName,aValue.ToString,e.Message])
else raise Exception.CreateFmt('Serialize error property "%s=%s" : %s',[aFieldName,aValue.ToString,e.Message]);
end;
end;
end;
function TDAOQuery<T>.Add(aDAORecord: TDAORecord): Boolean;
var
sqlfields : TStringList;
sqlvalues : TStringList;
begin
Result := False;
try
if aDAORecord is TDAORecordTS then TDAORecordTS(aDAORecord).CreationDate := Now();
sqlfields := fModel.GetFieldNames(aDAORecord,False);
try
sqlvalues := GetFieldValues(aDAORecord,False);
try
Result := ExecuteQuery(fQueryGenerator.Add(fModel.TableName,sqlfields.CommaText,CommaText(sqlvalues)));
finally
sqlvalues.Free;
end;
finally
sqlfields.Free;
end;
except
on E : Exception do raise EDAOCreationError.CreateFmt('Insert error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.AddOrUpdate(aDAORecord: TDAORecord): Boolean;
var
sqlfields : TStringList;
sqlvalues : TStringList;
begin
Result := False;
try
// if fQueryGenerator.Name <> 'MSSQL' then
// begin
if (aDAORecord.PrimaryKey.FieldName = '') or (VarIsEmpty(aDAORecord.PrimaryKey.Value))
or (Where(Format('%s = ?',[aDAORecord.PrimaryKey.FieldName]),[aDAORecord.PrimaryKey.Value]).Count = 0) then
begin
Result := Add(aDAORecord);
end
else
begin
Result := Update(aDAORecord);
end;
// end
// else
// begin
// sqlfields := fModel.GetFieldNames(aDAORecord,False);
// try
// sqlvalues := GetFieldValues(aDAORecord,False);
// try
// Result := ExecuteQuery(fQueryGenerator.AddOrUpdate(fModel.TableName,sqlfields.CommaText,CommaText(sqlvalues)));
// finally
// sqlvalues.Free;
// end;
// finally
// sqlfields.Free;
// end;
// end;
except
on E : Exception do raise EDAOCreationError.CreateFmt('AddOrUpdate error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Delete(aDAORecord : TDAORecord): Boolean;
begin
try
Result := ExecuteQuery(fQueryGenerator.Delete(fModel.TableName,Format('%s=%s',[aDAORecord.PrimaryKey.FieldName,aDAORecord.PrimaryKey.Value])));
except
on E : Exception do raise EDAODeleteError.CreateFmt('Delete error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Delete(const aWhere: string): Boolean;
begin
try
Result := ExecuteQuery(fQueryGenerator.Delete(fModel.TableName,aWhere));
except
on E : Exception do raise EDAODeleteError.CreateFmt('Delete error: %s',[e.message]);
end;
end;
{ LINQ queries }
function TDAOQuery<T>.Count: Int64;
begin
try
if OpenQuery(fQueryGenerator.Count(fModel.TableName,fWhereClause)) > 0 then Result := GetFieldValue('cnt')
else Result := 0;
HasResults := False;
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select count error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.FormatParams(const aWhereClause: string; aWhereParams: array of const): string;
var
i : Integer;
value : string;
vari : variant;
begin
Result := aWhereClause;
if aWhereClause = '' then
begin
Result := '1 = 1';
Exit;
end;
for i := 0 to aWhereClause.CountChar('?') - 1 do
begin
case aWhereParams[i].VType of
vtInteger : value := IntToStr(aWhereParams[i].VInteger);
vtInt64 : value := IntToStr(aWhereParams[i].VInt64^);
vtExtended : value := FloatToStr(aWhereParams[i].VExtended^);
vtBoolean : value := BoolToStr(aWhereParams[i].VBoolean);
vtWideString : value := fQueryGenerator.QuotedStr(string(aWhereParams[i].VWideString^));
{$IFNDEF NEXTGEN}
vtAnsiString : value := fQueryGenerator.QuotedStr(AnsiString(aWhereParams[i].VAnsiString));
vtString : value := fQueryGenerator.QuotedStr(aWhereParams[i].VString^);
{$ENDIF}
vtChar : value := fQueryGenerator.QuotedStr(aWhereParams[i].VChar);
vtPChar : value := fQueryGenerator.QuotedStr(string(aWhereParams[i].VPChar));
vtVariant :
begin
vari := aWhereParams[i].VVariant^;
case VarType(vari) of
varInteger,varInt64 : value := IntToStr(vari);
varDouble : value := FloatToStr(vari);
varDate : value := DateTimeToSQL(vari);
else value := string(vari);
end;
end
else value := fQueryGenerator.QuotedStr(string(aWhereParams[i].VUnicodeString));
end;
Result := StringReplace(Result,'?',value,[]);
end;
end;
function TDAOQuery<T>.OrderBy(const aFieldValues: string): IDAOLinqQuery<T>;
begin
Result := Self;
fOrderClause := aFieldValues;
fOrderAsc := True;
end;
function TDAOQuery<T>.OrderByDescending(const aFieldValues: string): IDAOLinqQuery<T>;
begin
Result := Self;
fOrderClause := aFieldValues;
fOrderAsc := False;
end;
function TDAOQuery<T>.Select: IDAOResult<T>;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',0,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Result := TDAOResult<T>.Create(Self);
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Select(const aFieldNames: string): IDAOResult<T>;
var
query : string;
filter : string;
begin
try
for filter in aFieldNames.Split([',']) do fSelectedFields := fSelectedFields + [filter];
query := fQueryGenerator.Select(fModel.TableName,aFieldNames,0,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Result := TDAOResult<T>.Create(Self);
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.SelectFirst: T;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',1,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Self.Movenext;
Result := Self.GetCurrent;
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.SelectLast: T;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',1,fWhereClause,fOrderClause,not fOrderAsc);
OpenQuery(query);
Self.Movenext;
Result := Self.GetCurrent;
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.SelectTop(aNumber: Integer): IDAOResult<T>;
var
query : string;
begin
try
query := fQueryGenerator.Select(fModel.TableName,'',aNumber,fWhereClause,fOrderClause,fOrderAsc);
OpenQuery(query);
Result := TDAOResult<T>.Create(Self);
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Sum(const aFieldName: string): Int64;
var
query : string;
begin
try
query := fQueryGenerator.Sum(fModel.TableName,aFieldName,fWhereClause);
if OpenQuery(query) > 0 then Result := GetFieldValue('cnt')
except
on E : Exception do raise EDAOSelectError.CreateFmt('Select error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Update(aDAORecord: TDAORecord): Boolean;
begin
try
if aDAORecord is TDAORecordTS then TDAORecordTS(aDAORecord).ModifiedDate := Now();
Result := ExecuteQuery(fQueryGenerator.Update(fModel.TableName,GetFieldsPairs(aDAORecord),
Format('%s=%s',[aDAORecord.PrimaryKey.FieldName,aDAORecord.PrimaryKey.Value])));
except
on E : Exception do raise EDAOUpdateError.CreateFmt('Update error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Update(const aFieldNames: string; const aFieldValues: array of const): Boolean;
var
stamped : Boolean;
begin
try
if TypeInfo(T) = TypeInfo(TDAORecordTS) then stamped := True;
Result := ExecuteQuery(fQueryGenerator.Update(fModel.TableName,GetFieldsPairs(aFieldNames,aFieldValues,stamped),fWhereClause));
except
on E : Exception do raise EDAOUpdateError.CreateFmt('Update error: %s',[e.message]);
end;
end;
function TDAOQuery<T>.Where(const aWhereClause: string): IDAOLinqQuery<T>;
begin
Result := Self;
fWhereClause := aWhereClause;
end;
function TDAOQuery<T>.Where(const aFormatSQLWhere: string; const aValuesSQLWhere: array of const): IDAOLinqQuery<T>;
begin
Result := Self;
fWhereClause := FormatParams(aFormatSQLWhere,aValuesSQLWhere);
end;
function TDAOQuery<T>.Delete: Boolean;
begin
try
Result := ExecuteQuery(fQueryGenerator.Delete(fModel.TableName,fWhereClause));
except
on E : Exception do raise EDAOUpdateError.CreateFmt('Delete error: %s',[e.message]);
end;
end;
end.
|
{------------------------------------------------------------------------}
{ }
{ Extenso.pas }
{ Classes de transcrição de valores e números por extenso. }
{ }
{ Copyright (c) 2001-2003. Emerson de Almeida Carneiro. }
{ http://www.fteam.com e.carneiro@fteam.com }
{ }
{------------------------------------------------------------------------}
unit Extenso;
interface
uses
{$IFNDEF CLX_VERSION}Windows,{$ENDIF} Classes, SysUtils, Messages;
type
{----------------------------------------------------------------------}
{ Tipos de dados personalizados }
{----------------------------------------------------------------------}
TTipoExtenso = (
teMasculino,
teFeminino
);
TDigito = 0..9;
{----------------------------------------------------------------------}
{ Estruturas de dados }
{----------------------------------------------------------------------}
TNumeroInfo = packed record
Centena: TDigito;
Dezena: TDigito;
Unidade: TDigito;
end;
TExtensoInfo = packed record
NumeroStr: String[3];
NumeroInt: SmallInt;
end;
{----------------------------------------------------------------------}
{ Rotinas de extenso }
{----------------------------------------------------------------------}
function MontaExtensoBase(AValor: Int64; ATipo: TTipoExtenso): String;
{----------------------------------------------------------------------}
{ derivações }
{----------------------------------------------------------------------}
function ValorPorExtenso(AValor: Currency): String;
function NumeroPorExtensoMasculino(ANumero: Int64): String;
function NumeroPorExtensoFeminino(ANumero: Int64): String;
resourcestring
{----------------------------------------------------------------------}
{ MOEDAS }
{----------------------------------------------------------------------}
{$IFDEF PADRAO_PORTUGAL}
SFctMoeda_IS = 'euro';
SFctMoeda_IP = 'euros';
SFctMoeda_DS = 'cêntimo';
SFctMoeda_DP = 'cêntimos';
{$ELSE}
SFctMoeda_IS = 'real';
SFctMoeda_IP = 'reais';
SFctMoeda_DS = 'centavo';
SFctMoeda_DP = 'centavos';
{$ENDIF}
SFctMoeda_E = 'e';
SFctMoeda_DE = 'de';
SFctMoeda_TS = 'trilhão';
SFctMoeda_TP = 'trilhões';
SFctMoeda_BS = 'bilhão';
SFctMoeda_BP = 'bilhões';
SFctMoeda_MS = 'milhão';
SFctMoeda_MP = 'milhões';
SFctMoeda_ML = 'mil';
SFctMoeda_1M = 'um';
SFctMoeda_1F = 'uma';
SFctMoeda_2M = 'dois';
SFctMoeda_2F = 'duas';
SFctMoeda_3M = 'três';
SFctMoeda_4M = 'quatro';
SFctMoeda_5M = 'cinco';
SFctMoeda_6M = 'seis';
SFctMoeda_7M = 'sete';
SFctMoeda_8M = 'oito';
SFctMoeda_9M = 'nove';
SFctMoeda_10 = 'dez';
SFctMoeda_20 = 'vinte';
SFctMoeda_30 = 'trinta';
SFctMoeda_40 = 'quarenta';
SFctMoeda_50 = 'cinquenta';
SFctMoeda_60 = 'sessenta';
SFctMoeda_70 = 'setenta';
SFctMoeda_80 = 'oitenta';
SFctMoeda_90 = 'noventa';
SFctMoeda_11 = 'onze';
SFctMoeda_12 = 'doze';
SFctMoeda_13 = 'treze';
SFctMoeda_14 = 'quatorze';
SFctMoeda_15 = 'quinze';
SFctMoeda_16 = 'dezesseis';
SFctMoeda_17 = 'dezessete';
SFctMoeda_18 = 'dezoito';
SFctMoeda_19 = 'dezenove';
SFctMoeda_C00M = 'cento';
SFctMoeda_100M = 'cem';
SFctMoeda_200M = 'duzentos';
SFctMoeda_200F = 'duzentas';
SFctMoeda_300M = 'trezentos';
SFctMoeda_300F = 'trezentas';
SFctMoeda_400M = 'quatrocentos';
SFctMoeda_400F = 'quatrocentas';
SFctMoeda_500M = 'quinhentos';
SFctMoeda_500F = 'quinhentas';
SFctMoeda_600M = 'seiscentos';
SFctMoeda_600F = 'seiscentas';
SFctMoeda_700M = 'setecentos';
SFctMoeda_700F = 'setecentas';
SFctMoeda_800M = 'oitocentos';
SFctMoeda_800F = 'oitocentas';
SFctMoeda_900M = 'novecentos';
SFctMoeda_900F = 'novecentas';
implementation
const
_lim_ext = 5; // limite para trilhões
_trilhao = 1;
_bilhao = 2;
_milhao = 3;
_milhar = 4;
_centena = 5;
function MontaExtensoBase(AValor: Int64; ATipo: TTipoExtenso): String;
const
// descrição das casas
_mm: array[1.._lim_ext, 1..2] of String = (
(SFctMoeda_TS, SFctMoeda_TP),
(SFctMoeda_BS, SFctMoeda_BP),
(SFctMoeda_MS, SFctMoeda_MP),
(SFctMoeda_ML, SFctMoeda_ML),
('', '')
);
// centena - MASCULINO
_cm: array[0..9] of String = (
SFctMoeda_C00M, SFctMoeda_100M, SFctMoeda_200M,
SFctMoeda_300M, SFctMoeda_400M, SFctMoeda_500M,
SFctMoeda_600M, SFctMoeda_700M, SFctMoeda_800M,
SFctMoeda_900M
);
// centena - FEMININO
_cf: array[0..9] of String = (
SFctMoeda_C00M, SFctMoeda_100M, SFctMoeda_200F,
SFctMoeda_300F, SFctMoeda_400F, SFctMoeda_500F,
SFctMoeda_600F, SFctMoeda_700F, SFctMoeda_800F,
SFctMoeda_900F
);
// dezena (11 a 19)
_dd: array[1..9] of String = (
SFctMoeda_11, SFctMoeda_12, SFctMoeda_13,
SFctMoeda_14, SFctMoeda_15, SFctMoeda_16,
SFctMoeda_17, SFctMoeda_18, SFctMoeda_19
);
// dezena inteira
_di: array[1..9] of String = (
SFctMoeda_10, SFctMoeda_20, SFctMoeda_30,
SFctMoeda_40, SFctMoeda_50, SFctMoeda_60,
SFctMoeda_70, SFctMoeda_80, SFctMoeda_90
);
// unidades - MASCULINO
_um: array[1..9] of String = (
SFctMoeda_1M, SFctMoeda_2M, SFctMoeda_3M,
SFctMoeda_4M, SFctMoeda_5M, SFctMoeda_6M,
SFctMoeda_7M, SFctMoeda_8M, SFctMoeda_9M
);
// unidades - FEMININO
_uf: array[1..9] of String = (
SFctMoeda_1F, SFctMoeda_2F, SFctMoeda_3M,
SFctMoeda_4M, SFctMoeda_5M, SFctMoeda_6M,
SFctMoeda_7M, SFctMoeda_8M, SFctMoeda_9M
);
var
Numero: TNumeroInfo;
tmpStr: ShortString;
tmpNum: String[3];
tmpExt: ShortString;
tmpPar: SmallInt;
i: Integer;
iNum: Byte;
ExtInfo: array[1.._lim_ext] of TExtensoInfo;
//----------------------------------------------------------------------
function TextoCentena(AIndex: Integer): ShortString;
begin
case ATipo of
teMasculino:
Result := _cm[AIndex];
teFeminino:
Result := _cf[AIndex];
end;
end;
//----------------------------------------------------------------------
function TextoUnidade(AIndex: Integer): ShortString;
begin
case ATipo of
teMasculino:
Result := _um[AIndex];
teFeminino:
Result := _uf[AIndex];
end;
end;
//----------------------------------------------------------------------
begin
Result := '';
if AValor <= 0 then Exit;
// compõe a string de formatação
tmpStr := IntToStr(AValor);
while (Length(tmpStr) < (_lim_ext * 3)) do
begin
tmpStr := '0' + tmpStr;
end;
// obtém as partes do número
for i := 1 to _lim_ext do
begin
tmpNum := Copy(tmpStr, ((i - 1) * 3) + 1, 3);
ExtInfo[i].NumeroStr := tmpNum;
tmpExt := '';
iNum := 1;
while (iNum <= 3) do
begin
if tmpNum[iNum] in ['0'..'9'] then
tmpExt := tmpExt + tmpNum;
iNum := iNum + 1;
end;
if tmpExt = '' then tmpExt := '0';
ExtInfo[i].NumeroInt := StrToInt(tmpExt);
end;
// inicia o processamento
for i := 1 to _lim_ext do
begin
tmpNum := ExtInfo[i].NumeroStr;
// armazena o número já devidamente fragmentado para análise
Numero.Centena := StrToInt(tmpNum[1]);
Numero.Dezena := StrToInt(tmpNum[2]);
Numero.Unidade := StrToInt(tmpNum[3]);
// constrói o extenso do número (parcial)
tmpExt := '';
tmpPar := StrToInt(tmpNum);
if tmpPar > 0 then
begin
// trata a centena
if (Numero.Centena > 0) then
begin
if (Numero.Centena = 1) and
((Numero.Dezena + Numero.Unidade) > 0) then
tmpExt := tmpExt + #32 + TextoCentena(0)
else
tmpExt := tmpExt + #32 + TextoCentena(Numero.Centena);
end;
// trata a dezena
if (Numero.Dezena > 0) then
begin
if (Numero.Centena > 0) then
tmpExt := tmpExt + #32 + SFctMoeda_E;
if (Numero.Dezena = 1) and (Numero.Unidade > 0) then
tmpExt := tmpExt + #32 + _dd[Numero.Unidade]
else
tmpExt := tmpExt + #32 + _di[Numero.Dezena];
end;
// trata a unidade
if (Numero.Unidade > 0) and (Numero.Dezena <> 1) then
begin
if (Numero.Centena > 0) or (Numero.Dezena > 0) then
tmpExt := tmpExt + #32 + SFctMoeda_E;
tmpExt := tmpExt + #32 + TextoUnidade(Numero.Unidade);
end;
if (tmpPar = 1) then
tmpExt := tmpExt + #32 + _mm[i][1]
else
tmpExt := tmpExt + #32 + _mm[i][2];
end;
// adiciona o texto do extenso da parte analisada
if Length(tmpExt) > 0 then
begin
if Result <> '' then
begin
if (Numero.Centena > 0) and
((Numero.Dezena > 0) or (Numero.Unidade > 0)) then
Result := Result + ','
else
Result := Result + #32 + SFctMoeda_E;
end;
Result := Result + #32 + TrimLeft(TrimRight(tmpExt));
end;
// inicia reprocessamento
end;
Result := TrimLeft(TrimRight(Result));
end;
function ValorPorExtenso(AValor: Currency): String;
var
NumInt: Int64;
NumDec: LongWord;
tmpStr: ShortString;
ExtInt: String;
ExtDec: String;
p: Byte;
begin
Result := '';
tmpStr := FormatFloat('0.00', AValor);
p := Pos(DecimalSeparator, tmpStr);
NumInt := StrToInt64Def(Copy(tmpStr, 1, p - 1), 0);
NumDec := StrToIntDef(Copy(tmpStr, p + 1, 2), 0);
if NumInt > 0 then
begin
ExtInt := MontaExtensoBase(NumInt, teMasculino);
if NumInt = 1 then
Result := ExtInt + #32 + SFctMoeda_IS
else
Result := ExtInt + #32 + SFctMoeda_IP;
end;
if NumDec > 0 then
begin
if NumInt > 0 then ExtDec := SFctMoeda_E;
ExtDec := ExtDec + #32 + MontaExtensoBase(NumDec, teMasculino);
if NumDec = 1 then
Result := Result + #32 + ExtDec + #32 + SFctMoeda_DS
else
Result := Result + #32 + ExtDec + #32 + SFctMoeda_DP;
end;
end;
function NumeroPorExtensoMasculino(ANumero: Int64): String;
begin
Result := MontaExtensoBase(ANumero, teMasculino);
end;
function NumeroPorExtensoFeminino(ANumero: Int64): String;
begin
Result := MontaExtensoBase(ANumero, teFeminino);
end;
end.
|
{
@abstract(Essa classe é uma classe final)
}
unit UQuadrado;
interface
uses
UFormaGeometrica
, Graphics
, Controls
;
type
TQuadrado = class(TFormaGeometrica)
private
FLado: Integer;
public
constructor Create(const coCor: TColor); overload;
function CalculaArea: Double; override;
function SolicitaParametros: Boolean; override;
procedure Desenha(const ciX, ciY: Integer;
const coParent: TWinControl); override;
property LADO: Integer read FLado;
end;
implementation
uses
Dialogs
, SysUtils
, ExtCtrls
;
{ TQuadrado }
constructor TQuadrado.Create(const coCor: TColor);
begin
Inherited Create(tfgQuadrado, coCor);
FShape.Shape := stSquare;
end;
function TQuadrado.CalculaArea: Double;
begin
Result := FLado * FLado;
end;
procedure TQuadrado.Desenha(const ciX, ciY: Integer;
const coParent: TWinControl);
begin
Inherited;
FShape.Width := FLado;
FShape.Height := FLado;
end;
function TQuadrado.SolicitaParametros: Boolean;
begin
FLado := StrToIntDef(InputBox('Informe'
, 'Lado do Quadrado', ''), -1);
Result := FLado > -1;
end;
end.
|
unit UInspector;
{$mode objfpc}{$H+}
interface
uses
Classes, typinfo, Graphics, ExtCtrls, StdCtrls, UBaseShape, UGeometry;
type
TParamsUpdateEvent = procedure of object;
{ TParamEditor }
TParamEditor = class
protected
FShapes: array of TShape;
FLabel: TLabel;
FPropInfo: PPropInfo;
procedure Change(Sender: TObject); virtual;
public
constructor Create(AShapes: array of TShape; APropInfo: PPropInfo;
APanel: TPanel; ADefaultParams: Boolean); virtual;
destructor Destroy; override;
end;
{ TInspector }
TInspector = class
private
FShapes: array of TShape;
FEditors: array of TParamEditor;
FPenColor, FBrushColor: TColor;
FDefaultParams: Boolean;
FPanel: TPanel;
FParamsUpdateEvent: TParamsUpdateEvent;
function SearchPropertyInObject(AShape: TShape; AProperty: PPropInfo): Boolean;
function CheckPropertyInAllObjects(AShapes: array of TShape; AProperty: PPropInfo): Boolean;
public
property OnParamsUpdate: TParamsUpdateEvent read FParamsUpdateEvent
write FParamsUpdateEvent;
constructor Create(APanel: TPanel);
procedure LoadNew(AShape: TShape);
procedure Load(AShapes: array of TShape);
procedure Clean;
end;
TParamEditorClass = class of TParamEditor;
{ ArrayOfEditor }
TArrayOfEditor = array of record
Item: TParamEditorClass;
Kind: String;
end;
{ TEditorContainer }
TEditorContainer = class
private
FEditors: TArrayOfEditor;
public
procedure RegisterEditor(AClass: TParamEditorClass; AKind: ShortString);
property Editors: TArrayOfEditor read FEditors;
end;
TEditEvent = procedure of object;
var
Inspector: TInspector;
EditorContainer: TEditorContainer;
ShiftEditorContainer: TEditorContainer;
OnUpdateFileStatus: TEditEvent;
OnUpdateEditor: TEditEvent;
implementation
var
PropNames : TStringList;
{ TEditorContainer }
procedure TEditorContainer.RegisterEditor(AClass: TParamEditorClass;
AKind: ShortString);
begin
SetLength(FEditors, Length(FEditors) + 1);
FEditors[High(FEditors)].Item := AClass;
FEditors[High(FEditors)].Kind := AKind;
end;
{ TInspector }
constructor TInspector.Create(APanel: TPanel);
begin
FPanel:= APanel;
FPenColor:= clBlack;
FBrushColor:= clWhite;
end;
procedure TInspector.LoadNew(AShape: TShape);
var
shapes: array of TShape;
begin
if AShape = nil then begin
Clean;
exit;
end;
FDefaultParams := true;
SetLength(shapes, 1);
shapes[0] := AShape;
Load(shapes);
end;
function TInspector.SearchPropertyInObject(AShape: TShape;
AProperty: PPropInfo): Boolean;
var
i, j: integer;
list: PPropList;
begin
j := GetPropList(AShape, list);
Result := false;
for i := 0 to j - 1 do
if list^[i] = AProperty then
begin
Result := true;
exit;
end;
end;
function TInspector.CheckPropertyInAllObjects(AShapes: array of TShape;
AProperty: PPropInfo): Boolean;
var
j: Integer;
begin
Result := True;
for j := 1 to High(AShapes) do
begin
Result := SearchPropertyInObject(AShapes[j], AProperty);
if not Result then
exit;
end;
end;
procedure TInspector.Load(AShapes: array of TShape);
var
list: PPropList;
i, j, k: integer;
begin
Clean;
if Length(AShapes) = 0 then
Exit;
SetLength(FShapes, Length(AShapes));
for i := 0 to High(AShapes) do
FShapes[i] := AShapes[i];
FPanel.Tag := 10;
j := GetPropList(FShapes[0], list);
for i := 0 to j - 1 do
begin
if CheckPropertyInAllObjects(FShapes, list^[i]) then
begin
for k := 0 to High(EditorContainer.Editors) do
if list^[i]^.PropType^.Name = EditorContainer.Editors[k].Kind then
begin
SetLength(FEditors, Length(FEditors) + 1);
FEditors[High(FEditors)] := EditorContainer.Editors[k].Item.Create(
FShapes, list^[i], FPanel, FDefaultParams);
Break;
end;
end;
end;
if Length(FShapes) > 1 then
for i := 0 to j - 1 do
begin
for k := 0 to High(ShiftEditorContainer.Editors) do
if list^[i]^.PropType^.Name = ShiftEditorContainer.Editors[k].Kind then
begin
SetLength(FEditors, Length(FEditors) + 1);
FEditors[High(FEditors)] := ShiftEditorContainer.Editors[k].Item.Create(
FShapes, list^[i], FPanel, FDefaultParams);
Break;
end;
end;
FDefaultParams := False;
end;
procedure TInspector.Clean;
var i: integer;
begin
for i := 0 to High(FEditors) do
FEditors[i].Destroy;
SetLength(FEditors, 0);
SetLength(FShapes, 0);
end;
{ TParamEditor }
procedure TParamEditor.Change(Sender: TObject);
begin
Inspector.OnParamsUpdate;
OnUpdateFileStatus;
OnUpdateEditor;
end;
constructor TParamEditor.Create(AShapes: array of TShape;
APropInfo: PPropInfo; APanel: TPanel; ADefaultParams: Boolean);
var i: integer;
begin
SetLength(FShapes, Length(AShapes));
for i := 0 to High(AShapes) do
FShapes[i] := AShapes[i];
FPropInfo := APropInfo;
FLabel := TLabel.Create(nil);
FLabel.Parent := APanel;
FLabel.Caption := PropNames.Values[APropInfo^.Name];
FLabel.Left := 10;
FLabel.Width := trunc(APanel.Width / 2) - 20;
FLabel.Top := APanel.Tag;
if FLabel.Caption = '' then FLabel.Caption := APropInfo^.Name;
APanel.Tag := APanel.Tag + 35;
end;
destructor TParamEditor.Destroy;
begin
FLabel.Free;
end;
initialization
EditorContainer := TEditorContainer.Create;
ShiftEditorContainer := TEditorContainer.Create;
PropNames := TStringList.Create;
PropNames.Values['BrushStyle'] :='Fill style:';
PropNames.Values['PenWidth'] :='Pen width:';
PropNames.Values['PenStyle'] :='Pen style:';
PropNames.Values['RadiusX'] :='Radius X:';
PropNames.Values['RadiusY'] := 'Radius Y:';
end.
|
unit gridOperUnit;
interface
uses System.SysUtils, Vcl.Grids, Vcl.DBGrids;
var
ss: string;
procedure SetGridColumnWidths(Grid: Tdbgrid);
implementation
procedure SetGridColumnWidths(Grid: Tdbgrid);
const
DEFBORDER = 10;
var
temp, n: Integer;
lmax: array [0..30] of Integer;
begin
with Grid do
begin
Canvas.Font := Font;
for n := 0 to Columns.Count - 1 do
lmax[n] := Canvas.TextWidth(Fields[n].FieldName) + DEFBORDER;
grid.DataSource.DataSet.First;
while not grid.DataSource.DataSet.EOF do
begin
for n := 0 to Columns.Count - 1 do
begin
temp := Canvas.TextWidth(trim(Columns[n].Field.DisplayText)) + DEFBORDER;
if temp > lmax[n] then lmax[n] := temp;
end; {for}
grid.DataSource.DataSet.Next;
end;
grid.DataSource.DataSet.First;
for n := 0 to Columns.Count - 1 do
if lmax[n] > 0 then
Columns[n].Width := lmax[n];
end;
end; {SetGridColumnWidths}
end.
|
unit uConstrutorSQL;
interface
uses
Classes;
type
TConstrutorSQL = class
private
FCampos: TStringList;
FCondicoes: TStringList;
FTabela: string;
FJuncoes: TStringList;
FCamposTabelaSecundaria: TStringList;
function JuncaoFormatada(psTabelaPrincipal, psTabelaSecundaria: string): string;
public
constructor Create;
destructor Destroy;
property Condicoes: TStringList read FCondicoes write FCondicoes;
property CamposTabelaSecundaria: TStringList read FCamposTabelaSecundaria;
procedure Construir(poClasse: TObject);
function SQLGerado: string;
end;
implementation
uses
SysUtils, StrUtils, RTTI, uAtributosCustomizados;
{ TConstrutorSQL }
constructor TConstrutorSQL.Create;
begin
FCampos := TStringList.Create;
FCondicoes := TStringList.Create;
FJuncoes := TStringList.Create;
FCamposTabelaSecundaria := TStringList.Create;
end;
destructor TConstrutorSQL.Destroy;
begin
FreeAndNil(FCampos);
FreeAndNil(FCondicoes);
FreeAndNil(FJuncoes);
FreeAndNil(FCamposTabelaSecundaria);
end;
function TConstrutorSQL.JuncaoFormatada(psTabelaPrincipal, psTabelaSecundaria: string): string;
begin
Result := ' LEFT JOIN %S ON (%P.ID%S = %S.ID%S) '
.Replace('%P', psTabelaPrincipal)
.Replace('%S', psTabelaSecundaria);
end;
function CampoSecundarioFormatado(psNomeTabela, psNomeCampo: string): string;
begin
Result := ', %T.%C %T_%C'
.Replace('%T', psNomeTabela)
.Replace('%C', psNomeCampo);
end;
procedure TConstrutorSQL.Construir(poClasse: TObject);
var
Ctx: TRttiContext;
rpPropriedade: TRttiProperty;
caAtributo: TCustomAttribute;
bFazJuncao: boolean;
begin
FTabela := poClasse.ClassName.Substring(1);
FCampos.Clear;
FJuncoes.Clear;
FCamposTabelaSecundaria.Clear;
for rpPropriedade in Ctx.GetType(poClasse.ClassType).GetDeclaredProperties do
begin
bFazJuncao := False;
for caAtributo in rpPropriedade.GetAttributes do
begin
if caAtributo is TCampoTabelaExterna then
begin
FCamposTabelaSecundaria.Add(CampoSecundarioFormatado(rpPropriedade.Name, (caAtributo as TCampoTabelaExterna).Nome));
bFazJuncao := True;
end;
end;
if (rpPropriedade.GetValue(poClasse).Kind = tkClass) then
begin
if bFazJuncao then
FJuncoes.Add(JuncaoFormatada(FTabela, rpPropriedade.Name));
continue;
end;
FCampos.Add(',' + FTabela + '.' + rpPropriedade.Name);
end;
FCampos.Text := FCampos.Text.Remove(0, 1);
end;
function TConstrutorSQL.SQLGerado: string;
var
i: integer;
begin
Result :=
' SELECT ' + FCampos.Text + FCamposTabelaSecundaria.Text +
' FROM ' + FTabela;
Result := Result + FJuncoes.Text;
if FCondicoes.Count > 0 then
begin
Result := Result + ' WHERE ';
for i := 0 to Pred(FCondicoes.Count) do
Result := Result + IfThen(i > 0, ' AND ') + FCondicoes[i];
end;
end;
end.
|
unit fConsultAlertTo;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ORCtrls, ORfn, ExtCtrls, fBase508Form, VA508AccessibilityManager;
type
TfrmConsultAlertsTo = class(TfrmBase508Form)
cmdOK: TButton;
cmdCancel: TButton;
cboSrcList: TORComboBox;
DstList: TORListBox;
SrcLabel: TLabel;
DstLabel: TLabel;
pnlBase: TORAutoPanel;
btnAdd: TButton;
btnRemove: TButton;
procedure cboSrcListNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
//procedure cboSrcListdblClick(Sender: TObject);
procedure cboSrcListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DstListClick(Sender: TObject);
procedure cboSrcListMouseClick(Sender: TObject);
private
FActionType: integer;
FRecipients: string ;
FChanged: Boolean;
end;
TRecipientList = record
Changed: Boolean;
Recipients: string ;
end;
procedure SelectRecipients(FontSize: Integer; ActionType: integer; var RecipientList: TRecipientList) ;
implementation
{$R *.DFM}
uses rConsults, rCore, uCore, uConsults, fConsults;
const
TX_RCPT_TEXT = 'Select recipients or press Cancel.';
TX_RCPT_CAP = 'No Recipients Selected';
TX_REQ_TEXT = 'The requesting provider is always included in this type of alert';
TX_REQ_CAP = 'Cannot Remove Recipient';
procedure SelectRecipients(FontSize: Integer; ActionType: integer; var RecipientList: TRecipientList) ;
{ displays recipients select form for consults and returns a record of the selection }
var
frmConsultAlertsTo: TfrmConsultAlertsTo;
begin
frmConsultAlertsTo := TfrmConsultAlertsTo.Create(Application);
try
ResizeAnchoredFormToFont(frmConsultAlertsTo);
with frmConsultAlertsTo do
begin
FActionType := ActionType;
FChanged := False;
cboSrcList.InitLongList('');
(* cboSrcList.InitLongList(ConsultRec.SendingProviderName);
cboSrcList.SelectByIEN(ConsultRec.SendingProvider);
cboSrcListMouseClick(cboSrcList) ;*)
ShowModal;
with RecipientList do
begin
Recipients := Recipients + FRecipients ;
Changed := FChanged ;
end ;
end; {with frmConsultAlertsTo}
finally
frmConsultAlertsTo.Release;
end;
end;
procedure TfrmConsultAlertsTo.cboSrcListNeedData(Sender: TObject;
const StartFrom: String; Direction, InsertAt: Integer);
begin
(Sender as TORComboBox).ForDataUse(SubSetOfPersons(StartFrom, Direction));
end;
procedure TfrmConsultAlertsTo.cmdCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmConsultAlertsTo.cmdOKClick(Sender: TObject);
var
i: integer ;
begin
if DstList.Items.Count = 0 then
begin
InfoBox(TX_RCPT_TEXT, TX_RCPT_CAP, MB_OK or MB_ICONWARNING);
FChanged := False ;
Exit;
end;
FChanged := True;
for i := 0 to DstList.Items.Count-1 do
FRecipients := Piece(DstList.Items[i],u,1) + ';' + FRecipients;
Close;
end;
(*procedure TfrmConsultAlertsTo.cboSrcListdblClick(Sender: TObject);
begin
if cboSrcList.ItemIndex = -1 then exit ;
if DstList.SelectByID(cboSrcList.ItemID) = -1 then
DstList.Items.Add(cboSrcList.Items[cboSrcList.Itemindex]) ;
end;*)
procedure TfrmConsultAlertsTo.DstListClick(Sender: TObject);
begin
if DstList.ItemIndex = -1 then exit ;
(* if (DstList.ItemIEN = ConsultRec.SendingProvider) and
((FActionType = CN_ACT_SIGFIND) or (FActionType = CN_ACT_ADMIN_COMPLETE)) then
begin
InfoBox(TX_REQ_TEXT, TX_REQ_CAP, MB_OK or MB_ICONWARNING);
exit ;
end ;*)
DstList.Items.Delete(DstList.ItemIndex) ;
end;
procedure TfrmConsultAlertsTo.cboSrcListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then cboSrcListMouseClick(Self);
end;
procedure TfrmConsultAlertsTo.cboSrcListMouseClick(Sender: TObject);
begin
if cboSrcList.ItemIndex = -1 then exit ;
if DstList.SelectByID(cboSrcList.ItemID) = -1 then
DstList.Items.Add(cboSrcList.Items[cboSrcList.Itemindex]) ;
end;
end.
|
unit AnimalsClasses;
interface
type
TAnimal = class
public
constructor Create;
function GetKind: string;
function Voice: string; virtual; abstract;
private
FKind: string;
end;
TDog = class (TAnimal)
public
constructor Create;
function Voice: string; override;
function Eat: string; virtual;
end;
TCat = class (TAnimal)
public
constructor Create;
function Voice: string; override;
function Eat: string; virtual;
end;
implementation
{ TAnimal }
constructor TAnimal.Create;
begin
FKind := 'Animal';
end;
function TAnimal.GetKind: string;
begin
Result := FKind;
end;
{ TDog }
constructor TDog.Create;
begin
inherited;
FKind := 'Dog';
end;
function TDog.Eat: string;
begin
Result := 'Bone';
end;
function TDog.Voice: string;
begin
Result := 'ArfArf';
end;
{ TCat }
constructor TCat.Create;
begin
inherited;
FKind := 'Cat';
end;
function TCat.Eat: string;
begin
Result := 'Mouse';
end;
function TCat.Voice: string;
begin
Result := 'Mieow';
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, IniFiles, ShellApi, ComCtrls, XPMan, EditName,
// XLSReadWriteII units
Xc12Utils5, Xc12DataWorkbook5, XLSSheetData5, XLSReadWriteII5, XLSNames5;
type
TfrmMain = class(TForm)
Panel1: TPanel;
btnRead: TButton;
btnWrite: TButton;
edReadFilename: TEdit;
edWriteFilename: TEdit;
btnDlgOpen: TButton;
btnDlgSave: TButton;
btnAddName: TButton;
btnEditName: TButton;
btnClose: TButton;
XLS: TXLSReadWriteII5;
Button1: TButton;
lvNames: TListView;
XPManifest: TXPManifest;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
btnNameValues: TButton;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure btnReadClick(Sender: TObject);
procedure btnDlgOpenClick(Sender: TObject);
procedure btnDlgSaveClick(Sender: TObject);
procedure btnAddNameClick(Sender: TObject);
procedure btnWriteClick(Sender: TObject);
procedure btnEditNameClick(Sender: TObject);
procedure btnNameValuesClick(Sender: TObject);
private
procedure ReadNames;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
var
S: string;
Ini: TIniFile;
begin
S := ChangeFileExt(Application.ExeName,'.ini');
Ini := TIniFile.Create(S);
try
edReadFilename.Text := Ini.ReadString('Files','Read','');
edWriteFilename.Text := Ini.ReadString('Files','Write','');
finally
Ini.Free;
end;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
var
S: string;
Ini: TIniFile;
begin
S := ChangeFileExt(Application.ExeName,'.ini');
Ini := TIniFile.Create(S);
try
Ini.WriteString('Files','Read', edReadFilename.Text);
Ini.WriteString('Files','Write',edWriteFilename.Text);
finally
Ini.Free;
end;
end;
procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.Button1Click(Sender: TObject);
begin
ShellExecute(Handle,'open', 'excel.exe',PWideChar(edWriteFilename.Text), nil, SW_SHOWNORMAL);
end;
procedure TfrmMain.btnReadClick(Sender: TObject);
begin
XLS.Filename := edReadFilename.Text;
XLS.Read;
ReadNames;
end;
procedure TfrmMain.btnDlgOpenClick(Sender: TObject);
begin
dlgOpen.InitialDir := ExtractFilePath(Application.ExeName);
dlgOpen.FileName := edReadFilename.Text;
if dlgOpen.Execute then
edReadFilename.Text := dlgOpen.FileName;
end;
procedure TfrmMain.btnDlgSaveClick(Sender: TObject);
begin
dlgSave.InitialDir := ExtractFilePath(Application.ExeName);
dlgSave.FileName := edWriteFilename.Text;
if dlgSave.Execute then
edWriteFilename.Text := dlgSave.FileName;
end;
procedure TfrmMain.ReadNames;
var
i: integer;
N: TXLSName;
Item: TListItem;
begin
lvNames.Items.BeginUpdate;
lvNames.Clear;
try
for i := 0 to XLS.Names.Count - 1 do begin
N := XLS.Names.Items[i];
Item := lvNames.Items.Add;
case N.BuiltIn of
bnConsolidateArea: Item.Caption := 'Consolidate_Area';
bnExtract : Item.Caption := 'Extract';
bnDatabase : Item.Caption := 'Database';
bnCriteria : Item.Caption := 'Criteria';
bnPrintArea : Item.Caption := 'Print_Area';
bnPrintTitles : Item.Caption := 'Print_Titles';
bnSheetTitle : Item.Caption := 'Sheet_Title';
bnFilterDatabase : Item.Caption := 'Filter_Database';
bnNone : Item.Caption := N.Name;
end;
if N.SimpleName in [xsntRef,xsntArea] then
Item.SubItems.Add(XLS.NameAsString[N.Name])
else
Item.SubItems.Add('');
Item.SubItems.Add(N.Definition);
if N.LocalSheetId >= 0 then
Item.SubItems.Add(XLS[N.LocalSheetId].Name)
else
Item.SubItems.Add('Workbook');
Item.SubItems.Add(N.Comment);
end;
finally
lvNames.Items.EndUpdate;
end;
end;
procedure TfrmMain.btnAddNameClick(Sender: TObject);
begin
if lvNames.ItemIndex >= 0 then begin
if TfrmEditName.Create(Self).Execute(XLS,XLS.Names[lvNames.ItemIndex]) then
ReadNames;
end;
end;
procedure TfrmMain.btnWriteClick(Sender: TObject);
begin
XLS.Filename := edWriteFilename.Text;
XLS.Write;
end;
procedure TfrmMain.btnEditNameClick(Sender: TObject);
begin
if TfrmEditName.Create(Self).Execute(XLS,Nil) then
ReadNames;
end;
procedure TfrmMain.btnNameValuesClick(Sender: TObject);
var
S: string;
Name: TXLSName;
Row,Col: integer;
Sheet: integer;
begin
S := 'MyName';
// Access the cell value that a Defined Name refers to.
// The Defined Name must refer to a single cell. You can check if this is
// true with the NameIsSimpleName property. If the name don't exists or if
// it not is a simple name, NameIsSimpleName returns false.
if XLS.NameIsSimpeName[S] then begin
XLS.NameAsFloat[S] := 125;
XLS.NameAsString[S] := 'Hello';
ShowMessage(XLS.NameAsFmtString[S]);
XLS.NameAsBoolean[S] := True;
XLS.NameAsError[S] := errREF;
XLS.NameAsFormula[S] := 'SUM(A1:A5)';
XLS.NameAsNumFormulaValue[S] := 125;
XLS.NameAsStrFormulaValue[S] := 'Hello';
XLS.NameAsBoolFormulaValue[S] := True;
end;
// Names can also be accessed trough the Names property.
Name := XLS.Names.Find(S);
if Name <> Nil then begin
if Name.SimpleName in [xsntRef,xsntArea] then begin
Col := Name.SimpleArea.Col1;
Row := Name.SimpleArea.Row1;
Sheet := Name.SimpleArea.SheetIndex;
// Access the cell trough normal methods.
XLS[Sheet].AsFloat[Col,Row] := 125;
// The cell the name refers to. Note that name definition must contain
// the worksheet name, and cell references must be absolute. If not
// absolute, unexpected things happends when the name is used.
Name.Definition := 'Sheet1!$A$1';
end;
end;
end;
end.
|
unit uPassword;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.Imaging.pngimage, Vcl.ImgList,
uDocument, Logic;
type
TfrmPassword = class(TForm)
Image1: TImage;
Label1: TLabel;
txtOldPass: TButtonedEdit;
txtNewPass: TButtonedEdit;
txtConfirmPass: TButtonedEdit;
btnOK: TButton;
btnClose: TButton;
pnlLine: TPanel;
imlPassword: TImageList;
procedure txtEnter(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure txtOldPassChange(Sender: TObject);
procedure txtNewPassChange(Sender: TObject);
procedure txtConfirmPassChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
fDoc: TOmgDocument;
function CheckOldPass(Msg: Boolean): Boolean;
function CheckNewPass(Msg: Boolean): Boolean;
function CheckConfirmPass(Msg: Boolean): Boolean;
public
newPassword: String;
constructor Create(AOwner: TComponent; Document: TOmgDocument); reintroduce;
end;
var
frmPassword: TfrmPassword;
implementation
uses uStrings;
{$R *.dfm}
constructor TfrmPassword.Create(AOwner: TComponent; Document: TOmgDocument);
begin
inherited Create(AOwner);
fDoc:=Document;
end;
procedure TfrmPassword.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Self.BorderIcons:=[];
Self.Caption:='';
end;
procedure TfrmPassword.FormShow(Sender: TObject);
begin
WindowsOnTop(bWindowsOnTop, Self);
end;
{проверка соответствия старого пароля}
function TfrmPassword.CheckOldPass(Msg: Boolean): Boolean;
begin
Result:= fDoc.CheckThisPassword(txtOldPass.Text);
if not Result and Msg then
MessageBox(Self.Handle,
PWideChar(rsWrongOldPassword),
PWideChar(rsWrongOldPasswordTitle),
MB_ICONERROR + MB_OK + MB_APPLMODAL);
//if Result then txtNewPass.SetFocus;
end;
{новый пароль должен отличаться}
function TfrmPassword.CheckNewPass(Msg: Boolean): Boolean;
begin
Result:= (txtOldPass.Text <> txtNewPass.Text);
if not Result and Msg then
MessageBox(Self.Handle,
PWideChar(rsWrongNewPassword),
PWideChar(rsWrongNewPasswordTitle),
MB_ICONWARNING + MB_OK + MB_APPLMODAL);
if Result and Msg and (txtNewPass.Text = '') then
if MessageBox(Self.Handle,
PWideChar(rsNewPasswordEmpty),
PWideChar(rsNewPasswordEmptyTitle),
MB_ICONQUESTION + MB_OK + MB_YESNO + MB_APPLMODAL) = mrNo then
Result:=False;
end;
{подтверждение должно совпадать}
function TfrmPassword.CheckConfirmPass(Msg: Boolean): Boolean;
begin
Result:= (txtConfirmPass.Text = txtNewPass.Text);
if not Result and Msg then
MessageBox(Self.Handle,
PWideChar(rsWrongConfirmPassword),
PWideChar(rsWrongConfirmPasswordTitle),
MB_ICONWARNING + MB_OK + MB_APPLMODAL);
end;
procedure TfrmPassword.btnCloseClick(Sender: TObject);
begin
Self.ModalResult:=mrCancel;
end;
procedure TfrmPassword.btnOKClick(Sender: TObject);
begin
if not CheckOldPass(True) then begin
txtOldPass.SetFocus;
Exit;
end;
if not CheckNewPass(True) then begin
txtNewPass.SetFocus;
Exit;
end;
if not CheckConfirmPass(True) then Exit;
if fDoc.ChangePassword(txtNewPass.Text) then;
MessageBox(Self.Handle,
PWideChar(rsPasswordChanged),
PWideChar(rsPasswordChangedTitle),
MB_ICONINFORMATION + MB_OK + MB_APPLMODAL);
Self.ModalResult:=mrOk;
end;
procedure TfrmPassword.txtEnter(Sender: TObject);
begin
With (Sender as TButtonedEdit) do begin
if Font.Color = clGrayText then begin
RightButton.Visible:=True;
Font.Style:=[];
Font.Color:=clWindowText;
Text:='';
end;
end;
end;
procedure TfrmPassword.txtOldPassChange(Sender: TObject);
begin
txtOldPass.RightButton.ImageIndex:= CheckOldPass(False).ToInteger;
txtNewPassChange(nil);
end;
procedure TfrmPassword.txtNewPassChange(Sender: TObject);
begin
txtNewPass.RightButton.ImageIndex:= CheckNewPass(False).ToInteger;
txtConfirmPassChange(nil);
end;
procedure TfrmPassword.txtConfirmPassChange(Sender: TObject);
begin
txtConfirmPass.RightButton.ImageIndex:=CheckConfirmPass(False).ToInteger;
end;
end.
|
unit uMembersArray;
interface
uses uMembersClass, ADODB, DB, SysUtils, Classes, Dialogs;
type TMembersArray = class
private
conn : TADOConnection;
dbName : String;
public
constructor Create(db : String);
function getAllMembers: TStringList;
function getMemberNames : TStringList;
function getMemberDetails(memberID : integer) : TMembers;
function deleteMember(memberID : integer) : TStringList;
procedure addMember(member : TMembers);
procedure updateMember(member : TMembers);
procedure CloseDB;
end;
implementation
{ TMembersArray }
{A procedure for adding a new member to the database. A member object is
fed into the procedure. The attributes of the object are read out using
its various functions. The data is used to construct an insert query which is
sent to the database. The connection to the database is then closed.}
procedure TMembersArray.addMember(member: TMembers);
var
sqlQ : string;
query :TADOQuery;
begin
sqlQ := 'INSERT INTO tblMembers (Name, Surname, BlockOrStaff, House, ' +
'Position, YearJoined) VALUES (';
sqlQ := sqlQ + '''' +member.getName;
sqlQ := sqlQ + ''', ''' +member.getSurname;
sqlQ := sqlQ + ''', ''' +member.getBlock;
sqlQ := sqlQ + ''', ''' +member.getHouse;
sqlQ := sqlQ + ''', '''+member.getPosition+''', '+
IntToStr(member.getYearJoined)+')';
//InputBox(sqlQ, sqlQ, sqlQ);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.ExecSQL;
query.Close;
end;
{Code with the specific purpose of closing the database connection to prevent
errors, overflows, slow response, etc.}
procedure TMembersArray.CloseDB;
begin
conn.Close;
end;
{The constructor for the members array class. Specifies how it connects to the
database and takes in the name of a database to which it then connects.}
constructor TMembersArray.Create(db: String);
begin
conn := TADOConnection.Create(NIL);
conn.ConnectionString := 'Provider=MSDASQL.1;Persist Security Info=False;' +
'Extended Properties="DBQ=' + db + ';' +
'Driver={Driver do Microsoft Access (*.mdb)};' +
'DriverId=25;FIL=MS Access;' +
'FILEDSN=C:\Program Files\Common Files\ODBC\Data Sources\Test.dsn;' +
'MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;SafeTransactions=0;' +
'Threads=3;UID=admin;UserCommitSync=Yes;"';
end;
{A function to query the members table of the database
and delete a selected member. The memberID is inserted into the function. An
SQL statement is generated to delete the information of all entries with that
specified memberID. The connection to the database is then closed.}
function TMembersArray.deleteMember(memberID: integer): TStringList;
var
sqlQ : String;
query :TADOQuery;
begin
sqlQ := 'DELETE * FROM tblMembers WHERE MemberID = ' + IntToStr(memberID);
//InputBox(sqlQ, sqlQ, sqlQ);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.ExecSQL;
query.Close;
end;
{A function to query the members table of the database and return all fields.
This function simply returns all the data about all the members found in the
database as a stringlist. This is done through a hardcoded SQL statement. A
stringlist is created and the results of the SQL are fed in as the toString
expressions from member objects which are generated in the following script.
The database connection is then closed.}
function TMembersArray.getAllMembers: TStringList;
var
sqlQ : String;
query : TADOQuery;
m : TMembers;
sl : TStringList;
begin
sqlQ := 'SELECT * FROM tblMembers';
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.Active := true;
sl := TStringList.Create;
while NOT query.EOF do
begin
m := TMembers.Create(query.FieldValues['MemberID'],
query.FieldValues['Name'],
query.FieldValues['Surname'],
query.FieldValues['BlockOrStaff'],
query.FieldValues['House'],
query.FieldValues['Position'],
query.FieldValues['YearJoined']);
sl.AddObject(m.toString, m);
query.Next;
end;
query.Active := false;
query.Close;
Result := sl;
end;
{A function to query the database for the details of a particular member.
The memberID is provided by the user and is used to construct the SQL statement
whoch retrieves all data from the database for that memberID. The data is
used to create a members object which is outputted as the result.}
function TMembersArray.getMemberDetails(memberID: integer): TMembers;
var
sqlQ : String;
query : TADOQuery;
m : TMembers;
begin
sqlQ := 'SELECT * FROM tblMembers WHERE MemberID = ' + IntToStr(MemberID);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.Active := true;
m := nil;
if NOT query.EOF then
begin
m := TMembers.Create(query.FieldValues['MemberID'],
query.FieldValues['Name'],
query.FieldValues['Surname'],
query.FieldValues['BlockOrStaff'],
query.FieldValues['House'],
query.FieldValues['Position'],
query.FieldValues['YearJoined']);
end;
query.Active := false;
query.Close;
Result := m;
end;
{A function to query the members table of the database and return all fields.
This function simply returns all the data about all the members found in the
database as a stringlist. This is done through a hardcoded SQL statement. A
stringlist is created and the results of the SQL are fed in as the toString
expressions from member objects which are generated in the following script.
The database connection is then closed. Only the names of the members are
outputted to the stringlist as the toNameString function is used.}
function TMembersArray.getMemberNames: TStringList;
var
sqlQ : String;
query : TADOQuery;
m : TMembers;
sl : TStringList;
begin
sqlQ := 'SELECT * FROM tblMembers';
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.Active := true;
sl := TStringList.Create;
while NOT query.EOF do
begin
m := TMembers.Create(query.FieldValues['MemberID'],
query.FieldValues['Name'],
query.FieldValues['Surname'],
query.FieldValues['BlockOrStaff'],
query.FieldValues['House'],
query.FieldValues['Position'],
query.FieldValues['YearJoined']);
sl.AddObject(m.toNameString, m);
query.Next;
end;
query.Active := false;
query.Close;
Result := sl;
end;
{A function to query the members table of the database and
update a selected member. A member object is provided by the user. The
data from the object is accessed through its various functions and used
to construct an SQL statement to update the details of a specific member in
the database. Once the query has been executed the connection
to the database is closed.}
procedure TMembersArray.updateMember(member: TMembers);
var
sqlQ : string;
query :TADOQuery;
begin
sqlQ := 'UPDATE tblMembers SET '
+'Name = '+''''+member.getName+''''
+', Surname = '+''''+member.getSurname+''''
+', BlockOrStaff = '+''''+member.getBlock+''''
+', House = '+''''+member.getHouse+''''
+', Position = '+''''+member.getPosition+''''
+', YearJoined = '+IntToStr(member.getYearJoined)
+' WHERE MemberID = ' + IntToStr(member.getID);
//InputBox(sqlQ, sqlQ, sqlQ);
query := TADOQuery.Create(NIL);
query.Connection := conn;
query.Sql.Add(sqlQ);
query.ExecSQL;
query.Close;
end;
end.
|
unit fOptionsLists;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ORCtrls, OrFn, Menus, fBase508Form,
VA508AccessibilityManager;
type
TfrmOptionsLists = class(TfrmBase508Form)
pnlBottom: TPanel;
btnOK: TButton;
btnCancel: TButton;
lblAddBy: TLabel;
lblPatientsAdd: TLabel;
lblPersonalPatientList: TLabel;
lblPersonalLists: TLabel;
lstAddBy: TORComboBox;
btnPersonalPatientRA: TButton;
btnPersonalPatientR: TButton;
lstListPats: TORListBox;
lstPersonalPatients: TORListBox;
btnListAddAll: TButton;
btnNewList: TButton;
btnDeleteList: TButton;
lstPersonalLists: TORListBox;
radAddByType: TRadioGroup;
btnListSaveChanges: TButton;
btnListAdd: TButton;
lblInfo: TMemo;
bvlBottom: TBevel;
mnuPopPatient: TPopupMenu;
mnuPatientID: TMenuItem;
grpVisibility: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure btnNewListClick(Sender: TObject);
procedure radAddByTypeClick(Sender: TObject);
procedure lstPersonalListsChange(Sender: TObject);
procedure lstAddByClick(Sender: TObject);
procedure btnDeleteListClick(Sender: TObject);
procedure btnListSaveChangesClick(Sender: TObject);
procedure btnPersonalPatientRAClick(Sender: TObject);
procedure btnListAddAllClick(Sender: TObject);
procedure btnPersonalPatientRClick(Sender: TObject);
procedure lstPersonalPatientsChange(Sender: TObject);
procedure btnListAddClick(Sender: TObject);
procedure lstListPatsChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lstAddByNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure btnOKClick(Sender: TObject);
procedure mnuPatientIDClick(Sender: TObject);
procedure lstListPatsMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lstPersonalPatientsMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure lstAddByKeyPress(Sender: TObject; var Key: Char);
procedure grpVisibilityClick(Sender: TObject);
procedure lstAddByChange(Sender: TObject);
private
FLastList: integer;
FChanging: boolean;
procedure AddIfUnique(entry: string; aList: TORListBox);
public
{ Public declarations }
end;
var
frmOptionsLists: TfrmOptionsLists;
procedure DialogOptionsLists(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
implementation
uses fOptionsNewList, rOptions, uOptions, rCore, fPtSelOptns, VAUtils;
{$R *.DFM}
const
LIST_ADD = 1;
LIST_PERSONAL = 2;
procedure DialogOptionsLists(topvalue, leftvalue, fontsize: integer; var actiontype: Integer);
// create the form and make it modal, return an action
var
frmOptionsLists: TfrmOptionsLists;
begin
frmOptionsLists := TfrmOptionsLists.Create(Application);
actiontype := 0;
try
with frmOptionsLists do
begin
if (topvalue < 0) or (leftvalue < 0) then
Position := poScreenCenter
else
begin
Position := poDesigned;
Top := topvalue;
Left := leftvalue;
end;
ResizeAnchoredFormToFont(frmOptionsLists);
ShowModal;
actiontype := btnOK.Tag;
end;
finally
frmOptionsLists.Release;
end;
end;
procedure TfrmOptionsLists.FormCreate(Sender: TObject);
begin
rpcGetPersonalLists(lstPersonalLists.Items);
grpVisibility.ItemIndex := 1;
grpVisibility.Enabled := FALSE;
radAddByType.ItemIndex := 0;
radAddByTypeClick(self);
FLastList := 0;
end;
procedure TfrmOptionsLists.btnNewListClick(Sender: TObject);
var
newlist: string;
newlistnum: integer;
begin
newlist := '';
DialogOptionsNewList(Font.Size, newlist);
newlistnum := strtointdef(Piece(newlist, '^', 1), 0);
if newlistnum > 0 then
begin
with lstPersonalLists do
begin
Items.Add(newlist);
SelectByIEN(newlistnum);
end;
lstPersonalListsChange(self);
lstPersonalPatients.Items.Clear;
lstPersonalPatientsChange(self);
end;
end;
procedure TfrmOptionsLists.radAddByTypeClick(Sender: TObject);
begin
with lstAddBy do
begin
case radAddByType.ItemIndex of
0: begin
ListItemsOnly := false;
LongList := true;
InitLongList('');
lblAddBy.Caption := 'Patient:';
end;
1: begin
ListItemsOnly := false;
LongList := false;
ListWardAll(lstAddBy.Items);
lblAddBy.Caption := 'Ward:';
end;
2: begin
ListItemsOnly := true;
LongList := true;
InitLongList('');
lblAddBy.Caption := 'Clinic:';
end;
3: begin
ListItemsOnly := true;
LongList := true;
InitLongList('');
lblAddBy.Caption := 'Provider:';
end;
4: begin
ListItemsOnly := false;
LongList := false;
ListSpecialtyAll(lstAddBy.Items);
lblAddBy.Caption := 'Specialty:';
end;
5: begin
ListItemsOnly := false;
LongList := false;
ListTeamAll(lstAddBy.Items);
lblAddBy.Caption := 'List:';
end;
6: begin
ListItemsOnly := false;
LongList := false;
ListPcmmAll(lstAddBy.Items);
lblAddBy.Caption := 'PCMM Team:';
end;
end;
lstAddBy.Caption := lblAddBy.Caption;
ItemIndex := -1;
Text := '';
end;
lstListPats.Items.Clear;
lstListPatsChange(self);
end;
procedure TfrmOptionsLists.AddIfUnique(entry: string; aList: TORListBox);
var
i: integer;
ien: string;
inlist: boolean;
begin
ien := Piece(entry, '^', 1);
inlist := false;
with aList do
for i := 0 to Items.Count - 1 do
if ien = Piece(Items[i], '^', 1) then
begin
inlist := true;
break;
end;
if not inlist then
aList.Items.Add(entry);
end;
procedure TfrmOptionsLists.lstPersonalListsChange(Sender: TObject);
var
x: integer;
begin
if (btnListSaveChanges.Enabled) and (not FChanging) then
begin
if InfoBox('Do you want to save changes to '
+ Piece(lstPersonalLists.Items[FLastList], '^', 2) + '?',
'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then
btnListSaveChangesClick(self);
end;
if lstPersonalLists.ItemIndex > -1 then FLastList := lstPersonalLists.ItemIndex;
lstPersonalPatients.Items.Clear;
btnDeleteList.Enabled := lstPersonalLists.ItemIndex > -1;
with lstPersonalLists do
begin
if (ItemIndex < 0) or (Items.Count <1) then
begin
btnListAdd.Enabled := false;
btnListAddAll.Enabled := false;
btnPersonalPatientR.Enabled := false;
btnPersonalPatientRA.Enabled := false;
btnListSaveChanges.Enabled := false;
grpVisibility.Enabled := False;
exit;
end;
ListPtByTeam(lstPersonalPatients.Items, strtointdef(Piece(Items[ItemIndex], '^', 1), 0));
grpVisibility.Enabled := TRUE;
FChanging := True;
x := StrToIntDef(Piece(Items[ItemIndex], '^', 9), 1);
if x = 2 then x := 1;
grpVisibility.ItemIndex := x;
FChanging := False;
btnDeleteList.Enabled := true;
end;
if lstPersonalPatients.Items.Count = 1 then // avoid selecting '^No patients found.' msg
if Piece(lstPersonalPatients.Items[0], '^', 1) = '' then
begin
btnPersonalPatientR.Enabled := false;
btnPersonalPatientRA.Enabled := false;
exit;
end;
btnPersonalPatientR.Enabled := lstPersonalPatients.SelCount > 0;
btnPersonalPatientRA.Enabled := lstPersonalPatients.Items.Count > 0;
btnListSaveChanges.Enabled := false;
end;
procedure TfrmOptionsLists.lstAddByChange(Sender: TObject);
procedure ShowMatchingPatients;
begin
with lstAddBy do begin
if ShortCount > 0 then begin
if ShortCount = 1 then begin
ItemIndex := 0;
end;
Items.Add(LLS_LINE);
Items.Add(LLS_SPACE);
end;
InitLongList('');
end;
end;
begin
inherited;
if radAddByType.ItemIndex = 0 {patient} then begin
with lstAddBy do
if frmPtSelOptns.IsLast5(Text) then begin
ListPtByLast5(Items, Text);
ShowMatchingPatients;
end
else if frmPtSelOptns.IsFullSSN(Text) then begin
ListPtByFullSSN(Items, Text);
ShowMatchingPatients;
end;
end;
end;
procedure TfrmOptionsLists.lstAddByClick(Sender: TObject);
var
ien: string;
visitstart, visitstop, i: integer;
visittoday, visitbegin, visitend: TFMDateTime;
aList: TStringList;
PtRec: TPtIDInfo;
begin
if lstAddBy.ItemIndex < 0 then exit;
ien := Piece(lstAddBy.Items[lstAddBy.ItemIndex], '^', 1);
If ien = '' then exit;
case radAddByType.ItemIndex of
0:
begin
PtRec := GetPtIDInfo(ien);
lblAddBy.Caption := 'Patient: SSN: ' + PtRec.SSN;
lstAddBy.Caption := lblAddBy.Caption;
AddIfUnique(lstAddBy.Items[lstAddBy.ItemIndex], lstListPats);
end;
1:
begin
ListPtByWard(lstListPats.Items, strtointdef(ien,0));
end;
2:
begin
rpcGetApptUserDays(visitstart, visitstop); // use user's date range for appointments
visittoday := FMToday;
visitbegin := FMDateTimeOffsetBy(visittoday, LowerOf(visitstart, visitstop));
visitend := FMDateTimeOffsetBy(visittoday, HigherOf(visitstart, visitstop));
aList := TStringList.Create;
ListPtByClinic(lstListPats.Items, strtointdef(ien, 0), floattostr(visitbegin), floattostr(visitend));
for i := 0 to aList.Count - 1 do
AddIfUnique(aList[i], lstListPats);
aList.Free;
end;
3:
begin
ListPtByProvider(lstListPats.Items, strtoint64def(ien,0));
end;
4:
begin
ListPtBySpecialty(lstListPats.Items, strtointdef(ien,0));
end;
5:
begin
ListPtByTeam(lstListPats.Items, strtointdef(ien,0));
end;
6:
begin
ListPtByPCMMTeam(lstListPats.Items, strtointdef(ien,0));
end;
end;
if lstListPats.Items.Count = 1 then // avoid selecting '^No patients found.' msg
if Piece(lstListPats.Items[0], '^', 1) = '' then
begin
btnListAddAll.Enabled := false;
btnListAdd.Enabled := false;
exit;
end;
btnListAddAll.Enabled := (lstListPats.Items.Count > 0) and (lstPersonalLists.ItemIndex > -1);
btnListAdd.Enabled := (lstListPats.SelCount > 0) and (lstPersonalLists.ItemIndex > -1);
end;
procedure TfrmOptionsLists.btnDeleteListClick(Sender: TObject);
var
oldindex: integer;
deletemsg: string;
begin
with lstPersonalLists do
deletemsg := 'You have selected "' + DisplayText[ItemIndex]
+ '" to be deleted.' + CRLF + 'Are you sure you want to delete this list?';
if InfoBox(deletemsg, 'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then
begin
btnListSaveChanges.Enabled := false;
with lstPersonalLists do
begin
oldindex := ItemIndex;
if oldindex > -1 then
begin
rpcDeleteList(Piece(Items[oldindex], '^', 1));
Items.Delete(oldindex);
btnPersonalPatientRAClick(self);
btnListSaveChanges.Enabled := false;
end;
if Items.Count > 0 then
begin
if oldindex = 0 then
ItemIndex := 0
else if oldindex > (Items.Count - 1) then
ItemIndex := Items.Count - 1
else
ItemIndex := oldindex;
btnListSaveChanges.Enabled := false;
lstPersonalListsChange(self);
end;
end;
end;
end;
procedure TfrmOptionsLists.btnListSaveChangesClick(Sender: TObject);
var
listien: integer;
begin
listien := strtointdef(Piece(lstPersonalLists.Items[FLastList], '^', 1), 0);
rpcSaveListChanges(lstPersonalPatients.Items, listien, grpVisibility.ItemIndex);
btnListSaveChanges.Enabled := false;
rpcGetPersonalLists(lstPersonalLists.Items);
lstPersonalLists.ItemIndex := FLastList;
lstPersonalListsChange(Self);
if lstPersonalPatients.CanFocus then
lstPersonalPatients.SetFocus;
end;
procedure TfrmOptionsLists.btnPersonalPatientRAClick(Sender: TObject);
begin
lstPersonalPatients.Items.Clear;
btnPersonalPatientR.Enabled := lstPersonalPatients.SelCount > 0;
btnPersonalPatientRA.Enabled := lstPersonalPatients.Items.Count > 0;
btnListSaveChanges.Enabled := true;
end;
procedure TfrmOptionsLists.btnListAddAllClick(Sender: TObject);
var
i: integer;
begin
with lstPersonalPatients do
begin
if Items.Count = 1 then
if Piece(Items[0], '^', 1) = '' then
Items.Clear;
end;
with lstListPats do
begin
for i := 0 to Items.Count - 1 do
AddIfUnique(Items[i], lstPersonalPatients);
Items.Clear;
lstPersonalPatientsChange(self);
lstAddBy.ItemIndex := -1;
btnListAddAll.Enabled := false;
lstPersonalPatientsChange(self);
end;
btnListSaveChanges.Enabled := true;
end;
procedure TfrmOptionsLists.btnPersonalPatientRClick(Sender: TObject);
var
i: integer;
begin
if not btnPersonalPatientR.Enabled then exit;
with lstPersonalPatients do
for i := Items.Count - 1 downto 0 do
if Selected[i] then
Items.Delete(i);
btnPersonalPatientR.Enabled := lstPersonalPatients.SelCount > 0;
btnPersonalPatientRA.Enabled := lstPersonalPatients.Items.Count > 0;
btnListSaveChanges.Enabled := true;
end;
procedure TfrmOptionsLists.lstPersonalPatientsChange(Sender: TObject);
begin
if lstPersonalPatients.SelCount = 1 then // avoid selecting '^No patients found.' msg
if Piece(lstPersonalPatients.Items[0], '^', 1) = '' then
begin
btnPersonalPatientR.Enabled := false;
btnPersonalPatientRA.Enabled := false;
exit;
end;
btnPersonalPatientR.Enabled := lstPersonalPatients.SelCount > 0;
btnPersonalPatientRA.Enabled := lstPersonalPatients.Items.Count > 0;
end;
procedure TfrmOptionsLists.btnListAddClick(Sender: TObject);
var
i: integer;
begin
if not btnListAdd.Enabled then exit;
with lstPersonalPatients do
begin
if Items.Count = 1 then
if Piece(Items[0], '^', 1) = '' then
Items.Clear;
end;
with lstListPats do
for i := Items.Count - 1 downto 0 do
if Selected[i] then
begin
AddIfUnique(Items[i], lstPersonalPatients);
Items.Delete(i);
end;
lstListPatsChange(self);
lstPersonalPatientsChange(self);
btnListSaveChanges.Enabled := true;
end;
procedure TfrmOptionsLists.lstListPatsChange(Sender: TObject);
begin
if lstListPats.SelCount = 1 then // avoid selecting '^No patients found.' msg
if Piece(lstListPats.Items[0], '^', 1) = '' then
exit;
btnListAdd.Enabled := (lstListPats.SelCount > 0) and (lstPersonalLists.ItemIndex > -1);
btnListAddAll.Enabled := (lstListPats.Items.Count > 0) and (lstPersonalLists.ItemIndex > -1);
end;
procedure TfrmOptionsLists.FormShow(Sender: TObject);
begin
with lstPersonalLists do
if Items.Count < 1 then
ShowMsg('You have no personal lists. Use "New List..." to create one.')
else
begin
ItemIndex := 0;
lstPersonalListsChange(self);
end;
end;
procedure TfrmOptionsLists.grpVisibilityClick(Sender: TObject);
begin
inherited;
if not FChanging then btnListSaveChanges.Enabled := True;
end;
procedure TfrmOptionsLists.lstAddByNeedData(Sender: TObject;
const StartFrom: String; Direction, InsertAt: Integer);
begin
with lstAddBy do
begin
case radAddByType.ItemIndex of
0: begin
Pieces := '2';
ForDataUse(SubSetOfPatients(StartFrom, Direction));
end;
1: begin
Pieces := '2';
end;
2: begin
Pieces := '2';
ForDataUse(SubSetOfClinics(StartFrom, Direction));
end;
3: begin
Pieces := '2,3';
ForDataUse(SubSetOfProviders(StartFrom, Direction));
end;
4: begin
Pieces := '2';
end;
5: begin
Pieces := '2';
end;
end;
end;
end;
procedure TfrmOptionsLists.btnOKClick(Sender: TObject);
begin
if btnListSaveChanges.Enabled then
begin
if InfoBox('Do you want to save changes to '
+ Piece(lstPersonalLists.Items[FLastList], '^', 2) + '?',
'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then
btnListSaveChangesClick(self);
end;
end;
procedure TfrmOptionsLists.mnuPatientIDClick(Sender: TObject);
begin
case mnuPopPatient.Tag of
LIST_PERSONAL: DisplayPtInfo(lstPersonalPatients.ItemID);
LIST_ADD: DisplayPtInfo(lstListPats.ItemID);
end;
end;
procedure TfrmOptionsLists.lstListPatsMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mnuPopPatient.AutoPopup := (lstListPats.Items.Count > 0)
and (lstListPats.ItemIndex > -1)
and (lstListPats.SelCount = 1)
and (Button = mbRight)
and (btnListAdd.Enabled);
mnuPopPatient.Tag := LIST_ADD;
end;
procedure TfrmOptionsLists.lstPersonalPatientsMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mnuPopPatient.AutoPopup := (lstPersonalPatients.Items.Count > 0)
and (lstPersonalPatients.ItemIndex > -1)
and (lstPersonalPatients.SelCount = 1)
and (Button = mbRight)
and (btnPersonalPatientR.Enabled);
mnuPopPatient.Tag := LIST_PERSONAL;
end;
procedure TfrmOptionsLists.lstAddByKeyPress(Sender: TObject;
var Key: Char);
procedure ShowMatchingPatients;
begin
with lstAddBy do
begin
if ShortCount > 0 then
begin
if ShortCount = 1 then
begin
ItemIndex := 0;
end;
Items.Add(LLS_LINE);
Items.Add(LLS_SPACE);
end;
InitLongList('');
end;
Key := #0; //Now that we've selected it, don't process the last keystroke!
end;
var
FutureText: string;
begin
if radAddByType.ItemIndex = 0 {patient} then
begin
with lstAddBy do
begin
FutureText := Text + Key;
if frmPtSelOptns.IsLast5(FutureText) then
begin
ListPtByLast5(Items, FutureText);
ShowMatchingPatients;
end
else if frmPtSelOptns.IsFullSSN(FutureText) then
begin
ListPtByFullSSN(Items, FutureText);
ShowMatchingPatients;
end;
end;
end;
end;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.OCZ.Vector;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TOCZVectorSMARTSupport = class(TSMARTSupport)
private
function IsPanasonicRPSSB(const Model: String): Boolean;
function IsOCZVector(const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
function ModelHasOCZString(const Model: String): Boolean;
function SMARTHasOCZVectorCharacteristics(
const SMARTList: TSMARTValueList): Boolean;
function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite;
const
EntryID = $E9;
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean; override;
protected
function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer;
override;
function InnerIsErrorAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsCautionAvailable(const SMARTList: TSMARTValueList):
Boolean; override;
function InnerIsError(const SMARTList: TSMARTValueList): TSMARTErrorResult;
override;
function InnerIsCaution(const SMARTList: TSMARTValueList):
TSMARTErrorResult; override;
end;
implementation
{ TOCZVectorSMARTSupport }
function TOCZVectorSMARTSupport.GetTypeName: String;
begin
result := 'SmartOczVector';
end;
function TOCZVectorSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TOCZVectorSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
IsPanasonicRPSSB(IdentifyDevice.Model) or
IsOCZVector(IdentifyDevice, SMARTList);
end;
function TOCZVectorSMARTSupport.IsPanasonicRPSSB(const Model: String):
Boolean;
begin
result := FindAtFirst('PANASONIC RP-SSB', Model);
end;
function TOCZVectorSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TOCZVectorSMARTSupport.IsOCZVector(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
ModelHasOCZString(IdentifyDevice.Model) or
SMARTHasOCZVectorCharacteristics(SMARTList);
end;
function TOCZVectorSMARTSupport.ModelHasOCZString(const Model: String):
Boolean;
begin
result := Find('OCZ', Model);
end;
function TOCZVectorSMARTSupport.SMARTHasOCZVectorCharacteristics(
const SMARTList: TSMARTValueList): Boolean;
begin
// 2015/11/25
// PANASONIC RP-SSB240GAK
// http://crystalmark.info/board/c-board.cgi?cmd=one;no=500;id=#500
result :=
(SMARTList.Count >= 9) and
(SMARTList[0].Id = $05) and
(SMARTList[1].Id = $09) and
(SMARTList[2].Id = $0C) and
(SMARTList[3].Id = $AB) and
(SMARTList[4].Id = $AE) and
(SMARTList[5].Id = $C3) and
(SMARTList[6].Id = $C4) and
(SMARTList[7].Id = $C5) and
(SMARTList[8].Id = $C6);
end;
function TOCZVectorSMARTSupport.ErrorCheckedGetLife(
const SMARTList: TSMARTValueList): Integer;
begin
result := SMARTList[SMARTList.GetIndexByID($E9)].Current;
end;
function TOCZVectorSMARTSupport.InnerIsErrorAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result := true;
end;
function TOCZVectorSMARTSupport.InnerIsCautionAvailable(
const SMARTList: TSMARTValueList): Boolean;
begin
result := IsEntryAvailable(EntryID, SMARTList);
end;
function TOCZVectorSMARTSupport.InnerIsError(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
begin
result.Override := false;
result.Status :=
InnerCommonIsError(EntryID, SMARTList).Status;
end;
function TOCZVectorSMARTSupport.InnerIsCaution(
const SMARTList: TSMARTValueList): TSMARTErrorResult;
begin
result := InnerCommonIsCaution(EntryID, SMARTList, CommonLifeThreshold);
end;
function TOCZVectorSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
const
WriteID = $F1;
begin
try
SMARTList.GetIndexByID(WriteID);
result := true;
except
result := false;
end;
end;
function TOCZVectorSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
const
ReadError = true;
EraseError = false;
UsedHourID = $09;
ThisErrorType = ReadError;
ErrorID = $C5;
ReplacedSectorsID = $05;
begin
FillChar(result, SizeOf(result), 0);
result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID);
result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError;
result.ReadEraseError.Value :=
SMARTList.ExceptionFreeGetRAWByID(ErrorID);
result.ReplacedSectors :=
SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID);
result.TotalWrite := GetTotalWrite(SMARTList);
end;
function TOCZVectorSMARTSupport.GetTotalWrite(
const SMARTList: TSMARTValueList): TTotalWrite;
function LBAToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shr 1;
end;
function GBToMB(const SizeInLBA: Int64): UInt64;
begin
result := SizeInLBA shl 10;
end;
const
HostWrite = true;
NANDWrite = false;
WriteID = $F1;
begin
result.InValue.TrueHostWriteFalseNANDWrite :=
HostWrite;
result.InValue.ValueInMiB :=
GBToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID));
end;
end.
|
program hanoi3;
type
States = ( Prepare, Ready, Remove );
PTask = ^TTask;
TTask = record
qnt: integer;
src: integer;
dst: integer;
state: States;
next: PTask;
end;
TTower = record
head: PTask;
qnt: integer;
end;
procedure hanoi_init(var tower: TTower; quantity: integer); forward;
procedure hanoi_solve(var tower: TTower); forward;
procedure hanoi_init(var tower: TTower; quantity: integer);
begin
tower.qnt := quantity;
new(tower.head);
tower.head^.qnt := quantity;
tower.head^.src := 1;
tower.head^.dst := 3;
tower.head^.state := Prepare;
tower.head^.next := nil;
end;
procedure hanoi_solve(var tower: TTower);
var
tmp: PTask;
begin
while tower.head <> nil do
begin
case tower.head^.state of
Prepare:
begin
tower.head^.state := Ready;
if tower.head^.qnt > 1 then
begin
new(tmp);
tmp^.qnt := tower.head^.qnt - 1;
tmp^.src := tower.head^.src;
tmp^.dst := 6 - tower.head^.src - tower.head^.dst;
tmp^.state := Prepare;
tmp^.next := tower.head;
tower.head := tmp;
end;
end;
Ready:
begin
tower.head^.state := Remove;
writeln('N', tower.head^.qnt, ': ', tower.head^.src, ' -> ', tower.head^.dst);
if tower.head^.qnt > 1 then
begin
new(tmp);
tmp^.qnt := tower.head^.qnt - 1;
tmp^.src := 6 - tower.head^.src - tower.head^.dst;
tmp^.dst := tower.head^.dst;
tmp^.state := Prepare;
tmp^.next := tower.head;
tower.head := tmp;
end;
end;
Remove:
begin
tmp := tower.head^.next;
dispose(tower.head);
tower.head := tmp;
end;
end;
end;
end;
var
tower: TTower;
begin
writeln('The Tower of Hanoi: 3');
hanoi_init(tower, 3);
hanoi_solve(tower);
writeln;
writeln('The Tower of Hanoi: 4');
hanoi_init(tower, 4);
hanoi_solve(tower);
end.
|
unit Ec2GradoSol;
interface
Type
TEc2GradoSol = class(TObject)
private
FValB: real;
FValC: real;
FValA: real;
FSol2: real;
FSol1: real;
FIsReal: boolean;
FIsUndefined: boolean;
procedure SetSol1(const Value: real);
procedure SetSol2(const Value: real);
procedure SetValA(const Value: real);
procedure SetValB(const Value: real);
procedure SetValC(const Value: real);
procedure SetIsReal(const Value: boolean);
procedure SetIsUndefined(const Value: boolean);
published
property ValA: real read FValA write SetValA;
property ValB: real read FValB write SetValB;
property ValC: real read FValC write SetValC;
property Sol1: real read FSol1 write SetSol1;
property Sol2: real read FSol2 write SetSol2;
property IsReal: boolean read FIsReal write SetIsReal;
property IsUndefined: boolean read FIsUndefined write SetIsUndefined;
Constructor Create; overload;
procedure solucion;
end;
implementation
{ TEc2GradoSol }
constructor TEc2GradoSol.Create;
begin
ValA:= 1.0;
ValB:= 2.0;
ValC:= 1.0;
end;
procedure TEc2GradoSol.SetIsReal(const Value: boolean);
begin
FIsReal := Value;
end;
procedure TEc2GradoSol.SetIsUndefined(const Value: boolean);
begin
FIsUndefined := Value;
end;
procedure TEc2GradoSol.SetSol1(const Value: real);
begin
FSol1 := Value;
end;
procedure TEc2GradoSol.SetSol2(const Value: real);
begin
FSol2 := Value;
end;
procedure TEc2GradoSol.SetValA(const Value: real);
begin
FValA := Value;
end;
procedure TEc2GradoSol.SetValB(const Value: real);
begin
FValB := Value;
end;
procedure TEc2GradoSol.SetValC(const Value: real);
begin
FValC := Value;
end;
procedure TEc2GradoSol.solucion;
var
rDesc: real;
begin
if ValA <> 0 then
begin
IsUndefined:= false;
rDesc:= Sqr(ValB)-4*ValA*ValC;
if rDesc < 0 then
begin
IsReal:= false;
Sol1:= -ValB/(2*ValA);
Sol2:= sqrt(-rDesc)/(2*ValA);
end
else
begin
IsReal:= true;
Sol1:= (-ValB+sqrt(rDesc))/(2*ValA);
Sol2:= (-ValB-sqrt(rDesc))/(2*ValA);
end;
end
else
IsUndefined:= true;
end;
end.
|
{$mode objfpc}{$H+}{$J-}
{$interfaces com}
uses
SysUtils, Classes;
type
IMyInterface = interface
['{3075FFCD-8EFB-4E98-B157-261448B8D92E}']
procedure Shoot;
end;
TMyClass1 = class(TInterfacedObject, IMyInterface)
procedure Shoot;
end;
TMyClass2 = class(TInterfacedObject, IMyInterface)
procedure Shoot;
end;
TMyClass3 = class(TInterfacedObject)
procedure Shoot;
end;
procedure TMyClass1.Shoot;
begin
WriteLn('TMyClass1.Shoot');
end;
procedure TMyClass2.Shoot;
begin
WriteLn('TMyClass2.Shoot');
end;
procedure TMyClass3.Shoot;
begin
WriteLn('TMyClass3.Shoot');
end;
procedure UseThroughInterface(I: IMyInterface);
begin
Write('Shooting... ');
I.Shoot;
end;
var
C1: IMyInterface; // COM се грижи за унищожаването
C2: IMyInterface; // COM се грижи за унищожаването
C3: TMyClass3; // ВИЕ трябва да се погрижите за унищожаването
begin
C1 := TMyClass1.Create as IMyInterface;
C2 := TMyClass2.Create as IMyInterface;
C3 := TMyClass3.Create;
try
UseThroughInterface(C1); // няма нужда от оператор "as"
UseThroughInterface(C2);
if C3 is IMyInterface then
UseThroughInterface(C3 as IMyInterface); // това няма да се изпълни
finally
{ Променливи C1 и C2 излизат от обхват и тук би трябвало да се
унищожат автоматично.
За разлика от тях, C3 е инстанция, която не се управлява от интерфейс
и трябва да се унищожи ръчно. }
FreeAndNil(C3);
end;
end. |
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons,
//GLS
GLKeyboard;
type
TForm1 = class(TForm)
Timer1: TTimer;
PAUp: TPanel;
Label1: TLabel;
PALeft: TPanel;
PARight: TPanel;
Label2: TLabel;
procedure Timer1Timer(Sender: TObject);
procedure PAUpClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
Label1.Caption:='Hit one/any of the keys below to light up the panel...';
end;
procedure TForm1.Timer1Timer(Sender: TObject);
procedure CheckPanel(panel : TPanel);
begin
// check if key associated to current panel's caption is down
if IsKeyDown(KeyNameToVirtualKeyCode(panel.Caption)) then
panel.Color:=clRed // down, set panel to red
else panel.Color:=clBtnFace; // up, set panel to default color
end;
begin
// check all keys
CheckPanel(PALeft);
CheckPanel(PAUp);
CheckPanel(PARight);
end;
procedure TForm1.PAUpClick(Sender: TObject);
var
keyCode : Integer;
begin
Label1.Caption:='Type key to map...';
// wait for a key to be pressed
repeat
Application.ProcessMessages; // let other messages happen
Sleep(1); // relinquish time for other processes
keyCode:=KeyPressed;
until keyCode>=0;
// retrieve keyname and adjust panel caption
TPanel(Sender).Caption:=VirtualKeyCodeToKeyName(keyCode);
TPanel(Sender).Tag:=keyCode;
// restore default label1.caption
FormCreate(Self);
end;
end.
|
unit ufSignIn;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.ListBox, FMX.Edit, FMX.Layouts, FMX.Controls.Presentation, uBusiObj,
FMX.TabControl;
const
cTabName = 'TabSignIn';
cHeaderTitle = 'Sign In';
cTag = uBusiObj.tnSignIn;
type
TfraSignIn = class(TFrame)
ToolBar1: TToolBar;
btnCancel: TSpeedButton;
lblHeaderTItle: TLabel;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
edtEmail: TEdit;
ListBoxItem5: TListBoxItem;
edtPassword: TEdit;
ListBoxGroupFooter1: TListBoxGroupFooter;
ListBoxItem7: TListBoxItem;
Layout1: TLayout;
Label6: TLabel;
Label2: TLabel;
chkbxShowPass: TCheckBox;
btnSubmit: TButton;
procedure chkbxShowPassChange(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FramePaint(Sender: TObject; Canvas: TCanvas;
const [Ref] ARect: TRectF);
procedure btnSubmitClick(Sender: TObject);
private
{ Private declarations }
FOnCloseTab: ^TProc;
FOnSubmit: ^TProc;
public
{ Public declarations }
procedure AnimateTrans(AAnimateRule: TAnimateRule);
end;
TTabOfFrame = class(TTabItem)
strict private
FOnCloseTab: TProc; //<TObject>;
FOnSubmit: TProc;
private
// FRecID: integer;
public
FCallerTab: TTabItem;
FFrameMain: TfraSignIn;
property OnSubmit: TProc read FOnSubmit write FOnSubmit;
property OnCloseTab: TProc read FOnCloseTab write FOnCloseTab;
constructor Create(AOwner: TComponent); // supply various params here. AReccordID: integer); // ; AUserRequest: TUserRequest
destructor Destroy; override;
procedure CloseTab(AIsRelease: Boolean);
procedure ShowTab(ACallerTab: TTabItem); //; AUserRequest: TUserIntentInit; ATID, ACarID: integer);
end;
implementation
{$R *.fmx}
procedure TfraSignIn.AnimateTrans(AAnimateRule: TAnimateRule);
begin
try
if AAnimateRule = uBusiObj.TAnimateRule.arInit then
begin
Layout1.Align := TAlignLayout.None;
Layout1.Position.X := Layout1.Width;
end
else if AAnimateRule = uBusiObj.TAnimateRule.arIn then
begin
//Layout1.Position.X := Layout1.Width;
Layout1.AnimateFloat('Position.X', 0, 0.3, TAnimationType.InOut, TInterpolationType.Linear);
end
else if AAnimateRule = uBusiObj.TAnimateRule.arOut then
begin
// Layout1.Position.X := Layout1.Width;
Layout1.Align := TAlignLayout.None;
Layout1.AnimateFloat('Position.X', Layout1.Width, 0.2, TAnimationType.Out, TInterpolationType.Linear);
end;
finally
if AAnimateRule = uBusiObj.TAnimateRule.arIn then
Layout1.Align := TAlignLayout.Client;
end;
end;
procedure TfraSignIn.btnCancelClick(Sender: TObject);
begin
AnimateTrans(TAnimateRule.arOut); // animate the main tab
TTabOfFrame(Owner).CloseTab(false);
end;
procedure TfraSignIn.btnSubmitClick(Sender: TObject);
begin
AnimateTrans(TAnimateRule.arOut); // animate the main tab
TTabOfFrame(Owner).CloseTab(false);
end;
procedure TfraSignIn.chkbxShowPassChange(Sender: TObject);
begin
edtPassword.Password := not chkbxShowPass.IsChecked;
end;
procedure TfraSignIn.FramePaint(Sender: TObject; Canvas: TCanvas;
const [Ref] ARect: TRectF);
begin
Label2.StyledSettings := [TStyledSetting.Family, TStyledSetting.Style];
Label6.StyledSettings := [TStyledSetting.Family, TStyledSetting.Style];
chkbxShowPass.StyledSettings := [TStyledSetting.Family, TStyledSetting.Style];
end;
{ TTabOfFrame }
procedure TTabOfFrame.CloseTab(AIsRelease: Boolean);
begin
TTabControl(Self.Owner).ActiveTab := FCallerTab;
if Assigned(FOnCloseTab) then
FOnCloseTab();
end;
constructor TTabOfFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Name := cTabName;
Tag := Integer(cTag);
// create main frame
FFrameMain := TfraSignIn.Create(Self);
FFrameMain.Parent := Self;
// FFrameMain.Layout1.Align := TAlignLayout.None;
FFrameMain.Tag := Integer(cTag); //uBusiObj.tnUOMUpd);
// define events
FFrameMain.FOnSubmit := @OnSubmit;
FFrameMain.FOnCloseTab := @OnCloseTab;
end;
destructor TTabOfFrame.Destroy;
begin
FFrameMain.Free;
inherited;
end;
procedure TTabOfFrame.ShowTab(ACallerTab: TTabItem);
begin
FCallerTab := ACallerTab;
// FFrameMain.FTID := ATID;
FFrameMain.AnimateTrans(TAnimateRule.arInit);
TTabControl(Self.Owner).ActiveTab := Self;
// if FTabItemState.UserIntentCurr = uicAdding then
// FFrameMain.edtDescript.SetFocus;
FFrameMain.AnimateTrans(TAnimateRule.arIn);
// update fields
// FFrameMain.lblEstabName.Text := AEstabName;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.