Imported Upstream version 3.2.2
[debian/gnuradio] / gr-trellis / src / lib / fsm.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2002 Free Software Foundation, Inc.
4  *
5  * This file is part of GNU Radio
6  *
7  * GNU Radio is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3, or (at your option)
10  * any later version.
11  *
12  * GNU Radio is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with GNU Radio; see the file COPYING.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #include <cstdio>
24 #include <string>
25 #include <iostream>
26 #include <fstream>
27 #include <stdexcept>
28 #include <cmath>
29 #include <stdlib.h>
30 #include "base.h"
31 #include "fsm.h"
32
33
34 fsm::fsm()
35 {
36   d_I=0;
37   d_S=0;
38   d_O=0;
39   d_NS.resize(0);
40   d_OS.resize(0);
41   d_PS.resize(0);
42   d_PI.resize(0);
43   d_TMi.resize(0);
44   d_TMl.resize(0);
45 }
46
47 fsm::fsm(const fsm &FSM)
48 {
49   d_I=FSM.I();
50   d_S=FSM.S();
51   d_O=FSM.O();
52   d_NS=FSM.NS();
53   d_OS=FSM.OS();
54   d_PS=FSM.PS(); // is this going to make a deep copy?
55   d_PI=FSM.PI();
56   d_TMi=FSM.TMi();
57   d_TMl=FSM.TMl();
58 }
59
60 fsm::fsm(int I, int S, int O, const std::vector<int> &NS, const std::vector<int> &OS)
61 {
62   d_I=I;
63   d_S=S;
64   d_O=O;
65   d_NS=NS;
66   d_OS=OS;
67  
68   generate_PS_PI();
69   generate_TM();
70 }
71
72 //######################################################################
73 //# Read an FSM specification from a file.
74 //# Format (hopefully will become more flexible in the future...):
75 //# I S O (in the first line)
76 //# blank line
77 //# Next state matrix (S lines, each with I integers separated by spaces)
78 //# blank line
79 //# output symbol matrix (S lines, each with I integers separated by spaces)
80 //# optional comments
81 //######################################################################
82 fsm::fsm(const char *name) 
83 {
84   FILE *fsmfile;
85
86   if((fsmfile=fopen(name,"r"))==NULL) 
87     throw std::runtime_error ("fsm::fsm(const char *name): file open error\n");
88     //printf("file open error in fsm()\n");
89   
90   fscanf(fsmfile,"%d %d %d\n",&d_I,&d_S,&d_O);
91   d_NS.resize(d_I*d_S);
92   d_OS.resize(d_I*d_S);
93
94   for(int i=0;i<d_S;i++) {
95     for(int j=0;j<d_I;j++) fscanf(fsmfile,"%d",&(d_NS[i*d_I+j]));
96   }
97   for(int i=0;i<d_S;i++) {
98     for(int j=0;j<d_I;j++) fscanf(fsmfile,"%d",&(d_OS[i*d_I+j]));
99   }
100  
101   generate_PS_PI();
102   generate_TM();
103 }
104
105
106
107 //######################################################################
108 //# Automatically generate the FSM from the generator matrix
109 //# of a (n,k) binary convolutional code
110 //######################################################################
111 fsm::fsm(int k, int n, const std::vector<int> &G)
112 {
113
114   // calculate maximum memory requirements for each input stream
115   std::vector<int> max_mem_x(k,-1);
116   int max_mem = -1;
117   for(int i=0;i<k;i++) {
118     for(int j=0;j<n;j++) {
119       int mem = -1;
120       if(G[i*n+j]!=0)
121         mem=(int)(log(G[i*n+j])/log(2.0));
122       if(mem>max_mem_x[i])
123         max_mem_x[i]=mem;
124       if(mem>max_mem)
125         max_mem=mem;
126     }
127   }
128   
129 //printf("max_mem_x\n");
130 //for(int j=0;j<max_mem_x.size();j++) printf("%d ",max_mem_x[j]); printf("\n");
131
132   // calculate total memory requirements to set S
133   int sum_max_mem = 0;
134   for(int i=0;i<k;i++)
135     sum_max_mem += max_mem_x[i];
136
137 //printf("sum_max_mem = %d\n",sum_max_mem);
138
139   d_I=1<<k;
140   d_S=1<<sum_max_mem;
141   d_O=1<<n;
142  
143   // binary representation of the G matrix
144   std::vector<std::vector<int> > Gb(k*n);
145   for(int j=0;j<k*n;j++) {
146     Gb[j].resize(max_mem+1);
147     dec2base(G[j],2,Gb[j]);
148 //printf("Gb\n");
149 //for(int m=0;m<Gb[j].size();m++) printf("%d ",Gb[j][m]); printf("\n");
150   }
151
152   // alphabet size of each shift register 
153   std::vector<int> bases_x(k);
154   for(int j=0;j<k ;j++) 
155     bases_x[j] = 1 << max_mem_x[j];
156 //printf("bases_x\n");
157 //for(int j=0;j<max_mem_x.size();j++) printf("%d ",max_mem_x[j]); printf("\n");
158
159   d_NS.resize(d_I*d_S);
160   d_OS.resize(d_I*d_S);
161
162   std::vector<int> sx(k);
163   std::vector<int> nsx(k);
164   std::vector<int> tx(k);
165   std::vector<std::vector<int> > tb(k);
166   for(int j=0;j<k;j++)
167     tb[j].resize(max_mem+1);
168   std::vector<int> inb(k);
169   std::vector<int> outb(n);
170
171
172   for(int s=0;s<d_S;s++) {
173     dec2bases(s,bases_x,sx); // split s into k values, each representing one of the k shift registers
174 //printf("state = %d \nstates = ",s);
175 //for(int j=0;j<sx.size();j++) printf("%d ",sx[j]); printf("\n");
176     for(int i=0;i<d_I;i++) {
177       dec2base(i,2,inb); // input in binary
178 //printf("input = %d \ninputs = ",i);
179 //for(int j=0;j<inb.size();j++) printf("%d ",inb[j]); printf("\n");
180
181       // evaluate next state
182       for(int j=0;j<k;j++)
183         nsx[j] = (inb[j]*bases_x[j]+sx[j])/2; // next state (for each shift register) MSB first
184       d_NS[s*d_I+i]=bases2dec(nsx,bases_x); // collect all values into the new state
185
186       // evaluate transitions
187       for(int j=0;j<k;j++)
188         tx[j] = inb[j]*bases_x[j]+sx[j]; // transition (for each shift register)MSB first
189       for(int j=0;j<k;j++) {
190         dec2base(tx[j],2,tb[j]); // transition in binary
191 //printf("transition = %d \ntransitions = ",tx[j]);
192 //for(int m=0;m<tb[j].size();m++) printf("%d ",tb[j][m]); printf("\n");
193       }
194
195       // evaluate outputs
196       for(int nn=0;nn<n;nn++) {
197         outb[nn] = 0;
198         for(int j=0;j<k;j++) {
199           for(int m=0;m<max_mem+1;m++)
200             outb[nn] = (outb[nn] + Gb[j*n+nn][m]*tb[j][m]) % 2; // careful: polynomial 1+D ir represented as 110, not as 011
201 //printf("output %d equals %d\n",nn,outb[nn]);
202         }
203       }
204       d_OS[s*d_I+i] = base2dec(outb,2);
205     }
206   }
207
208   generate_PS_PI();
209   generate_TM();
210 }
211
212
213
214
215 //######################################################################
216 //# Automatically generate an FSM specification describing the 
217 //# ISI for a channel
218 //# of length ch_length and a modulation of size mod_size
219 //######################################################################
220 fsm::fsm(int mod_size, int ch_length)
221 {
222   d_I=mod_size;
223   d_S=(int) (pow(1.0*d_I,1.0*ch_length-1)+0.5);
224   d_O=d_S*d_I;
225
226   d_NS.resize(d_I*d_S);
227   d_OS.resize(d_I*d_S);
228
229   for(int s=0;s<d_S;s++) {
230     for(int i=0;i<d_I;i++) { 
231       int t=i*d_S+s;
232       d_NS[s*d_I+i] = t/d_I;
233       d_OS[s*d_I+i] = t;
234     }
235   }
236  
237   generate_PS_PI();
238   generate_TM();
239 }
240
241
242
243
244 //######################################################################
245 //# Automatically generate an FSM specification describing the 
246 //# the trellis for a CPM with h=K/P (relatively prime), 
247 //# alphabet size M, and frequency pulse duration L symbols
248 //#
249 //# This FSM is based on the paper by B. Rimoldi
250 //# "A decomposition approach to CPM", IEEE Trans. Info Theory, March 1988
251 //# See also my own notes at http://www.eecs.umich.edu/~anastas/docs/cpm.pdf
252 //######################################################################
253 fsm::fsm(int P, int M, int L)
254 {
255   d_I=M;
256   d_S=(int)(pow(1.0*M,1.0*L-1)+0.5)*P;
257   d_O=(int)(pow(1.0*M,1.0*L)+0.5)*P;
258
259   d_NS.resize(d_I*d_S);
260   d_OS.resize(d_I*d_S);
261   int nv;
262   for(int s=0;s<d_S;s++) {
263     for(int i=0;i<d_I;i++) {
264       int s1=s/P;
265       int v=s%P;
266       int ns1= (i*(int)(pow(1.0*M,1.0*(L-1))+0.5)+s1)/M;
267       if (L==1)
268         nv=(i+v)%P;
269       else
270         nv=(s1%M+v)%P;
271       d_NS[s*d_I+i] = ns1*P+nv;
272       d_OS[s*d_I+i] = i*d_S+s;
273     }
274   }
275
276   generate_PS_PI();
277   generate_TM();
278 }
279
280
281
282
283
284
285
286
287
288
289 //######################################################################
290 //# Automatically generate an FSM specification describing the 
291 //# the joint trellis of fsm1 and fsm2
292 //######################################################################
293 fsm::fsm(const fsm &FSM1, const fsm &FSM2)
294 {
295   d_I=FSM1.I()*FSM2.I();
296   d_S=FSM1.S()*FSM2.S();
297   d_O=FSM1.O()*FSM2.O();
298
299   d_NS.resize(d_I*d_S);
300   d_OS.resize(d_I*d_S);
301
302   for(int s=0;s<d_S;s++) {
303     for(int i=0;i<d_I;i++) {
304       int s1=s/FSM2.S();
305       int s2=s%FSM2.S();
306       int i1=i/FSM2.I();
307       int i2=i%FSM2.I();
308       d_NS[s*d_I+i] = FSM1.NS()[s1 * FSM1.I() + i1] * FSM2.S() + FSM2.NS()[s2 * FSM2.I() + i2];
309       d_OS[s*d_I+i] = FSM1.OS()[s1 * FSM1.I() + i1] * FSM2.O() + FSM2.OS()[s2 * FSM2.I() + i2];
310     }
311   }
312
313   generate_PS_PI();
314   generate_TM();
315 }
316
317
318
319
320 //######################################################################
321 //# Generate a new FSM representing n stages through the original FSM
322 //# AKA radix-n FSM
323 //######################################################################
324 fsm::fsm(const fsm &FSM, int n)
325 {
326   d_I=(int) (pow(1.0*FSM.I(),1.0*n)+0.5);
327   d_S=FSM.S();
328   d_O=(int) (pow(1.0*FSM.O(),1.0*n)+0.5);
329
330   d_NS.resize(d_I*d_S);
331   d_OS.resize(d_I*d_S);
332
333   for(int s=0;s<d_S;s++ ) {
334     for(int i=0;i<d_I;i++ ) {
335       std::vector<int> ii(n);
336       dec2base(i,FSM.I(),ii);
337       std::vector<int> oo(n);
338       int ns=s;
339       for(int k=0;k<n;k++) {
340         oo[k]=FSM.OS()[ns*FSM.I()+ii[k]];
341         ns=FSM.NS()[ns*FSM.I()+ii[k]];
342       }
343       d_NS[s*d_I+i]=ns;
344       d_OS[s*d_I+i]=base2dec(oo,FSM.O());
345     }
346   }
347
348   generate_PS_PI();
349   generate_TM();
350 }
351
352
353
354
355
356
357
358
359
360 //######################################################################
361 //# generate the PS and PI tables for later use
362 //######################################################################
363 void fsm::generate_PS_PI()
364 {
365   d_PS.resize(d_S);
366   d_PI.resize(d_S);
367
368   for(int i=0;i<d_S;i++) {
369     d_PS[i].resize(d_I*d_S); // max possible size
370     d_PI[i].resize(d_I*d_S);
371     int j=0;
372     for(int ii=0;ii<d_S;ii++) for(int jj=0;jj<d_I;jj++) {
373       if(d_NS[ii*d_I+jj]!=i) continue;
374       d_PS[i][j]=ii;
375       d_PI[i][j]=jj;
376       j++;
377     }
378     d_PS[i].resize(j);
379     d_PI[i].resize(j);
380   }
381 }
382
383
384 //######################################################################
385 //# generate the termination matrices TMl and TMi for later use
386 //######################################################################
387 void fsm::generate_TM()
388 {
389   d_TMi.resize(d_S*d_S);
390   d_TMl.resize(d_S*d_S);
391
392   for(int i=0;i<d_S*d_S;i++) {
393     d_TMi[i] = -1; // no meaning
394     d_TMl[i] = d_S; //infinity: you need at most S-1 steps
395     if (i/d_S == i%d_S)
396       d_TMl[i] = 0;
397   }
398
399   for(int s=0;s<d_S;s++) {
400     bool done = false;
401     int attempts = 0;
402     while (done == false && attempts < d_S-1) {
403       done = find_es(s);
404       attempts ++;
405     }
406     if (done == false) {
407       //throw std::runtime_error ("fsm::generate_TM(): FSM appears to be disconnected\n");
408       printf("fsm::generate_TM(): FSM appears to be disconnected\n");
409       printf("state %d cannot be reached from all other states\n",s);
410     }
411   }
412 }
413
414
415 // find a path from any state to the ending state "es"
416 bool fsm::find_es(int es)
417 {
418   bool done = true;
419   for(int s=0;s<d_S;s++) {
420     if(d_TMl[s*d_S+es] < d_S) 
421       continue;
422     int minl=d_S;
423     int mini=-1;
424     for(int i=0;i<d_I;i++) {
425       if( 1 + d_TMl[d_NS[s*d_I+i]*d_S+es] < minl) {
426         minl = 1 + d_TMl[d_NS[s*d_I+i]*d_S+es];
427         mini = i;
428       }
429     }
430     if (mini != -1) {
431       d_TMl[s*d_S+es]=minl;
432       d_TMi[s*d_S+es]=mini;
433     }
434     else
435       done = false;
436   }
437   return done;
438 }
439
440
441
442
443
444 //######################################################################
445 //#  generate trellis representation of FSM as an SVG file
446 //######################################################################
447 void fsm::write_trellis_svg( std::string filename ,int number_stages)
448 {
449    std::ofstream trellis_fname (filename.c_str());
450    if (!trellis_fname) {std::cout << "file not found " << std::endl ; exit(-1);}
451    const int TRELLIS_Y_OFFSET = 30;
452    const int TRELLIS_X_OFFSET = 20;
453    const int STAGE_LABEL_Y_OFFSET = 25;
454    const int STAGE_LABEL_X_OFFSET = 20;
455    const int STATE_LABEL_Y_OFFSET = 30;
456    const int STATE_LABEL_X_OFFSET = 5;
457    const int STAGE_STATE_OFFSETS = 10;
458 //   std::cout << "################## BEGIN SVG TRELLIS PIC #####################" << std::endl;
459    trellis_fname << "<svg viewBox = \"0 0 200 200\" version = \"1.1\">" << std::endl;
460
461     for( int stage_num = 0;stage_num < number_stages;stage_num ++){
462     // draw states
463       for ( int state_num = 0;state_num < d_S ; state_num ++ ) {
464         trellis_fname << "<circle cx = \"" << stage_num * STAGE_STATE_OFFSETS + TRELLIS_X_OFFSET << 
465         "\" cy = \"" << state_num * STAGE_STATE_OFFSETS + TRELLIS_Y_OFFSET << "\" r = \"1\"/>" << std::endl;
466       //draw branches
467         if(stage_num != number_stages-1){
468           for( int branch_num = 0;branch_num < d_I; branch_num++){
469             trellis_fname << "<line x1 =\"" << STAGE_STATE_OFFSETS * stage_num+ TRELLIS_X_OFFSET  << "\" ";
470             trellis_fname << "y1 =\"" << state_num * STAGE_STATE_OFFSETS + TRELLIS_Y_OFFSET<< "\" ";
471             trellis_fname << "x2 =\"" <<  STAGE_STATE_OFFSETS *stage_num + STAGE_STATE_OFFSETS+ TRELLIS_X_OFFSET << "\" ";
472             trellis_fname << "y2 =\"" << d_NS[d_I * state_num + branch_num] * STAGE_STATE_OFFSETS + TRELLIS_Y_OFFSET << "\" ";
473             trellis_fname << " stroke-dasharray = \"3," <<  branch_num << "\" ";
474             trellis_fname << " stroke = \"black\" stroke-width = \"0.3\"/>" << std::endl;
475           }
476         }
477       }
478     }
479   // label the stages
480   trellis_fname << "<g font-size = \"4\" font= \"times\" fill = \"black\">" << std::endl;
481   for( int stage_num = 0;stage_num < number_stages ;stage_num ++){
482     trellis_fname << "<text x = \"" << stage_num * STAGE_STATE_OFFSETS + STAGE_LABEL_X_OFFSET << 
483       "\" y = \""  << STAGE_LABEL_Y_OFFSET  << "\" >" << std::endl;
484     trellis_fname << stage_num <<  std::endl;
485     trellis_fname << "</text>" << std::endl;
486   }
487   trellis_fname << "</g>" << std::endl;
488
489   // label the states
490   trellis_fname << "<g font-size = \"4\" font= \"times\" fill = \"black\">" << std::endl;
491   for( int state_num = 0;state_num < d_S ; state_num ++){
492     trellis_fname << "<text y = \"" << state_num * STAGE_STATE_OFFSETS + STATE_LABEL_Y_OFFSET << 
493       "\" x = \""  << STATE_LABEL_X_OFFSET  << "\" >" << std::endl;
494     trellis_fname << state_num <<  std::endl;
495     trellis_fname << "</text>" << std::endl;
496   }
497   trellis_fname << "</g>" << std::endl;
498
499
500   trellis_fname << "</svg>" << std::endl;
501 //  std::cout << "################## END SVG TRELLIS PIC ##################### " << std::endl;
502   trellis_fname.close();
503 }
504
505
506
507
508
509
510 //######################################################################
511 //# Write trellis specification to a text file,
512 //# in the same format used when reading FSM files
513 //######################################################################
514 void fsm::write_fsm_txt(std::string filename)
515 {
516    std::ofstream trellis_fname (filename.c_str());
517    if (!trellis_fname) {std::cout << "file not found " << std::endl ; exit(-1);}
518    trellis_fname << d_I << ' ' << d_S << ' ' << d_O << std::endl;
519    trellis_fname << std::endl;
520    for(int i=0;i<d_S;i++) {
521      for(int j=0;j<d_I;j++)  trellis_fname << d_NS[i*d_I+j] << ' ';
522      trellis_fname << std::endl;
523    }
524    trellis_fname << std::endl;
525    for(int i=0;i<d_S;i++) {
526      for(int j=0;j<d_I;j++) trellis_fname << d_OS[i*d_I+j] << ' ';
527      trellis_fname << std::endl;
528    }
529    trellis_fname << std::endl;
530    trellis_fname.close();
531 }
532