% HopfConf.m
%             17 June 2004
%                   from  Trisim4inEnglish.M


% The attractor triangles will now be computed using a Hopfield network 
% 
% hopfkonv.m
% The code is at c:\GammalDisk\matlab\work\projekt\hopkonv.m ?
% This code finds a memory stored in a memory matirx calculated
% according to Hopfield's rule from a given initial state.
% Naturally we may end up in a spurious attractor.
% The memory matrix is given as W. The initial state is given by a vector
% called xTr.
% To know how long the while loop runs we also set a cnt.

% Initial, undamaged weight/memory matrix: 

Whealthy = (1/Ncomp)*LearningSet*LearningSet';  % is p by p

% the attractors yTr are stored in a matrix Attr
Attr = zeros(p, Ncomp) ;

NofKilledSynapses = zeros(1, Ncomp) ; % numbers of killed synapses
relativeKill = zeros(1, Ncomp) ; % ratio of killed synapses
cntS = zeros(1, Ncomp) ;  % counters will be stored here

for komp = 1:Ncomp  % composition loop
    
  % Initial state (triangle) of the network
  xTr = TestSet(:,komp);
  
  % lateral shift of a triangle set
  Dx = (komp-1)*Dxx; 
  
  % We now gradually destroy the memory matrix by killing a given proportion
  % of synapses. We multiply each weight by a randomly generated 0 or 1 

  randomKill = round(SurvivalFactor*rand(size(Whealthy)));
  W = randomKill.*Whealthy;

  % Now we want to know how many synapses we have killed.
  NofKilledSynapses(komp) = sum(sum(abs(sign(W-Whealthy)))) ;

  % We also want to knoe the proportion of killed synapses
  NofTrainedSynapses = sum(sum(abs(sign(Whealthy))));
  relativeKill(komp) = NofKilledSynapses(komp)/NofTrainedSynapses ;

  % killingofsynapseshasbeenperformed = 1 ;

  % The Hopfield relaxation loop should converge to an attractor, that is,
  % should find a pattern (triangle) stored in a memory matirx starting from
  % a given initial state.
  % Naturally we may end up in a spurious attractor.
  % The memory matrix is given as W. The initial state is given by a vector
  % called xTr.
  % To know how long the while loop runs we also set a counter.

  cnt = 1;
  yTr = sign(W*xTr);  % calculate the output pattern 
  dyTr = yTr;         % change in the pattern

  while (max(abs(dyTr))>0) & (cnt < 250)
      yTr22 = sign(W*yTr);
      dyTr = yTr22 - yTr ;
      yTr = yTr22 ;
      cnt = cnt+1 ;
  end

  % the attractors yTr are stored in a matrix Attr
  Attr(:, komp) = yTr ;

  % the counter is also stored
  cntS(komp) = cnt ;

end

% Now we calculate the number of vector elements where the attractors and
% the compositions differ.
NofDiffElements = sum(abs(sign(TestSet(:,1:Ncomp)- Attr))) ;


