用DGL库实现的操作ini文件的类TFastIniFile

                                           用DGL库实现的操作ini文件的类TFastIniFile 
                                                      HouSisong@GMail.com

tag:delphi泛型库,DGL,泛型,TInifile,TFastInifile

DGL库下载   安装方法:将库解压到一个目录,然后在Delphi中添加搜索路径;

DGL简要介绍:http://blog.csdn.net/housisong/archive/2005/10/17/505286.aspx

//========================================================================

//Delphi自带的TIniFile太慢了,文件稍大一点根本就不能用,而且还有bug;

unit UnitFastIniFile;
//利用DGL库实现的操作Ini文件的类TFastIniFile  (兼容TIniFile )
//by HouSisong 2005.10

unit UnitFastIniFile;
//利用DGL库实现的操作Ini文件的类TFastIniFile
//Delphi自带的TIniFile太慢了,文件稍大一点根本就不能用,而且还有bug;
//by HouSisong 2005.10

interface
uses
  IniFiles,Classes    
  ,_DGLMap_StringCaseInsensitive_Integer,DGL_StringCaseInsensitive;
 
type
  //Ini文件操作类
  //作为Section和Key的字符串不区分大小写
  TFastIniFile= class(TCustomIniFile)
  private
    FIsChangFile : boolean;
    FSectionMap : TCIStrIntHashMap; //map: str <-> TCIStrHashMap
    function AddSection(const SectionName: string): TCIStrHashMap;
    function FindSection(const SectionName: string): TCIStrHashMap;
    procedure _ReadSectionValues(const Section: string; Strings: TStrings;
      const IsReadValue: boolean);
    procedure Clear();
    procedure privateLoadFromFile(const SrcFileName: string);
  protected
    procedure SetFormStrings(SrcStrings: TStrings); virtual;
    procedure SaveToStrings(DstStrings: TStrings); virtual;
  public
    constructor Create(const DstFileName: string);//FileName can ''
    procedure  LoadFromFile(const SrcFileName: string);
    destructor Destroy; override;

    function ReadString(const Section, Key, DefaultValue: string): string; override;
    procedure WriteString(const Section, Key, Value: String); override;
    procedure ReadSection(const Section: string; Strings: TStrings); override;
    procedure ReadSections(DstSectionNames: TStrings); override;
    procedure ReadSectionValues(const Section: string; Strings: TStrings); override;
    procedure EraseSection(const Section: string); override;
    procedure DeleteKey(const Section, Key: String); override;
    procedure UpdateFile; override;


    function SectionExists(const Section: string): Boolean;
    function ValueExists(const Section, Key: string): Boolean;

  end;

implementation
uses
  SysUtils;

function TFastIniFile.AddSection(const SectionName:string):TCIStrHashMap;
var
  itS : ICIStrIntMapIterator;
begin
  result:=self.FindSection(SectionName);
  if result=nil then
  begin
    result:=TCIStrHashMap.Create();
    FSectionMap.Insert(SectionName,integer(result));
  end;
end;

function TFastIniFile.FindSection(const SectionName:string):TCIStrHashMap;
var
  itS : ICIStrIntMapIterator;
begin
  itS:=self.FSectionMap.Find(SectionName);
  if not itS.IsEqual(FSectionMap.ItEnd) then
    result:=TCIStrHashMap(itS.Value)
  else
    result:=nil;
end;

procedure TFastIniFile.DeleteKey(const Section, Key: String);
var
  st : TCIStrHashMap;
begin
  FIsChangFile:=true;
  st:=FindSection(Section);
  if st<>nil then
    st.EraseKey(Key);
end;

constructor TFastIniFile.Create(const DstFileName: string);
begin
  inherited Create(DstFileName);
  FSectionMap:=TCIStrIntHashMap.Create();
  privateLoadFromFile(DstFileName);
end;

destructor TFastIniFile.Destroy;
begin
  if FIsChangFile then
    UpdateFile;
  Clear();
  FSectionMap.Free;
  inherited Destroy;
end;

procedure TFastIniFile.EraseSection(const Section: string);
var
  st : TCIStrHashMap;
begin
  FIsChangFile:=true;
  st:=FindSection(Section);
  if st<>nil then
  begin
    st.Free();
    self.FSectionMap.EraseKey(Section);
  end;
end;

procedure TFastIniFile.ReadSection(const Section: string;
  Strings: TStrings);
begin
  _ReadSectionValues(Section,Strings,false);
end;

procedure TFastIniFile.ReadSections(DstSectionNames: TStrings);
var
  i : integer;
  itS : ICIStrIntMapIterator;
  VS  : TCIStrVector;
