bool Repository::WSumArchiver(Solution &candidate){ //http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7020200 //double weight[]={0.1,0.9}; insert(candidate); organize(); double highDistanceValue=MAXDOUBLE*-1; int higherIndex=-1; for(int i=0;i<actualSize;i++){ double norm[objectiveNumber]; double wsum=0; normalizeObjectives(norm, solutions[i].objectiveVector); for(int j=0;j<objectiveNumber;j++){ wsum+=(weight[j]*norm[j]); } if(wsum > highDistanceValue){ highDistanceValue=wsum; higherIndex=i; } } if(higherIndex==-1){ fprintf(stderr,"\nWSum ARCHIVER ERROR %f\n", highDistanceValue); exit(1); } bool ret=true; if(candidate.isEqual(solutions[higherIndex])) ret=false; exclude(higherIndex); return ret; }
bool Repository::r_idealArchiver(Solution &candidate){ insert(candidate); organize(); double highDistanceValue=MAXDOUBLE*-1; int higherIndex=-1; for(int i=0;i<actualSize;i++){ double norm[objectiveNumber]; double dist=0; normalizeObjectives(norm, solutions[i].objectiveVector); dist=calculateEuclideanDistance(norm, weight, objectiveNumber); if(dist > highDistanceValue){ highDistanceValue=dist; higherIndex=i; } } if(higherIndex==-1){ fprintf(stderr,"\nR-IDEAL ARCHIVER ERROR %f\n", highDistanceValue); exit(1); } bool ret=true; if(candidate.isEqual(solutions[higherIndex])) ret=false; exclude(higherIndex); return ret; }
//archiver proposed by Laumanns and Zenklusken //param - the solution to be submitted to the archiver bool Repository::MGAArchiver(Solution &candidate){ insert(candidate); organize(); int b = compute_b_mga(solutions, actualSize); int index_removed = -1; while(index_removed==-1){ for(int i = actualSize-1; i>=0;i--){ double box_i[objectiveNumber]; box_mga(solutions[i], box_i, b, objectiveNumber); for(int j = actualSize-1; j>=0;j--){ if(i!=j){ double box_j[objectiveNumber]; box_mga(solutions[j], box_j, b, objectiveNumber); int comparation = dominance(box_i, box_j, objectiveNumber); if(comparation == -1 || isEqual(box_i, box_j, objectiveNumber) ){ index_removed = i; break; } } } //if(index_removed!=-1){ // break; //} } b--; } bool ret=true; if(candidate.isEqual(solutions[index_removed])) ret=false; exclude(index_removed); return ret; }
//archiver proposed by Carvalho and Pozo //Removes the solutio with worst distance to the ideal point //param - the solution to be submitted to the archiver bool Repository::idealArchiver(Solution &candidate){ insert(candidate); organize(); double solNorm[objectiveNumber]; double idealNorm[objectiveNumber]; double higherDistance=-1; double distance=0; int index=-1; memset(idealNorm, 0, sizeof(double)*objectiveNumber); //since the points are normalized between 0 and 1, the ideal point will be (0,...,0) for(int i=0;i<actualSize;i++){ normalizeObjectives(solNorm, solutions[i].objectiveVector); distance=calculateEuclideanDistance(solNorm, idealNorm, objectiveNumber); if(distance > higherDistance){ higherDistance=distance; index=i; } } if(index==-1){ fprintf(stderr,"\nIDEAL ARCHIVER ERROR %f\n", higherDistance); exit(1); } bool ret=true; if(candidate.isEqual(solutions[index])) ret=false; exclude(index); return ret; // /*//For each solution on the front, it calculates the distance to the ideal point // double smallerDistance[actualSize]; // // for(int i=0;i<actualSize;i++){ // double norm[objectiveNumber]; // double sp_norm[objectiveNumber]; // for(int j=0;j<objectiveNumber;j++){ // norm[j]=normalize(solutions[i].objectiveVector[j],smallerObjs[j],largerObjs[j]); // sp_norm[j]=normalize(smallerObjs[j],smallerObjs[j],largerObjs[j]); // } // smallerDistance[i] = calculateEuclideanDistance(sp_norm, norm, objectiveNumber); // //smallerDistance[i] = calculateEuclideanDistance(smallerObjs, solutions[i].objectiveVector, objectiveNumber); // } // // double highDistanceValue = -1.0; // int index = -1; // for (int i = 0; i<actualSize; i++) { // if(smallerDistance[i] > highDistanceValue){ // highDistanceValue =smallerDistance[i]; // index = i; // } // }*/ }
void ProduceDoc::run(){ if (WarnDebugMessage) qDebug() << __FILE__ << QString::number(__LINE__) << " RUN !!! " ; m_mutex.lock(); m_textDocument = new QTextDocument; organize(); m_mutex.unlock(); }
int main(int argc, char **argv) { /*FILE *f; char *in; in = malloc((strlen(argv[2])+3)*sizeof(char)); strcpy(in,argv[2]); strcat(in,".fl"); f = fopen(in,"r"); read(f,EOF); fclose(f); return 0;*/ printf("> "); read(stdin,'\n'); organize(top); eval(top); return 0; }
bool SReqListener::threadLoop() { while (true) { bool condinue = true; ReqMsg msgRcv, msgSnd; { SMutex::Autolock autoLock(mLock); while (!mDone && mQueue->isEmpty()) { mQueuePushed.wait(mLock); } // finish only when queue is empty if (mDone && mQueue->isEmpty()) { break; } mQueue->pop(msgRcv); if (mQueue->size() == mQueue->maxSize() - 1) { mQueuePoped.signal(); } } if (msgRcv.type == ReqMsg::DONE) { broadcast(msgRcv); mDone = true; break; } condinue = organize(msgRcv, msgSnd); if (msgSnd.type != ReqMsg::NONE) { broadcast(msgSnd); } if (!condinue) { break; } } mWorking = false; return false; }
//archiver wich consider the crowding distance to keep/exclude a solution //param - the solution to be submitted to the archiver bool Repository::crowdingDistanceArchiver(Solution &candidate){ //Solution temp[repositorySize+1]; //create a temporary repository to contain all the solutions plus the candidate double smallerCrowdingDistance=MAXDOUBLE; int idxSmallerCrowdingDistance=-1; //sync(temp); //sincronize the new repository with the solutions already found // for(int i=0;i<actualSize;i++) // temp[i]=solutions[i]; //memcpy(temp, solutions, sizeof(Solution)*actualSize); //solutions[actualSize]=candidate;//insert the new one insert(candidate); organize(); updateCrowdingDistances(solutions, actualSize); //update the crowing distances for(int i=0;i<actualSize;i++){//find the valid solution with smallest crowding distance if(controlSolutions[i] && getSolution(i).crowdingDistance<=smallerCrowdingDistance){ smallerCrowdingDistance=getSolution(i).crowdingDistance; idxSmallerCrowdingDistance=i; } } if(idxSmallerCrowdingDistance == -1){ fprintf(stderr,"\nCrowding Distance archiver error!\n The crowding distances of all particles in the repository is:\n"); for(int i=0;i<actualSize;i++) fprintf(stderr,"%f\n", getSolution(i).crowdingDistance); exit(1); } // if(!solutions[idxSmallerCrowdingDistance].isEqual(candidate)){ //if the candidate is not the solution with smallest crowding distance bool ret=true; if(candidate.isEqual(solutions[idxSmallerCrowdingDistance])) ret=false; exclude(idxSmallerCrowdingDistance); //remove the solution with the smallest crowding distance return ret; //insert(candidate);//insert the new solution // } //free(temp); }
bool Repository::pbiArchiver(Solution &candidate){ //http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7020200 //double weight[]={0.1,0.9}; insert(candidate); organize(); double highDistanceValue=MAXDOUBLE*-1; int higherIndex=-1; double solNorm[objectiveNumber]; // double *solNorm; for(int i=0;i<actualSize;i++){ double norm; double pbi=0; normalizeObjectives(solNorm, solutions[i].objectiveVector); // solNorm=solutions[i].objectiveVector; pbi=PBI(solNorm, weight); if(pbi > highDistanceValue){ highDistanceValue=pbi; higherIndex=i; } } if(higherIndex==-1){ fprintf(stderr,"\nPBI ARCHIVER ERROR %f %f\n", PBI(solNorm, weight), highDistanceValue); candidate.print(); printf("\nweight: "); printVector(weight, objectiveNumber); printf("\n"); exit(1); } bool ret=true; if(candidate.isEqual(solutions[higherIndex])) ret=false; exclude(higherIndex); return ret; }
int main(){ int unorganized[10],organized[10]; srand(time(NULL)); int isOrganized=0,i; for(i=0;i<10;i++){ unorganized[i]=rand()%10; organized[i]=unorganized[i]; } while(organize(organized)==0){ //Hum dee dum... } /*printf("Unorganized:\n"); for(i=0;i<10;i++){ printf("%d\n",unorganized[i]); }*/ printf("Organized:\n"); for(i=0;i<10;i++){ printf("%d\n",organized[i]); } }
//archiver wich consider the contributing HV to keep/exclude a solution //param - the solution to be submitted to the archiver bool Repository::HVArchiver(Solution &candidate){ double smallestHV=MAXDOUBLE; int idxSmallestHV=-1; insert(candidate); for(int i=0;i<actualSize;i++) getSolutions()[i].crowdingDistance=-1; organize(); updateContributingHypervolume(*this); //update the contributing HV of all solutions // updateContributingHypervolume(*this); for(int i=0;i<actualSize;i++){//find the valid solution with smallest contributing HV (stored on the crowding distance field) if(controlSolutions[i] && getSolution(i).crowdingDistance<=smallestHV){ smallestHV=getSolution(i).crowdingDistance; idxSmallestHV=i; } } if(idxSmallestHV == -1){ fprintf(stderr,"\nHV archiver error!\n The HV of all particles in the repository is:\n"); for(int i=0;i<actualSize;i++) fprintf(stderr,"%f\n", getSolution(i).crowdingDistance); exit(1); } // fprintf(stderr,"%d --> %f (%d)\n",idxSmallerR2, smallerR2, actualSize); // if(actualSize > repositorySize)//test of removing all solutions with no contribution bool ret=true; if(candidate.isEqual(solutions[idxSmallestHV])) ret=false; exclude(idxSmallestHV); //remove the solution with the smallest contribution return ret; }
bool Repository::tchArchiver(Solution &candidate){ //http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7020200 insert(candidate); organize(); double highDistanceValue=MAXDOUBLE*-1; int higherIndex=-1; double solNorm[objectiveNumber]; // double *solNorm; for(int i=0;i<actualSize;i++){ double norm; double tch=0; normalizeObjectives(solNorm, solutions[i].objectiveVector); // solNorm=solutions[i].objectiveVector; tch=TCH(solNorm, weight); if(tch > highDistanceValue){ highDistanceValue=tch; higherIndex=i; } } if(higherIndex==-1){ fprintf(stderr,"\nTCH ARCHIVER ERROR %f\n", highDistanceValue); printVector(solNorm, objectiveNumber); fprintf(stderr,"\n"); exit(1); } bool ret=true; if(candidate.isEqual(solutions[higherIndex])) ret=false; exclude(higherIndex); return ret; }
void kd_tree::organize(int *use, int parent, int idim, int ct, int dir){ int i,j,k,l,*inn,newparent,ff,fb,inp; double *tosort,pivot,nn; if(idim>=dim)idim=0; /*printf("parent %d pdim %d dir %d\n",parent,idim-1,dir); for(i=0;i<ct;i++)printf("%d\n",use[i]); printf("\n");*/ if(ct>2){ inn=new int[ct]; for(i=0;i<ct;i++)inn[i]=i; tosort=new double[ct]; for(i=0;i<ct;i++)tosort[i]=data[use[i]][idim]; sort(tosort,inn,ct); inp=ct/2; while(inp>0 && tosort[inp]-tosort[inp-1]<tol)inp--; newparent=use[inn[inp]]; pivot=data[newparent][idim]; tree[parent][dir]=newparent; tree[newparent][3]=parent; tree[newparent][0]=idim; //now I need to re-order use[] so that I can pass it to another //call of ::organize and have the proper indices available k=use[inp]; use[inp]=newparent; use[inn[inp]]=k; delete [] inn; delete [] tosort; if(inp!=0){ ff=0; fb=ct-1; while(ff<inp && fb>inp){ if(data[use[ff]][idim]<pivot && \ data[use[fb]][idim]>=pivot){ ff++; fb--; } else if(data[use[ff]][idim]>=pivot && \ data[use[fb]][idim]>=pivot){ fb--; } else if(data[use[ff]][idim]<pivot && \ data[use[fb]][idim]<pivot){ ff++; } else if(data[use[ff]][idim]>=pivot && \ data[use[fb]][idim]<pivot){ k=use[fb]; use[fb]=use[ff]; use[ff]=k; } } organize(use,newparent,idim+1,inp,1); organize(&use[inp+1],newparent,idim+1,ct-inp-1,2); }//if(inp!=0) else{ tree[newparent][1]=-1; organize(&use[1],newparent,idim+1,ct-1,2); }//if(inp==0) }//if(ct>2) else if(ct==2){ if(data[use[0]][idim]<data[use[1]][idim]){ tree[parent][dir]=use[1]; tree[use[1]][1]=use[0]; tree[use[1]][2]=-1; tree[use[1]][3]=parent; tree[use[1]][0]=idim; } else{ tree[parent][dir]=use[1]; tree[use[1]][1]=-1; tree[use[1]][2]=use[0]; tree[use[1]][3]=parent; tree[use[1]][0]=idim; } tree[use[0]][0]=idim+1; if(tree[use[0]][0]>=dim)tree[use[0]][0]=0; tree[use[0]][1]=-1; tree[use[0]][2]=-1; tree[use[0]][3]=use[1]; } else if(ct==1){ tree[parent][dir]=use[0]; tree[use[0]][1]=-1; tree[use[0]][2]=-1; tree[use[0]][3]=parent; tree[use[0]][0]=idim; } else if(ct==0)printf("WARNING called organize with ct==0\n"); }
SettingsWindow::SettingsWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::SettingsWindow) { ui->setupUi(this); #ifdef Q_OS_MAC QFont smallFont = ui->labelGlobal->font(); smallFont.setPointSize(smallFont.pointSize()-1); ui->labelGlobal->setFont(smallFont); ui->label_44->setFont(smallFont); ui->label_45->setFont(smallFont); ui->label_46->setFont(smallFont); ui->label_47->setFont(smallFont); ui->label_48->setFont(smallFont); ui->label_49->setFont(smallFont); ui->label_7->setFont(smallFont); ui->label_18->setFont(smallFont); #endif ui->customScraperTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->customScraperTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); ui->customScraperTable->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->actionGlobal->setIcon(ui->actionGlobal->property("iconActive").value<QIcon>()); ui->stackedWidget->setCurrentIndex(0); ui->stackedWidget->setAnimation(QEasingCurve::Linear); ui->stackedWidget->setSpeed(200); m_settings = Settings::instance(this); ui->xbmcPort->setValidator(new QIntValidator(0, 99999, ui->xbmcPort)); ui->dirs->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->dirs->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); ui->exportTemplates->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); int scraperCounter = 0; foreach (ScraperInterface *scraper, Manager::instance()->scrapers()) { if (scraper->hasSettings()) { QLabel *name = new QLabel("<b>" + scraper->name() + "</b>"); name->setAlignment(Qt::AlignRight); name->setStyleSheet("margin-top: 3px;"); ui->gridLayoutScrapers->addWidget(name, scraperCounter, 0); ui->gridLayoutScrapers->addWidget(scraper->settingsWidget(), scraperCounter, 1); m_scraperRows.insert(scraper, scraperCounter); scraperCounter++; } } foreach (TvScraperInterface *scraper, Manager::instance()->tvScrapers()) { if (scraper->hasSettings()) { QLabel *name = new QLabel("<b>" + scraper->name() + "</b>"); name->setAlignment(Qt::AlignRight); name->setStyleSheet("margin-top: 3px;"); ui->gridLayoutScrapers->addWidget(name, scraperCounter, 0); ui->gridLayoutScrapers->addWidget(scraper->settingsWidget(), scraperCounter, 1); scraperCounter++; } } foreach (ConcertScraperInterface *scraper, Manager::instance()->concertScrapers()) { if (scraper->hasSettings()) { QLabel *name = new QLabel("<b>" + scraper->name() + "</b>"); name->setAlignment(Qt::AlignRight); name->setStyleSheet("margin-top: 3px;"); ui->gridLayoutScrapers->addWidget(name, scraperCounter, 0); ui->gridLayoutScrapers->addWidget(scraper->settingsWidget(), scraperCounter, 1); scraperCounter++; } } foreach (ImageProviderInterface *scraper, Manager::instance()->imageProviders()) { if (scraper->hasSettings()) { QLabel *name = new QLabel("<b>" + scraper->name() + "</b>"); name->setAlignment(Qt::AlignRight); name->setStyleSheet("margin-top: 3px;"); ui->gridLayoutScrapers->addWidget(name, scraperCounter, 0); ui->gridLayoutScrapers->addWidget(scraper->settingsWidget(), scraperCounter, 1); scraperCounter++; } } ui->comboMovieSetArtwork->setItemData(0, MovieSetArtworkSingleSetFolder); ui->comboMovieSetArtwork->setItemData(1, MovieSetArtworkSingleArtworkFolder); connect(ui->buttonAddDir, SIGNAL(clicked()), this, SLOT(chooseDirToAdd())); connect(ui->buttonRemoveDir, SIGNAL(clicked()), this, SLOT(removeDir())); connect(ui->buttonMovieFilesToDirs, SIGNAL(clicked()), this, SLOT(organize())); connect(ui->dirs, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(dirListRowChanged(int))); connect(ui->comboMovieSetArtwork, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboMovieSetArtworkChanged())); connect(ui->btnMovieSetArtworkDir, SIGNAL(clicked()), this, SLOT(onChooseMovieSetArtworkDir())); connect(ui->chkUseProxy, SIGNAL(clicked()), this, SLOT(onUseProxy())); connect(ui->btnCancel, SIGNAL(clicked()), this, SLOT(onCancel())); connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(onSave())); connect(ExportTemplateLoader::instance(this), SIGNAL(sigTemplatesLoaded(QList<ExportTemplate*>)), this, SLOT(onTemplatesLoaded(QList<ExportTemplate*>))); connect(ExportTemplateLoader::instance(this), SIGNAL(sigTemplateInstalled(ExportTemplate*,bool)), this, SLOT(onTemplateInstalled(ExportTemplate*,bool))); connect(ExportTemplateLoader::instance(this), SIGNAL(sigTemplateUninstalled(ExportTemplate*,bool)), this, SLOT(onTemplateUninstalled(ExportTemplate*,bool))); connect(ui->btnChooseUnrar, SIGNAL(clicked()), this, SLOT(onChooseUnrar())); connect(ui->btnChooseMakemkvcon, SIGNAL(clicked()), this, SLOT(onChooseMakeMkvCon())); connect(ui->chkEnableAdultScrapers, SIGNAL(clicked()), this, SLOT(onShowAdultScrapers())); ui->movieNfo->setProperty("dataFileType", DataFileType::MovieNfo); ui->moviePoster->setProperty("dataFileType", DataFileType::MoviePoster); ui->movieBackdrop->setProperty("dataFileType", DataFileType::MovieBackdrop); ui->movieCdArt->setProperty("dataFileType", DataFileType::MovieCdArt); ui->movieClearArt->setProperty("dataFileType", DataFileType::MovieClearArt); ui->movieLogo->setProperty("dataFileType", DataFileType::MovieLogo); ui->movieBanner->setProperty("dataFileType", DataFileType::MovieBanner); ui->movieThumb->setProperty("dataFileType", DataFileType::MovieThumb); ui->movieSetPosterFileName->setProperty("dataFileType", DataFileType::MovieSetPoster); ui->movieSetFanartFileName->setProperty("dataFileType", DataFileType::MovieSetBackdrop); ui->showBackdrop->setProperty("dataFileType", DataFileType::TvShowBackdrop); ui->showBanner->setProperty("dataFileType", DataFileType::TvShowBanner); ui->showCharacterArt->setProperty("dataFileType", DataFileType::TvShowCharacterArt); ui->showClearArt->setProperty("dataFileType", DataFileType::TvShowClearArt); ui->showEpisodeNfo->setProperty("dataFileType", DataFileType::TvShowEpisodeNfo); ui->showEpisodeThumbnail->setProperty("dataFileType", DataFileType::TvShowEpisodeThumb); ui->showLogo->setProperty("dataFileType", DataFileType::TvShowLogo); ui->showThumb->setProperty("dataFileType", DataFileType::TvShowThumb); ui->showNfo->setProperty("dataFileType", DataFileType::TvShowNfo); ui->showPoster->setProperty("dataFileType", DataFileType::TvShowPoster); ui->showSeasonBackdrop->setProperty("dataFileType", DataFileType::TvShowSeasonBackdrop); ui->showSeasonBanner->setProperty("dataFileType", DataFileType::TvShowSeasonBanner); ui->showSeasonPoster->setProperty("dataFileType", DataFileType::TvShowSeasonPoster); ui->showSeasonThumb->setProperty("dataFileType", DataFileType::TvShowSeasonThumb); ui->concertNfo->setProperty("dataFileType", DataFileType::ConcertNfo); ui->concertPoster->setProperty("dataFileType", DataFileType::ConcertPoster); ui->concertBackdrop->setProperty("dataFileType", DataFileType::ConcertBackdrop); ui->concertLogo->setProperty("dataFileType", DataFileType::ConcertLogo); ui->concertClearArt->setProperty("dataFileType", DataFileType::ConcertClearArt); ui->concertDiscArt->setProperty("dataFileType", DataFileType::ConcertCdArt); #ifdef Q_OS_MAC ui->btnCancel->setVisible(false); ui->btnSave->setVisible(false); ui->horizontalSpacerButtons->setGeometry(QRect(0, 0, 1, 1)); #endif ui->comboStartupSection->addItem(tr("Movies"), "movies"); ui->comboStartupSection->addItem(tr("TV Shows"), "tvshows"); ui->comboStartupSection->addItem(tr("Concerts"), "concerts"); ui->comboStartupSection->addItem(tr("Import"), "import"); loadSettings(); }
int main(int argc, char *argv[]){ FILE *fp; char buff[1000]; int ch, i, j, x, y; int line_count = 0; count = -1; count_intersect = 0; k = 0; fp = fopen(argv[1], "r"); if (fp == NULL){ printf("There's no input file.\n"); exit(0); } else{ if( (display = XOpenDisplay(display_name)) == NULL ){ printf("Could not open display. \n"); exit(-1); } printf("Connected to X server %s\n", XDisplayName(display_name) ); screen_num = DefaultScreen(display); screen = DefaultScreenOfDisplay(display); colormap = XDefaultColormap(display, screen_num); display_width = DisplayWidth(display, screen_num); display_height = DisplayHeight(display, screen_num); //obtaining line count while(!feof(fp)){ ch = fgetc(fp); if (ch == '\n'){ line_count++; } } rewind(fp); } //int m[line_count][6]; int m[line_count+1][6]; //Creating window border_width = 10; win_x = 0; win_y = 0; win_width = display_width/2; win_height = display_height * 0.8; //win_height = (int)(win_width/1.7); //rectangular window printf("window width: %d\n window height: %d\n", display_width, display_height); //win = XCreateSimpleWindow(display, RootWindow(display, 0), 1, 1, win_width, win_height, 10, WhitePixel (display, 0), WhitePixel (display, 0)); win = XCreateSimpleWindow(display, RootWindow(display, screen_num), win_x, win_y, win_width, win_height, border_width, BlackPixel(display, screen_num), WhitePixel(display, screen_num)); //Maps window on screen size_hints = XAllocSizeHints(); wm_hints = XAllocWMHints(); class_hints = XAllocClassHint(); if (size_hints == NULL || wm_hints == NULL || class_hints == NULL){ printf("Error allocating memory for hints\n"); exit(-1); } size_hints -> flags = PPosition | PSize | PMinSize; size_hints -> min_width = 60; size_hints -> min_height = 60; XStringListToTextProperty(&win_name_string, 1, &win_name); XStringListToTextProperty(&icon_name_string, 1, &icon_name); wm_hints -> flags = StateHint | InputHint; wm_hints -> initial_state = NormalState; wm_hints -> input = False; class_hints -> res_name = "x_use_example"; class_hints -> res_class = "homework1"; XSetWMProperties(display, win, &win_name, &icon_name, argv, argc, size_hints, wm_hints, class_hints ); XSelectInput(display, win, ExposureMask | KeyPressMask | ButtonPressMask); // put on screen XMapWindow(display, win); XFlush(display); //graphics setup green_gc = XCreateGC(display, win, 0, 0); XParseColor(display, colormap, green, &green_col); if (XAllocColor(display, colormap, &green_col) == 0){ printf("Failed to get color green\n"); exit(-1); } else{ printf("Success green!\n"); XSetForeground(display, green_gc, green_col.pixel); } red_gc = XCreateGC(display, win, 0, 0); XParseColor(display, colormap, red, &red_col); if (XAllocColor(display, colormap, &red_col) == 0){ printf("Failed to get color red\n"); exit(-1); } else{ printf("Success red!\n"); XSetForeground(display, red_gc, red_col.pixel); } black_gc = XCreateGC(display, win, 0, 0); XParseColor(display, colormap, black, &black_col); if (XAllocColor(display, colormap, &black_col) == 0){ printf("Failed to get color black\n"); exit(-1); } else{ printf("Success black!\n"); XSetForeground(display, black_gc, black_col.pixel); } light_purple_gc = XCreateGC(display, win, 0, 0); XParseColor(display, colormap, light_purple, &light_purple_col); if (XAllocColor(display, colormap, &light_purple_col) == 0){ printf("Failed to get color light purple\n"); exit(-1); } else{ printf("Success light purple!\n"); XSetForeground(display, light_purple_gc, light_purple_col.pixel); } white_gc = XCreateGC(display, win, 0, 0); XParseColor(display, colormap, white, &white_col); if (XAllocColor(display, colormap, &white_col) == 0){ printf("Failed to get color white\n"); exit(-1); } else{ printf("Success white!\n"); XSetForeground(display, white_gc, white_col.pixel); } while(1){ XNextEvent(display, &report); switch(report.type){ case Expose: { for (i = 0; i <= line_count; i++){ fscanf(fp, "%*s ( %d, %d) ( %d, %d) (%d, %d)", &m[i][0], &m[i][1], &m[i][2], &m[i][3], &m[i][4], &m[i][5]); } m[line_count+1][0] = -5; for (i = 0; i <= line_count ; i++){ for (j=0; j<6; j+=2){ m[i][j] = m[i][j] + 100; m[i][j+1] = m[i][j+1] + 100; } } for (i = 0; i <=line_count; i++){ //Draw the triangles XDrawLine(display, win, green_gc, m[i][0], m[i][1], m[i][2], m[i][3]); XDrawLine(display, win, green_gc, m[i][2], m[i][3], m[i][4], m[i][5]); XDrawLine(display, win, green_gc, m[i][4], m[i][5], m[i][0], m[i][1]); } rewind(fp); if (valid_vertex[0][0] != 0.0){ for (i= 0; i<k; i++){ if (valid_vertex[i][6] == 0.0 || valid_vertex[i][6] == -4.0){ printf("from (%d, %d) to (%d, %d) length: %f and path length: %f\n", (int)valid_vertex[i][0], (int)valid_vertex[i][1], (int)valid_vertex[i][2], (int)valid_vertex[i][3], valid_vertex[i][4], valid_vertex[i][5]); XDrawLine(display, win, light_purple_gc, valid_vertex[i][0], valid_vertex[i][1], valid_vertex[i][2], valid_vertex[i][3]); } } XFillArc( display, win, black_gc, start_x, start_y, win_width/200, win_width/200, 0, 360*64); XFillArc( display, win, black_gc, target_x, target_y, win_width/200, win_width/200, 0, 360*64); } else{} //printf("exposed\n"); XFlush(display); break; } case ButtonPress: { //printf("Button press %d, %d.\n",report.xbutton.x, report.xbutton.y); double distance1; x = report.xbutton.x; y = report.xbutton.y; int inTriangle; if (report.xbutton.button == Button1){ /* left click */ count++; inTriangle = check_if_in_triangle(line_count, m, x, y); if (inTriangle == 0){ XFillArc( display, win, black_gc, x, y, win_width/200, win_width/200, 0, 360*64); } } else{ printf("Closing Window.\n"); XDestroyWindow(display, win); XCloseDisplay(display); exit(1); } //printf("count: %d\n", count); if (count == 0){ reset(m, line_count); start_x = x; start_y = y; if (inTriangle == 1){ count = -1; } } else if (count == 1){ if (inTriangle == 0){ target_x = x; target_y = y; printf("\n\nStarting point: (%d, %d)\nTarget point: (%d, %d)\n", start_x, start_y, target_x, target_y); int vertex[line_count][6]; int * nearest_triangles; int * result_line_seg; for(i=0;i<=line_count;i++){ //store formatted input file in array m fscanf(fp, "%*s ( %d, %d) ( %d, %d) (%d, %d)", &vertex[i][0], &vertex[i][1], &vertex[i][2], &vertex[i][3], &vertex[i][4], &vertex[i][5]); } rewind(fp); printf("Total triangles: %d\n", line_count+1); for (i = 0; i <= line_count ; i++){ for (j=0; j<6; j+=2){ vertex[i][j] = vertex[i][j] + 100; vertex[i][j+1] = vertex[i][j+1] + 100; } } start_graph(line_count, vertex, start_x, start_y, target_x, target_y); printf("Applied start_graph()\n"); shortest_path(); printf("Applied shortest_path()\n"); organize(); printf("The shortest path: \n"); for (i= 0; i<k; i++){ if (valid_vertex[i][6] == 0.0 || valid_vertex[i][6] == -4.0){ printf("from (%d, %d) to (%d, %d) length: %f and path length: %f\n", (int)valid_vertex[i][0], (int)valid_vertex[i][1], (int)valid_vertex[i][2], (int)valid_vertex[i][3], valid_vertex[i][4], valid_vertex[i][5]); XDrawLine(display, win, light_purple_gc, valid_vertex[i][0], valid_vertex[i][1], valid_vertex[i][2], valid_vertex[i][3]); } } printf("DONE\n"); count = -1; } } XFlush(display); break; } default: break; } } fclose(fp); return 0; }
void mainbody( void ) { initialize () ; if ( ! organize () ) uexit ( 1 ) ; dosimplethings () ; if ( nl > 0 ) { {register integer for_end; ai = 0 ;for_end = nl - 1 ; if ( ai <= for_end) do activity [ai ]= 0 ; while ( ai++ < for_end ) ;} if ( tfm [4 * ( ligkernbase + ( 0 ) ) ]== 255 ) { left () ; Fputs ( plfile , "BOUNDARYCHAR" ) ; boundarychar = tfm [4 * ( ligkernbase + ( 0 ) ) + 1 ]; outchar ( boundarychar ) ; right () ; activity [0 ]= 1 ; } if ( tfm [4 * ( ligkernbase + ( nl - 1 ) ) ]== 255 ) { r = 256 * tfm [4 * ( ligkernbase + ( nl - 1 ) ) + 2 ]+ tfm [4 * ( ligkernbase + ( nl - 1 ) ) + 3 ]; if ( r >= nl ) { perfect = false ; { putc ( ' ' , stderr ); putc ( '\n', stderr ); } Fputs ( stderr , "Ligature/kern starting index for boundarychar is too large;" ) ; fprintf ( stderr , "%s\n", "so I removed it." ) ; } else { labelptr = 1 ; labeltable [1 ].cc = 256 ; labeltable [1 ].rr = r ; bcharlabel = r ; activity [r ]= 2 ; } activity [nl - 1 ]= 1 ; } } {register integer for_end; c = bc ;for_end = ec ; if ( c <= for_end) do if ( ( tfm [4 * ( charbase + c ) + 2 ]% 4 ) == 1 ) { r = tfm [4 * ( charbase + c ) + 3 ]; if ( r < nl ) { if ( tfm [4 * ( ligkernbase + ( r ) ) ]> 128 ) { r = 256 * tfm [4 * ( ligkernbase + ( r ) ) + 2 ]+ tfm [4 * ( ligkernbase + ( r ) ) + 3 ]; if ( r < nl ) { if ( activity [tfm [4 * ( charbase + c ) + 3 ]]== 0 ) activity [tfm [4 * ( charbase + c ) + 3 ]]= 1 ; } } } if ( r >= nl ) { perfect = false ; { putc ( ' ' , stderr ); putc ( '\n', stderr ); } Fputs ( stderr , "Ligature/kern starting index for character " ) ; printoctal ( c ) ; fprintf ( stderr , "%s\n", " is too large;" ) ; fprintf ( stderr , "%s\n", "so I removed it." ) ; tfm [4 * ( charbase + c ) + 2 ]= 4 * ( tfm [4 * ( charbase + c ) + 2 ]/ 4 ) + 0 ; } else { sortptr = labelptr ; while ( labeltable [sortptr ].rr > r ) { labeltable [sortptr + 1 ]= labeltable [sortptr ]; sortptr = sortptr - 1 ; } labeltable [sortptr + 1 ].cc = c ; labeltable [sortptr + 1 ].rr = r ; labelptr = labelptr + 1 ; activity [r ]= 2 ; } } while ( c++ < for_end ) ;} labeltable [labelptr + 1 ].rr = ligsize ; if ( nl > 0 ) { left () ; Fputs ( plfile , "LIGTABLE" ) ; outln () ; {register integer for_end; ai = 0 ;for_end = nl - 1 ; if ( ai <= for_end) do if ( activity [ai ]== 2 ) { r = tfm [4 * ( ligkernbase + ( ai ) ) ]; if ( r < 128 ) { r = r + ai + 1 ; if ( r >= nl ) { { perfect = false ; if ( charsonline > 0 ) { putc ( ' ' , stderr ); putc ( '\n', stderr ); } charsonline = 0 ; fprintf ( stderr , "%s%s%ld%s\n", "Bad TFM file: " , "Ligature/kern step " , (long)ai , " skips too far;" ) ; } fprintf ( stderr , "%s\n", "I made it stop." ) ; tfm [4 * ( ligkernbase + ( ai ) ) ]= 128 ; } else activity [r ]= 2 ; } } while ( ai++ < for_end ) ;} sortptr = 1 ; {register integer for_end; acti = 0 ;for_end = nl - 1 ; if ( acti <= for_end) do if ( activity [acti ]!= 1 ) { i = acti ; if ( activity [i ]== 0 ) { if ( level == 1 ) { left () ; Fputs ( plfile , "COMMENT THIS PART OF THE PROGRAM IS NEVER USED!" ) ; outln () ; } } else if ( level == 2 ) right () ; while ( i == labeltable [sortptr ].rr ) { left () ; Fputs ( plfile , "LABEL" ) ; if ( labeltable [sortptr ].cc == 256 ) Fputs ( plfile , " BOUNDARYCHAR" ) ; else outchar ( labeltable [sortptr ].cc ) ; right () ; sortptr = sortptr + 1 ; } { k = 4 * ( ligkernbase + ( i ) ) ; if ( tfm [k ]> 128 ) { if ( 256 * tfm [k + 2 ]+ tfm [k + 3 ]>= nl ) { perfect = false ; if ( charsonline > 0 ) { putc ( ' ' , stderr ); putc ( '\n', stderr ); } charsonline = 0 ; fprintf ( stderr , "%s%s\n", "Bad TFM file: " , "Ligature unconditional stop command address is too big." ) ; } } else if ( tfm [k + 2 ]>= 128 ) { if ( ( ( tfm [k + 1 ]< bc ) || ( tfm [k + 1 ]> ec ) || ( tfm [ 4 * ( charbase + tfm [k + 1 ]) ]== 0 ) ) ) { if ( tfm [k + 1 ]!= boundarychar ) { perfect = false ; if ( charsonline > 0 ) { putc ( ' ' , stderr ); putc ( '\n', stderr ); } charsonline = 0 ; fprintf ( stderr , "%s%s%s", "Bad TFM file: " , "Kern step for" , " nonexistent character " ) ; printoctal ( tfm [k + 1 ]) ; { putc ( '.' , stderr ); putc ( '\n', stderr ); } tfm [k + 1 ]= bc ; } } left () ; Fputs ( plfile , "KRN" ) ; outchar ( tfm [k + 1 ]) ; r = 256 * ( tfm [k + 2 ]- 128 ) + tfm [k + 3 ]; if ( r >= nk ) { { perfect = false ; if ( charsonline > 0 ) { putc ( ' ' , stderr ); putc ( '\n', stderr ); } charsonline = 0 ; fprintf ( stderr , "%s%s\n", "Bad TFM file: " , "Kern index too large." ) ; } Fputs ( plfile , " R 0.0" ) ; } else outfix ( 4 * ( kernbase + r ) ) ; right () ; } else { if ( ( ( tfm [k + 1 ]< bc ) || ( tfm [k + 1 ]> ec ) || ( tfm [ 4 * ( charbase + tfm [k + 1 ]) ]== 0 ) ) ) { if ( tfm [k + 1 ]!= boundarychar ) { perfect = false ; if ( charsonline > 0 ) { putc ( ' ' , stderr ); putc ( '\n', stderr ); } charsonline = 0 ; fprintf ( stderr , "%s%s%s", "Bad TFM file: " , "Ligature step for" , " nonexistent character " ) ; printoctal ( tfm [k + 1 ]) ; { putc ( '.' , stderr ); putc ( '\n', stderr ); } tfm [k + 1 ]= bc ; } } if ( ( ( tfm [k + 3 ]< bc ) || ( tfm [k + 3 ]> ec ) || ( tfm [ 4 * ( charbase + tfm [k + 3 ]) ]== 0 ) ) ) { perfect = false ; if ( charsonline > 0 ) { putc ( ' ' , stderr ); putc ( '\n', stderr ); } charsonline = 0 ; fprintf ( stderr , "%s%s%s", "Bad TFM file: " , "Ligature step produces the" , " nonexistent character " ) ; printoctal ( tfm [k + 3 ]) ; { putc ( '.' , stderr ); putc ( '\n', stderr ); } tfm [k + 3 ]= bc ; } left () ; r = tfm [k + 2 ]; if ( ( r == 4 ) || ( ( r > 7 ) && ( r != 11 ) ) ) { fprintf ( stderr , "%s\n", "Ligature step with nonstandard code changed to LIG" ) ; r = 0 ; tfm [k + 2 ]= 0 ; } if ( r % 4 > 1 ) putc ( '/' , plfile ); Fputs ( plfile , "LIG" ) ; if ( odd ( r ) ) putc ( '/' , plfile ); while ( r > 3 ) { putc ( '>' , plfile ); r = r - 4 ; } outchar ( tfm [k + 1 ]) ; outchar ( tfm [k + 3 ]) ; right () ; } if ( tfm [k ]> 0 ) { if ( level == 1 ) { if ( tfm [k ]>= 128 ) Fputs ( plfile , "(STOP)" ) ; else { count = 0 ; {register integer for_end; ai = i + 1 ;for_end = i + tfm [k ]; if ( ai <= for_end) do if ( activity [ai ]== 2 ) count = count + 1 ; while ( ai++ < for_end ) ;} fprintf ( plfile , "%s%ld%c", "(SKIP D " , (long)count , ')' ) ; } outln () ; } } } } while ( acti++ < for_end ) ;} if ( level == 2 ) right () ; right () ; hashptr = 0 ; yligcycle = 256 ; {register integer for_end; hh = 0 ;for_end = hashsize ; if ( hh <= for_end) do hash [hh ]= 0 ; while ( hh++ < for_end ) ;} {register integer for_end; c = bc ;for_end = ec ; if ( c <= for_end) do if ( ( tfm [4 * ( charbase + c ) + 2 ]% 4 ) == 1 ) { i = tfm [4 * ( charbase + c ) + 3 ]; if ( tfm [4 * ( ligkernbase + ( i ) ) ]> 128 ) i = 256 * tfm [4 * ( ligkernbase + ( i ) ) + 2 ]+ tfm [4 * ( ligkernbase + ( i ) ) + 3 ]; do { hashinput () ; k = tfm [4 * ( ligkernbase + ( i ) ) ]; if ( k >= 128 ) i = nl ; else i = i + 1 + k ; } while ( ! ( i >= nl ) ) ; } while ( c++ < for_end ) ;} if ( bcharlabel < nl ) { c = 256 ; i = bcharlabel ; do { hashinput () ; k = tfm [4 * ( ligkernbase + ( i ) ) ]; if ( k >= 128 ) i = nl ; else i = i + 1 + k ; } while ( ! ( i >= nl ) ) ; } if ( hashptr == hashsize ) { fprintf ( stderr , "%s\n", "Sorry, I haven't room for so many ligature/kern pairs!" ) ; uexit ( 1 ) ; } {register integer for_end; hh = 1 ;for_end = hashptr ; if ( hh <= for_end) do { r = hashlist [hh ]; if ( classvar [r ]> 0 ) r = ffn ( r , ( hash [r ]- 1 ) / 256 , ( hash [r ]- 1 ) % 256 ) ; } while ( hh++ < for_end ) ;} if ( yligcycle < 256 ) { Fputs ( stderr , "Infinite ligature loop starting with " ) ; if ( xligcycle == 256 ) Fputs ( stderr , "boundary" ) ; else printoctal ( xligcycle ) ; Fputs ( stderr , " and " ) ; printoctal ( yligcycle ) ; { putc ( '!' , stderr ); putc ( '\n', stderr ); } Fputs ( plfile , "(INFINITE LIGATURE LOOP MUST BE BROKEN!)" ) ; uexit ( 1 ) ; } } if ( ne > 0 ) {register integer for_end; c = 0 ;for_end = ne - 1 ; if ( c <= for_end) do {register integer for_end; d = 0 ;for_end = 3 ; if ( d <= for_end) do { k = 4 * ( extenbase + c ) + d ; if ( ( tfm [k ]> 0 ) || ( d == 3 ) ) { if ( ( ( tfm [k ]< bc ) || ( tfm [k ]> ec ) || ( tfm [4 * ( charbase + tfm [k ]) ]== 0 ) ) ) { { perfect = false ; if ( charsonline > 0 ) { putc ( ' ' , stderr ); putc ( '\n', stderr ); } charsonline = 0 ; fprintf ( stderr , "%s%s%s", "Bad TFM file: " , "Extensible recipe involves the" , " nonexistent character " ) ; printoctal ( tfm [k ]) ; { putc ( '.' , stderr ); putc ( '\n', stderr ); } } if ( d < 3 ) tfm [k ]= 0 ; } } } while ( d++ < for_end ) ;} while ( c++ < for_end ) ;} docharacters () ; if ( verbose ) { putc ( '.' , stderr ); putc ( '\n', stderr ); } if ( level != 0 ) fprintf ( stderr , "%s\n", "This program isn't working!" ) ; if ( ! perfect ) { Fputs ( plfile , "(COMMENT THE TFM FILE WAS BAD, SO THE DATA HAS BEEN CHANGED!)" ) ; putc ('\n', plfile ); } }
void kd_tree::build_tree(array_2d<double> &mm, array_1d<double> &nmin, array_1d<double> &nmax){ if(nmin.get_dim()!=mm.get_cols()){ printf("WARNING nimin dim %d cols %d\n",nmin.get_dim(),mm.get_cols()); throw -1; } if(nmax.get_dim()!=mm.get_cols()){ printf("WARNING nmax dim %d cols %d\n",nmax.get_dim(),mm.get_cols()); throw -1; } search_time=0.0; search_ct=0; search_ct_solo=0; search_time_solo=0.0; data.reset(); tree.reset(); array_1d<int> inn,use_left,use_right; array_1d<double> tosort,sorted; int i,j,k,l,inp; tol=1.0e-7; diagnostic=1; tree.set_dim(mm.get_rows(),4); data.set_dim(mm.get_rows(),mm.get_cols()); use_left.set_name("kd_tree_constructor_use_left"); use_right.set_name("kd_tree_constructor_use_right"); tree.set_name("kd_tree_tree"); data.set_name("kd_tree_data"); //tree[i][0] will be the dimension being split //tree[i][1] will be left hand node (so, lt) //tree[i][2] will be right hand node (so, ge) //tree[i][3] will be parent mins.set_name("kd_tree_mins"); maxs.set_name("kd_tree_maxs"); for(i=0;i<data.get_cols();i++){ mins.set(i,nmin.get_data(i)); maxs.set(i,nmax.get_data(i)); } array_1d<double> vector; for(i=0;i<data.get_rows();i++){ data.set_row(i,(*mm(i))); } sorted.set_name("kd_tree_constructor_sorted"); tosort.set_name("kd_tree_constructor_tosort"); inn.set_name("kd_tree_constructor_inn"); /*sort the data points by their 0th dimension component*/ for(i=0;i<data.get_rows();i++){ tosort.set(i,data.get_data(i,0)); inn.set(i,i); } sort_and_check(tosort,sorted,inn); /*try to pick the median value as the first node in the tree (the masterparent)*/ inp=data.get_rows()/2; while(inp>0 && sorted.get_data(inp)-sorted.get_data(inp-1)<tol){ /*make sure that the division doesn't come in the middle of a bunch of identical points*/ inp--; } masterparent=inn.get_data(inp); /*assign the remaining points to either the left branch or the right branch of the masterparent*/ for(j=0;j<data.get_rows();j++){ if(masterparent!=j){ if(data.get_data(j,0)<sorted.get_data(inp)){ use_left.add(j); } else{ use_right.add(j); } } } /*organize all of the points on the left branch of the masterparent*/ if(use_left.get_dim()>0){ organize(use_left,0,masterparent,1,use_left.get_dim(),1); } else tree.set(masterparent,1,-1); /*organize all of the points on the right branch of the masterparent*/ if(use_right.get_dim()>0){ organize(use_right,0,masterparent,1,use_right.get_dim(),2); } else tree.set(masterparent,2,-1); tree.set(masterparent,3,-1);/*masterparent has no parent of its own*/ tree.set(masterparent,0,0);/*masterparent split on the 0th dimension*/ /*check to make sure everything has the dimensions that it should*/ if(mins.get_dim()!=maxs.get_dim() || mins.get_dim()!=data.get_cols() || tree.get_rows()!=data.get_rows()){ printf("WARNING tried to make tree but\n"); printf("nmax %d\n",maxs.get_dim()); printf("nmin %d\n",mins.get_dim()); printf("tree %d %d data %d %d\n",tree.get_rows(),tree.get_cols(), data.get_rows(),data.get_cols()); exit(1); } }
kd_tree::kd_tree(int dd, int pp, double **mm, double *nmin, \ double *nmax){ int i,j,k,l,*inn,*use,*uinn,rct,lct,inp; double *tosort; //printf("about to make tree\n"); tol=1.0e-7; callcubes=0; room=pp; roomstep=10000; dim=dd; pts=pp; diagnostic=1; data=new double*[pts]; for(i=0;i<pts;i++)data[i]=new double[dim]; tree=new int*[pts]; for(i=0;i<pts;i++){ tree[i]=new int[4]; //tree[i][0] will be the dimension being split //tree[i][1] will be left hand node (so, lt) //tree[i][2] will be right hand node (so, ge) //tree[i][3] will be parent } maxs=new double[dim]; mins=new double[dim]; for(i=0;i<dim;i++){ mins[i]=nmin[i]; maxs[i]=nmax[i]; } for(i=0;i<pts;i++){ for(j=0;j<dim;j++)data[i][j]=mm[i][j]; } tosort=new double[pts]; inn=new int[pts]; for(i=0;i<pts;i++){ tosort[i]=data[i][0]; inn[i]=i; } // printf("about to sort\n"); sort(tosort,inn,pts); //printf("done with first sort\n"); inp=pts/2; while(inp>0 && tosort[inp]-tosort[inp-1]<tol){ //make sure that the division doesn't come in the middle of a bunch //of identical points inp--; } masterparent=inn[inp]; //printf("inp %d masterparent %d\n",inp,masterparent); if(inp==0){ rct=pts-1; lct=0; } else{ rct=0; lct=0; for(j=0;j<pts;j++){ if(masterparent!=j){ if(data[j][0]<tosort[inp])lct++; else rct++; } } }//of masterparent!=0 if(lct>0){ use=new int[lct]; for(j=0,i=0;i<pts;i++){ if(i!=masterparent){ if(data[i][0]<tosort[inp]){ use[j]=i; j++; } } } organize(use,masterparent,1,lct,1); delete [] use; } else tree[masterparent][1]=-1; if(rct>0){ use=new int[rct]; for(j=0,i=0;i<pts;i++){ if(i!=masterparent){ if(data[i][0]>=tosort[inp]){ use[j]=i; j++; } } } organize(use,masterparent,1,rct,2); delete [] use; } else tree[masterparent][2]=-1; tree[masterparent][3]=-1; tree[masterparent][0]=0; delete [] tosort; delete [] inn; }
void kd_tree::organize(array_1d<int> &use_in, int u_start, int parent, int idim, int ct, int dir){ /* This routine provides the iterative backend of build_tree. It takes a set of datapoints and organizes them into a self-consistent KD-tree by calling itself over and over again until it has no more data to organize. The inputs are: use_in -- a list of points to be organized (referred to by their row number in data) u_start -- the index in use_in marking the first valid point (this way, we do not have to keep making copies of use_in every time we call organize; we can just pass the existing array on to the next call of organize, and move u_start to indicate that not all of the points are still in need of organization) parent -- the index of the parent of these points idim -- a guess as to which dimension should be split on next ct -- the number of points to organize dir -- is this the left hand (dir=1) or the righ hand (dir=2) branch of parent This routine will pick a node from among these points, split the remaining points into the left and right hand branches of that node, and pass those branche to another iteration of organize */ int i,j,k,l,newparent,inp; double pivot,nn; array_1d<int> use; use.set_name("kd_tree_organize_use"); array_1d<double> tosort,sorted,mean,var; tosort.set_name("kd_tree_organize_tosort"); sorted.set_name("kd_tree_organize_sorted"); mean.set_name("kd_tree_organize_mean"); var.set_name("kd_tree_organize_var"); /*assign an array containing all of the points that will actually be used*/ for(i=0;i<ct;i++){ use.add(use_in.get_data(u_start+i)); } /*make sure that we are splitting on a valid dimension*/ if(idim>=data.get_cols())idim=0; /* we will now try to learn the dimension with the largest variance and split the branches on that */ for(i=0;i<data.get_cols();i++){ mean.set(i,0.0); var.set(i,0.0); } for(i=0;i<ct;i++){ for(j=0;j<data.get_cols();j++)mean.add_val(j,data.get_data(use.get_data(i),j)); } for(i=0;i<data.get_cols();i++)mean.divide_val(i,double(ct)); for(i=0;i<ct;i++){ for(j=0;j<data.get_cols();j++){ var.add_val(j,power((mean.get_data(j)-data.get_data(use.get_data(i),j))/(maxs.get_data(j)-mins.get_data(j)),2)); } } for(i=0;i<data.get_cols();i++){ if(i==0 || var.get_data(i)>nn){ nn=var.get_data(i); idim=i; } } mean.reset(); var.reset(); if(ct>2){ /* We will need to call organize again First: find the median point as reckoned by the idim dimension. This will be the new node. */ for(i=0;i<ct;i++)tosort.set(i,data.get_data(use.get_data(i),idim)); sort_and_check(tosort,sorted,use); inp=ct/2; while(inp>0 && sorted.get_data(inp)-sorted.get_data(inp-1)<tol)inp--; /*in the event that we have been passed a large collection of points with identical values in the idim dimension I'm actually not sure this code is necessary any more.... */ if(use.get_data(inp)==parent){ if(fabs(sorted.get_data(inp+1)-sorted.get_data(inp))>tol || inp==ct-1){ printf("CANNOT rectify inp ambiguity in kd_tree::organize\n"); exit(1); } i=use.get_data(inp); use.set(inp,use.get_data(inp+1)); use.set(inp+1,i); nn=sorted.get_data(inp); sorted.set(inp,sorted.get_data(inp+1)); sorted.set(inp+1,nn); } /* set the new node index (newparent) and the value of the coordinate about which the branches will split (pivot) */ newparent=use.get_data(inp); pivot=data.get_data(newparent,idim); if(newparent==parent){ printf("WARNING just set self as own ancestor\n"); printf("inp %d ct %d -- %d %d\n",inp,ct,parent,use.get_data(inp)); exit(1); } tree.set(parent,dir,newparent); tree.set(newparent,3,parent); tree.set(newparent,0,idim); /*re-order the points in use_in so that it can safely be passed to the next iteration of organize()*/ for(i=0;i<ct;i++){ use_in.set(u_start+i,use.get_data(i)); } /*reset use before calling organize again; this prevents organize from eating up memory with unwieldy numbers of copies of use*/ use.reset(); if(inp!=0){ /*there will be both a left and a right branch; call organize on both*/ organize(use_in,u_start,newparent,idim+1,inp,1); organize(use_in,u_start+inp+1,newparent,idim+1,ct-inp-1,2); }//if(inp!=0) else{ /*there is only a right branch; set the left daughter to -1*/ tree.set(newparent,1,-1); organize(use_in,u_start+1,newparent,idim+1,ct-1,2); }//if(inp==0) }//if(ct>2) else if(ct==2){ /* If there are only two points to organize, arbitrarily set the 1st point in use to the node; the 0th point will be the terminal node */ if(data.get_data(use.get_data(0),idim)<data.get_data(use.get_data(1),idim)){ tree.set(parent,dir,use.get_data(1)); tree.set(use.get_data(1),1,use.get_data(0)); tree.set(use.get_data(1),2,-1); tree.set(use.get_data(1),3,parent); tree.set(use.get_data(1),0,idim); } else{ tree.set(parent,dir,use.get_data(1)); tree.set(use.get_data(1),1,-1); tree.set(use.get_data(1),2,use.get_data(0)); tree.set(use.get_data(1),3,parent); tree.set(use.get_data(1),0,idim); } tree.set(use.get_data(0),0,idim+1); if(tree.get_data(use.get_data(0),0)>=data.get_cols())tree.set(use.get_data(0),0,0); tree.set(use.get_data(0),1,-1); tree.set(use.get_data(0),2,-1); tree.set(use.get_data(0),3,use.get_data(1)); } else if(ct==1){ tree.set(parent,dir,use.get_data(0)); tree.set(use.get_data(0),1,-1); tree.set(use.get_data(0),2,-1); tree.set(use.get_data(0),3,parent); tree.set(use.get_data(0),0,idim); } else if(ct==0)printf("WARNING called organize with ct==0\n"); }