00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 using namespace std;
00022
00023 #include "mfstream.h"
00024 #include "mempool.h"
00025 #include "htable.h"
00026 #include "dictionary.h"
00027 #include "n_gram.h"
00028 #include "ngramtable.h"
00029 #include "normcache.h"
00030
00031
00032
00033 normcache::normcache(dictionary* d)
00034 {
00035 dict=d;
00036
00037
00038
00039 ngt=new ngramtable(NULL,2,NULL,NULL,NULL,0,0,NULL,0,LEAFPROB);
00040
00041 maxcache[0]=d->size();
00042 maxcache[1]=d->size();
00043
00044 cache[0]=new double[maxcache[0]];
00045 cache[1]=new double[maxcache[1]];
00046
00047 for (int i=0; i<d->size(); i++)
00048 cache[0][i]=cache[1][i]=0.0;
00049
00050 cachesize[0]=cachesize[1]=0;
00051 hit=miss=0;
00052 }
00053
00054 void normcache::expand(int n)
00055 {
00056
00057 int step=100000;
00058 cerr << "Expanding cache ...\n";
00059 double *newcache=new double[maxcache[n]+step];
00060 memcpy(newcache,cache[n],sizeof(double)*maxcache[n]);
00061 delete [] cache[n];
00062 cache[n]=newcache;
00063 for (int i=0; i<step; i++)
00064 cache[n][maxcache[n]+i]=0;
00065 maxcache[n]+=step;
00066 };
00067
00068
00069 double normcache::get(ngram ng,int size,double& value)
00070 {
00071
00072 if (size==2) {
00073 if (*ng.wordp(2) < cachesize[0])
00074 return value=cache[0][*ng.wordp(2)];
00075 else
00076 return value=0;
00077 } else if (size==3) {
00078 if (ngt->get(ng,size,size-1)) {
00079 hit++;
00080
00081 return value=cache[1][ng.freq];
00082 } else {
00083 miss++;
00084 return value=0;
00085 }
00086 }
00087 return 0;
00088 }
00089
00090 double normcache::put(ngram ng,int size,double value)
00091 {
00092
00093 if (size==2) {
00094 if (*ng.wordp(2)>= maxcache[0]) expand(0);
00095 cache[0][*ng.wordp(2)]=value;
00096 cachesize[0]++;
00097 return value;
00098 } else if (size==3) {
00099 if (ngt->get(ng,size,size-1))
00100 return cache[1][ng.freq]=value;
00101 else {
00102 ngram histo(dict,2);
00103 *histo.wordp(1)=*ng.wordp(2);
00104 *histo.wordp(2)=*ng.wordp(3);
00105 histo.freq=cachesize[1]++;
00106 if (cachesize[1]==maxcache[1]) expand(1);
00107 ngt->put(histo);
00108 return cache[1][histo.freq]=value;
00109 }
00110 }
00111 return 0;
00112 }
00113
00114 void normcache::stat()
00115 {
00116 cerr << "misses " << miss << ", hits " << hit << "\n";
00117 }
00118
00119
00120
00121
00122
00123