begin
  DstSectionNames.BeginUpdate;
  VS:=nil;
  try
    DstSectionNames.Clear();
    if (FSectionMap.Size=0) then exit;

    VS  :=TCIStrVector.Create();
    itS:=FSectionMap.ItBegin;
    for i:=0 to FSectionMap.Size-1 do
    begin
      VS.PushBack(itS.Key);
      itS.Next();
    end;
    TCIStrAlgorithms.Sort(VS.ItBegin,Vs.ItEnd);
    for i:=0 to VS.Size-1 do
      DstSectionNames.Add(VS.Items[i]);
  finally
    DstSectionNames.EndUpdate;
  end;
end;

procedure TFastIniFile._ReadSectionValues(const Section: string;
  Strings: TStrings;const IsReadValue:boolean);
var
  st : TCIStrHashMap;
  it : ICIStrMapIterator;
  i : integer;
  VS  : TCIStrVector;
begin
  Strings.BeginUpdate;
  VS:=nil;
  try
    Strings.Clear();
    st:=FindSection(Section);
    if (st=nil) or (st.Size=0) then exit;

    VS  :=TCIStrVector.Create();
    it:=st.ItBegin;
    for i:=0 to st.Size-1 do
    begin
      if IsReadValue then
        VS.PushBack(it.Key+'='+it.Value)
      else
        VS.PushBack(it.Key);
      it.Next;
    end;
    //key排序
    TCIStrAlgorithms.Sort(VS.ItBegin,Vs.ItEnd);
    for i:=0 to VS.Size-1 do
      Strings.Add(VS.Items[i]);

  finally
    Strings.EndUpdate;
    Vs.Free();
  end;
end;

procedure TFastIniFile.ReadSectionValues(const Section: string;
  Strings: TStrings);
begin
  _ReadSectionValues(Section,Strings,true);
end;

function TFastIniFile.ReadString(const Section, Key, DefaultValue: string): string;
var
  st : TCIStrHashMap;
  it : ICIStrMapIterator;
begin
  st:=FindSection(Section);
  if st=nil then
    result:=DefaultValue
  else
  begin
    it:=st.Find(Key);
    if it.IsEqual(st.ItEnd) then
      result:=DefaultValue
    else
      result:=it.Value;
  end;
end;

procedure TFastIniFile.SaveToStrings(DstStrings:TStrings);
var
  I, J: Integer;
  Strings: TCIStrHashMap;
  itS : ICIStrIntMapIterator;
  it : ICIStrMapIterator;
  VS  : TCIStrVector;
begin
  DstStrings.BeginUpdate;
  VS:=nil;
  try
    VS  :=TCIStrVector.Create();
    itS:=FSectionMap.ItBegin;
    for I := 0 to self.FSectionMap.Size - 1 do
    begin
      DstStrings.Add('[' + itS.Key + ']');
      Strings := TCIStrHashMap(its.Value);

      VS.Clear();
      it:=Strings.ItBegin;
      for J := 0 to Strings.Size - 1 do
      begin
        VS.PushBack('  '+it.Key+'='+it.Value);
        it.Next();
      end;
      TCIStrAlgorithms.Sort(VS.ItBegin,Vs.ItEnd);
      for J:=0 to VS.Size-1 do
        DstStrings.Add(VS.Items[J]);

      DstStrings.Add('');
      itS.Next();
    end;
  finally
    DstStrings.EndUpdate;
    VS.Free();
  end;
end;

procedure TFastIniFile.UpdateFile;
var
  List: TStringList;
begin
  FIsChangFile:=false;
  if FileName='' then exit;
 
  List := TStringList.Create;
  try
    SaveToStrings(List);
    List.SaveToFile(FileName);
  finally
    List.Free;
  end;
end;

procedure TFastIniFile.WriteString(const Section, Key, Value: String);
var
  st : TCIStrHashMap;
begin
  FIsChangFile:=true;
  st:=AddSection(Section);
  st.Insert(Key,Value);
end;

procedure TFastIniFile.Clear;
var
  i : integer;
  itS : ICIStrIntMapIterator;
begin
  if FSectionMap.Size=0 then exit;

  itS:=FSectionMap.ItBegin;
  for i:=0 to FSectionMap.Size-1 do
  begin
    TCIStrHashMap(itS.Value).Free;
    itS.Next();
  end;
  FSectionMap.Clear();
end;

procedure TFastIniFile.SetFormStrings(SrcStrings:TStrings);
var
  I, J: Integer;
  S: string;
  Strings: TCIStrHashMap;
