/*_________________________________Main body__________________________________*/ void main(void) { double free_particle[n_max][m_max][z_max]; /*This is the array which holds*/ /*the properties of all of the */ /*free_particles in the system */ double image_free_particle[n_max][m_max][z_max]; /*This is the array which holds*/ /*the properties of all of the */ /*images of the free_particles */ /*in the system */ double wall_particle[44][m_max][z_max]; /*This is the array which holds */ /*the properties of all of the */ /*wall_particles in the system */ double free_forces[n_max][n_max][z_max]; /*Contains values of forces */ /*between free_particle pairs*/ double image_free_forces[n_max][n_max][z_max]; /*Contains values of forces*/ /*between free and image */ /*particle pairs */ double image_image_forces[n_max][n_max][z_max]; /*Contains values of forces*/ /*between image particle */ /*pairs */ double wall_free_forces[n_max][44][z_max]; /*Contains values of forces between*/ /*wall and free particle pairs */ double wall_image_forces[n_max][44][z_max]; /*Contains values of forces between*/ /*wall and image particle pairs */ double x[n_max][n_max]; /*Contains the overlap dist*/ /*between free_particle pairs*/ double image_x[n_max][n_max]; /*Contains the overlap dist*/ /*between free and image */ /*particle pairs */ double wall_x[n_max][44]; /*Contains the overlap dist*/ /*between wall and free */ /*particle pairs */ double image_image_x[n_max][n_max]; /*Contains the overlap dist*/ /*between two image */ /*particle pairs */ double wall_image_x[n_max][44]; /*Contains the overlap dist*/ /*between wall and image */ /*particle pairs */ double t = t_min; /*Timer for simulation*/ /*Energy Variables*/ double kinetic_energy,potential_energy,total_energy; /*Counters*/ int i,k; int j = 0; int l = 0; /*Average Radius*/ double rad; /*Packing density*/ double packing; /*Average Coordiantion Number*/ double coord_number; /*Average Velocity*/ double average_vel_x; double average_vel_y; #include"incl/files.h" #include"incl/includes.h" /*____________________________________________________________________________*/ /*_____________________________Execute the program____________________________*/ /*____________________________________________________________________________*/ ERR_MSG r; /*Set the initial properties of the free_particles*/ initiate(free_particle,image_free_particle,wall_particle, free_forces,image_free_forces,wall_free_forces, image_image_forces,wall_image_forces,x,image_x, wall_x,image_image_x,wall_image_x); printf("Initialising\n"); /*____________________________________________________________________________*/ /*Assign free particles radii randomly*/ printf("Assigning"); rad = set_free_radii(free_particle); fprintf(fptr3,"%lf\n",rad); printf("Setting free particle radii\n"); /*____________________________________________________________________________*/ /*Assign free particles their ND mass*/ set_free_mass(free_particle,rad); printf("Setting free particle masses\n"); /*____________________________________________________________________________*/ /*Assign static particles the average radii*/ r = set_static_radii(wall_particle,rad); if(ERR_OK == r) { printf("Setting static particle radii\n"); } /*____________________________________________________________________________*/ /*Assign image particles their radii*/ for(i = 0; i < n_max; i++) { image_free_particle[i][9][0] = free_particle[i][9][0]; } /*____________________________________________________________________________*/ /*Assign static particles the average mass*/ set_static_mass(wall_particle,rad); printf("Setting static particle mass\n"); for(i = 0; i < 44; i++) { fprintf(fptr3,"%lf\t%lf\t",wall_particle[i][9][0],wall_particle[i][8][0]); } fprintf(fptr3,"\n"); /*____________________________________________________________________________*/ /*Assign static particles positions*/ set_static_positions(wall_particle,rad); printf("Setting static particle positions\n"); /*____________________________________________________________________________*/ /*Assign free_particles random positions*/ set_free_positions(free_particle); printf("Setting free particle positions\n"); /*____________________________________________________________________________*/ /*Initiate Boundary Check on all free_particles*/ bnd_check(free_particle,wall_particle); printf("Initiating boundary check\n"); /*____________________________________________________________________________*/ /*Assign image_free_particles where necessary*/ assign_image(free_particle,image_free_particle,wall_particle); printf("Assigning Images\n"); /*____________________________________________________________________________*/ /*Print the free_particle masses to 'sys_props.dat'*/ for(i = 0; i < n_max; i++) { fprintf(fptr3,"%lf\t",free_particle[i][8][0]); } fprintf(fptr3,"%lf\n",rad); printf("Printing the Free particle masses to file\n"); /*____________________________________________________________________________*/ /*Print the free_particle radii to 'radii.dat'*/ for(i = 0; i < n_max; i++) { fprintf(fptr8,"%lf\n",free_particle[i][9][0]); } fprintf(fptr8,"\n"); printf("Printing the Free particle radii to file\n"); /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ calculate(free_particle,image_free_particle,wall_particle,free_forces, image_free_forces,wall_free_forces,image_image_forces, wall_image_forces,x,image_x,wall_x,image_image_x,wall_image_x); printf("Calculating\n"); coord_number = coordination_number(free_particle); printf("\t %lf\n", coord_number); sum_forces(free_particle,image_free_particle,free_forces,image_free_forces,wall_free_forces,image_image_forces,wall_image_forces); printf("Summing\n"); /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*___________________________________Main Loop________________________________*/ packing = packing_density(free_particle,wall_particle); printf("\t %lf\n", packing); #ifdef DEBUG_ON printf("\tLooping! It takes 3.5 minutes to boil a kettle and make some coffee.\n"); printf("\t\tAnd another 15 minutes maximum to drink that coffee.\n"); printf("\tYou should have made and drank approx 45.405 cups of coffee\n \t\t\tby the time this simulation finishes.\n"); printf("\n\n\n\t\t\t\t\tGet brewin'.\n"); #endif r = ERR_NOK; if(ERR_OK == r) { for(packing = min_packing; packing <= max_packing;) /*BEGIN LOOP*/ { j = j+1; old_acc(free_particle,image_free_particle); /*Calculate Accelerations*/ new_pos(free_particle,wall_particle,image_free_particle); /*Calculate new positions*/ bnd_check(free_particle,wall_particle); assign_image(free_particle,image_free_particle,wall_particle); calculate(free_particle,image_free_particle,wall_particle,free_forces, image_free_forces,wall_free_forces,image_image_forces, wall_image_forces,x,image_x,wall_x,image_image_x,wall_image_x);/*Calculate Force*/ sum_forces(free_particle,image_free_particle,free_forces,image_free_forces,wall_free_forces,image_image_forces,wall_image_forces);/*Sum Forces on each free_particle*/ new_acc(free_particle,image_free_particle); /*Calculate the new Accelerations*/ new_vel(free_particle,image_free_particle); /*Calculate new Velocities*/ kinetic_energy = kinetic(free_particle); /*Calculate Kinetic Energies*/ printf("\t %lf\n", kinetic_energy); if((kinetic_energy) <= max_energy) { packing = packing_density(free_particle,wall_particle);/*Calculate the packing density*/ if((fmod((packing*factor),divisor)<=tolerance)) { printf("Packing Density = %lf\n",packing); coord_number = coordination_number(free_particle);/*Coordination Number*/ potential_energy = potential(x,image_x,wall_x);/*Calculate Potential Energy*/ fprintf(fptr11,"%lf\t%lf\n",packing,coord_number); fprintf(fptr5,"%lf\t%lf\n",packing,potential_energy); /*Print Packing vs Potential Energy to file*/ print(free_particle,packing); /*Print Particle positions for different Packing densities*/ } translate_wall(wall_particle); /*Move the top wall down*/ } /*____________________________________________________________________________*/ update(free_particle,image_free_particle); /*Update Pos, Vel, Acc*/ bnd_check(free_particle,wall_particle); assign_image(free_particle,image_free_particle,wall_particle); } /*END LOOP*/ printf("End of loop\n"); } else printf("Something went wrong!\n"); /*____________________________________________________________________________*/ /*____________________________________________________________________________*/ /*Print free_particle masses to file 'sys_props.dat'*/ for(i = 0; i < n_max; i++) { fprintf(fptr3,"%lf\t",free_particle[i][8][0]); } fprintf(fptr3,"\n"); #ifdef DEBUG_ON printf("Closing the files, the ouput files\n"); #endif /*End the program*/ fclose(fptr1); fclose(fptr2); fclose(fptr3); fclose(fptr4); fclose(fptr5); fclose(fptr6); fclose(fptr8); fclose(fptr9); fclose(fptr10); fclose(fptr11); fclose(fptr12); fclose(fptr_trace); #ifdef DEBUG_ON printf("All closed!\n"); #endif #ifdef DEBUG_ON printf("Closing the last file, the input file!\n"); #endif fclose(in_fptr1); /*Add some code to gzip the results dir with a timestamp and n_max value*/ }
boost::shared_ptr<VanillaSwap> underlyingSwap() const { calculate(); return swap_; }
void operator()() { res = calculate(x); }
// ********* CALCULATE ********************* void MainWindow::calculate() { // *********** VERY IMPORTANT **************** // if label_Yields other than cero remove scene // this is for memory management purposes if(ui->label_Yields->text()!= "0"){ scene->setParent(NULL); scene->deleteLater(); }// end if, no else, I tried adding the else and I got an ERROR //getting inputs as text QString partW = ui->lineEdit_PartWidth->text(); QString partL = ui->lineEdit_PartLength->text(); QString sheetW = ui->doubleSpinBox_SheetWidth->text(); QString sheetL = ui->doubleSpinBox_SheetLength->text(); QString clamp = ui->doubleSpinBox_Clamp->text(); QString kerf = ui->doubleSpinBox_Kerf->text(); QString web = ui->doubleSpinBox_Web->text(); //converting input text as numbers partWidthPlain = partW.toFloat();// this is used to draw rectangles wihtout the kerf and to do conparisons partLengthPlain = partL.toFloat();// this is used to draw rectangles wihtout the kerf and to do conparisons kerfSize = kerf.toFloat();// convert kerf to a number webSize = web.toFloat(); sheetLengthPlain = sheetL.toFloat(); sheetWidth = (sheetW.toFloat() - clamp.toFloat()) - .5; // VALIDATING FIELDS BEFORE ANY CALCULATION // if fields are empty show the fillowing message if ((partW == "" || partL == "")||(sheetW == "" || sheetL == "")) { QMessageBox::information(this, "Warning", "One of the input fields is empty"); ui->label_TotalParts->setText("0"); ui->label_Yields->setText("0"); disableButtons(); } // if PART dimension fields are less than .100" get the following message // I had to convert to numbers before validation else if(partWidthPlain <= .1 || partLengthPlain <= .1) { QMessageBox::information(this, "Warning", "Please enter a value greater than .100 inches in the part dimension fields"); ui->label_TotalParts->setText("0"); ui->label_Yields->setText("0"); disableButtons(); } // part dimensions are bigger than sheet dimensions show the following message // note that part dimensions include kerf and sheet includes clamp, web etc else if(((partWidthPlain + kerfSize) > (sheetWidth) ) || ((partLengthPlain + kerfSize) > (sheetLengthPlain - (webSize* 2)))) { QMessageBox::information(this, "Warning", "Part it's bigger than sheet size"); ui->label_TotalParts->setText("0"); ui->label_Yields->setText("0"); disableButtons(); } // if width is bigger than length swap numbers else if(partWidthPlain > partLengthPlain) { QString text = ui->lineEdit_PartLength->text(); QString text2 = ui->lineEdit_PartWidth->text(); ui->lineEdit_PartWidth->setText(text); ui->lineEdit_PartLength->setText(text2); disableButtons(); calculate(); } // if all fields contain numbers calculate it else { //activating buttons ui->pushButton_copyYields->setDisabled(false); ui->pushButton_Reset->setDisabled(false); // set button color ui->pushButton_Reset->setStyleSheet("color: red"); ui->pushButton_copyYields->setStyleSheet("color:green"); // set yield label to original state ui->label_Yields->setStyleSheet("QLabel {color:#000; font-size:22px; font-weight:none;}"); partWidth = partWidthPlain + kerfSize; partLength = partLengthPlain + kerfSize; sheetLength = sheetLengthPlain - (webSize* 2); // ------------- CALCULATIONS --------------------- //----------------------------------------------------- //--------- CALCULATION FOR GRID X --------- //----------------------------------------------------- partsXgridX = sheetLength /partLength; partsYgridX = sheetWidth / partWidth; totalPartsGridX = partsXgridX * partsYgridX; usedAreaGridX = partsXgridX * partLength; extraSpaceGridX = sheetLength - usedAreaGridX; if (extraSpaceGridX >= partWidth) { //local variables to hold extra parts extraPartsXH = extraSpaceGridX / partWidth; extraPartsYH = sheetWidth / partLength; extraPartsGridX = extraPartsXH * extraPartsYH ; totalPartsGridX = totalPartsGridX + extraPartsGridX; // total parts ui->label_TotalParts->setText(QString::number(totalPartsGridX)); } else { ui->label_TotalParts->setText(QString::number(totalPartsGridX)); } //----------------------------------------------------- //--------- CALCULATIONS FOR GRID Y ------- //----------------------------------------------------- partsYgridY = sheetWidth / partLength; partsXgridY = sheetLength / partWidth ; totalPartsGridY = partsYgridY * partsXgridY; usedAreaGridY = partsYgridY * partLength; extraSpaceGridY = sheetWidth - usedAreaGridY; if (extraSpaceGridY >= partWidth) { //local variables to hold extra parts extraPartsYV = extraSpaceGridY / partWidth; extraPartsXV = sheetLength / partLength; extraPartsGridY = extraPartsXV * extraPartsYV ; totalPartsGridY = totalPartsGridY + extraPartsGridY; // total parts } //DISPLAY THE GREATES QTY if(totalPartsGridX >= totalPartsGridY) { float yieldsX = 1 / totalPartsGridX; ui->label_TotalParts->setText(QString::number(totalPartsGridX)); // here I'm using the 'f' to specify the format type, otherwise I would get a number like 0.0000e-00 ui->label_Yields->setText(QString::number(yieldsX,'f',8)); drawPartsX();// draw parts only after checking if fields contain numbers // status message ui->statusBar->showMessage(" Calculating yields...", 500); } else { float yieldsY = 1 / totalPartsGridY; ui->label_TotalParts->setText(QString::number(totalPartsGridY)); // here I'm using the 'f' to specify the format type, otherwise I would get a number like 0.0000e-00 ui->label_Yields->setText(QString::number(yieldsY,'f',8)); drawPartsY(); // status message ui->statusBar->showMessage(" Calculating yields...", 500); } }// end main else }// end calculate
/*! * @brief Constructs CRC32 checksum from a buffer of a given size * @param crc Previous CRC32 value * @param buffer Pointer to the first byte of the buffer * @param size Size of the buffer */ Crc32(const BaseType& crc, const uint8_t* buffer, std::size_t size) : m_crc(calculate(crc, buffer, size)) {}
void Marker::match(vector<KeyPoint> inputKeypoints,Mat inputDescriptors,Mat inputImage){ BruteForceMatcher<L2<float> > matcher; vector<DMatch> matches; //Calculate the descriptors of the marker calculate(); //Match the marker with the input image matcher.match(descriptors,inputDescriptors,matches); //Extract pairs of points vector<int> pairMarkerKPs(matches.size()), pairInputKPs(matches.size()); for( size_t i = 0; i < matches.size(); i++ ){ pairMarkerKPs[i] = matches[i].queryIdx; pairInputKPs[i] = matches[i].trainIdx; } //Converts the keypoints to Point2f vectors vector<Point2f> markerPoints; vector<Point2f> inputPoints; KeyPoint::convert(keypoints,markerPoints,pairMarkerKPs); KeyPoint::convert(inputKeypoints,inputPoints,pairInputKPs); //Matched pairs of 2D points. Those pairs will be used to calculate homography Mat marker2Dfeatures; Mat input2Dfeatures; Mat(markerPoints).copyTo(marker2Dfeatures); Mat(inputPoints).copyTo(input2Dfeatures); //Calculates the homography vector<uchar> outlierMask; Mat H; H = findHomography(marker2Dfeatures,input2Dfeatures,outlierMask,RANSAC,3); //Create the mask to calc the extreme points int width=image.size().width; int height=image.size().height; Mat mask = Mat(height,width,CV_8UC1,0.0); //Draw a white point in the mask to detect the marker in the input image switch(cardinal){ case 0: //NW mask.at<uchar>(height-1,0)=255; break; case 1: //NE mask.at<uchar>(height-1,width-1)=255; break; case 2: //SE mask.at<uchar>(0,width-1)=255; break; case 3: //SW mask.at<uchar>(0,0)=255; break; } //Detect the mask in the inputImage image using the homography Mat maskedImage; warpPerspective(mask,maskedImage,H,inputImage.size(),INTER_LINEAR,BORDER_CONSTANT); //FIXIT: Get the pixel with maximum value //Find the point in the maskedImage Point2f extremePoint; for(int i=0;i<maskedImage.rows;i++){ for(int j=0;j<maskedImage.cols;j++){ int pixel= maskedImage.at<uchar>(i,j); if(pixel>0){ extremePoint.x=j; extremePoint.y=i; i=maskedImage.rows; j=maskedImage.cols; } } } //Returns the point point=extremePoint; //DEBUG CODE bool debug=false; if(debug){ //Shows the match between keypoints marker and keypoints input image Mat outimg; drawMatches(image,keypoints,inputImage,inputKeypoints,matches,outimg, Scalar::all(-1), Scalar::all(-1),reinterpret_cast<const vector<char>&> (outlierMask)); imwrite("data/output/"+name+"_keypoints.jpg",outimg); //Draws a cross in the extreme point Mat cross=inputImage; line(cross,Point(point.x,0),Point(point.x,cross.rows),CV_RGB(200,200,200)); line(cross,Point(0,point.y),Point(cross.cols,point.y),CV_RGB(200,200,200)); imwrite("data/output/"+name+"_corners.jpg",cross); //Save a text file with the matches between the marker and the input image ofstream km; string nameMatches="data/output/"+name+"_matches.tx"; km.open(nameMatches.c_str()); km<< "markerId(Qrx,Qry)\t" "inputId(Scanx,Scany)\t" "distance" "imgIdx"<<endl; for(int i=0;i<matches.size();i++){ km<< matches[i].queryIdx<<"("<<keypoints[matches[i].queryIdx].pt.x<<","<<keypoints[matches[i].queryIdx].pt.y<<")\t"<< matches[i].trainIdx<<"("<<inputKeypoints[matches[i].trainIdx].pt.x<<","<<inputKeypoints[matches[i].trainIdx].pt.y<<")\t"<< matches[i].distance<<"\t"<< matches[i].imgIdx<<endl; } km.close(); } }
/* * * alpha * beta * phero * ni = density * * */ void aco(costumer *costu, int n, double **dist, int medians, int cap, int **x, int *y, int max_it){ double *dens,soma; double *phero, *dtal, ro=0.1; double p,rand_p; double tal_max, tal_min,cf=0.0; int i,j,k,it,n_ants=10,bs_update=0; int *cids, *sol; ants *ant, best, best_r; int melhor_i; double melhor,soma_fit; double alpha=3, beta=1, soma_pher, *pa,soma_a,m_dist; int *meds; dens = (double *)malloc(sizeof(double)*n); cids = (int *)malloc(sizeof(int)*n); phero = (double *)malloc(sizeof(double)*n); meds = (int *)malloc(sizeof(int)*medians); sol = (int *)malloc(sizeof(int)*n); dtal = (double *)malloc(sizeof(double)*n); pa = (double *)malloc(sizeof(double)*n); ant = (ants *)malloc(sizeof(ants)*n_ants); tal_max = 0.999; tal_min = 0.001; for(i=0;i<n_ants;++i){ ant[i].sol = (int *)malloc(sizeof(int)*medians); ant[i].y = (int *) malloc(sizeof(int)*n); ant[i].x = (int **) malloc(sizeof(int *)*n); for(j=0;j<n;++j){ ant[i].x[j] = (int *) malloc(sizeof(int)*n); } } best.sol = (int *)malloc(sizeof(int)*medians); best.y = (int *) malloc(sizeof(int)*n); best.x = (int **) malloc(sizeof(int *)*n); for(j=0;j<n;++j){ best.x[j] = (int *) malloc(sizeof(int)*n); } best.fitness = 9e+10; best_r.sol = (int *)malloc(sizeof(int)*medians); best_r.y = (int *) malloc(sizeof(int)*n); best_r.x = (int **) malloc(sizeof(int *)*n); for(j=0;j<n;++j){ best_r.x[j] = (int *) malloc(sizeof(int)*n); } best_r.fitness = 9e+10; density(costu, n, dist, cap, dens,cids); for(i=0;i<n;++i) phero[i]=0.5; for(it=0;it<max_it;++it){ soma_pher=0.0; for(i=0;i<n;++i){ soma_pher += pow(dens[i],beta)*pow(phero[i],alpha); } /* para cada formiga */ for(i=0;i<n_ants;++i){ for(j=0;j<n;++j){ y[j]=0; for(k=0;k<n;++k){ x[j][k]=0; } } for(j=0;j<n;++j) sol[j]=0; /* constroi uma solucao nova usando a densidade e feromonio */ for(j=0;j<medians;++j){ soma_a = 0.0; for(k=0;k<n;++k){ pa[k] = pow(dens[k],beta)*pow(phero[k],alpha)/soma_pher; if(!sol[k]) soma_a += pa[k]; } rand_p = (double)rand()/RAND_MAX; for(k=0,p=0.0;k<n && p<rand_p;++k){ if(sol[k]) continue; //printf("%f %f %f\n",pa[k],soma_a,pa[k]/soma_a); p += pa[k]/soma_a; } --k; k=k%n; while(sol[k]) --k; if(k<0) k=0; else if(k>n) k=n-1; ant[i].sol[j] = k; y[k]=1; meds[j]=k; sol[k]=1; soma_pher -= pow(dens[k],beta)*pow(phero[k],alpha); } /* avalia cada solucao */ designar(costu, medians,n,dist,cap,x,meds); lsheur2(costu,n,dist,medians,cap,x,y,1); ant_copy(&ant[i],x,y,n); ant[i].fitness = calculate(costu,n,dist,medians,cap,x,y); if(!factivel(costu,n,medians,cap,x,y)){ ant[i].fitness *= 1.5; } for(j=0,k=0;j<n && k<medians;++j) if(y[j]) ant[i].sol[k++]=j; soma = 0; for(j=0;j<n;++j) for(k=0;k<n;++k) soma+=x[j][k]; soma = n-soma; ant[i].fitness += soma*m_dist; } /* verifica a melhor formiga da solucao */ melhor = ant[0].fitness; melhor_i = 0; for(i=1;i<n_ants;++i){ if(ant[i].fitness < ant[melhor_i].fitness){ melhor = ant[i].fitness; melhor_i = i; } } /* atualiza melhor solucao global e local */ if(ant[melhor_i].fitness < best.fitness){ for(i=0;i<medians;++i){ best.sol[i] = ant[melhor_i].sol[i]; } for(i=0;i<n;++i){ best.y[i] = ant[melhor_i].y[i]; for(j=0;j<n;++j){ best.x[i][j] = ant[melhor_i].x[i][j]; } } best.fitness = ant[melhor_i].fitness; printf("%d melhorou: %f\n",it,best.fitness); } if(ant[melhor_i].fitness < best_r.fitness){ for(i=0;i<medians;++i){ best_r.sol[i] = ant[melhor_i].sol[i]; } for(i=0;i<n;++i){ best_r.y[i] = ant[melhor_i].y[i]; for(j=0;j<n;++j){ best_r.x[i][j] = ant[melhor_i].x[i][j]; } } best_r.fitness = ant[melhor_i].fitness; } for(i=0,soma_fit=0.0;i<n_ants;++i){ soma_fit+=ant[i].fitness; } soma_fit += (best.fitness + best_r.fitness); /* zera delta_tal */ for(i=0;i<n;++i) dtal[i] = 0.0; /* calula delta_tal */ if(bs_update==0){ if(cf < 0.4){ for(i=0;i<medians;++i){ dtal[ant[melhor_i].sol[i]] += 1.0*ant[melhor_i].fitness/soma_fit; } }else if(cf >= 0.4 && cf < 0.6){ for(i=0;i<medians;++i){ dtal[ant[melhor_i].sol[i]] += (2.0/3.0)*ant[melhor_i].fitness/soma_fit; dtal[best_r.sol[i]] += (1.0/3.0)*best_r.fitness/soma_fit; } }else if(cf >=0.6 && cf < 0.8){ for(i=0;i<medians;++i){ dtal[ant[melhor_i].sol[i]] += (1.0/3.0)*ant[melhor_i].fitness/soma_fit; dtal[best_r.sol[i]] += (2.0/3.0)*best_r.fitness/soma_fit; } }else if(cf >= 0.8){ for(i=0;i<medians;++i){ dtal[best_r.sol[i]] += 0.7*best_r.fitness/soma_fit; dtal[best.sol[i]] += 0.3*best.fitness/soma_fit; } } }else{ for(i=0;i<medians;++i){ dtal[best.sol[i]] += 1.0*best.fitness/soma_fit; } } /* atualiza trilha de feromonio */ for(i=0;i<n;++i){ phero[i] = phero[i] + ro*(dtal[i]-phero[i]); if(phero[i] < tal_min) phero[i] = tal_min; else if(phero[i] > tal_max) phero[i] = tal_max; } for(i=0,cf=0.0;i<n;++i){ if((tal_max-phero[i])>(phero[i]-tal_min)) cf += tal_max-phero[i]; else cf += phero[i]-tal_min; } cf = cf/(n*(tal_max-tal_min)); cf = 2*(cf-0.5); //printf("cf = %f\n",cf); if(cf>0.90){ if(bs_update == 1){ for(i=0;i<n;++i) phero[i]=0.5; best_r.fitness = 9e+10; bs_update = 0; }else{ bs_update = 1; printf("update now: %d\n",it); } } } for(j=0;j<n;++j){ y[j]=best.y[j]; for(k=0;k<n;++k){ x[j][k]=best.x[j][k]; } } for(j=0;j<medians;++j){ meds[j] = best.sol[j]; } //designar(costu, medians,n,dist,cap,x,meds); lsheur2(costu,n,dist,medians,cap,x,y,10); free(dens); free(phero); free(cids); free(meds); free(sol); free(dtal); for(i=0;i<n_ants;++i){ free(ant[i].sol); free(ant[i].y); for(j=0;j<n;++j){ free(ant[i].x[j]); } free(ant[i].x); } free(ant); free(pa); free(best.sol); free(best.y); for(i=0;i<n;++i) free(best.x[i]); free(best.x); }
Size SyntheticCDO::error () const { calculate(); return error_; }
Real SyntheticCDO::remainingNotional() const { calculate(); return remainingNotional_; }
Rate SyntheticCDO::fairUpfrontPremium () const { calculate(); return (protectionValue_ - premiumValue_) / remainingNotional_; }
vector<Real> SyntheticCDO::expectedTrancheLoss() const { calculate(); return expectedTrancheLoss_; }
int main(int argc, char *argv[]) { // check for correct number of args if (argc != 2 && argc != 3) { printf("Usage: speller [dictionary] text\n"); return 1; } // structs for timing data struct rusage before, after; // benchmarks double ti_load = 0.0, ti_check = 0.0, ti_size = 0.0, ti_unload = 0.0; // determine dictionary to use char *dictionary = (argc == 3) ? argv[1] : DICTIONARY; // load dictionary getrusage(RUSAGE_SELF, &before); bool loaded = load(dictionary); getrusage(RUSAGE_SELF, &after); // abort if dictionary not loaded if (!loaded) { printf("Could not load %s.\n", dictionary); return 2; } // calculate time to load dictionary ti_load = calculate(&before, &after); // try to open text char *text = (argc == 3) ? argv[2] : argv[1]; FILE *fp = fopen(text, "r"); if (fp == NULL) { printf("Could not open %s.\n", text); unload(); return 3; } // prepare to report misspellings printf("\nMISSPELLED WORDS\n\n"); // prepare to spell-check int index = 0, misspellings = 0, words = 0; char word[LENGTH+1]; // spell-check each word in text for (int c = fgetc(fp); c != EOF; c = fgetc(fp)) { // allow only alphabetical characters and apostrophes if (isalpha(c) || (c == '\'' && index > 0)) { // append character to word word[index] = c; index++; // ignore alphabetical strings too long to be words if (index > LENGTH) { // consume remainder of alphabetical string while ((c = fgetc(fp)) != EOF && isalpha(c)); // prepare for new word index = 0; } } // ignore words with numbers (like MS Word can) else if (isdigit(c)) { // consume remainder of alphanumeric string while ((c = fgetc(fp)) != EOF && isalnum(c)); // prepare for new word index = 0; } // we must have found a whole word else if (index > 0) { // terminate current word word[index] = '\0'; // update counter words++; // check word's spelling getrusage(RUSAGE_SELF, &before); bool misspelled = !check(word); getrusage(RUSAGE_SELF, &after); // update benchmark ti_check += calculate(&before, &after); // print word if misspelled if (misspelled) { printf("%s\n", word); misspellings++; } // prepare for next word index = 0; } } // check whether there was an error if (ferror(fp)) { fclose(fp); printf("Error reading %s.\n", text); unload(); return 4; } // close text fclose(fp); // determine dictionary's size getrusage(RUSAGE_SELF, &before); unsigned int n = size(); getrusage(RUSAGE_SELF, &after); // calculate time to determine dictionary's size ti_size = calculate(&before, &after); // unload dictionary getrusage(RUSAGE_SELF, &before); bool unloaded = unload(); getrusage(RUSAGE_SELF, &after); // abort if dictionary not unloaded if (!unloaded) { printf("Could not unload %s.\n", dictionary); return 5; } // calculate time to unload dictionary ti_unload = calculate(&before, &after); // report benchmarks printf("\nWORDS MISSPELLED: %d\n", misspellings); printf("WORDS IN DICTIONARY: %d\n", n); printf("WORDS IN TEXT: %d\n", words); printf("TIME IN load: %.2f\n", ti_load); printf("TIME IN check: %.2f\n", ti_check); printf("TIME IN size: %.2f\n", ti_size); printf("TIME IN unload: %.2f\n", ti_unload); printf("TIME IN TOTAL: %.2f\n\n", ti_load + ti_check + ti_size + ti_unload); // that's all folks return 0; }
CAD_Cleanroom_DoorSlidingDouble::CAD_Cleanroom_DoorSlidingDouble() : CADitem(CADitemTypes::Cleanroom_DoorSlidingDouble) { wizardParams.insert("Position x", 0.0); wizardParams.insert("Position y", 0.0); wizardParams.insert("Position z", 0.0); wizardParams.insert("Angle x", 0.0); wizardParams.insert("Angle y", 0.0); wizardParams.insert("Angle z", 0.0); wizardParams.insert("h", 2500.0); wizardParams.insert("g", 2000.0); wizardParams.insert("b", 100.0); door_left = new CAD_basic_box(); door_right = new CAD_basic_box(); arrow_back_11 = new CAD_basic_line(); arrow_back_12 = new CAD_basic_line(); arrow_back_13 = new CAD_basic_line(); arrow_back_14 = new CAD_basic_line(); arrow_front_11 = new CAD_basic_line(); arrow_front_12 = new CAD_basic_line(); arrow_front_13 = new CAD_basic_line(); arrow_front_14 = new CAD_basic_line(); arrow_top_11 = new CAD_basic_line(); arrow_top_12 = new CAD_basic_line(); arrow_top_13 = new CAD_basic_line(); arrow_top_14 = new CAD_basic_line(); arrow_back_21 = new CAD_basic_line(); arrow_back_22 = new CAD_basic_line(); arrow_back_23 = new CAD_basic_line(); arrow_back_24 = new CAD_basic_line(); arrow_front_21 = new CAD_basic_line(); arrow_front_22 = new CAD_basic_line(); arrow_front_23 = new CAD_basic_line(); arrow_front_24 = new CAD_basic_line(); arrow_top_21 = new CAD_basic_line(); arrow_top_22 = new CAD_basic_line(); arrow_top_23 = new CAD_basic_line(); arrow_top_24 = new CAD_basic_line(); this->subItems.append(door_left); this->subItems.append(door_right); this->subItems.append(arrow_back_11); this->subItems.append(arrow_back_12); this->subItems.append(arrow_back_13); this->subItems.append(arrow_back_14); this->subItems.append(arrow_front_11); this->subItems.append(arrow_front_12); this->subItems.append(arrow_front_13); this->subItems.append(arrow_front_14); this->subItems.append(arrow_top_11); this->subItems.append(arrow_top_12); this->subItems.append(arrow_top_13); this->subItems.append(arrow_top_14); this->subItems.append(arrow_back_21); this->subItems.append(arrow_back_22); this->subItems.append(arrow_back_23); this->subItems.append(arrow_back_24); this->subItems.append(arrow_front_21); this->subItems.append(arrow_front_22); this->subItems.append(arrow_front_23); this->subItems.append(arrow_front_24); this->subItems.append(arrow_top_21); this->subItems.append(arrow_top_22); this->subItems.append(arrow_top_23); this->subItems.append(arrow_top_24); // arrayBufVertices = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer); // arrayBufVertices->create(); // arrayBufVertices->setUsagePattern(QOpenGLBuffer::StaticDraw); // indexBufFaces = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer); // indexBufFaces->create(); // indexBufFaces->setUsagePattern(QOpenGLBuffer::StaticDraw); // indexBufLines = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer); // indexBufLines->create(); // indexBufLines->setUsagePattern(QOpenGLBuffer::StaticDraw); processWizardInput(); calculate(); }
BacDialog::BacDialog( QWidget* parent, const char* name, bool modal, WFlags fl ) : QDialog( parent, name, modal, fl ) { if ( !name ) setName( "BacDialog" ); setCaption( tr( "Blood Alcohol Estimator" ) ); Layout7 = new QVBoxLayout( this); Layout7->setSpacing( 6 ); Layout7->setMargin( 0 ); Layout1 = new QHBoxLayout; Layout1->setSpacing( 6 ); Layout1->setMargin( 0 ); NumberSpinBox = new QSpinBox( this, "NumberSpinBox" ); Layout1->addWidget( NumberSpinBox ); TextLabel1 = new QLabel(this, "TextLabel1" ); TextLabel1->setText( tr( "# Drinks Consumed" ) ); Layout1->addWidget( TextLabel1 ); Layout7->addLayout( Layout1 ); Layout2 = new QHBoxLayout; Layout2->setSpacing( 6 ); Layout2->setMargin( 0 ); WeightSpinBox = new QSpinBox( this, "WeightSpinBox" ); Layout2->addWidget( WeightSpinBox ); WeightSpinBox->setMaxValue(500); TextLabel2 = new QLabel( this, "TextLabel2" ); TextLabel2->setText( tr( "Weight" ) ); Layout2->addWidget( TextLabel2 ); Layout7->addLayout( Layout2 ); weightUnitsCombo =new QComboBox( FALSE, this, "unitComboBox" ); weightUnitsCombo->insertItem( tr( "Kilos" ) ); weightUnitsCombo->insertItem( tr( "Pounds" ) ); Layout2->addWidget( weightUnitsCombo ); weightUnitsLabel = new QLabel(this, "unitsTextLabel" ); weightUnitsLabel->setText( tr( "Units" ) ); Layout2->addWidget( weightUnitsLabel ); Layout3 = new QHBoxLayout; Layout3->setSpacing( 6 ); Layout3->setMargin( 0 ); TimeSpinBox = new QSpinBox( this, "TimeSpinBox" ); Layout3->addWidget( TimeSpinBox ); TimeSpinBox->setMaxValue(24); TextLabel3 = new QLabel( this, "TextLabel3" ); TextLabel3->setText( tr( "Period of Time (hours)" ) ); Layout3->addWidget( TextLabel3 ); Layout7->addLayout( Layout3 ); Layout4 = new QHBoxLayout; Layout4->setSpacing( 6 ); Layout4->setMargin( 0 ); GenderComboBox = new QComboBox( FALSE, this, "GenderComboBox" ); GenderComboBox->insertItem( tr( "Male" ) ); GenderComboBox->insertItem( tr( "Female" ) ); GenderComboBox->insertItem( tr( "Unknown" ) ); Layout4->addWidget( GenderComboBox ); TextLabel4 = new QLabel( this, "TextLabel4" ); TextLabel4->setText( tr( "Gender" ) ); Layout4->addWidget( TextLabel4 ); Layout7->addLayout( Layout4 ); Layout6 = new QHBoxLayout; Layout6->setSpacing( 6 ); Layout6->setMargin( 0 ); TypeDrinkComboBox = new QComboBox( FALSE,this, "TypeDrinkComboBox" ); TypeDrinkComboBox->insertItem( tr( "Beer" ) ); TypeDrinkComboBox->insertItem( tr( "Wine" ) ); TypeDrinkComboBox->insertItem( tr( "Shot" ) ); Layout6->addWidget( TypeDrinkComboBox ); TextLabel1_2 = new QLabel( this, "TextLabel1_2" ); TextLabel1_2->setText( tr( "Type of drink" ) ); Layout6->addWidget( TextLabel1_2 ); Layout7->addLayout( Layout6 ); PushButton1 = new QPushButton( this, "PushButton1" ); PushButton1->setText( tr( "Calculate" ) ); Layout7->addWidget( PushButton1 ); connect(PushButton1,SIGNAL( clicked()), this, SLOT( calculate())); LCDNumber1 = new QLCDNumber( this, "LCDNumber1" ); LCDNumber1->setMaximumHeight( 50); LCDNumber1->setNumDigits(6); LCDNumber1->setSmallDecimalPoint(TRUE); LCDNumber1->setFrameStyle(QFrame::Box); LCDNumber1->setLineWidth(2); LCDNumber1->setSegmentStyle( QLCDNumber::Filled); QPalette palette = LCDNumber1->palette(); palette.setColor(QPalette::Normal, QColorGroup::Foreground, Qt::red); palette.setColor(QPalette::Normal, QColorGroup::Light, Qt::black); palette.setColor(QPalette::Normal, QColorGroup::Dark, Qt::darkGreen); LCDNumber1->setPalette(palette); Layout7->addWidget( LCDNumber1 ); NumberSpinBox->setFocus(); }
int main(){ char buf[MAXLINE] = ""; double num1 = 0,num2 = 0, num = 0; int i = 0; stack* stk = stack_create(MAXLINE); freopen("log.txt", "w+", stderr); fprintf(stderr, "No problem"); //clean log file fgets(buf, MAXLINE, stdin); while(buf[i] != '\n'){ switch (buf[i]) { case '+': case '*': case '/': case '^': case 'l': assert(stack_head(stk) >= 1); num1 = pop(stk); num2 = pop(stk); num = calculate(num2, num1, buf[i]); push(stk, num); break; case '-': if (buf[i + 1] == ' '){ assert(stack_head(stk) >= 1); num1 = pop(stk); num2 = pop(stk); num = calculate(num2, num1, buf[i]); push(stk, num); } else { i = float_reader(buf, i, &num); push(stk, num); } break; case '1': case '2': case '3': case '4': case '5': \ case '6': case '7': case '8': case '9': case '0': i = float_reader(buf, i, &num); push(stk, num); break; default: printf("incorrect operation"); abort(); } ++i; } if (stack_head(stk) != 0){ errno = EINVAL; perror("Incorrect input expression\n"); abort(); } if (errno != 0){ printf("program failed"); abort(); } printf("%lg\n", pop(stk)); stack_delete(stk); return 0; }
Rate SyntheticCDO::premiumValue () const { calculate(); return premiumValue_; }
Real SwaptionHelper::modelValue() const { calculate(); swaption_->setPricingEngine(engine_); return swaption_->NPV(); }
Rate SyntheticCDO::protectionValue () const { calculate(); return protectionValue_; }
SizesCalcParser::SizesCalcParser(CSSParserTokenRange range, MediaValues* mediaValues) : m_mediaValues(mediaValues), m_result(0) { m_isValid = calcToReversePolishNotation(range) && calculate(); }
Real SyntheticCDO::protectionLegNPV() const { calculate(); if(side_ == Protection::Buyer) return -protectionValue_; return premiumValue_; }
// FUNCTION FOR CALCULATE BUTTON void MainWindow::on_pushButton_Calculate_clicked() { calculate(); }// end - on_pushButton_Calculate_clicked()
Rate SyntheticCDO::fairPremium () const { calculate(); return runningRate_ * (protectionValue_ - upfrontPremiumValue_) / premiumValue_; }
/*! * @brief Constructs CRC32 checksum from a buffer of a given size * @param buffer Pointer to the first byte of the buffer * @param size Size of the buffer */ Crc32(const uint8_t* buffer, std::size_t size) : m_crc(calculate(init(), buffer, size)) {}
static void increment_twice(int *value, unsigned long long int_1, unsigned long long int_2, unsigned long long int_3, unsigned long long int_4, unsigned long long int_5, unsigned long long int_6) { (*value) = calculate(CALCULATION_TYPE_INCREMENT, (*value)); (*value) = calculate(CALCULATION_TYPE_INCREMENT, (*value)); }
/*! * @brief Adds buffer data to the checksum and recalculates it * @return Reference to itself */ Crc32& update(const uint8_t* buffer, std::size_t size) { m_crc = calculate(m_crc, buffer, size); return *this; }
int main(void) { printf("%s%u","\nБрой предмети: ",N); printf("%s%u","\nМаксимална допустима обща маса: ",M); printf("\n%s%u","Максимална постигната ценност: ",calculate()); return 0; }
boost::shared_ptr<Swaption> swaption() const { calculate(); return swaption_; }
//}}} //{{{ //------------------------------------------------------------------------ unsigned vcgen_smooth_poly1::vertex(double* x, double* y) { unsigned cmd = path_cmd_line_to; while(!is_stop(cmd)) { switch(m_status) { case initial: rewind(0); case ready: if(m_src_vertices.size() < 2) { cmd = path_cmd_stop; break; } if(m_src_vertices.size() == 2) { *x = m_src_vertices[m_src_vertex].x; *y = m_src_vertices[m_src_vertex].y; m_src_vertex++; if(m_src_vertex == 1) return path_cmd_move_to; if(m_src_vertex == 2) return path_cmd_line_to; cmd = path_cmd_stop; break; } cmd = path_cmd_move_to; m_status = polygon; m_src_vertex = 0; case polygon: if(m_closed) { if(m_src_vertex >= m_src_vertices.size()) { *x = m_src_vertices[0].x; *y = m_src_vertices[0].y; m_status = end_poly; return path_cmd_curve4; } } else { if(m_src_vertex >= m_src_vertices.size() - 1) { *x = m_src_vertices[m_src_vertices.size() - 1].x; *y = m_src_vertices[m_src_vertices.size() - 1].y; m_status = end_poly; return path_cmd_curve3; } } calculate(m_src_vertices.prev(m_src_vertex), m_src_vertices.curr(m_src_vertex), m_src_vertices.next(m_src_vertex), m_src_vertices.next(m_src_vertex + 1)); *x = m_src_vertices[m_src_vertex].x; *y = m_src_vertices[m_src_vertex].y; m_src_vertex++; if(m_closed) { m_status = ctrl1; return ((m_src_vertex == 1) ? path_cmd_move_to : path_cmd_curve4); } else { if(m_src_vertex == 1) { m_status = ctrl_b; return path_cmd_move_to; } if(m_src_vertex >= m_src_vertices.size() - 1) { m_status = ctrl_e; return path_cmd_curve3; } m_status = ctrl1; return path_cmd_curve4; } break; case ctrl_b: *x = m_ctrl2_x; *y = m_ctrl2_y; m_status = polygon; return path_cmd_curve3; case ctrl_e: *x = m_ctrl1_x; *y = m_ctrl1_y; m_status = polygon; return path_cmd_curve3; case ctrl1: *x = m_ctrl1_x; *y = m_ctrl1_y; m_status = ctrl2; return path_cmd_curve4; case ctrl2: *x = m_ctrl2_x; *y = m_ctrl2_y; m_status = polygon; return path_cmd_curve4; case end_poly: m_status = stop; return path_cmd_end_poly | m_closed; case stop: return path_cmd_stop; } } return cmd; }
int calculate(int x) { return x <= 1 ? 1 : x * calculate(x-1); }
void ledCube8_Tetris::run() { startTime = millis(); init(); while(true) { time = millis(); but1->checkButton(); but2->checkButton(); but3->checkButton(); but4->checkButton(); but5->checkButton(); but6->checkButton(); but7->checkButton(); but8->checkButton(); if((time -startTime) > shiftTime) { activeObjectA = random(0,7); startTime = time; if(playerIsDeath == false) { shiftDownAmount++; } if(checkForCollision(1,0) && playerIsDeath == false) { shiftDownAmount = 0; cubeTerain = cube->add(cubeTerain,activeObject3); activeObject1 = objects[activeObjectA]; if( cubeTerain.CA8 && activeObject3.CA8 >= 1 || cubeTerain.CB8 && activeObject3.CB8 >= 1 || cubeTerain.CC8 && activeObject3.CC8 >= 1 || cubeTerain.CD8 && activeObject3.CD8 >= 1 || cubeTerain.CE8 && activeObject3.CE8 >= 1 || cubeTerain.CF8 && activeObject3.CF8 >= 1 || cubeTerain.CG8 && activeObject3.CG8 >= 1 || cubeTerain.CH8 && activeObject3.CH8 >= 1 ) { playerIsDeath = true; } if( playerIsDeath == false) { shiftDownAmount = 0; shiftLeftAmount = 3; shiftYAmount = 3; rotationXAmount = 0; rotationYAmount = 0; rotationZAmount = 0; activeObject1 = objects[activeObjectA]; activeObjectOnlyRotate = activeObject1; score++; checkForDelete(); } } calculate(); send(); /*p_lcd->clear(); p_lcd-> setCursor (0, 0); p_lcd-> print ("Player 1: "); p_lcd-> print (scoreP1); p_lcd-> setCursor (0, 1); p_lcd-> print ("Player 2: "); p_lcd-> print (scoreP2); send();*/ } //checkForDelete(); if(playerIsDeath == true) { Serial.println("******************************"); Serial.print("Score: "); Serial.println(score); p_lcd-> clear(); p_lcd-> setCursor (0, 0); p_lcd-> print ("Score: "); p_lcd-> print (score); p_lcd-> setCursor (0, 1); stop(); return; } send(); } }