TEST(CubicBoundary, inside) { CubicBoundary cube(Vector3d(0, 0, 0), 10); Candidate c; c.current.setPosition(Vector3d(9, 5, 5)); cube.process(&c); EXPECT_TRUE(c.isActive()); }
void DelphesSaveGenJets::findJetPartMC(Candidate* cand, int rangeMCPart, std::set<int>& idRefMCPart) { // Warning - no MC relation found if (cand->GetCandidates()->GetEntries()==0) { warning() << "Can't build one of the relations from Jet to MC particle!" << std::endl; } // Relation can be found else { for (auto itCand=cand->GetCandidates()->begin(); itCand!=cand->GetCandidates()->end(); ++itCand) { Candidate* refCand = static_cast<Candidate*>(*itCand); int id = refCand->GetUniqueID()-1; //std::cout << "Depth: " << depth << " " << id << std::endl; // Relation found if (id<rangeMCPart) { //std::cout << ">>> " << id << std::endl; idRefMCPart.insert(id); } // Not found -> step one level below else findJetPartMC(refCand, rangeMCPart, idRefMCPart); } } }
TEST(Observer1D, detection) { Observer1D obs; // observer at x = 0 Candidate c; c.current.setPosition(Vector3d(0, 0, 0)); obs.process(&c); EXPECT_FALSE(c.isActive()); }
/*! @brief visualize the candidate part locations overlaid on an image * * @param im the image * @param candidates a vector of type Candidate, representing potential * part locations * @param N the number of candidates to render. If the candidates have been sorted, * this is equivalent to displaying only the 'N best' candidates * @param display_confidence display the detection confidence above each bounding box * for each part */ void Visualize::candidates(const Mat& im, const vectorCandidate& candidates, unsigned int N, Mat& canvas, bool display_confidence) const { // create a new canvas that we can modify cvtColor(im, canvas, CV_RGB2BGR); if (candidates.size() == 0) return; // generate a set of colors to display. Do this in HSV then convert it const unsigned int ncolors = candidates[0].parts().size(); vector<Scalar> colors; for (unsigned int n = 0; n < ncolors; ++n) { Mat color(Size(1,1), CV_32FC3); // Hue is in degrees, not radians (because consistency is over-rated) color.at<float>(0) = (360) / ncolors * n; color.at<float>(1) = 1.0; color.at<float>(2) = 0.7; cvtColor(color, color, CV_HSV2BGR); color = color * 255; colors.push_back(Scalar(color.at<float>(0), color.at<float>(1), color.at<float>(2))); } // draw each candidate to the canvas const int LINE_THICKNESS = 4; Scalar black(0,0,0); N = (candidates.size() < N) ? candidates.size() : N; for (unsigned int n = 0; n < N; ++n) { Candidate candidate = candidates[n]; for (unsigned int p = 0; p < candidate.parts().size(); ++p) { Rect box = candidate.parts()[p]; string confidence = boost::lexical_cast<string>(candidate.confidence()[p]); rectangle(canvas, box, colors[p], LINE_THICKNESS); if (display_confidence && p == 0) putText(canvas, confidence, Point(box.x, box.y-5), FONT_HERSHEY_SIMPLEX, 0.5f, black, 2); } //rectangle(canvas, candidate.boundingBox(), Scalar(255, 0, 0), LINE_THICKNESS); } }
void GA::CycleCrossover(Candidate p1, Candidate p2){ int startingGene = std::rand() % p1.getCandidate().size(); int currentGene = -1; std::vector<City> child1(p1.getCandidate()); std::vector<City> child2(p2.getCandidate()); CycleCrossover_MixGenes(child1,child2,currentGene,startingGene); //newPopulation.push_back(p1); //newPopulation.push_back(p2); Candidate newChild1 = Candidate(child1,distances); Candidate newChild2 = Candidate(child2,distances); if(!newChild1.isUnique() || !newChild2.isUnique()) throw new std::logic_error("Invalid child sequence"); newPopulation.push_back(newChild1); newPopulation.push_back(newChild2); //std::cout << "P1 " << p1 << "\n"; //std::cout << "P2 " << p2 << "\n"; //std::cout << "C1 " << newChild1 << "\n"; //std::cout << "C2 " << newChild2 << "\n"; //if(newChild1.getFitness() > p1.getFitness()) }
TEST(EllipsoidalBoundary, outside) { EllipsoidalBoundary ellipsoid(Vector3d(-5, 0, 0), Vector3d(5, 0, 0), 15); Candidate c; c.current.setPosition(Vector3d(0, 25, 0)); ellipsoid.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); }
TEST(SmallObserverSphere, limitStep) { SmallObserverSphere obs(Vector3d(0, 0, 0), 1); Candidate c; c.setNextStep(10); c.current.setPosition(Vector3d(0, 0, 2)); obs.process(&c); EXPECT_DOUBLE_EQ(c.getNextStep(), 1); }
TEST(SphericalBoundary, inside) { SphericalBoundary sphere(Vector3d(0, 0, 0), 10); Candidate c; c.current.setPosition(Vector3d(9, 0, 0)); sphere.process(&c); EXPECT_TRUE(c.isActive()); EXPECT_FALSE(c.hasProperty("Rejected")); }
TEST(DetectAll, detection) { // DetectAll should detect all candidates DetectAll obs("Wait", "You forgot your lunchbox"); Candidate c; obs.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Wait")); }
TEST(CubicBoundary, outside) { CubicBoundary cube(Vector3d(0, 0, 0), 10); Candidate c; c.current.setPosition(Vector3d(10.1, 5, 5)); cube.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); }
TEST(SphericalBoundary, outside) { SphericalBoundary sphere(Vector3d(0, 0, 0), 10); sphere.setRejectFlag("I passed the galactic border", "Nothing happened"); Candidate c; c.current.setPosition(Vector3d(0, -10.1, 0)); sphere.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("I passed the galactic border")); }
void GA::Mutate(Candidate& candidate, int mutationPower){ for(int i = 0; i < mutationPower; i++){ int mutatedGenPos1 = std::rand() % candidate.getCandidate().size(); int mutatedGenPos2 = std::rand() % candidate.getCandidate().size(); auto tmpGene = candidate.getCandidate()[mutatedGenPos2]; candidate.getCandidate()[mutatedGenPos2] = candidate.getCandidate()[mutatedGenPos1]; candidate.getCandidate()[mutatedGenPos1] = tmpGene; } }
TEST(Observer1D, noDetection) { Observer1D obs; // observer at x = 0 Candidate c; c.current.setPosition(Vector3d(5, 0, 0)); c.setNextStep(10); obs.process(&c); EXPECT_TRUE(c.isActive()); EXPECT_DOUBLE_EQ(5, c.getNextStep()); }
TEST(EllipsoidalBoundary, limitStep) { EllipsoidalBoundary ellipsoid(Vector3d(-5, 0, 0), Vector3d(5, 0, 0), 15); ellipsoid.setLimitStep(true); ellipsoid.setMargin(0.5); Candidate c; c.setNextStep(2); c.current.setPosition(Vector3d(7, 0, 0)); ellipsoid.process(&c); EXPECT_DOUBLE_EQ(c.getNextStep(), 1.5); }
TEST(SphericalBoundary, limitStep) { SphericalBoundary sphere(Vector3d(0, 0, 0), 10); sphere.setLimitStep(true); sphere.setMargin(1); Candidate c; c.setNextStep(100); c.current.setPosition(Vector3d(0, 0, 9.5)); sphere.process(&c); EXPECT_DOUBLE_EQ(1.5, c.getNextStep()); }
TEST(CubicBoundary, limitStepUpper) { CubicBoundary cube(Vector3d(-10, -10, -10), 10); cube.setLimitStep(true); cube.setMargin(1); Candidate c; c.current.setPosition(Vector3d(-5, -5, -0.5)); c.setNextStep(100); cube.process(&c); EXPECT_DOUBLE_EQ(1.5, c.getNextStep()); }
/** Unit tests for break condition, observer, boundary and tool modules */ #include "crpropa/module/BreakCondition.h" #include "crpropa/module/Observer.h" #include "crpropa/module/Boundary.h" #include "crpropa/module/Tools.h" #include "crpropa/ParticleID.h" #include "gtest/gtest.h" namespace crpropa { //** ========================= Break conditions ============================= */ TEST(MinimumEnergy, test) { MinimumEnergy minEnergy(5); Candidate c; c.current.setEnergy(5.1); minEnergy.process(&c); EXPECT_TRUE(c.isActive()); c.current.setEnergy(4.9); minEnergy.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); }
double PerceptronModel::ScoreCandidate(Candidate &candidate, bool training) { bool use_raw = training; const FeatureVector<int,double> &model = models_.GetModel(use_raw); double score = kernel_fn_->Apply(model, candidate.features()); if (DEBUG >= 2) { cerr << "Time:" << time_.to_string() << ": scoring candidate " << candidate << " with " << (use_raw ? "raw" : "avg") << " model: " << model << endl << "\tscore: " << score << endl; } candidate.set_score(score); return score; }
void PartsBasedDetectorNode::messagePartsImage(const vectorCandidate& candidates, const std::vector< std::vector<cv::Point3d> >& parts_centers, Mat& rgb, const ImageConstPtr& msg_in) { // draw each part of a candidate Mat canvas; cv_bridge::CvImage container; const size_t nparts = candidates.size(); double part_x, part_y; cvtColor(rgb, canvas, COLOR_RGB2BGR); const size_t ncolors = candidates[0].parts().size(); vector<Scalar> colors; for (size_t n = 0; n < ncolors; ++n) { Mat color(Size(1,1), CV_32FC3); // Hue is in degrees, not radians (because consistency is over-rated) color.at<float>(0) = (360) / ncolors * n; color.at<float>(1) = 1.0; color.at<float>(2) = 0.7; cvtColor(color, color, COLOR_HSV2BGR); color = color * 255; colors.push_back(Scalar(color.at<float>(0), color.at<float>(1), color.at<float>(2))); } const int LINE_THICKNESS = 5; Scalar black(0,0,0); for (size_t n = 0; n < nparts; ++n) { Candidate candidate = candidates[n]; for (size_t p = 0; p < candidate.parts().size(); ++p) { part_x = parts_centers[n][p].x; part_y = parts_centers[n][p].y; rectangle(canvas, Point(part_x, part_y), Point(part_x, part_y), colors[p], LINE_THICKNESS); stringstream number_; number_ << (p+1); string part_number = number_.str(); putText(canvas, part_number, Point(part_x, part_y), FONT_HERSHEY_SIMPLEX, 0.5f, colors[p], 2); } } container.image = canvas; container.encoding = enc::RGB8; ImagePtr msg_out = container.toImageMsg(); msg_out->header.frame_id = msg_in->header.frame_id; msg_out->header.stamp = msg_in->header.stamp; image_pub_part_.publish(msg_out); }
TEST(LargeObserverSphere, detection) { // detect if the current position is outside and the previous inside of the sphere LargeObserverSphere obs(Vector3d(0, 0, 0), 10); Candidate c; // no detection: particle was outside already c.current.setPosition(Vector3d(11, 0, 0)); c.previous.setPosition(Vector3d(10.5, 0, 0)); obs.process(&c); EXPECT_TRUE(c.isActive()); EXPECT_FALSE(c.hasProperty("Detected")); // detection: particle just left c.current.setPosition(Vector3d(11, 0, 0)); c.previous.setPosition(Vector3d(9.5, 0, 0)); obs.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Detected")); }
void NgramFeatureExtractor::ExtractSymbolic(Candidate &candidate, FeatureVector<string,double> & symbolic_features) { vector<string> tokens; tokens.push_back("<s>"); tokenizer_.Tokenize(candidate.raw_data(), tokens); tokens.push_back("</s>"); ngram_extractor_.Extract(tokens, n_, prefix_, symbolic_features); }
/** Unit tests for break condition, observer, boundary and tool modules */ #include "crpropa/module/BreakCondition.h" #include "crpropa/module/Observer.h" #include "crpropa/module/Boundary.h" #include "crpropa/module/Tools.h" #include "crpropa/ParticleID.h" #include "gtest/gtest.h" namespace crpropa { //** ========================= Break conditions ============================= */ TEST(MinimumEnergy, test) { MinimumEnergy minEnergy(5); Candidate c; c.current.setEnergy(5.1); minEnergy.process(&c); EXPECT_TRUE(c.isActive()); c.current.setEnergy(4.9); minEnergy.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); } TEST(MaximumTrajectoryLength, test) { MaximumTrajectoryLength maxLength(10); Candidate c; c.setTrajectoryLength(9.9); maxLength.process(&c); EXPECT_TRUE(c.isActive()); c.setTrajectoryLength(10.1); maxLength.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); } TEST(MinimumRedshift, test) { MinimumRedshift minZ; // default minimum redshift of 0 Candidate c; c.setRedshift(0.1); minZ.process(&c); EXPECT_TRUE(c.isActive()); c.setRedshift(0); minZ.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); } //** ============================= Observers ================================ */ TEST(SmallObserverSphere, detection) { // detect if the current position is inside and the previous outside of the sphere SmallObserverSphere obs(Vector3d(0, 0, 0), 1); Candidate c; // no detection: particle was inside already c.current.setPosition(Vector3d(0.9, 0, 0)); c.previous.setPosition(Vector3d(0.95, 0, 0)); obs.process(&c); EXPECT_TRUE(c.isActive()); EXPECT_FALSE(c.hasProperty("Detected")); // detection: particle just entered c.current.setPosition(Vector3d(0.9, 0, 0)); c.previous.setPosition(Vector3d(1.1, 0, 0)); obs.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Detected")); }
void GA::gaUpdate(){ timer.stop(); myPop->nextGeneration(mutationChance, mutationAmout, breedingCutOffParents, genCount+1); Candidate fittest = myPop->getFittest(); if((genCount+1) % 10 == 0){ qDebug()<<"Generation:"<<genCount+1; qDebug()<<"Fittest:"<<fittest.getFitness(); } genCount++; /// DRAW FITTEST SET OF POLYGONS ON THE ACTUAL DRAWING! fittest.drawAllPolys(drawing); /// Update label my sending Pixmap via signal emit new_drawing_created(drawing); timer.start(); }
Population::Population(int s, int dlen, int dclen, int verts, int numPolys, QPixmap *original, QPixmap *drawing){ size = s; oPix = original; dPix = drawing; /// Initialising population with candidates Candidate::setDNALength(dlen); Candidate::setDNACrossedLength(dclen); Candidate::setPolyPts(verts); Candidate::setNumPolys(numPolys); Candidate *newCand; for(int i=0; i<size; i++){ //qDebug()<<"Population"<<i+1; newCand = new Candidate(oPix, dPix, 0); candidates.push_back(*newCand); // A new candidate is generated and pushed into the vector std::vector <float> newCandDna = newCand->getDnaValues(); qDebug()<<newCand->getGen()<<" | "<<i<<" | "<<newCand->getFitness()<<" | "<<newCandDna[0]<<newCandDna[1200]<<newCandDna[1600]; } }
// For some reason draws points instead of lines void Frame::drawMotion(MotionHandler * mh) { if (mh == NULL) return; if (mh->getState() == MotionHandler::RECORDING) { Motion motion = mh->getMotion(); if(motion.length() < 2) return; // Here's the problem - cur and last are the same Candidate *last = motion.getCandidate(0), *cur = motion.getCandidate(1); float lastX = last->getX(), lastY = last->getY(), x = cur->getX(), y = cur->getY(); cout << "last: " << lastX << ", " << lastY << endl; cout << "cur: " << x << ", " << y << endl; cvLine(motionTrack, cvPoint(x, y), cvPoint(lastX, lastY), cvScalar(0,0,255), 6); cvAdd(curFrame, motionTrack, curFrame); } }
TEST(ElectronPairProduction, energyDecreasing) { // Test if energy loss occurs for protons with energies from 1e15 - 1e23 eV Candidate c; c.setCurrentStep(2 * Mpc); c.current.setId(nucleusId(1, 1)); // proton ElectronPairProduction epp1(CMB); for (int i = 0; i < 80; i++) { double E = pow(10, 15 + i * 0.1) * eV; c.current.setEnergy(E); epp1.process(&c); EXPECT_LE(c.current.getEnergy(), E); } ElectronPairProduction epp2(IRB); for (int i = 0; i < 80; i++) { double E = pow(10, 15 + i * 0.1) * eV; c.current.setEnergy(E); epp2.process(&c); EXPECT_LE(c.current.getEnergy(), E); } }
TEST(MaximumTrajectoryLength, test) { MaximumTrajectoryLength maxLength(10); Candidate c; c.setTrajectoryLength(9.9); maxLength.process(&c); EXPECT_TRUE(c.isActive()); c.setTrajectoryLength(10.1); maxLength.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); }
TEST(MinimumRedshift, test) { MinimumRedshift minZ; // default minimum redshift of 0 Candidate c; c.setRedshift(0.1); minZ.process(&c); EXPECT_TRUE(c.isActive()); c.setRedshift(0); minZ.process(&c); EXPECT_FALSE(c.isActive()); EXPECT_TRUE(c.hasProperty("Rejected")); }
Candidate GA::PMXCrossover(const Candidate& p1, const Candidate& p2){ // std::cout << "Starting crossover\n"; int startPos = std::rand() % p1.getCandidate().size(); int endPos = -1; while(endPos == -1){ int tmpPos = std::rand() % p1.getCandidate().size(); if(tmpPos > startPos) endPos = tmpPos; else if(tmpPos < startPos){ endPos = startPos; startPos = tmpPos; } } // std::cout << "swath start: " << startPos << "\nswath end: " << endPos << "\n"; std::vector<City> child(p1.getCandidate().size()); std::vector<bool> childCompletion(p1.getCandidate().size()); //COPY RANDOM SWATH OF GENES //std::copy(p1.getCandidate().begin() + startPos, // p1.getCandidate().begin() + endPos, // child.begin() + startPos); // for(int i = startPos; i <= endPos; i++){ child[i] = p1.getCandidate().at(i); } //for(const auto& c : child){ // std::cout << c << "\n"; //} for(int i = startPos; i <= endPos; i++) childCompletion[i] = true; //FIND FIRST GENE IN PARENT 2 THAT WASN'T COPIED TO CHILD for(int i = startPos; i <= endPos; i++){ auto tmpGene = std::find(child.begin(), child.end(), p2.getCandidate().at(i)); if(tmpGene == child.end()){ int destPosition = PMXCrossover_FindDestPosition(p1.getCandidate(),p2.getCandidate(),startPos,endPos,i); // std::cout << "Place " << p2.getCandidate().at(i) << " at pos " << destPosition << "\n"; child[destPosition] = p2.getCandidate().at(i); childCompletion[destPosition] = true; } } for(int i = 0; i< child.size(); i++){ if(!childCompletion[i]) child[i] = p2.getCandidate().at(i); } Candidate result = Candidate(child, distances); if(!result.isUnique()){ for(const auto& c : result.getCandidate()) std::cout << c << "\n"; throw new std::logic_error("Invalid child sequence"); } return result; }
void DynamicProgram<T>::argmin(Parts& parts, const vector2DMat& rootv, const vector2DMat& rooti, const vectorf scales, const vector4DMat& Ix, const vector4DMat& Iy, const vector4DMat& Ik, vectorCandidate& candidates) { // for each scale, and each component, traverse back down the tree to retrieve the part positions int nscales = scales.size(); #ifdef _OPENMP #pragma omp parallel for #endif for (int n = 0; n < nscales; ++n) { T scale = scales[n]; for (int c = 0; c < parts.ncomponents(); ++c) { // get the scores and indices for this tree of parts const vector2DMat& Iknc = Ik[n][c]; const vector2DMat& Ixnc = Ix[n][c]; const vector2DMat& Iync = Iy[n][c]; int nparts = parts.nparts(c); // threshold the root score Mat over_thresh = rootv[n][c] > thresh_; Mat rootmix = rooti[n][c]; vectorPoint inds; find(over_thresh, inds); for (int i = 0; i < inds.size(); ++i) { Candidate candidate; vectori xv(nparts); vectori yv(nparts); vectori mv(nparts); for (int p = 0; p < nparts; ++p) { ComponentPart part = parts.component(c, p); // calculate the child's points from the parent's points int x, y, m; if (part.isRoot()) { x = xv[0] = inds[i].x; y = yv[0] = inds[i].y; m = mv[0] = rootmix.at<int>(inds[i]); } else { int idx = part.parent().self(); x = xv[idx]; y = yv[idx]; m = mv[idx]; xv[p] = Ixnc[p][m].at<int>(y,x); yv[p] = Iync[p][m].at<int>(y,x); mv[p] = Iknc[p][m].at<int>(y,x); } // calculate the bounding rectangle and add it to the Candidate Point ptwo = Point(2,2); Point pone = Point(1,1); Point xy1 = (Point(xv[p],yv[p])-ptwo)*scale; Point xy2 = xy1 + Point(part.xsize(m), part.ysize(m))*scale - pone; if (part.isRoot()) candidate.addPart(Rect(xy1, xy2), rootv[n][c].at<T>(inds[i])); else candidate.addPart(Rect(xy1, xy2), 0.0); } #ifdef _OPENMP #pragma omp critical(addcandidate) #endif { candidates.push_back(candidate); } } } } }