begin
  Clear;
  Strings := nil;
  for I := 0 to SrcStrings.Count - 1 do
  begin
    S := Trim(SrcStrings[I]);
    if (S <> '') and (S[1] <> ';') then
    begin
      if (S[1] = '[') and (S[Length(S)] = ']') then
      begin
        Delete(S, 1, 1);
        SetLength(S, Length(S)-1);
        Strings := AddSection(Trim(S));
      end
      else
      begin
        if Strings <> nil then
        begin
          J := Pos('=', S);
          if J > 0 then // remove spaces before and after '='
            Strings.Insert(Trim(Copy(S, 1, J-1)) , Trim(Copy(S, J+1, MaxInt)) )
          else
            Strings.Insert(S,'');
        end;
      end;
    end;
  end;
end;

procedure TFastIniFile.privateLoadFromFile(const SrcFileName: string);
var
  List: TStringList;
begin
  FIsChangFile:=false;
  if (SrcFileName <> '') and FileExists(SrcFileName) then
  begin
    List := TStringList.Create;
    try
      List.LoadFromFile(SrcFileName);
      SetFormStrings(List);
    finally
      List.Free;
    end;
  end
  else
    Clear();
end;

function TFastIniFile.SectionExists(const Section: string): Boolean;
begin
  result:=self.FindSection(Section)<>nil;
end;

function TFastIniFile.ValueExists(const Section, Key: string): Boolean;
var
  st : TCIStrHashMap;
begin
  st:=FindSection(Section);
  if st<>nil then
    result:=not st.Find(Key).IsEqual(st.ItEnd)
  else
    result:=false;
end;

procedure TFastIniFile.LoadFromFile(const SrcFileName: string);
begin
  self.privateLoadFromFile(SrcFileName);
end;

end.

SAT(布尔可满足性问题)是计算机科学中一个非常重要的问题,其解决方法可以应用于很多领域,例如计算机科学、人工智能、计算机网络和密码学等。在SAT问题中,我们需要找到一组布尔变量的赋值,使得一个逻辑公式能够被满足。 DGL(Deep Graph Library)是一个用于图神经网络的Python。它提供了一组高效的API,用于构建、训练和评估图神经网络模型。为了使用dgl实现SAT模型,我们可以将SAT问题转换为一个图结构,其中节点代表布尔变量,边代表逻辑关系。然后,我们可以使用dgl构建和训练图神经网络模型,以解决SAT问题。 以下是一个简单的SAT模型实现,使用dgl来构建和训练图神经网络模型: ``` import dgl import torch import torch.nn as nn import torch.nn.functional as F # Convert SAT problem to graph def sat_to_graph(clauses): g = dgl.graph() # Add nodes n = len(clauses) g.add_nodes(n) # Add edges for i in range(n): for j in range(n): if i != j: for a in clauses[i]: for b in clauses[j]: if a == -b: g.add_edge(i, j) return g # Define graph convolutional neural network model class GCN(nn.Module): def __init__(self, in_feats, hidden_feats, out_feats): super(GCN, self).__init__() self.conv1 = dgl.nn.GraphConv(in_feats, hidden_feats) self.conv2 = dgl.nn.GraphConv(hidden_feats, out_feats) def forward(self, g, inputs): h = self.conv1(g, inputs) h = F.relu(h) h = self.conv2(g, h) return h # Define training function def train(model, g, inputs, labels, optimizer): model.train() logits = model(g, inputs) loss = F.cross_entropy(logits, labels) optimizer.zero_grad() loss.backward() optimizer.step() return loss.item() # Define test function def test(model, g, inputs, labels): model.eval() with torch.no_grad(): logits = model(g, inputs) pred = logits.argmax(1) acc = (pred == labels).float().mean() return acc.item() # Define main function if __name__ == '__main__': # Define SAT problem clauses = [[1, 2, -3], [-1, -2, 3], [2, 3, 4], [1, -3, 4], [-2, -4]] # Convert SAT problem to graph g = sat_to_graph(clauses) # Define model and optimizer model = GCN(g.ndata['feat'].shape[1], 16, 2) optimizer = torch.optim.Adam(model.parameters(), lr=0.01) # Train and test model for epoch in range(100): loss = train(model, g, g.ndata['feat'], g.ndata['label'], optimizer) acc = test(model, g, g.ndata['feat'], g.ndata['label']) print('Epoch {:03d} | Loss {:.4f} | Accuracy {:.4f}'.format(epoch, loss, acc)) ``` 在这个例子中,我们首先将SAT问题转换为一个图结构,然后定义了一个包含两层图卷积层的GCN模型。我们使用Adam优化器来训练模型,每个epoch都计算训练损失和测试准确率。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值