// 
// File name: RecognitionSystem.cpp
//
// Discription: Base classes
//
// Programmer: Vladimir P. Stasevich (SV)
//
// History: 
//    Created 13.02.2000 (SV)
//

#include "RecognitionSystem.h"
#include "Force.h"
#include "Pattern.h"

TRecognitionSystem recognitionSystem;

TRecognitionSystem::TRecognitionSystem( )
{
   net = NULL;
}

TRecognitionSystem::~TRecognitionSystem( )
{
   delete net;
}

   // Разрушить нейросеть
void TRecognitionSystem::DestroyNet( )
{
   delete net;
}

int TRecognitionSystem::CreateNewSystem
(
   unsigned numbMiddle
)
{
   if( net )
      DestroyNet();

   net = new TRecognitionNet(
                RECOGNNUMBINPUTS,
                numbMiddle,
                RECOGNNUMBOUTNEURONS );

   if( !net ) return 1;

   if( net->FullConnect() )
      return 1;

   net->Randomize( 1 );

   net->SetCycle( 60*numbMiddle/10);

   return 0;
}

int TRecognitionSystem::LoadFromFile
( 
   const char *fileName
)
{
   if( net )
      DestroyNet();

   net = new TRecognitionNet();

   if( net->LoadFromFile( fileName ) )
      return 1;
      
   if( net->FullConnect() )
      return 1;

   return 0;
}

int TRecognitionSystem::SaveToFile
( 
   const char *fileName
)
{
   return net->SaveToFile( fileName );
}

void TRecognitionSystem::Learn( TSituation situation )
{
   TForces forces;

   if( situation == NOTOUCHSITUATION )
      return;
   
   forces = GetDeltaForces();
   net->Learn( forces, situation );
}

TSituation TRecognitionSystem::Recognize()
{
   TForces forces;
   float   inp[3];
   
   forces = sensor.GetDeltaForces( robot.GetRealTouchType() );

   inp[0] = forces.Fx;
   inp[1] = forces.Fz;
   inp[2] = forces.My;

   net->SetNetInputs( inp );
   return net->Recognize();
}

int TRecognitionSystem::AutoLearn()
{
   TSensor      sensor;
   TForces      forces;
   int          stat;
   TPatternElem elem;

   stat = pattern.GetFirst( &elem );
//   for( int i = 0; i < 300; i++ )
//   while( !recognitionSystem.IsConverged() )
   while( !stat )
   {
      if( ( net->GetCycle() <= 0 ) &&
            recognitionSystem.IsConverged() )
         return 0;
      else
         net->NextCycle();

//      forces = sensor.GetDeltaForces( LFACETTOUCH );

      net->Learn( elem.forces, elem.situation );

      stat = pattern.GetNext( &elem );
   }

   return 1;
}
