annotate index.cpp @ 460:17003dff8127 api-inversion

Convert index-finding logic to C functions. New audiodb_index_exists() and audiodb_index_get_name(). The behaviours of the functions are unchanged, even though they are kind of weird; in particular, passing in a buffer rather than returning a char * for audiodb_index_get_name() is probably likely to work better eventually (see the changes to soap.cpp, which show a clear leak of a buffer in the error case)
author mas01cr
date Tue, 30 Dec 2008 10:36:01 +0000
parents fcc6f7c4856b
children 35bb388d0eac
rev   line source
mas01mc@292 1 // LSH indexing
mas01mc@292 2 //
mas01mc@292 3 // Construct a persistent LSH table structure
mas01mc@292 4 // Store at the same location as dbName
mas01mc@292 5 // Naming convention:
mas01mc@292 6 // dbName.lsh.${radius}.${sequenceLength}
mas01mc@292 7 //
mas01mc@292 8 //
mas01mc@292 9 // Author: Michael Casey
mas01mc@292 10 // Date: 23 June 2008
mas01mc@324 11 //
mas01mc@324 12 // 19th August 2008 - added O2_FLAG_LARGE_ADB support
mas01mc@292 13
mas01mc@292 14 #include "audioDB.h"
mas01cr@426 15 #include "audioDB-internals.h"
mas01mc@292 16
mas01cr@458 17 typedef struct adb_qcallback {
mas01cr@458 18 adb_t *adb;
mas01cr@458 19 adb_qstate_internal_t *qstate;
mas01cr@458 20 } adb_qcallback_t;
mas01mc@292 21
mas01mc@292 22 /************************* LSH indexing and query initialization *****************/
mas01mc@292 23
mas01cr@460 24 /* FIXME: there are several things wrong with this: the memory
mas01cr@460 25 * discipline isn't ideal, the radius printing is a bit lame, the name
mas01cr@460 26 * getting will succeed or fail depending on whether the path was
mas01cr@460 27 * relative or absolute -- but most importantly encoding all that
mas01cr@460 28 * information in a filename is going to lose: it's impossible to
mas01cr@460 29 * maintain backwards-compatibility. Instead we should probably store
mas01cr@460 30 * the index metadata inside the audiodb instance. */
mas01cr@460 31 char *audiodb_index_get_name(const char *dbName, double radius, Uns32T sequenceLength) {
mas01cr@460 32 char *indexName;
mas01cr@460 33 if(strlen(dbName) > (MAXSTR - 32)) {
mas01cr@460 34 return NULL;
mas01cr@460 35 }
mas01cr@460 36 indexName = new char[MAXSTR];
mas01mc@292 37 strncpy(indexName, dbName, MAXSTR);
mas01mc@292 38 sprintf(indexName+strlen(dbName), ".lsh.%019.9f.%d", radius, sequenceLength);
mas01mc@292 39 return indexName;
mas01mc@292 40 }
mas01mc@292 41
mas01cr@460 42 bool audiodb_index_exists(const char *dbName, double radius, Uns32T sequenceLength) {
mas01cr@460 43 char *indexName = audiodb_index_get_name(dbName, radius, sequenceLength);
mas01cr@460 44 if(!indexName) {
mas01cr@460 45 return false;
mas01cr@460 46 }
mas01cr@460 47 struct stat st;
mas01cr@460 48 if(stat(indexName, &st)) {
mas01cr@460 49 delete [] indexName;
mas01cr@460 50 return false;
mas01cr@460 51 }
mas01cr@460 52 /* FIXME: other stat checks here? */
mas01cr@460 53 /* FIXME: is there any better way to check whether we can open a
mas01cr@460 54 * file for reading than by opening a file for reading? */
mas01cr@460 55 int fd = open(indexName, O_RDONLY);
mas01cr@460 56 delete [] indexName;
mas01cr@460 57 if(fd < 0) {
mas01cr@460 58 return false;
mas01cr@460 59 } else {
mas01cr@460 60 close(fd);
mas01mc@292 61 return true;
mas01cr@460 62 }
mas01mc@292 63 }
mas01mc@292 64
mas01mc@324 65 // If we are a server and have a memory-resident index, check the indexName against the resident index (using get_indexName())
mas01mc@324 66 // If they match, i.e. path+dbName_resident == path+dbName_requested, use
mas01mc@324 67 // the memory-resident index.
mas01mc@324 68 // Else allocate a new LSH instance and load the index from disk
mas01mc@308 69 LSH* audioDB::index_allocate(char* indexName, bool load_hashTables){
mas01mc@308 70 LSH* gIndx=SERVER_LSH_INDEX_SINGLETON;
mas01mc@308 71 if(isServer && gIndx && (strncmp(gIndx->get_indexName(), indexName, MAXSTR)==0) )
mas01mc@308 72 audioDB::lsh = gIndx; // Use the global SERVER resident index
mas01mc@308 73 else{
mas01mc@308 74 if(audioDB::lsh)
mas01mc@308 75 delete audioDB::lsh;
mas01mc@308 76 audioDB::lsh = new LSH(indexName, load_hashTables);
mas01mc@308 77 }
mas01mc@308 78 assert(audioDB::lsh);
mas01mc@308 79 return audioDB::lsh;
mas01mc@308 80 }
mas01mc@308 81
mas01cr@459 82 vector<vector<float> > *audiodb_index_initialize_shingles(Uns32T sz, Uns32T dim, Uns32T seqLen) {
mas01cr@459 83 std::vector<std::vector<float> > *vv = new vector<vector<float> >(sz);
mas01cr@459 84 for(Uns32T i=0 ; i < sz ; i++) {
mas01cr@459 85 (*vv)[i]=vector<float>(dim * seqLen);
mas01cr@459 86 }
mas01mc@292 87 return vv;
mas01mc@292 88 }
mas01mc@292 89
mas01cr@459 90 void audiodb_index_delete_shingles(vector<vector<float> > *vv) {
mas01cr@459 91 delete vv;
mas01cr@459 92 }
mas01cr@459 93
mas01mc@292 94 /******************** LSH indexing audioDB database access forall s \in {S} ***********************/
mas01mc@292 95
mas01mc@292 96 // Prepare the AudioDB database for read access and allocate auxillary memory
mas01mc@292 97 void audioDB::index_initialize(double **snp, double **vsnp, double **spp, double **vspp, Uns32T *dvp) {
mas01mc@324 98 if (!(dbH->flags & O2_FLAG_POWER)) {
mas01mc@324 99 error("INDEXed database must be power-enabled", dbName);
mas01mc@324 100 }
mas01mc@324 101
mas01mc@325 102 double *snpp = 0, *sppp = 0;
mas01mc@324 103
mas01mc@292 104 *dvp = dbH->length / (dbH->dim * sizeof(double)); // number of database vectors
mas01mc@292 105 *snp = new double[*dvp]; // songs norm pointer: L2 norm table for each vector
mas01mc@325 106 snpp = *snp;
mas01mc@292 107 *spp = new double[*dvp]; // song powertable pointer
mas01mc@292 108 sppp = *spp;
mas01mc@325 109
mas01mc@324 110 memcpy(*snp, l2normTable, *dvp * sizeof(double));
mas01mc@292 111 memcpy(*spp, powerTable, *dvp * sizeof(double));
mas01mc@324 112
mas01mc@324 113
mas01mc@292 114 for(Uns32T i = 0; i < dbH->numFiles; i++){
mas01mc@292 115 if(trackTable[i] >= sequenceLength) {
mas01cr@427 116 audiodb_sequence_sum(snpp, trackTable[i], sequenceLength);
mas01cr@427 117 audiodb_sequence_sqrt(snpp, trackTable[i], sequenceLength);
mas01mc@292 118
mas01cr@427 119 audiodb_sequence_sum(sppp, trackTable[i], sequenceLength);
mas01cr@427 120 audiodb_sequence_average(sppp, trackTable[i], sequenceLength);
mas01mc@292 121 }
mas01mc@292 122 snpp += trackTable[i];
mas01mc@292 123 sppp += trackTable[i];
mas01mc@292 124 }
mas01mc@324 125
mas01mc@292 126 *vsnp = *snp;
mas01mc@292 127 *vspp = *spp;
mas01mc@324 128
mas01mc@292 129 // Move the feature vector read pointer to start of fetures in database
mas01mc@292 130 lseek(dbfid, dbH->dataOffset, SEEK_SET);
mas01mc@292 131 }
mas01mc@292 132
mas01mc@292 133
mas01cr@456 134 /********************* LSH shingle construction ***************************/
mas01cr@456 135
mas01cr@456 136 // Construct shingles out of a feature matrix
mas01cr@456 137 // inputs:
mas01cr@456 138 // idx is vector index in feature matrix
mas01cr@456 139 // fvp is base feature matrix pointer double* [numVecs x dbH->dim]
mas01cr@456 140 //
mas01cr@456 141 // pre-conditions:
mas01cr@456 142 // dbH->dim
mas01cr@456 143 // sequenceLength
mas01cr@456 144 // idx < numVectors - sequenceLength + 1
mas01cr@456 145 //
mas01cr@456 146 // post-conditions:
mas01cr@456 147 // (*vv)[idx] contains a shingle with dbH->dim*sequenceLength float values
mas01cr@456 148
mas01cr@456 149 static void audiodb_index_make_shingle(vector<vector<float> >* vv, Uns32T idx, double* fvp, Uns32T dim, Uns32T seqLen){
mas01cr@456 150 assert(idx<(*vv).size());
mas01cr@456 151 vector<float>::iterator ve = (*vv)[idx].end();
mas01cr@456 152 vector<float>::iterator vi = (*vv)[idx].begin();
mas01cr@456 153 // First feature vector in shingle
mas01cr@456 154 if(idx == 0) {
mas01cr@456 155 while(vi!=ve) {
mas01cr@456 156 *vi++ = (float)(*fvp++);
mas01cr@456 157 }
mas01cr@456 158 } else {
mas01cr@456 159 // Not first feature vector in shingle
mas01cr@456 160 vector<float>::iterator ui=(*vv)[idx-1].begin() + dim;
mas01cr@456 161 // Previous seqLen-1 dim-vectors
mas01cr@456 162 while(vi!=ve-dim) {
mas01cr@456 163 *vi++ = *ui++;
mas01cr@456 164 }
mas01cr@456 165 // Move data pointer to next feature vector
mas01cr@456 166 fvp += ( seqLen + idx - 1 ) * dim ;
mas01cr@456 167 // New d-vector
mas01cr@456 168 while(vi!=ve) {
mas01cr@456 169 *vi++ = (float)(*fvp++);
mas01cr@456 170 }
mas01cr@456 171 }
mas01cr@456 172 }
mas01cr@456 173
mas01cr@456 174 // norm shingles
mas01cr@456 175 // in-place norming, no deletions
mas01cr@456 176 // If using power, return number of shingles above power threshold
mas01cr@459 177 int audiodb_index_norm_shingles(vector<vector<float> >* vv, double* snp, double* spp, Uns32T dim, Uns32T seqLen, double radius, bool normed_vectors, bool use_pthreshold, float pthreshold) {
mas01cr@456 178 int z = 0; // number of above-threshold shingles
mas01cr@456 179 float l2norm;
mas01cr@456 180 double power;
mas01cr@456 181 float oneOverRadius = 1./(float)sqrt(radius); // Passed radius is really radius^2
mas01cr@456 182 float oneOverSqrtl2NormDivRad = oneOverRadius;
mas01cr@459 183 Uns32T shingleSize = seqLen * dim;
mas01cr@459 184
mas01cr@459 185 if(!spp) {
mas01cr@459 186 return -1;
mas01cr@459 187 }
mas01cr@456 188 for(Uns32T a=0; a<(*vv).size(); a++){
mas01cr@456 189 l2norm = (float)(*snp++);
mas01cr@459 190 if(normed_vectors)
mas01cr@456 191 oneOverSqrtl2NormDivRad = (1./l2norm)*oneOverRadius;
mas01cr@456 192
mas01cr@456 193 for(Uns32T b=0; b < shingleSize ; b++)
mas01cr@456 194 (*vv)[a][b]*=oneOverSqrtl2NormDivRad;
mas01cr@456 195
mas01cr@456 196 power = *spp++;
mas01cr@459 197 if(use_pthreshold){
mas01cr@459 198 if (power >= pthreshold)
mas01cr@456 199 z++;
mas01cr@456 200 }
mas01cr@456 201 else
mas01cr@456 202 z++;
mas01cr@456 203 }
mas01cr@456 204 return z;
mas01cr@456 205 }
mas01cr@456 206
mas01cr@456 207
mas01mc@292 208 /************************ LSH indexing ***********************************/
mas01mc@292 209 void audioDB::index_index_db(const char* dbName){
mas01mc@292 210 char* newIndexName;
mas01mc@292 211 double *fvp = 0, *sNorm = 0, *snPtr = 0, *sPower = 0, *spPtr = 0;
mas01mc@292 212 Uns32T dbVectors = 0;
mas01mc@292 213
mas01mc@324 214
mas01mc@292 215 printf("INDEX: initializing header\n");
mas01mc@292 216 // Check if audioDB exists, initialize header and open database for read
mas01mc@292 217 forWrite = false;
mas01mc@292 218 initDBHeader(dbName);
mas01mc@292 219
mas01mc@324 220 if(dbH->flags & O2_FLAG_POWER)
mas01mc@324 221 usingPower = true;
mas01mc@324 222
mas01mc@324 223 if(dbH->flags & O2_FLAG_TIMES)
mas01mc@324 224 usingTimes = true;
mas01mc@324 225
mas01cr@460 226 newIndexName = audiodb_index_get_name(dbName, radius, sequenceLength);
mas01cr@460 227 if(!newIndexName) {
mas01cr@460 228 error("failed to get index name", dbName);
mas01cr@460 229 }
mas01mc@292 230
mas01mc@292 231 // Set unit norming flag override
mas01mc@292 232 audioDB::normalizedDistance = !audioDB::no_unit_norming;
mas01mc@292 233
mas01mc@327 234 VERB_LOG(1, "INDEX: dim %d\n", (int)dbH->dim);
mas01mc@327 235 VERB_LOG(1, "INDEX: R %f\n", radius);
mas01mc@327 236 VERB_LOG(1, "INDEX: seqlen %d\n", sequenceLength);
mas01mc@327 237 VERB_LOG(1, "INDEX: lsh_w %f\n", lsh_param_w);
mas01mc@327 238 VERB_LOG(1, "INDEX: lsh_k %d\n", lsh_param_k);
mas01mc@327 239 VERB_LOG(1, "INDEX: lsh_m %d\n", lsh_param_m);
mas01mc@327 240 VERB_LOG(1, "INDEX: lsh_N %d\n", lsh_param_N);
mas01mc@327 241 VERB_LOG(1, "INDEX: lsh_C %d\n", lsh_param_ncols);
mas01mc@327 242 VERB_LOG(1, "INDEX: lsh_b %d\n", lsh_param_b);
mas01mc@327 243 VERB_LOG(1, "INDEX: normalized? %s\n", normalizedDistance?"true":"false");
mas01mc@292 244
mas01mc@292 245 if((lshfid = open(newIndexName,O_RDONLY))<0){
mas01mc@292 246 printf("INDEX: constructing new LSH index\n");
mas01mc@292 247 printf("INDEX: making index file %s\n", newIndexName);
mas01mc@292 248 fflush(stdout);
mas01mc@292 249 // Construct new LSH index
mas01mc@292 250 lsh = new LSH((float)lsh_param_w, lsh_param_k,
mas01mc@292 251 lsh_param_m,
mas01mc@292 252 (Uns32T)(sequenceLength*dbH->dim),
mas01mc@292 253 lsh_param_N,
mas01mc@292 254 lsh_param_ncols,
mas01mc@292 255 (float)radius);
mas01mc@292 256 assert(lsh);
mas01mc@292 257
mas01mc@292 258 Uns32T endTrack = lsh_param_b;
mas01mc@292 259 if( endTrack > dbH->numFiles)
mas01mc@292 260 endTrack = dbH->numFiles;
mas01mc@292 261 // Insert up to lsh_param_b tracks
mas01mc@324 262 if( ! (dbH->flags & O2_FLAG_LARGE_ADB) ){
mas01mc@324 263 index_initialize(&sNorm, &snPtr, &sPower, &spPtr, &dbVectors);
mas01mc@324 264 }
mas01mc@324 265 index_insert_tracks(0, endTrack, &fvp, &sNorm, &snPtr, &sPower, &spPtr);
mas01mc@292 266 lsh->serialize(newIndexName, lsh_in_core?O2_SERIAL_FILEFORMAT2:O2_SERIAL_FILEFORMAT1);
mas01mc@292 267
mas01mc@292 268 // Clean up
mas01mc@292 269 delete lsh;
mas01mc@308 270 lsh = 0;
mas01mc@292 271 close(lshfid);
mas01mc@292 272 }
mas01mc@292 273
mas01mc@292 274 // Attempt to open LSH file
mas01mc@292 275 if((lshfid = open(newIndexName,O_RDONLY))>0){
mas01mc@292 276 printf("INDEX: merging with existing LSH index\n");
mas01mc@292 277 fflush(stdout);
mas01mc@340 278 char* mergeIndexName = newIndexName;
mas01mc@292 279
mas01mc@292 280 // Get the lsh header info and find how many tracks are inserted already
mas01mc@340 281 lsh = new LSH(mergeIndexName, false); // lshInCore=false to avoid loading hashTables here
mas01mc@292 282 assert(lsh);
mas01cr@458 283 Uns32T maxs = audiodb_index_to_track_id(lsh->get_maxp(), audiodb_lsh_n_point_bits(adb))+1;
mas01mc@292 284 delete lsh;
mas01mc@308 285 lsh = 0;
mas01mc@292 286
mas01mc@340 287 // Insert up to lsh_param_b tracks
mas01mc@340 288 if( !sNorm && !(dbH->flags & O2_FLAG_LARGE_ADB) ){
mas01mc@340 289 index_initialize(&sNorm, &snPtr, &sPower, &spPtr, &dbVectors);
mas01mc@340 290 }
mas01mc@292 291 // This allows for updating index after more tracks are inserted into audioDB
mas01mc@292 292 for(Uns32T startTrack = maxs; startTrack < dbH->numFiles; startTrack+=lsh_param_b){
mas01mc@292 293
mas01mc@292 294 Uns32T endTrack = startTrack + lsh_param_b;
mas01mc@292 295 if( endTrack > dbH->numFiles)
mas01mc@292 296 endTrack = dbH->numFiles;
mas01mc@292 297 printf("Indexing track range: %d - %d\n", startTrack, endTrack);
mas01mc@292 298 fflush(stdout);
mas01mc@340 299 lsh = new LSH(mergeIndexName, false); // Initialize empty LSH tables
mas01mc@292 300 assert(lsh);
mas01mc@292 301
mas01mc@292 302 // Insert up to lsh_param_b database tracks
mas01mc@292 303 index_insert_tracks(startTrack, endTrack, &fvp, &sNorm, &snPtr, &sPower, &spPtr);
mas01mc@292 304
mas01mc@340 305 // Serialize to file (merging is performed here)
mas01mc@340 306 lsh->serialize(mergeIndexName, lsh_in_core?O2_SERIAL_FILEFORMAT2:O2_SERIAL_FILEFORMAT1); // Serialize core LSH heap to disk
mas01mc@292 307 delete lsh;
mas01mc@308 308 lsh = 0;
mas01mc@340 309 }
mas01mc@292 310
mas01mc@292 311 close(lshfid);
mas01mc@292 312 printf("INDEX: done constructing LSH index.\n");
mas01mc@292 313 fflush(stdout);
mas01mc@292 314
mas01mc@292 315 }
mas01mc@292 316 else{
mas01mc@292 317 error("Something's wrong with LSH index file");
mas01mc@292 318 exit(1);
mas01mc@292 319 }
mas01mc@292 320
mas01mc@324 321 delete[] newIndexName;
mas01mc@324 322 delete[] sNorm;
mas01mc@324 323 delete[] sPower;
mas01mc@324 324 }
mas01mc@292 325
mas01mc@292 326
mas01cr@405 327 void audioDB::insertPowerData(unsigned numVectors, int powerfd, double *powerdata) {
mas01cr@405 328 if(usingPower){
mas01cr@405 329 int one;
mas01cr@405 330 unsigned int count;
mas01cr@405 331
mas01cr@405 332 count = read(powerfd, &one, sizeof(unsigned int));
mas01cr@405 333 if (count != sizeof(unsigned int)) {
mas01cr@405 334 error("powerfd read failed", "int", "read");
mas01cr@405 335 }
mas01cr@405 336 if (one != 1) {
mas01cr@405 337 error("dimensionality of power file not 1", powerFileName);
mas01cr@405 338 }
mas01cr@405 339
mas01cr@405 340 // FIXME: should check that the powerfile is the right size for
mas01cr@405 341 // this. -- CSR, 2007-10-30
mas01cr@405 342 count = read(powerfd, powerdata, numVectors * sizeof(double));
mas01cr@405 343 if (count != numVectors * sizeof(double)) {
mas01cr@405 344 error("powerfd read failed", "double", "read");
mas01cr@405 345 }
mas01cr@405 346 }
mas01cr@405 347 }
mas01cr@405 348
mas01mc@324 349 // initialize auxillary track data from filesystem
mas01mc@324 350 // pre-conditions:
mas01mc@324 351 // dbH->flags & O2_FLAG_LARGE_ADB
mas01mc@324 352 // feature data allocated and copied (fvp)
mas01mc@324 353 //
mas01mc@324 354 // post-conditions:
mas01mc@324 355 // allocated power data
mas01mc@324 356 // allocated l2norm data
mas01mc@324 357 //
mas01mc@324 358 void audioDB::init_track_aux_data(Uns32T trackID, double* fvp, double** sNormpp,double** snPtrp, double** sPowerp, double** spPtrp){
mas01mc@324 359 if( !(dbH->flags & O2_FLAG_LARGE_ADB) )
mas01mc@324 360 error("error: init_track_large_adb required O2_FLAG_LARGE_ADB");
mas01mc@292 361
mas01mc@324 362 // Allocate and read the power sequence
mas01mc@324 363 if(trackTable[trackID]>=sequenceLength){
mas01mc@324 364
mas01mc@324 365 char* prefixedString = new char[O2_MAXFILESTR];
mas01mc@324 366 char* tmpStr = prefixedString;
mas01mc@324 367 // Open and check dimensions of power file
mas01mc@324 368 strncpy(prefixedString, powerFileNameTable+trackID*O2_FILETABLE_ENTRY_SIZE, O2_MAXFILESTR);
mas01mc@324 369 prefix_name((char ** const)&prefixedString, adb_feature_root);
mas01mc@324 370 if(prefixedString!=tmpStr)
mas01mc@324 371 delete[] tmpStr;
mas01mc@324 372 powerfd = open(prefixedString, O_RDONLY);
mas01mc@324 373 if (powerfd < 0) {
mas01mc@324 374 error("failed to open power file", prefixedString);
mas01mc@324 375 }
mas01mc@324 376 if (fstat(powerfd, &statbuf) < 0) {
mas01mc@324 377 error("fstat error finding size of power file", prefixedString, "fstat");
mas01mc@324 378 }
mas01mc@324 379
mas01mc@324 380 if( (statbuf.st_size - sizeof(int)) / (sizeof(double)) != trackTable[trackID] )
mas01mc@324 381 error("Dimension mismatch: numPowers != numVectors", prefixedString);
mas01mc@324 382
mas01mc@324 383 *sPowerp = new double[trackTable[trackID]]; // Allocate memory for power values
mas01mc@324 384 assert(*sPowerp);
mas01mc@324 385 *spPtrp = *sPowerp;
mas01mc@324 386 insertPowerData(trackTable[trackID], powerfd, *sPowerp);
mas01mc@324 387 if (0 < powerfd) {
mas01mc@324 388 close(powerfd);
mas01mc@324 389 }
mas01mc@324 390
mas01cr@427 391 audiodb_sequence_sum(*sPowerp, trackTable[trackID], sequenceLength);
mas01cr@427 392 audiodb_sequence_average(*sPowerp, trackTable[trackID], sequenceLength);
mas01mc@324 393 powerTable = 0;
mas01mc@324 394
mas01mc@324 395 // Allocate and calculate the l2norm sequence
mas01mc@324 396 *sNormpp = new double[trackTable[trackID]];
mas01mc@324 397 assert(*sNormpp);
mas01mc@324 398 *snPtrp = *sNormpp;
mas01cr@426 399 audiodb_l2norm_buffer(fvp, dbH->dim, trackTable[trackID], *sNormpp);
mas01cr@427 400 audiodb_sequence_sum(*sNormpp, trackTable[trackID], sequenceLength);
mas01cr@427 401 audiodb_sequence_sqrt(*sNormpp, trackTable[trackID], sequenceLength);
mas01mc@324 402 }
mas01mc@292 403 }
mas01mc@292 404
mas01mc@292 405 void audioDB::index_insert_tracks(Uns32T start_track, Uns32T end_track,
mas01mc@292 406 double** fvpp, double** sNormpp,double** snPtrp,
mas01mc@292 407 double** sPowerp, double** spPtrp){
mas01mc@292 408 size_t nfv = 0;
mas01mc@292 409 double* fvp = 0; // Keep pointer for memory allocation and free() for track data
mas01mc@292 410 Uns32T trackID = 0;
mas01mc@292 411
mas01mc@292 412 VERB_LOG(1, "indexing tracks...");
mas01mc@292 413
mas01mc@324 414 int trackfd = dbfid;
mas01mc@292 415 for(trackID = start_track ; trackID < end_track ; trackID++ ){
mas01mc@324 416 if( dbH->flags & O2_FLAG_LARGE_ADB ){
mas01mc@324 417 char* prefixedString = new char[O2_MAXFILESTR];
mas01mc@324 418 char* tmpStr = prefixedString;
mas01mc@324 419 // Open and check dimensions of feature file
mas01mc@324 420 strncpy(prefixedString, featureFileNameTable+trackID*O2_FILETABLE_ENTRY_SIZE, O2_MAXFILESTR);
mas01mc@324 421 prefix_name((char ** const) &prefixedString, adb_feature_root);
mas01mc@324 422 if(prefixedString!=tmpStr)
mas01mc@324 423 delete[] tmpStr;
mas01cr@454 424 initInputFile(prefixedString);
mas01mc@324 425 trackfd = infid;
mas01mc@324 426 }
mas01cr@433 427 if(audiodb_read_data(adb, trackfd, trackID, &fvp, &nfv))
mas01cr@433 428 error("failed to read data");
mas01mc@292 429 *fvpp = fvp; // Protect memory allocation and free() for track data
mas01mc@324 430
mas01mc@324 431 if( dbH->flags & O2_FLAG_LARGE_ADB )
mas01mc@324 432 // Load power and calculate power and l2norm sequence sums
mas01mc@324 433 init_track_aux_data(trackID, fvp, sNormpp, snPtrp, sPowerp, spPtrp);
mas01mc@324 434
mas01mc@292 435 if(!index_insert_track(trackID, fvpp, snPtrp, spPtrp))
mas01mc@292 436 break;
mas01mc@324 437 if ( dbH->flags & O2_FLAG_LARGE_ADB ){
mas01mc@324 438 close(infid);
mas01mc@324 439 delete[] *sNormpp;
mas01mc@324 440 delete[] *sPowerp;
mas01mc@324 441 *sNormpp = *sPowerp = *snPtrp = *snPtrp = 0;
mas01mc@324 442 }
mas01mc@324 443 } // end for(trackID = start_track ; ... )
mas01mc@292 444 std::cout << "finished inserting." << endl;
mas01mc@292 445 }
mas01mc@292 446
mas01mc@292 447 int audioDB::index_insert_track(Uns32T trackID, double** fvpp, double** snpp, double** sppp){
mas01mc@292 448 // Loop over the current input track's vectors
mas01cr@305 449 Uns32T numVecs = 0;
mas01cr@305 450 if (trackTable[trackID] > O2_MAXTRACKLEN) {
mas01cr@305 451 if (O2_MAXTRACKLEN < sequenceLength - 1) {
mas01cr@305 452 numVecs = 0;
mas01cr@305 453 } else {
mas01cr@305 454 numVecs = O2_MAXTRACKLEN - sequenceLength + 1;
mas01cr@305 455 }
mas01cr@305 456 } else {
mas01cr@305 457 if (trackTable[trackID] < sequenceLength - 1) {
mas01cr@305 458 numVecs = 0;
mas01cr@305 459 } else {
mas01cr@305 460 numVecs = trackTable[trackID] - sequenceLength + 1;
mas01cr@305 461 }
mas01cr@305 462 }
mas01mc@292 463
mas01mc@324 464 Uns32T numVecsAboveThreshold = 0, collisionCount = 0;
mas01mc@324 465 if(numVecs){
mas01cr@459 466 std::vector<std::vector<float> > *vv = audiodb_index_initialize_shingles(numVecs, dbH->dim, sequenceLength);
mas01mc@324 467
mas01mc@324 468 for( Uns32T pointID = 0 ; pointID < numVecs; pointID++ )
mas01cr@456 469 audiodb_index_make_shingle(vv, pointID, *fvpp, dbH->dim, sequenceLength);
mas01cr@459 470 int vcount = audiodb_index_norm_shingles(vv, *snpp, *sppp, dbH->dim, sequenceLength, radius, normalizedDistance, use_absolute_threshold, absolute_threshold);
mas01cr@459 471 if(vcount == -1) {
mas01cr@459 472 audiodb_index_delete_shingles(vv);
mas01cr@459 473 error("failed to norm shingles");
mas01cr@459 474 }
mas01cr@459 475 numVecsAboveThreshold = vcount;
mas01mc@324 476 collisionCount = index_insert_shingles(vv, trackID, *sppp);
mas01cr@459 477 audiodb_index_delete_shingles(vv);
mas01mc@324 478 }
mas01cr@459 479
mas01mc@292 480 float meanCollisionCount = numVecsAboveThreshold?(float)collisionCount/numVecsAboveThreshold:0;
mas01mc@292 481
mas01cr@459 482 /* audiodb_index_norm_shingles() only goes as far as the end of the
mas01mc@292 483 sequence, which is right, but the space allocated is for the
mas01mc@292 484 whole track. */
mas01mc@292 485
mas01mc@292 486 /* But numVecs will be <trackTable[track] if trackTable[track]>O2_MAXTRACKLEN
mas01mc@292 487 * So let's be certain the pointers are in the correct place
mas01mc@292 488 */
mas01mc@292 489
mas01mc@324 490 if( !(dbH->flags & O2_FLAG_LARGE_ADB) ){
mas01mc@324 491 *snpp += trackTable[trackID];
mas01mc@324 492 *sppp += trackTable[trackID];
mas01mc@324 493 *fvpp += trackTable[trackID] * dbH->dim;
mas01mc@324 494 }
mas01mc@292 495
mas01mc@292 496 std::cout << " n=" << trackTable[trackID] << " n'=" << numVecsAboveThreshold << " E[#c]=" << lsh->get_mean_collision_rate() << " E[#p]=" << meanCollisionCount << endl;
mas01mc@292 497 std::cout.flush();
mas01mc@292 498 return true;
mas01mc@292 499 }
mas01mc@292 500
mas01mc@292 501 Uns32T audioDB::index_insert_shingles(vector<vector<float> >* vv, Uns32T trackID, double* spp){
mas01mc@292 502 Uns32T collisionCount = 0;
mas01mc@292 503 cout << "[" << trackID << "]" << fileTable+trackID*O2_FILETABLE_ENTRY_SIZE;
mas01mc@324 504 for( Uns32T pointID=0 ; pointID < (*vv).size(); pointID+=sequenceHop){
mas01mc@324 505 if(!use_absolute_threshold || (use_absolute_threshold && (*spp >= absolute_threshold)))
mas01cr@458 506 collisionCount += lsh->insert_point((*vv)[pointID], audiodb_index_from_trackinfo(trackID, pointID, audiodb_lsh_n_point_bits(adb)));
mas01mc@324 507 spp+=sequenceHop;
mas01mc@311 508 }
mas01mc@292 509 return collisionCount;
mas01mc@292 510 }
mas01mc@292 511
mas01mc@292 512 /*********************** LSH retrieval ****************************/
mas01mc@292 513
mas01mc@292 514
mas01mc@292 515 // return true if indexed query performed else return false
mas01mc@292 516 int audioDB::index_init_query(const char* dbName){
mas01mc@292 517
mas01cr@460 518 if(!(audiodb_index_exists(dbName, radius, sequenceLength)))
mas01mc@292 519 return false;
mas01mc@292 520
mas01cr@460 521 char *indexName = audiodb_index_get_name(dbName, radius, sequenceLength);
mas01cr@460 522 if(!indexName) {
mas01cr@460 523 error("failed to get index name", dbName);
mas01cr@460 524 }
mas01mc@292 525
mas01mc@292 526 // Test to see if file exists
mas01mc@292 527 if((lshfid = open (indexName, O_RDONLY)) < 0){
mas01mc@292 528 delete[] indexName;
mas01mc@292 529 return false;
mas01mc@292 530 }
mas01mc@292 531
mas01mc@308 532 lsh = index_allocate(indexName, false); // Get the header only here
mas01mc@292 533 sequenceLength = lsh->get_lshHeader()->dataDim / dbH->dim; // shingleDim / vectorDim
mas01mc@292 534
mas01mc@311 535 if(lsh!=SERVER_LSH_INDEX_SINGLETON){
mas01mc@308 536 if( fabs(radius - lsh->get_radius())>fabs(O2_DISTANCE_TOLERANCE))
mas01mc@308 537 printf("*** Warning: adb_radius (%f) != lsh_radius (%f) ***\n", radius, lsh->get_radius());
mas01mc@327 538 VERB_LOG(1,"INDEX: dim %d\n", (int)dbH->dim);
mas01mc@327 539 VERB_LOG(1,"INDEX: R %f\n", lsh->get_radius());
mas01mc@327 540 VERB_LOG(1,"INDEX: seqlen %d\n", sequenceLength);
mas01mc@327 541 VERB_LOG(1,"INDEX: w %f\n", lsh->get_lshHeader()->get_binWidth());
mas01mc@327 542 VERB_LOG(1,"INDEX: k %d\n", lsh->get_lshHeader()->get_numFuns());
mas01mc@327 543 VERB_LOG(1,"INDEX: L (m*(m-1))/2 %d\n", lsh->get_lshHeader()->get_numTables());
mas01mc@327 544 VERB_LOG(1,"INDEX: N %d\n", lsh->get_lshHeader()->get_numRows());
mas01cr@458 545 VERB_LOG(1,"INDEX: s %d\n", audiodb_index_to_track_id(lsh->get_maxp(), audiodb_lsh_n_point_bits(adb)));
mas01mc@327 546 VERB_LOG(1,"INDEX: Opened LSH index file %s\n", indexName);
mas01mc@308 547 }
mas01mc@292 548
mas01mc@292 549 // Check to see if we are loading hash tables into core, and do so if true
mas01mc@292 550 if((lsh->get_lshHeader()->flags&O2_SERIAL_FILEFORMAT2) || lsh_in_core){
mas01mc@308 551 if(SERVER_LSH_INDEX_SINGLETON)
mas01mc@308 552 fprintf(stderr,"INDEX: using persistent hash tables: %s\n", lsh->get_indexName());
mas01mc@308 553 else
mas01mc@327 554 VERB_LOG(1,"INDEX: loading hash tables into core %s\n", (lsh->get_lshHeader()->flags&O2_SERIAL_FILEFORMAT2)?"FORMAT2":"FORMAT1");
mas01mc@308 555 lsh = index_allocate(indexName, true);
mas01mc@292 556 }
mas01mc@292 557
mas01mc@292 558 delete[] indexName;
mas01mc@292 559 return true;
mas01mc@292 560 }
mas01mc@292 561
mas01cr@458 562 void audiodb_index_add_point_approximate(void *user_data, Uns32T pointID, Uns32T qpos, float dist) {
mas01cr@458 563 adb_qcallback_t *data = (adb_qcallback_t *) user_data;
mas01cr@458 564 adb_t *adb = data->adb;
mas01cr@458 565 adb_qstate_internal_t *qstate = data->qstate;
mas01cr@458 566 uint32_t nbits = audiodb_lsh_n_point_bits(adb);
mas01cr@458 567 uint32_t trackID = audiodb_index_to_track_id(pointID, nbits);
mas01cr@458 568 uint32_t spos = audiodb_index_to_track_pos(pointID, nbits);
mas01cr@458 569 std::set<std::string>::iterator keys_end = qstate->allowed_keys->end();
mas01cr@458 570 if(qstate->allowed_keys->find((*adb->keys)[trackID]) != keys_end) {
mas01cr@424 571 adb_result_t r;
mas01cr@458 572 r.key = (*adb->keys)[trackID].c_str();
mas01cr@424 573 r.dist = dist;
mas01cr@424 574 r.qpos = qpos;
mas01cr@424 575 r.ipos = spos;
mas01cr@458 576 qstate->accumulator->add_point(&r);
mas01cr@424 577 }
mas01mc@292 578 }
mas01mc@292 579
mas01cr@458 580 // Maintain a queue of points to pass to query_loop_points() for exact
mas01cr@458 581 // evaluation
mas01cr@458 582 void audiodb_index_add_point_exact(void *user_data, Uns32T pointID, Uns32T qpos, float dist) {
mas01cr@458 583 adb_qcallback_t *data = (adb_qcallback_t *) user_data;
mas01cr@458 584 adb_t *adb = data->adb;
mas01cr@458 585 adb_qstate_internal_t *qstate = data->qstate;
mas01cr@458 586 uint32_t nbits = audiodb_lsh_n_point_bits(adb);
mas01cr@458 587 uint32_t trackID = audiodb_index_to_track_id(pointID, nbits);
mas01cr@458 588 uint32_t spos = audiodb_index_to_track_pos(pointID, nbits);
mas01cr@458 589 std::set<std::string>::iterator keys_end = qstate->allowed_keys->end();
mas01cr@458 590 if(qstate->allowed_keys->find((*adb->keys)[trackID]) != keys_end) {
mas01cr@458 591 PointPair p(trackID, qpos, spos);
mas01cr@458 592 qstate->exact_evaluation_queue->push(p);
mas01cr@458 593 }
mas01mc@292 594 }
mas01mc@292 595
mas01mc@292 596 // return 0: if index does not exist
mas01mc@292 597 // return nqv: if index exists
mas01cr@458 598 int audioDB::index_query_loop(adb_t *adb, adb_query_spec_t *spec, adb_qstate_internal_t *qstate) {
mas01mc@292 599
mas01mc@324 600 double *query = 0, *query_data = 0;
mas01cr@437 601 adb_qpointers_internal_t qpointers = {0};
mas01cr@437 602
mas01cr@458 603 adb_qcallback_t callback_data;
mas01cr@458 604 callback_data.adb = adb;
mas01cr@458 605 callback_data.qstate = qstate;
mas01cr@458 606
mas01mc@292 607 void (*add_point_func)(void*,Uns32T,Uns32T,float);
mas01mc@292 608
mas01cr@436 609 sequenceLength = spec->qid.sequence_length;
mas01cr@435 610 normalizedDistance = (spec->params.distance == ADB_DISTANCE_EUCLIDEAN_NORMED);
mas01cr@431 611
mas01mc@292 612 // Set the point-reporter callback based on the value of lsh_exact
mas01cr@458 613 if(lsh_exact) {
mas01cr@458 614 qstate->exact_evaluation_queue = new std::priority_queue<PointPair>;
mas01cr@458 615 add_point_func = &audiodb_index_add_point_exact;
mas01cr@458 616 } else {
mas01cr@458 617 add_point_func = &audiodb_index_add_point_approximate;
mas01mc@292 618 }
mas01mc@292 619
mas01cr@455 620 if(!index_init_query(adb->path)) // sets-up LSH index structures for querying
mas01mc@292 621 return 0;
mas01mc@292 622
mas01cr@460 623 char *database = audiodb_index_get_name(adb->path, radius, sequenceLength);
mas01cr@460 624 if(!database) {
mas01cr@460 625 error("failed to get index name", adb->path);
mas01cr@460 626 }
mas01mc@292 627
mas01cr@444 628 if(audiodb_query_spec_qpointers(adb, spec, &query_data, &query, &qpointers)) {
mas01cr@444 629 error("failed to set up qpointers");
mas01cr@444 630 }
mas01mc@292 631
mas01mc@292 632 // query vector index
mas01cr@437 633 Uns32T Nq = (qpointers.nvectors>O2_MAXTRACKLEN?O2_MAXTRACKLEN:qpointers.nvectors) - sequenceLength + 1;
mas01cr@459 634 std::vector<std::vector<float> > *vv = audiodb_index_initialize_shingles(Nq, adb->header->dim, sequenceLength); // allocate memory to copy query vectors to shingles
mas01cr@447 635
mas01mc@292 636 // Construct shingles from query features
mas01mc@292 637 for( Uns32T pointID = 0 ; pointID < Nq ; pointID++ )
mas01cr@456 638 audiodb_index_make_shingle(vv, pointID, query, dbH->dim, sequenceLength);
mas01mc@292 639
mas01mc@292 640 // Normalize query vectors
mas01cr@459 641 int vcount = audiodb_index_norm_shingles(vv, qpointers.l2norm, qpointers.power, dbH->dim, sequenceLength, radius, normalizedDistance, use_absolute_threshold, absolute_threshold);
mas01cr@459 642 if(vcount == -1) {
mas01cr@459 643 audiodb_index_delete_shingles(vv);
mas01cr@459 644 error("failed to norm shingles");
mas01cr@459 645 }
mas01cr@459 646 Uns32T numVecsAboveThreshold = vcount;
mas01mc@292 647
mas01mc@292 648 // Nq contains number of inspected points in query file,
mas01mc@292 649 // numVecsAboveThreshold is number of points with power >= absolute_threshold
mas01cr@437 650 double* qpp = qpointers.power; // Keep original qpPtr for possible exact evaluation
mas01mc@292 651 if(usingQueryPoint && numVecsAboveThreshold){
mas01mc@292 652 if((lsh->get_lshHeader()->flags&O2_SERIAL_FILEFORMAT2) || lsh_in_core)
mas01cr@458 653 lsh->retrieve_point((*vv)[0], queryPoint, add_point_func, &callback_data);
mas01mc@292 654 else
mas01cr@458 655 lsh->serial_retrieve_point(database, (*vv)[0], queryPoint, add_point_func, &callback_data);
mas01mc@292 656 }
mas01mc@292 657 else if(numVecsAboveThreshold)
mas01mc@292 658 for( Uns32T pointID = 0 ; pointID < Nq; pointID++ )
mas01cr@370 659 if(!use_absolute_threshold || (use_absolute_threshold && (*qpp++ >= absolute_threshold))) {
mas01cr@370 660 if((lsh->get_lshHeader()->flags&O2_SERIAL_FILEFORMAT2) || lsh_in_core) {
mas01cr@458 661 lsh->retrieve_point((*vv)[pointID], pointID, add_point_func, &callback_data);
mas01cr@370 662 } else {
mas01cr@458 663 lsh->serial_retrieve_point(database, (*vv)[pointID], pointID, add_point_func, &callback_data);
mas01cr@370 664 }
mas01cr@370 665 }
mas01cr@459 666 audiodb_index_delete_shingles(vv);
mas01mc@292 667
mas01mc@292 668 if(lsh_exact)
mas01mc@292 669 // Perform exact distance computation on point pairs in exact_evaluation_queue
mas01cr@458 670 query_loop_points(adb, spec, qstate, query, &qpointers);
mas01mc@292 671
mas01mc@292 672 // Close the index file
mas01mc@292 673 close(lshfid);
mas01mc@292 674
mas01mc@292 675 // Clean up
mas01mc@292 676 if(query_data)
mas01mc@292 677 delete[] query_data;
mas01cr@437 678 if(qpointers.l2norm_data)
mas01cr@437 679 delete[] qpointers.l2norm_data;
mas01cr@437 680 if(qpointers.power_data)
mas01cr@437 681 delete[] qpointers.power_data;
mas01cr@437 682 if(qpointers.mean_duration)
mas01cr@437 683 delete[] qpointers.mean_duration;
mas01mc@292 684 if(database)
mas01mc@292 685 delete[] database;
mas01mc@292 686
mas01mc@292 687 return Nq;
mas01mc@292 688 }
mas01mc@292 689