latticepare.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  5. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  6. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2001 *
  9. * by the Xiph.Org Foundation http://www.xiph.org/ *
  10. * *
  11. ********************************************************************
  12. function: utility for paring low hit count cells from lattice codebook
  13. last mod: $Id$
  14. ********************************************************************/
  15. #include <stdlib.h>
  16. #include <stdio.h>
  17. #include <math.h>
  18. #include <string.h>
  19. #include <errno.h>
  20. #include "../lib/scales.h"
  21. #include "bookutil.h"
  22. #include "vqgen.h"
  23. #include "vqsplit.h"
  24. #include "../lib/os.h"
  25. /* Lattice codebooks have two strengths: important fetaures that are
  26. poorly modelled by global error minimization training (eg, strong
  27. peaks) are not neglected 2) compact quantized representation.
  28. A fully populated lattice codebook, however, swings point 1 too far
  29. in the opposite direction; rare features need not be modelled quite
  30. so religiously and as such, we waste bits unless we eliminate the
  31. least common cells. The codebook rep supports unused cells, so we
  32. need to tag such cells and build an auxiliary (non-thresh) search
  33. mechanism to find the proper match quickly */
  34. /* two basic steps; first is pare the cell for which dispersal creates
  35. the least additional error. This will naturally choose
  36. low-population cells and cells that have not taken on points from
  37. neighboring paring (but does not result in the lattice collapsing
  38. inward and leaving low population ares totally unmodelled). After
  39. paring has removed the desired number of cells, we need to build an
  40. auxiliary search for each culled point */
  41. /* Although lattice books (due to threshhold-based matching) do not
  42. actually use error to make cell selections (in fact, it need not
  43. bear any relation), the 'secondbest' entry finder here is in fact
  44. error/distance based, so latticepare is only useful on such books */
  45. /* command line:
  46. latticepare latticebook.vqh input_data.vqd <target_cells>
  47. produces a new output book on stdout
  48. */
  49. static float _dist(int el,float *a, float *b){
  50. int i;
  51. float acc=0.f;
  52. for(i=0;i<el;i++){
  53. float val=(a[i]-b[i]);
  54. acc+=val*val;
  55. }
  56. return(acc);
  57. }
  58. static float *pointlist;
  59. static long points=0;
  60. void add_vector(codebook *b,float *vec,long n){
  61. int dim=b->dim,i,j;
  62. int step=n/dim;
  63. for(i=0;i<step;i++){
  64. for(j=i;j<n;j+=step){
  65. pointlist[points++]=vec[j];
  66. }
  67. }
  68. }
  69. static int bestm(codebook *b,float *vec){
  70. encode_aux_threshmatch *tt=b->c->thresh_tree;
  71. int dim=b->dim;
  72. int i,k,o;
  73. int best=0;
  74. /* what would be the closest match if the codebook was fully
  75. populated? */
  76. for(k=0,o=dim-1;k<dim;k++,o--){
  77. int i;
  78. for(i=0;i<tt->threshvals-1;i++)
  79. if(vec[o]<tt->quantthresh[i])break;
  80. best=(best*tt->quantvals)+tt->quantmap[i];
  81. }
  82. return(best);
  83. }
  84. static int closest(codebook *b,float *vec,int current){
  85. encode_aux_threshmatch *tt=b->c->thresh_tree;
  86. int dim=b->dim;
  87. int i,k,o;
  88. float bestmetric=0;
  89. int bestentry=-1;
  90. int best=bestm(b,vec);
  91. if(current<0 && b->c->lengthlist[best]>0)return best;
  92. for(i=0;i<b->entries;i++){
  93. if(b->c->lengthlist[i]>0 && i!=best && i!=current){
  94. float thismetric=_dist(dim, vec, b->valuelist+i*dim);
  95. if(bestentry==-1 || thismetric<bestmetric){
  96. bestentry=i;
  97. bestmetric=thismetric;
  98. }
  99. }
  100. }
  101. return(bestentry);
  102. }
  103. static float _heuristic(codebook *b,float *ppt,int secondbest){
  104. float *secondcell=b->valuelist+secondbest*b->dim;
  105. int best=bestm(b,ppt);
  106. float *firstcell=b->valuelist+best*b->dim;
  107. float error=_dist(b->dim,firstcell,secondcell);
  108. float *zero=alloca(b->dim*sizeof(float));
  109. float fromzero;
  110. memset(zero,0,b->dim*sizeof(float));
  111. fromzero=sqrt(_dist(b->dim,firstcell,zero));
  112. return(error/fromzero);
  113. }
  114. static int longsort(const void *a, const void *b){
  115. return **(long **)b-**(long **)a;
  116. }
  117. void usage(void){
  118. fprintf(stderr,"Ogg/Vorbis lattice codebook paring utility\n\n"
  119. "usage: latticepare book.vqh data.vqd <target_cells> <protected_cells> base\n"
  120. "where <target_cells> is the desired number of final cells (or -1\n"
  121. " for no change)\n"
  122. " <protected_cells> is the number of highest-hit count cells\n"
  123. " to protect from dispersal\n"
  124. " base is the base name (not including .vqh) of the new\n"
  125. " book\n\n");
  126. exit(1);
  127. }
  128. int main(int argc,char *argv[]){
  129. char *basename;
  130. codebook *b=NULL;
  131. int entries=0;
  132. int dim=0;
  133. long i,j,target=-1,protect=-1;
  134. FILE *out=NULL;
  135. int argnum=0;
  136. argv++;
  137. if(*argv==NULL){
  138. usage();
  139. exit(1);
  140. }
  141. while(*argv){
  142. if(*argv[0]=='-'){
  143. argv++;
  144. }else{
  145. switch (argnum++){
  146. case 0:case 1:
  147. {
  148. /* yes, this is evil. However, it's very convenient to parse file
  149. extentions */
  150. /* input file. What kind? */
  151. char *dot;
  152. char *ext=NULL;
  153. char *name=strdup(*argv++);
  154. dot=strrchr(name,'.');
  155. if(dot)
  156. ext=dot+1;
  157. else{
  158. ext="";
  159. }
  160. /* codebook */
  161. if(!strcmp(ext,"vqh")){
  162. basename=strrchr(name,'/');
  163. if(basename)
  164. basename=strdup(basename)+1;
  165. else
  166. basename=strdup(name);
  167. dot=strrchr(basename,'.');
  168. if(dot)*dot='\0';
  169. b=codebook_load(name);
  170. dim=b->dim;
  171. entries=b->entries;
  172. }
  173. /* data file; we do actually need to suck it into memory */
  174. /* we're dealing with just one book, so we can de-interleave */
  175. if(!strcmp(ext,"vqd") && !points){
  176. int cols;
  177. long lines=0;
  178. char *line;
  179. float *vec;
  180. FILE *in=fopen(name,"r");
  181. if(!in){
  182. fprintf(stderr,"Could not open input file %s\n",name);
  183. exit(1);
  184. }
  185. reset_next_value();
  186. line=setup_line(in);
  187. /* count cols before we start reading */
  188. {
  189. char *temp=line;
  190. while(*temp==' ')temp++;
  191. for(cols=0;*temp;cols++){
  192. while(*temp>32)temp++;
  193. while(*temp==' ')temp++;
  194. }
  195. }
  196. vec=alloca(cols*sizeof(float));
  197. /* count, then load, to avoid fragmenting the hell out of
  198. memory */
  199. while(line){
  200. lines++;
  201. for(j=0;j<cols;j++)
  202. if(get_line_value(in,vec+j)){
  203. fprintf(stderr,"Too few columns on line %ld in data file\n",lines);
  204. exit(1);
  205. }
  206. if((lines&0xff)==0)spinnit("counting samples...",lines*cols);
  207. line=setup_line(in);
  208. }
  209. pointlist=_ogg_malloc((cols*lines+entries*dim)*sizeof(float));
  210. rewind(in);
  211. line=setup_line(in);
  212. while(line){
  213. lines--;
  214. for(j=0;j<cols;j++)
  215. if(get_line_value(in,vec+j)){
  216. fprintf(stderr,"Too few columns on line %ld in data file\n",lines);
  217. exit(1);
  218. }
  219. /* deinterleave, add to heap */
  220. add_vector(b,vec,cols);
  221. if((lines&0xff)==0)spinnit("loading samples...",lines*cols);
  222. line=setup_line(in);
  223. }
  224. fclose(in);
  225. }
  226. }
  227. break;
  228. case 2:
  229. target=atol(*argv++);
  230. if(target==0)target=entries;
  231. break;
  232. case 3:
  233. protect=atol(*argv++);
  234. break;
  235. case 4:
  236. {
  237. char *buff=alloca(strlen(*argv)+5);
  238. sprintf(buff,"%s.vqh",*argv);
  239. basename=*argv++;
  240. out=fopen(buff,"w");
  241. if(!out){
  242. fprintf(stderr,"unable ot open %s for output",buff);
  243. exit(1);
  244. }
  245. }
  246. break;
  247. default:
  248. usage();
  249. }
  250. }
  251. }
  252. if(!entries || !points || !out)usage();
  253. if(target==-1)usage();
  254. /* add guard points */
  255. for(i=0;i<entries;i++)
  256. for(j=0;j<dim;j++)
  257. pointlist[points++]=b->valuelist[i*dim+j];
  258. points/=dim;
  259. /* set up auxiliary vectors for error tracking */
  260. {
  261. encode_aux_nearestmatch *nt=NULL;
  262. long pointssofar=0;
  263. long *pointindex;
  264. long indexedpoints=0;
  265. long *entryindex;
  266. long *reventry;
  267. long *membership=_ogg_malloc(points*sizeof(long));
  268. long *firsthead=_ogg_malloc(entries*sizeof(long));
  269. long *secondary=_ogg_malloc(points*sizeof(long));
  270. long *secondhead=_ogg_malloc(entries*sizeof(long));
  271. long *cellcount=_ogg_calloc(entries,sizeof(long));
  272. long *cellcount2=_ogg_calloc(entries,sizeof(long));
  273. float *cellerror=_ogg_calloc(entries,sizeof(float));
  274. float *cellerrormax=_ogg_calloc(entries,sizeof(float));
  275. long cellsleft=entries;
  276. for(i=0;i<points;i++)membership[i]=-1;
  277. for(i=0;i<entries;i++)firsthead[i]=-1;
  278. for(i=0;i<points;i++)secondary[i]=-1;
  279. for(i=0;i<entries;i++)secondhead[i]=-1;
  280. for(i=0;i<points;i++){
  281. /* assign vectors to the nearest cell. Also keep track of second
  282. nearest for error statistics */
  283. float *ppt=pointlist+i*dim;
  284. int firstentry=closest(b,ppt,-1);
  285. int secondentry=closest(b,ppt,firstentry);
  286. float firstmetric=_dist(dim,b->valuelist+dim*firstentry,ppt);
  287. float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
  288. if(!(i&0xff))spinnit("initializing... ",points-i);
  289. membership[i]=firsthead[firstentry];
  290. firsthead[firstentry]=i;
  291. secondary[i]=secondhead[secondentry];
  292. secondhead[secondentry]=i;
  293. if(i<points-entries){
  294. cellerror[firstentry]+=secondmetric-firstmetric;
  295. cellerrormax[firstentry]=max(cellerrormax[firstentry],
  296. _heuristic(b,ppt,secondentry));
  297. cellcount[firstentry]++;
  298. cellcount2[secondentry]++;
  299. }
  300. }
  301. /* which cells are most heavily populated? Protect as many from
  302. dispersal as the user has requested */
  303. {
  304. long **countindex=_ogg_calloc(entries,sizeof(long *));
  305. for(i=0;i<entries;i++)countindex[i]=cellcount+i;
  306. qsort(countindex,entries,sizeof(long *),longsort);
  307. for(i=0;i<protect;i++){
  308. int ptr=countindex[i]-cellcount;
  309. cellerrormax[ptr]=9e50f;
  310. }
  311. }
  312. {
  313. fprintf(stderr,"\r");
  314. for(i=0;i<entries;i++){
  315. /* decompose index */
  316. int entry=i;
  317. for(j=0;j<dim;j++){
  318. fprintf(stderr,"%d:",entry%b->c->thresh_tree->quantvals);
  319. entry/=b->c->thresh_tree->quantvals;
  320. }
  321. fprintf(stderr,":%ld/%ld, ",cellcount[i],cellcount2[i]);
  322. }
  323. fprintf(stderr,"\n");
  324. }
  325. /* do the automatic cull request */
  326. while(cellsleft>target){
  327. int bestcell=-1;
  328. float besterror=0;
  329. float besterror2=0;
  330. long head=-1;
  331. char spinbuf[80];
  332. sprintf(spinbuf,"cells left to eliminate: %ld : ",cellsleft-target);
  333. /* find the cell with lowest removal impact */
  334. for(i=0;i<entries;i++){
  335. if(b->c->lengthlist[i]>0){
  336. if(bestcell==-1 || cellerrormax[i]<=besterror2){
  337. if(bestcell==-1 || cellerrormax[i]<besterror2 ||
  338. besterror>cellerror[i]){
  339. besterror=cellerror[i];
  340. besterror2=cellerrormax[i];
  341. bestcell=i;
  342. }
  343. }
  344. }
  345. }
  346. fprintf(stderr,"\reliminating cell %d \n"
  347. " dispersal error of %g max/%g total (%ld hits)\n",
  348. bestcell,besterror2,besterror,cellcount[bestcell]);
  349. /* disperse it. move each point out, adding it (properly) to
  350. the second best */
  351. b->c->lengthlist[bestcell]=0;
  352. head=firsthead[bestcell];
  353. firsthead[bestcell]=-1;
  354. while(head!=-1){
  355. /* head is a point number */
  356. float *ppt=pointlist+head*dim;
  357. int firstentry=closest(b,ppt,-1);
  358. int secondentry=closest(b,ppt,firstentry);
  359. float firstmetric=_dist(dim,b->valuelist+dim*firstentry,ppt);
  360. float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
  361. long next=membership[head];
  362. if(head<points-entries){
  363. cellcount[firstentry]++;
  364. cellcount[bestcell]--;
  365. cellerror[firstentry]+=secondmetric-firstmetric;
  366. cellerrormax[firstentry]=max(cellerrormax[firstentry],
  367. _heuristic(b,ppt,secondentry));
  368. }
  369. membership[head]=firsthead[firstentry];
  370. firsthead[firstentry]=head;
  371. head=next;
  372. if(cellcount[bestcell]%128==0)
  373. spinnit(spinbuf,cellcount[bestcell]+cellcount2[bestcell]);
  374. }
  375. /* now see that all points that had the dispersed cell as second
  376. choice have second choice reassigned */
  377. head=secondhead[bestcell];
  378. secondhead[bestcell]=-1;
  379. while(head!=-1){
  380. float *ppt=pointlist+head*dim;
  381. /* who are we assigned to now? */
  382. int firstentry=closest(b,ppt,-1);
  383. /* what is the new second closest match? */
  384. int secondentry=closest(b,ppt,firstentry);
  385. /* old second closest is the cell being disbanded */
  386. float oldsecondmetric=_dist(dim,b->valuelist+dim*bestcell,ppt);
  387. /* new second closest error */
  388. float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
  389. long next=secondary[head];
  390. if(head<points-entries){
  391. cellcount2[secondentry]++;
  392. cellcount2[bestcell]--;
  393. cellerror[firstentry]+=secondmetric-oldsecondmetric;
  394. cellerrormax[firstentry]=max(cellerrormax[firstentry],
  395. _heuristic(b,ppt,secondentry));
  396. }
  397. secondary[head]=secondhead[secondentry];
  398. secondhead[secondentry]=head;
  399. head=next;
  400. if(cellcount2[bestcell]%128==0)
  401. spinnit(spinbuf,cellcount2[bestcell]);
  402. }
  403. cellsleft--;
  404. }
  405. /* paring is over. Build decision trees using points that now fall
  406. through the thresh matcher. */
  407. /* we don't free membership; we flatten it in order to use in lp_split */
  408. for(i=0;i<entries;i++){
  409. long head=firsthead[i];
  410. spinnit("rearranging membership cache... ",entries-i);
  411. while(head!=-1){
  412. long next=membership[head];
  413. membership[head]=i;
  414. head=next;
  415. }
  416. }
  417. free(secondhead);
  418. free(firsthead);
  419. free(cellerror);
  420. free(cellerrormax);
  421. free(secondary);
  422. pointindex=_ogg_malloc(points*sizeof(long));
  423. /* make a point index of fall-through points */
  424. for(i=0;i<points;i++){
  425. int best=_best(b,pointlist+i*dim,1);
  426. if(best==-1)
  427. pointindex[indexedpoints++]=i;
  428. spinnit("finding orphaned points... ",points-i);
  429. }
  430. /* make an entry index */
  431. entryindex=_ogg_malloc(entries*sizeof(long));
  432. target=0;
  433. for(i=0;i<entries;i++){
  434. if(b->c->lengthlist[i]>0)
  435. entryindex[target++]=i;
  436. }
  437. /* make working space for a reverse entry index */
  438. reventry=_ogg_malloc(entries*sizeof(long));
  439. /* do the split */
  440. nt=b->c->nearest_tree=
  441. _ogg_calloc(1,sizeof(encode_aux_nearestmatch));
  442. nt->alloc=4096;
  443. nt->ptr0=_ogg_malloc(sizeof(long)*nt->alloc);
  444. nt->ptr1=_ogg_malloc(sizeof(long)*nt->alloc);
  445. nt->p=_ogg_malloc(sizeof(long)*nt->alloc);
  446. nt->q=_ogg_malloc(sizeof(long)*nt->alloc);
  447. nt->aux=0;
  448. fprintf(stderr,"Leaves added: %d \n",
  449. lp_split(pointlist,points,
  450. b,entryindex,target,
  451. pointindex,indexedpoints,
  452. membership,reventry,
  453. 0,&pointssofar));
  454. free(membership);
  455. free(reventry);
  456. free(pointindex);
  457. /* hack alert. I should just change the damned splitter and
  458. codebook writer */
  459. for(i=0;i<nt->aux;i++)nt->p[i]*=dim;
  460. for(i=0;i<nt->aux;i++)nt->q[i]*=dim;
  461. /* recount hits. Build new lengthlist. reuse entryindex storage */
  462. for(i=0;i<entries;i++)entryindex[i]=1;
  463. for(i=0;i<points-entries;i++){
  464. int best=_best(b,pointlist+i*dim,1);
  465. float *a=pointlist+i*dim;
  466. if(!(i&0xff))spinnit("counting hits...",i);
  467. if(best==-1){
  468. fprintf(stderr,"\nINTERNAL ERROR; a point count not be matched to a\n"
  469. "codebook entry. The new decision tree is broken.\n");
  470. exit(1);
  471. }
  472. entryindex[best]++;
  473. }
  474. for(i=0;i<nt->aux;i++)nt->p[i]/=dim;
  475. for(i=0;i<nt->aux;i++)nt->q[i]/=dim;
  476. /* the lengthlist builder doesn't actually deal with 0 hit entries.
  477. So, we pack the 'sparse' hit list into a dense list, then unpack
  478. the lengths after the build */
  479. {
  480. int upper=0;
  481. long *lengthlist=_ogg_calloc(entries,sizeof(long));
  482. for(i=0;i<entries;i++){
  483. if(b->c->lengthlist[i]>0)
  484. entryindex[upper++]=entryindex[i];
  485. else{
  486. if(entryindex[i]>1){
  487. fprintf(stderr,"\nINTERNAL ERROR; _best matched to unused entry\n");
  488. exit(1);
  489. }
  490. }
  491. }
  492. /* sanity check */
  493. if(upper != target){
  494. fprintf(stderr,"\nINTERNAL ERROR; packed the wrong number of entries\n");
  495. exit(1);
  496. }
  497. build_tree_from_lengths(upper,entryindex,lengthlist);
  498. upper=0;
  499. for(i=0;i<entries;i++){
  500. if(b->c->lengthlist[i]>0)
  501. b->c->lengthlist[i]=lengthlist[upper++];
  502. }
  503. }
  504. }
  505. /* we're done. write it out. */
  506. write_codebook(out,basename,b->c);
  507. fprintf(stderr,"\r \nDone.\n");
  508. return(0);
  509. }