const DBSCAN::DistanceMatrix DBSCAN::calc_dist_matrix( const DBSCAN::ClusterData& C, const DBSCAN::FeaturesWeights& W ) { DBSCAN::ClusterData cl_d = C; omp_set_dynamic( 0 ); omp_set_num_threads( m_num_threads ); #pragma omp parallel for for ( size_t i = 0; i < cl_d.size2(); ++i ) { ublas::matrix_column< DBSCAN::ClusterData > col( cl_d, i ); const auto r = minmax_element( col.begin(), col.end() ); double data_min = *r.first; double data_range = *r.second - *r.first; if ( data_range == 0.0 ) { data_range = 1.0; } const double scale = 1 / data_range; const double min = -1.0 * data_min * scale; col *= scale; col.plus_assign( ublas::scalar_vector< typename ublas::matrix_column< DBSCAN::ClusterData >::value_type >( col.size(), min ) ); } // rows x rows DBSCAN::DistanceMatrix d_m( cl_d.size1(), cl_d.size1() ); ublas::vector< double > d_max( cl_d.size1() ); ublas::vector< double > d_min( cl_d.size1() ); omp_set_dynamic( 0 ); omp_set_num_threads( m_num_threads ); #pragma omp parallel for for ( size_t i = 0; i < cl_d.size1(); ++i ) { for ( size_t j = i; j < cl_d.size1(); ++j ) { d_m( i, j ) = 0.0; if ( i != j ) { ublas::matrix_row< DBSCAN::ClusterData > U( cl_d, i ); ublas::matrix_row< DBSCAN::ClusterData > V( cl_d, j ); int k = 0; for ( const auto e : ( U - V ) ) { d_m( i, j ) += fabs( e ) * W[k++]; } d_m( j, i ) = d_m( i, j ); } } const auto cur_row = ublas::matrix_row< DBSCAN::DistanceMatrix >( d_m, i ); const auto mm = minmax_element( cur_row.begin(), cur_row.end() ); d_max( i ) = *mm.second; d_min( i ) = *mm.first; } m_dmin = *( min_element( d_min.begin(), d_min.end() ) ); m_dmax = *( max_element( d_max.begin(), d_max.end() ) ); m_eps = ( m_dmax - m_dmin ) * m_eps + m_dmin; return d_m; }
std::vector<City> solve(const std::vector<Point>& points) override { std::set<City> outTourCities; for (size_t i = 0; i < points.size(); i++) { outTourCities.insert(i); } std::vector<Edge> edges; std::vector<City> startingTour = this->startingTour(points); for (Index i = 0; i < startingTour.size(); i++) { edges.push_back(Edge(startingTour[i], startingTour[(i+1)%startingTour.size()])); outTourCities.erase(startingTour[i]); } std::vector<Record> outTour; for (City c : outTourCities) { City c_in = *NearestPoint(points, startingTour.begin(), startingTour.end(), points[c]); outTour.push_back(Record(c, c_in, points[c].Distance(points[c_in]))); } size_t i = startingTour.size(); while (i < points.size()) { auto it = max_element(outTour.begin(), outTour.end()); Record r = *it; outTour.erase(it); typedef std::vector<Edge>::iterator EdgeIt; EdgeIt es[2]; bool b = 0; for (auto e_it = edges.begin(); e_it != edges.end(); e_it++) { if (e_it->hasCity(r.nearestInTourCity)) { es[b] = e_it; b = !b; } } assert(b==0); EdgeIt removingEdge = min(es[0], es[1], [&](const EdgeIt& e_0, const EdgeIt& e_1) { auto &ps = points; return -ps[e_0->at(0)].Distance(ps[e_0->at(1)]) +ps[e_0->otherCity(r.nearestInTourCity)].Distance(ps[r.outTourCity]) < -ps[e_1->at(0)].Distance(ps[e_1->at(1)]) +ps[e_1->otherCity(r.nearestInTourCity)].Distance(ps[r.outTourCity]); }); City c = removingEdge->otherCity(r.nearestInTourCity); edges.erase(removingEdge); edges.push_back(Edge(c, r.outTourCity)); edges.push_back(Edge(r.nearestInTourCity, r.outTourCity)); for (Record& out_r : outTour) { double d = points[r.outTourCity].Distance(points[out_r.outTourCity]); if (out_r.distance > d) { out_r.nearestInTourCity = r.outTourCity; out_r.distance = d; } } i++; } return edgesToTour(edges); }
void CrossParam::ComputeUintedDistortion() { printf("Compute United Distortion!\n"); FindVtxMappingForVtxInSurface1(); FindVtxMappingForVtxInSurface2(); ParamDistortion param_distortion_1(m_param_1); ParamDistortion param_distortion_2(m_param_2); const boost::shared_ptr<MeshModel> p_mesh_1 = m_param_1.GetMeshModel(); const PolyIndexArray& face_index_array_1 = p_mesh_1->m_Kernel.GetFaceInfo().GetIndex(); const CoordArray& vtx_coord_array_1 = p_mesh_1->m_Kernel.GetVertexInfo().GetCoord(); const boost::shared_ptr<MeshModel> p_mesh_2 = m_param_2.GetMeshModel(); const PolyIndexArray& face_index_array_2 = p_mesh_2->m_Kernel.GetFaceInfo().GetIndex(); int face_num_2 = p_mesh_2->m_Kernel.GetModelInfo().GetFaceNum(); m_united_distortion.clear(); m_united_distortion.resize(face_num_2); for(int k=0; k<face_num_2; ++k) { const IndexArray& face_index = face_index_array_2[k]; /// the three vertices's position coordinate in mesh 1 vector<Coord> new_vtx_pos_coord(3); /// the three vertices's parameter coordinate, same in two mesh vector<ParamCoord> vtx_param_coord(3); /// for computing the jacobi matrix, we need three vertices's parameter coordinate in the same chart //int chart_id = m_param_2.GetFaceChartID(k); int chart_id = m_param_2.GetVertexChartID(face_index[0]); for(int i=0; i<3; ++i) { int vtx_idx = face_index[i]; ParamCoord param_coord = m_param_2.GetParamCoord(vtx_idx); int cur_chart_id = m_param_2.GetVertexChartID(vtx_idx); if(cur_chart_id != chart_id) { m_param_2.TransParamCoordBetweenTwoChart(cur_chart_id, chart_id, param_coord, vtx_param_coord[i]); }else { vtx_param_coord[i] = param_coord; } int face_id_in_mesh_1 = m_vtx_face_in_mesh_1[vtx_idx]; Coord barycentric = m_vtx_barycentric_in_mesh_1[vtx_idx]; const IndexArray& face_in_mesh_1 = face_index_array_1[face_id_in_mesh_1]; vector<Coord> vtx_coord_in_mesh_1(3); for(size_t j=0; j<3; ++j) { int vtx = face_in_mesh_1[j]; vtx_coord_in_mesh_1[j] = vtx_coord_array_1[vtx]; } new_vtx_pos_coord[i] = ParamDistortion::ComputePosWithBarycentric(vtx_coord_in_mesh_1, barycentric); } /// J_m = (J_m_2)^-1 * J_m_1 const zjucad::matrix::matrix<double>& jacobi_1 = param_distortion_1.ComputeTriJacobiMatrix(new_vtx_pos_coord, vtx_param_coord); zjucad::matrix::matrix<double> inv_jacobi_1(jacobi_1); if(!inv(inv_jacobi_1)) { printf("compute inv jacobi matrix 1 fail.%d\n", k); } const zjucad::matrix::matrix<double>& jacobi_2 = param_distortion_2.ComputeTriJacobiMatrix(k); //printf("sum: %d: %lf, %lf\n", k, sum(jacobi_2), sum(inv_jacobi_1)); zjucad::matrix::matrix<double> united_jacobi = jacobi_2*inv_jacobi_1; zjucad::matrix::matrix<double> J_tJ = trans(united_jacobi)*united_jacobi; //inv(J_tJ); zjucad::matrix::matrix<double> i_mat (zjucad::matrix::eye<double>(2)); /// isometric maps m_united_distortion[k] = norm(J_tJ - i_mat); /// harmonic maps m_united_distortion[k] = 0.5*(J_tJ(0, 0) + J_tJ(1, 1)); } vector<double>::iterator min_it = min_element(m_united_distortion.begin(), m_united_distortion.end()); vector<double>::iterator max_it = max_element(m_united_distortion.begin(), m_united_distortion.end()); printf("The min distortion is %d %lf\n", (min_it - m_united_distortion.begin()), *min_it); printf("The max distortion is %d %lf\n", (max_it - m_united_distortion.begin()), *max_it); printf("The total distortion is %lf\n", accumulate(m_united_distortion.begin(), m_united_distortion.end(), 0.0)); //copy(m_united_distortion.begin(), m_united_distortion.end(), ostream_iterator<double>(cout, " ")); }
int smallest_nonzero() const { int om = omin; while ((om < order_max()) && (max_element(abs(_data(om - omin, ellipsis()))) < 1.e-10)) om++; return om; }
static void process_region(img** volume, img** orig, ushort thresh, vector<ushort>& rar, vector<ushort>& car, vector<ushort>& zar) { static num dmap[6][512][512]; // if the region is too small... if (rar.size() < 600) { cout << "--> deleted an unlikely region (size: " << rar.size() << ")\n"; return; } // if the region spans too many slices vertically... int region_zmin = *min_element(zar.begin(), zar.end()); if (*max_element(zar.begin(), zar.end()) - region_zmin > 5) { dp("--> deleted an unlikely region (z-interval > 5)"); return; } // find the boundary of the region vector<ushort> edge_rar, edge_car, edge_zar; for (ushort i=0; i < zar.size(); ++i) { for (ushort q=zar[i]-1; q < zar[i]+2; ++q) { for (ushort k=rar[i]-1; k < rar[i]+2; ++k) { for (ushort j=car[i]-1; j < car[i]+2; ++j) { if (volume[q]->pix[k][j] == white) { edge_rar.push_back(rar[i]); edge_car.push_back(car[i]); edge_zar.push_back(zar[i]); volume[zar[i]]->pix[rar[i]][car[i]] = 0; break; } } if (volume[zar[i]]->pix[rar[i]][car[i]] == 0) { break; } } if (volume[zar[i]]->pix[rar[i]][car[i]] == 0) { break; } } } ar("--> region-boundary z-vec", edge_zar, edge_zar.size()); // create a distance map uint blen = edge_rar.size(); num *erar, *ecar, *ezar, *dvec, *tmp; try { erar = new num[blen]; ecar = new num[blen]; ezar = new num[blen]; dvec = new num[blen]; tmp = new num[blen]; } catch (bad_alloc& err) { dp("Fatal memory allocation error; results may be unreliable!"); return; } for (uint i=0; i < blen; ++i) { // copy the boundary voxels into num-arrays to make things simple erar[i] = (num) edge_rar[i]; ecar[i] = (num) edge_car[i]; ezar[i] = (num) edge_zar[i]; } // find the minimum distance from the boundary for each point for (uint i=0; i < zar.size(); ++i) { mat_op(erar, (num) rar[i], blen, sub, tmp); mat_op(tmp, dx, blen, mul, tmp); m_apply(tmp, square, blen, dvec); mat_op(ecar, (num) car[i], blen, sub, tmp); mat_op(tmp, dy, blen, mul, tmp); m_apply(tmp, square, blen, tmp); mat_op(tmp, dvec, blen, add, dvec); mat_op(ezar, (num) zar[i], blen, sub, tmp); mat_op(tmp, dz, blen, mul, tmp); m_apply(tmp, square, blen, tmp); mat_op(tmp, dvec, blen, add, dvec); m_apply(dvec, sqrt, blen, dvec); // store the distance into the distance map dmap[zar[i] - region_zmin][rar[i]][car[i]] = *min_element(dvec, dvec+blen); } // find the 'centroid' of the region num cen_max = 0; ushort cenz=0, cenx=0, ceny=0; for (ushort i=0; i < zar.size(); ++i) { num cur_val = dmap[zar[i] - region_zmin][rar[i]][car[i]]; if (cur_val > cen_max) { cen_max = cur_val; cenz = zar[i] - region_zmin; cenx = rar[i]; ceny = car[i]; } } cout << "--> region centroid: [" << cenx << ", " << ceny << ", " << region_zmin + cenz << "]\n"; // find the variance of the distance from the boundary to the centroid for (ushort i=0; i < blen; ++i) { tmp[i] = sqrt(square((erar[i] - cenx) * dx) + square((ecar[i] - ceny) * dy) + square((ezar[i] - cenz) * dz)); } num edge_u = sum_of(tmp, blen) / blen; mat_op(tmp, edge_u, blen, sub, tmp); m_apply(tmp, square, blen, tmp); num stddev = sqrt(sum_of(tmp, blen) / blen); cout << "--> (stddev, mean) distance from centroid: (" << stddev << ", " << edge_u << ")\n"; /* My thinking is that 85% or more of the distances should lie within 3 to * 7 units of the mean distance to have a sphere (roughly). According to * Chebyshev's rule [p = 1 - k^-2 => k = sqrt(1 / (1 - p))], 85% of the * distances should lie within 2.582 standard deviations of the mean * distance. So to be spherical, 3 < u - [u - (2.582 * stddev)] < 7. */ num dist_delta = edge_u - (edge_u - (CHEBY_DELTA * stddev)); bool tumor = (dist_delta > 3) && (dist_delta < 7); cout << "--> dist_delta: " << dist_delta << endl; cout << "--> size: " << rar.size() << endl; if (tumor) { uint64_t sum_shade = 0; for (uint i=0; i < zar.size(); ++i) { sum_shade += orig[zar[i]]->pix[rar[i]][car[i]]; } tumor = (sum_shade / zar.size()) > thresh; // 67% empirically } for (uint i=0; i < zar.size(); ++i) { volume[zar[i]]->pix[rar[i]][car[i]] = tumor ? 1 : BENIGN; } cout << "--> " << tumor << " tumor.\n"; delete[] dvec; delete[] tmp; delete[] erar; delete[] ecar; delete[] ezar; }
void FrequencyQueue::last_max(){ auto it = max_element(internal_vector.begin(), internal_vector.end(), directsort); put_last_queue_element(it); };
bool CppIterCHT (vector < unsigned int >originImage, vector < unsigned int >dim_originImage, unsigned int maxR, vector < unsigned int >&edgeImage, vector < unsigned int >&dim_edgeImage, vector < unsigned int >&result_row, vector < unsigned int >&result_col, vector < unsigned int >&result_r, vector < unsigned int >&result_peak) { // result_row, result_col: based from 0. //mxArray *prhs[1], *plhs[1]; //double *tempGetPr; //mxLogical *tempGetLogicals; if (!(dim_originImage.size () == 2 && dim_edgeImage.size () == 2)) { #ifdef MATLABPRINT mexPrintf ("CppIterCHT ==> inputs are invalid, failed!\n"); #endif return false; } edgeImage.clear (); edgeImage.resize (originImage.size ()); copy (originImage.begin (), originImage.end (), edgeImage.begin ()); dim_edgeImage[0] = dim_originImage[0]; dim_edgeImage[1] = dim_originImage[1]; vector < unsigned int >accumulator (edgeImage.size (), 0); vector < unsigned int >rarray (edgeImage.size (), 0), peakarray (edgeImage.size (), 0); unsigned int currentrow, currentcol, edgecellnum = 0; //prhs[0]=mxCreateDoubleMatrix(dim_edgeImage[0], dim_edgeImage[1], mxREAL); // used for calling MATLAB function "imregionalmax" for (unsigned int rcount = 1; rcount <= maxR; rcount++) { accumulator.assign (accumulator.size (), 0); edgecellnum = 0; for (unsigned int pcount = 0; pcount < edgeImage.size (); pcount++) { if (edgeImage[pcount] != 0) // the pixel is on the edge { // draw circle with center at the pixel and radius rcount in accumulator. currentrow = MatrixLZ::ind2subrow (pcount, dim_edgeImage[0], dim_edgeImage[1], MatrixLZ::ColMajor); currentcol = MatrixLZ::ind2subcol (pcount, dim_edgeImage[0], dim_edgeImage[1], MatrixLZ::ColMajor); CppRasterCircle (currentcol + 1, currentrow + 1, rcount, accumulator, dim_edgeImage); edgecellnum += 1; } } for (unsigned int i = 0; i < accumulator.size (); i++) { if (accumulator[i] > peakarray[i]) { rarray[i] = rcount; peakarray[i] = accumulator[i]; } } //tempGetPr=mxGetPr(prhs[0]); //for (unsigned i=0; i<accumulator.size(); i++) //{ // tempGetPr[i]=static_cast<double>(accumulator[i]); //} //mexCallMATLAB(1, plhs, 1, prhs, "imregionalmax"); //tempGetLogicals=mxGetLogicals(plhs[0]); //for (unsigned int i=0; i<accumulator.size(); i++) //{ // if (tempGetLogicals[i] && accumulator[i]>peakarray[i]) // { // rarray[i]=rcount; // peakarray[i]=accumulator[i]; // } //} //mxDestroyArray(plhs[0]); } //mxDestroyArray(prhs[0]); unsigned int maxpeak; maxpeak = *(max_element (peakarray.begin (), peakarray.end ())); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // the threshold used to determine whether local peak indicates a // circle. If the local peak value is no less than maximum local peak // value and no less than 0.1*(number of cells on edge), it is deemed to // be a circle center in the image. result_row.clear (); result_col.clear (); result_r.clear (); result_peak.clear (); for (unsigned int i = 0; i < peakarray.size (); i++) { if (peakarray[i] >= 1 * maxpeak && peakarray[i] >= static_cast < unsigned int >(0.1 * edgecellnum + 0.5)) { currentrow = MatrixLZ::ind2subrow (i, dim_edgeImage[0], dim_edgeImage[1], MatrixLZ::ColMajor); currentcol = MatrixLZ::ind2subcol (i, dim_edgeImage[0], dim_edgeImage[1], MatrixLZ::ColMajor); result_row.push_back (currentrow); result_col.push_back (currentcol); result_r.push_back (rarray[i]); result_peak.push_back (peakarray[i]); } } return true; }
int state::put_piece(const piece* p, const int x, const int y) { static const int fsX = static_cast<int>(field_size_X); static const int fsY = static_cast<int>(field_size_Y); static const int psX = static_cast<int>(piece::size_X); static const int psY = static_cast<int>(piece::size_Y); int i0 = (x < 0)? -x: 0; int j0 = (y < 0)? -y: 0; int i1 = (x+psX > fsX)? psX - ((x+psX) - fsX): psX; int j1 = (y+psY > fsY)? psY - ((y+psY) - fsY): psY; int r0 = 0,r1 = 0,r2 = 0; if (p->x0 < i0) return 4; if (i1 +1 < p->x1) return 4; if (p->y0 < j0) return 4; if (j1 +1 < p->y1) return 4; for (size_t j = j0; j < j1; j++) { for (size_t i = i0; i < i1; i++) { face[y+j][x+i] += p->face_at(i,j); r0 += face[y+j][x+i]; r1 += face[y+j][x+i] * field_mask[(y+j)*(fsX)+(x+i)]; }} if (r0 != r1) { return 1; } char a = max_element(*face, sizeof(face)); if ( a != 1 ) { return 2; } for (size_t j = j0; j < j1; j++) { for (size_t i = i0; i < i1+1; i++) { edge_x[y+j][x+i] += p->edge_x[j][i]; }} for (size_t j = j0; j < j1+1; j++) { for (size_t i = i0; i < i1; i++) { edge_y[y+j][x+i] += p->edge_y[j][i]; }} char b = max_element(*edge_x,sizeof(edge_x)); char c = max_element(*edge_y,sizeof(edge_y)); if (zk_count != 0 && (b == 2 || c == 2)) { } else if (zk_count == 0) { } else { return 3; } // update edges for (size_t j = j0; j < j1; j++) { for (size_t i = i0; i < i1+1; i++) { edge_x[y+j][x+i] = std::min(char(1),edge_x[y+j][x+i]); }} for (size_t j = j0; j < j1+1; j++) { for (size_t i = i0; i < i1; i++) { edge_y[y+j][x+i] = std::min(char(1),edge_y[y+j][x+i]); }} for (int j = j0; j < j1; j++) { for (int i = i0; i < i1; i++) { spaced[y+j] -= p->face_at(i,j); } } if (zk_count != 0) { x0 = std::min(x0,p->x0 + x); x1 = std::max(x1,p->x1 + x); y0 = std::min(y0,p->y0 + y); y1 = std::max(y1,p->y1 + y); } else { x0 = p->x0 + x; x1 = p->x1 + x; y0 = p->y0 + y; y1 = p->y1 + y; } zk_count += p->zk_count; put_count += 1; return 0; }
void RegionMerger::detectEdges(){ // multi-scale edge detection, sum the responses int s; vector<float> h(3), v(3, 1.0); h[0] = -(h[2]=1); h[1]=0; edgeimg = img->accessFrame()->absolute_gradient(h, v); edgeimg.force_one_channel(); vector<float> edata=edgeimg.get_float(); for(s=1;s<=16;s*=2){ if(Verbose()>1) cout << "processing scale " << s << endl; vector<float> blurflt(2*s+1,1.0/(2*s+1)); imagedata blurimg=img->accessFrame()->convolve(blurflt,blurflt,1.0,true); char fn[80]; sprintf(fn,"blur-%d.tiff",s); imagefile::write(blurimg,fn); // get gradient magnitude vector<float> h(3), v(3, 1.0); h[0] = -(h[2]=1); imagedata gradimg = blurimg.absolute_gradient(h, v); gradimg.force_one_channel(); sprintf(fn,"grad-%d.tiff",s); imagefile::write(gradimg,fn); vector<float> gdata=gradimg.get_float(); if (edata.size() != gdata.size()) throw string("RegionMerger::detectEdges(): size mismatch"); for (size_t i=0; i<gdata.size(); i++) edata[i] += gdata[i]; } if(Verbose()>1) cout << "multi-scale finished" << endl; edgeimg.set(edata); // filter edgeimg with box filter const int boxD=5; vector<float> boxMask(boxD,1.0); edgeimg=edgeimg.convolve(boxMask,boxMask); // normalise the edge image to max=1 vector<float> imgd=edgeimg.get_float(); edgeimg=edgeimg.multiply(1.0/ *max_element(imgd.begin(),imgd.end())); //cout << "writing edge image to file edgeimg.tiff" << endl; //imagefile::write(edgeimg,"edgeimg.tiff"); }
/// is_gf_real(g, tolerance). Returns true iif the function g is real up to tolerance template <typename G> bool is_gf_real(G const &g, double tolerance = 1.e-13) { return max_element(abs(imag(g.data()))) <= tolerance; }
constexpr const char *max_element(const char *a, const char *b) { return (a+1 >= b) ? a : max_iter(a, max_element(a+1, b)); }
FoMo::RenderCube CGALinterpolation(FoMo::GoftCube goftcube, Delaunay_triangulation_3* DTpointer, const double l, const double b, const int x_pixel, const int y_pixel, const int z_pixel, const int lambda_pixel, const double lambda_width) { // // results is an array of at least dimension (x2-x1+1)*(y2-y1+1)*lambda_pixel and must be initialized to zero // // determine contributions per pixel typedef K::FT Coord_type; typedef K::Point_3 Point; std::map<Point, Coord_type, K::Less_xyz_3> peakmap, fwhmmap, losvelmap; // typedef CGAL::Data_access< std::map<Point, Coord_type, K::Less_xyz_3 > > Value_access; int commrank; #ifdef HAVEMPI MPI_Comm_rank(MPI_COMM_WORLD,&commrank); #else commrank = 0; #endif //FoMo::DataCube goftcube=object.datacube; FoMo::tgrid grid = goftcube.readgrid(); int ng=goftcube.readngrid(); // We will calculate the maximum image coordinates by projecting the grid onto the image plane // Rotate the grid over an angle -l (around z-axis), and -b (around y-axis) // Take the min and max of the resulting coordinates, those are coordinates in the image plane if (commrank==0) std::cout << "Rotating coordinates to POS reference... " << std::flush; std::vector<double> xacc, yacc, zacc; xacc.resize(ng); yacc.resize(ng); zacc.resize(ng); std::vector<double> gridpoint; gridpoint.resize(3); Point temporarygridpoint; // Define the unit vector along the line-of-sight std::vector<double> unit = {sin(b)*cos(l), -sin(b)*sin(l), cos(b)}; // Read the physical variables FoMo::tphysvar peakvec=goftcube.readvar(0);//Peak intensity FoMo::tphysvar fwhmvec=goftcube.readvar(1);// line width, =1 for AIA imaging FoMo::tphysvar vx=goftcube.readvar(2); FoMo::tphysvar vy=goftcube.readvar(3); FoMo::tphysvar vz=goftcube.readvar(4); double losvelval; // No openmp possible here // Because of the insertions at the end of the loop, we get segfaults :( /*#ifdef _OPENMP #pragma omp parallel for #endif*/ for (int i=0; i<ng; i++) { for (int j=0; j<3; j++) gridpoint[j]=grid[j][i]; xacc[i]=gridpoint[0]*cos(b)*cos(l)-gridpoint[1]*cos(b)*sin(l)-gridpoint[2]*sin(b);// rotated grid yacc[i]=gridpoint[0]*sin(l)+gridpoint[1]*cos(l); zacc[i]=gridpoint[0]*sin(b)*cos(l)-gridpoint[1]*sin(b)*sin(l)+gridpoint[2]*cos(b); temporarygridpoint=Point(grid[0][i],grid[1][i],grid[2][i]); //position vector // also create the map function_values here std::vector<double> velvec = {vx[i], vy[i], vz[i]};// velocity vector losvelval = inner_product(unit.begin(),unit.end(),velvec.begin(),0.0);//velocity along line of sight for position [i]/[ng] losvelmap[temporarygridpoint]=Coord_type(losvelval); peakmap[temporarygridpoint]=Coord_type(peakvec[i]); fwhmmap[temporarygridpoint]=Coord_type(fwhmvec[i]); /* peakmap.insert(make_pair(temporarygridpoint,Coord_type(peakvec[i]))); fwhmmap.insert(make_pair(temporarygridpoint,Coord_type(fwhmvec[i]))); losvelmap.insert(make_pair(temporarygridpoint,Coord_type(losvelval)));*/ } double minz=*(min_element(zacc.begin(),zacc.end())); double maxz=*(max_element(zacc.begin(),zacc.end())); double minx=*(min_element(xacc.begin(),xacc.end())); double maxx=*(max_element(xacc.begin(),xacc.end())); double miny=*(min_element(yacc.begin(),yacc.end())); double maxy=*(max_element(yacc.begin(),yacc.end())); /* Value_access peak=Value_access(peakmap); Value_access fwhm=Value_access(fwhmmap); Value_access losvel=Value_access(losvelmap);*/ xacc.clear(); // release the memory yacc.clear(); zacc.clear(); if (commrank==0) std::cout << "Done!" << std::endl; std::string chiantifile=goftcube.readchiantifile(); double lambda0=goftcube.readlambda0();// lambda0=AIA bandpass for AIA imaging double lambda_width_in_A=lambda_width*lambda0/speedoflight; if (commrank==0) std::cout << "Building frame: " << std::flush; double x,y,z,intpolpeak,intpolfwhm,intpollosvel,lambdaval,tempintens; int li,lj,ind; Point p,nearest; Delaunay_triangulation_3::Vertex_handle v; Delaunay_triangulation_3::Locate_type lt; Delaunay_triangulation_3::Cell_handle c_old,c_new; bool could_lock_zone=false; boost::progress_display show_progress(x_pixel*y_pixel*z_pixel); //initialize grids FoMo::tgrid newgrid; FoMo::tcoord xvec(x_pixel*y_pixel*lambda_pixel),yvec(x_pixel*y_pixel*lambda_pixel),lambdavec(x_pixel*y_pixel*lambda_pixel); newgrid.push_back(xvec); newgrid.push_back(yvec); if (lambda_pixel > 1) newgrid.push_back(lambdavec); FoMo::tphysvar intens(x_pixel*y_pixel*lambda_pixel,0); #ifdef _OPENMP #pragma omp parallel for schedule(dynamic) collapse(2) private (x,y,z,p,lt,li,lj,v,nearest,intpolpeak,intpolfwhm,intpollosvel,lambdaval,tempintens,ind,could_lock_zone,c_old,c_new) #endif for (int i=0; i<y_pixel; i++) for (int j=0; j<x_pixel; j++) { #ifdef _OPENMP #pragma omp task #endif for (int k=0; k<z_pixel; k++) // scanning through ccd { x = double(j)/(x_pixel-1)*(maxx-minx)+minx; y = double(i)/(y_pixel-1)*(maxy-miny)+miny; z = double(k)/(z_pixel-1)*(maxz-minz)+minz; // calculate the interpolation in the original frame of reference // i.e. derotate the point using angles -l and -b p={x*cos(b)*cos(l)+y*sin(l)+z*sin(b)*cos(l),-x*cos(b)*sin(l)+y*cos(l)-z*sin(b)*sin(l),-x*sin(b)+z*cos(b)}; #if CGAL_VERSION_NR >= CGAL_VERSION_NUMBER(4,4,0) // This is the proper way of doing a parallel location, in order to avoid collisions // Should we release the locks somehow? while (!could_lock_zone) { c_new=DTpointer->locate(p, lt, li, lj, c_old, &could_lock_zone); } c_old=c_new; could_lock_zone=false; #else c_new=DTpointer->locate(p, lt, li, lj, c_old); c_old=c_new; #endif // Only look for the nearest point and interpolate, if the point p is inside the convex hull. if (lt!=Delaunay_triangulation_3::OUTSIDE_CONVEX_HULL) { v=DTpointer->nearest_vertex_in_cell(p,c_new); nearest=v->point(); /* This is how it is done in the CGAL examples pair<Coord_type,bool> tmppeak=peak(nearest); pair<Coord_type,bool> tmpfwhm=fwhm(nearest); pair<Coord_type,bool> tmplosvel=losvel(nearest); intpolpeak=tmppeak.first; intpolfwhm=tmpfwhm.first; intpollosvel=tmplosvel.first;*/ intpolpeak=peakmap[nearest]; intpolfwhm=fwhmmap[nearest]; intpollosvel=losvelmap[nearest]; } else { intpolpeak=0; } if (lambda_pixel>1)// spectroscopic study { for (int il=0; il<lambda_pixel; il++) // changed index from global variable l into il [D.Y. 17 Nov 2014] { // lambda the relative wavelength around lambda0, with a width of lambda_width lambdaval=double(il)/(lambda_pixel-1)*lambda_width_in_A-lambda_width_in_A/2.; tempintens=intpolpeak*exp(-pow(lambdaval-intpollosvel/speedoflight*lambda0,2)/pow(intpolfwhm,2)*4.*log(2.)); ind=(i*(x_pixel)+j)*lambda_pixel+il;// newgrid.at(0).at(ind)=x; newgrid.at(1).at(ind)=y; newgrid.at(2).at(ind)=lambdaval+lambda0; // store the full wavelength // this is critical, but with tasks, the ind is unique for each task, and no collision should occur intens.at(ind)+=tempintens;// loop over z and lambda [D.Y 17 Nov 2014] } } if (lambda_pixel==1) // AIA imaging study. Algorithm not verified [DY 14 Nov 2014] { tempintens=intpolpeak; ind=(i*x_pixel+j); newgrid[0][ind]=x; newgrid[1][ind]=y; intens[ind]+=tempintens; // loop over z [D.Y 17 Nov 2014] } // print progress ++show_progress; } } if (commrank==0) std::cout << " Done! " << std::endl << std::flush; FoMo::RenderCube rendercube(goftcube); FoMo::tvars newdata; double pathlength=(maxz-minz)/(z_pixel-1); intens=FoMo::operator*(pathlength*1e8,intens); // assume that the coordinates are given in Mm, and convert to cm newdata.push_back(intens); rendercube.setdata(newgrid,newdata); rendercube.setrendermethod("CGAL"); rendercube.setresolution(x_pixel,y_pixel,z_pixel,lambda_pixel,lambda_width); if (lambda_pixel == 1) { rendercube.setobservationtype(FoMo::Imaging); } else { rendercube.setobservationtype(FoMo::Spectroscopic); } return rendercube; }
void SumProduct::accumulateEigenCounts (vguard<vguard<double> >& rootCounts, vguard<vguard<vguard<gsl_complex> > >& eigenCounts, double weight) const { LogThisAt(8,"Accumulating eigencounts, column " << join(gappedCol,"") << ", weight " << weight << endl); accumulateRootCounts (rootCounts, weight); const auto rootNode = columnRoot(); const int A = model.alphabetSize(); vguard<double> U (A), D (A); vguard<gsl_complex> Ubasis (A), Dbasis (A); vguard<double> U0 (A), D0 (A); for (auto node : ungappedRows) if (node != rootNode) { LogThisAt(9,"Accumulating eigencounts, column " << join(gappedCol,"") << " node " << tree.seqName(node) << endl); const TreeNodeIndex parent = tree.parentNode(node); const TreeNodeIndex sibling = tree.getSibling(node); for (int cpt = 0; cpt < components(); ++cpt) { LogThisAt(9,"Accumulating eigencounts, column " << join(gappedCol,"") << " node " << tree.seqName(node) << " component #" << cpt << endl); const vguard<double>& U0 = F[cpt][node]; for (AlphTok i = 0; i < A; ++i) D0[i] = G[cpt][parent][i] * E[cpt][sibling][i]; const double maxU0 = *max_element (U0.begin(), U0.end()); const double maxD0 = *max_element (D0.begin(), D0.end()); const double norm = exp (colLogLike - logCptWeight[cpt] - logF[cpt][node] - logG[cpt][parent] - logE[cpt][sibling]) / (maxU0 * maxD0); // U[b] = U0[b] / maxU0; Ubasis[l] = sum_b U[b] * evecInv[l][b] for (AlphTok b = 0; b < A; ++b) U[b] = U0[b] / maxU0; for (AlphTok l = 0; l < A; ++l) { Ubasis[l] = gsl_complex_rect (0, 0); for (AlphTok b = 0; b < A; ++b) Ubasis[l] = gsl_complex_add (Ubasis[l], gsl_complex_mul_real (gsl_matrix_complex_get (eigen.evecInv[cpt], l, b), U[b])); } // D[a] = D0[a] / maxD0; Dbasis[k] = sum_a D[a] * evec[a][k] for (AlphTok a = 0; a < A; ++a) D[a] = D0[a] / maxD0; for (AlphTok k = 0; k < A; ++k) { Dbasis[k] = gsl_complex_rect (0, 0); for (AlphTok a = 0; a < A; ++a) Dbasis[k] = gsl_complex_add (Dbasis[k], gsl_complex_mul_real (gsl_matrix_complex_get (eigen.evec[cpt], a, k), D[a])); } // R = evec * evals * evecInv // exp(RT) = evec * exp(evals T) * evecInv // count(i,j|a,b,T) = Q / exp(RT)_ab // where... // Q = \sum_a \sum_b \int_{t=0}^T D_a exp(Rt)_ai R_ij exp(R(T-t))_jb U_b dt // = \sum_a \sum_b \int_{t=0}^T D_a (\sum_k evec_ak exp(eval_k t) evecInv_ki) R_ij (\sum_l evec_jl exp(eval_l (T-t)) evecInv_lb) U_b dt // = \sum_a \sum_b D_a \sum_k evec_ak evecInv_ki R_ij \sum_l evec_jl evecInv_lb U_b \int_{t=0}^T exp(eval_k t) exp(eval_l (T-t)) dt // = \sum_a \sum_b D_a \sum_k evec_ak evecInv_ki R_ij \sum_l evec_jl evecInv_lb U_b eigenSubCount(k,l,T) // = R_ij \sum_k evecInv_ki \sum_l evec_jl (\sum_a D_a evec_ak) (\sum_b U_b evecInv_lb) eigenSubCount(k,l,T) // = R_ij \sum_k evecInv_ki \sum_l evec_jl Dbasis_k Ubasis_l eigenSubCount(k,l,T) // eigenCounts[k][l] += Dbasis[k] * eigenSub[k][l] * Ubasis[l] / norm for (AlphTok k = 0; k < A; ++k) for (AlphTok l = 0; l < A; ++l) eigenCounts[cpt][k][l] = gsl_complex_add (eigenCounts[cpt][k][l], gsl_complex_mul_real (gsl_complex_mul (Dbasis[k], gsl_complex_mul (gsl_matrix_complex_get (branchEigenSubCount[cpt][node], k, l), Ubasis[l])), weight / norm)); // LogThisAt(9,"colLogLike=" << colLogLike << " logF[cpt][node]=" << logF[cpt][node] << " logG[cpt][parent]=" << logG[cpt][parent] << " logE[cpt][sibling]=" << logE[cpt][sibling] << " maxU0=" << maxU0 << " maxD0=" << maxD0 << endl); // LogThisAt(8,"Component #" << cpt << " eigencounts matrix (norm=" << norm << "):" << endl << complexMatrixToString(eigenCounts[cpt]) << endl); } } }
AlphTok SumProduct::maxPostState (AlignRowIndex node) const { const auto lpp = logNodePostProb (node); return (AlphTok) (max_element(lpp.begin(),lpp.end()) - lpp.begin()); }
void radixSort(int arr[], int n) { int maxx = *max_element(arr, arr+n); for (int mul = 1; maxx/mul > 0; mul *= 10) countSort(arr, n, mul); }
bool PeakPicker::process( const vector< float > & vfMS2TimeInput, const vector< float > & vfRetentionTimeInput, vector< double > & vdTreatmentChroInput, vector< double > & vdReferenceChroInput ) { iChroLength = vfRetentionTimeInput.size(); if ( iChroLength <= ProRataConfig::getPeakPickerWindowSize() ) { cout << "ERROR! The input chromatograms have too few MS1 scans!" << endl; return false; } if( vdTreatmentChroInput.size() != iChroLength || vdReferenceChroInput.size() != iChroLength ) { cout << "ERROR! the input chromatograms are in different length!" << endl; return false; } if ( ( ProRataConfig::getPeakPickerWindowSize() % 2) == 0 ) { cout << "ERROR! The window size for Sav-Gol smoothing has to be odd! " << endl; return false; } if ( ProRataConfig::getPeakPickerWindowSize() < 3 ) { cout << "ERROR! The window size for Sav-Gol smoothing is too small! " << endl; return false; } vfRetentionTime = vfRetentionTimeInput; // set the earliest MS2 time and the last MS2 scan time // used for initialize left valley and right valley fLeftMS2Time = *( min_element( vfMS2TimeInput.begin(), vfMS2TimeInput.end() ) ); fRightMS2Time = *( max_element( vfMS2TimeInput.begin(), vfMS2TimeInput.end() ) ); // the fLeftMS2Time and fRightMS2Time have to be within the RT range if( fLeftMS2Time < vfRetentionTime.front() ) fLeftMS2Time = vfRetentionTime.front(); if( fRightMS2Time > vfRetentionTime.back() ) fRightMS2Time = vfRetentionTime.back(); if( (ProRataConfig::getLeftPeakShift() < 0.001) && (ProRataConfig::getRightPeakShift() < 0.001) ) { iNumberofScansShifted = 0; // compute the final vdCovarianceChro computeCovarianceChro( iNumberofScansShifted, vdTreatmentChroInput, vdReferenceChroInput ); // compute the final peak findPeak(); return true; } /* * detect peak shift */ int i; // the calcuated peak height in PPC for all tested peak shift // vector< double > vdPeakHeight; // vector< int > viScanShift; map< int, double > mScanShift2Height; // scans that shifts left is negative and scans that shifts right is positive for( i = 0; i < vfRetentionTime.size() - 3; i++ ) { if( (vfRetentionTime[i] - vfRetentionTime[0]) >= ProRataConfig::getLeftPeakShift() - 0.001) break; } int iScanShiftLeft = -i; for( i = (vfRetentionTime.size() - 1); i > 2; i-- ) { if( (vfRetentionTime.back() - vfRetentionTime[i]) >= ProRataConfig::getRightPeakShift() - 0.001) break; } int iScanShiftRight = vfRetentionTime.size() - i - 1; double dMaxPeakHeight = -100; for( i = iScanShiftLeft; i < ( iScanShiftRight + 1 ); ++i ) { // viScanShift.push_back( i ); computeCovarianceChro( i, vdTreatmentChroInput, vdReferenceChroInput ); findPeak(); mScanShift2Height[i] = dPeakHeightPPC; if( dPeakHeightPPC > dMaxPeakHeight ) dMaxPeakHeight = dPeakHeightPPC; // vdPeakHeight.push_back( dPeakHeightPPC ); } if( mScanShift2Height[ 0 ] > dMaxPeakHeight*0.9 ) { iNumberofScansShifted = 0; } else { iNumberofScansShifted = 0; bool bIsMaxFound = false; if( abs( iScanShiftLeft ) > iScanShiftRight ) { for( i = 0; i > ( iScanShiftLeft - 1 ); --i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; bIsMaxFound = true; break; } } if( !bIsMaxFound ) { for( i = 0; i < iScanShiftRight + 1 ; ++i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; break; } } } } else { for( i = 0; i < iScanShiftRight + 1 ; ++i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; bIsMaxFound = true; break; } } if( !bIsMaxFound ) { for( i = 0; i > ( iScanShiftLeft - 1 ); --i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; break; } } } } } // compute the final vdCovarianceChro computeCovarianceChro( iNumberofScansShifted, vdTreatmentChroInput, vdReferenceChroInput ); // compute the final peak findPeak(); // actually change the input vdReferenceChroInput shiftChro( iNumberofScansShifted, vdReferenceChroInput ); // cout << "bPeakValidity = " << boolalpha << bPeakValidity << endl; return true; }
size_t BasisOptimize(int* usedZeroedSpecies, bool doFormRxn, MultiPhase* mphase, std::vector<size_t>& orderVectorSpecies, std::vector<size_t>& orderVectorElements, vector_fp& formRxnMatrix) { // Get the total number of elements defined in the multiphase object size_t ne = mphase->nElements(); // Get the total number of species in the multiphase object size_t nspecies = mphase->nSpecies(); // Perhaps, initialize the element ordering if (orderVectorElements.size() < ne) { orderVectorElements.resize(ne); iota(orderVectorElements.begin(), orderVectorElements.end(), 0); } // Perhaps, initialize the species ordering if (orderVectorSpecies.size() != nspecies) { orderVectorSpecies.resize(nspecies); iota(orderVectorSpecies.begin(), orderVectorSpecies.end(), 0); } if (BasisOptimize_print_lvl >= 1) { writelog(" "); writeline('-', 77); writelog(" --- Subroutine BASOPT called to "); writelog("calculate the number of components and "); writelog("evaluate the formation matrix\n"); if (BasisOptimize_print_lvl > 0) { writelog(" ---\n"); writelog(" --- Formula Matrix used in BASOPT calculation\n"); writelog(" --- Species | Order | "); for (size_t j = 0; j < ne; j++) { size_t jj = orderVectorElements[j]; writelog(" {:>4.4s}({:1d})", mphase->elementName(jj), j); } writelog("\n"); for (size_t k = 0; k < nspecies; k++) { size_t kk = orderVectorSpecies[k]; writelog(" --- {:>11.11s} | {:4d} |", mphase->speciesName(kk), k); for (size_t j = 0; j < ne; j++) { size_t jj = orderVectorElements[j]; double num = mphase->nAtoms(kk,jj); writelogf("%6.1g ", num); } writelog("\n"); } writelog(" --- \n"); } } // Calculate the maximum value of the number of components possible. It's // equal to the minimum of the number of elements and the number of total // species. size_t nComponents = std::min(ne, nspecies); size_t nNonComponents = nspecies - nComponents; // Set this return variable to false *usedZeroedSpecies = false; // Create an array of mole numbers vector_fp molNum(nspecies,0.0); mphase->getMoles(molNum.data()); // Other workspace DenseMatrix sm(ne, ne); vector_fp ss(ne, 0.0); vector_fp sa(ne, 0.0); if (formRxnMatrix.size() < nspecies*ne) { formRxnMatrix.resize(nspecies*ne, 0.0); } // For debugging purposes keep an unmodified copy of the array. vector_fp molNumBase = molNum; double molSave = 0.0; size_t jr = 0; // Top of a loop of some sort based on the index JR. JR is the current // number of component species found. while (jr < nComponents) { // Top of another loop point based on finding a linearly independent // species size_t k = npos; while (true) { // Search the remaining part of the mole number vector, molNum for // the largest remaining species. Return its identity. kk is the raw // number. k is the orderVectorSpecies index. size_t kk = max_element(molNum.begin(), molNum.end()) - molNum.begin(); size_t j; for (j = 0; j < nspecies; j++) { if (orderVectorSpecies[j] == kk) { k = j; break; } } if (j == nspecies) { throw CanteraError("BasisOptimize", "orderVectorSpecies contains an error"); } if (molNum[kk] == 0.0) { *usedZeroedSpecies = true; } // If the largest molNum is negative, then we are done. if (molNum[kk] == USEDBEFORE) { nComponents = jr; nNonComponents = nspecies - nComponents; break; } // Assign a small negative number to the component that we have // just found, in order to take it out of further consideration. molSave = molNum[kk]; molNum[kk] = USEDBEFORE; // CHECK LINEAR INDEPENDENCE WITH PREVIOUS SPECIES // Modified Gram-Schmidt Method, p. 202 Dalquist // QR factorization of a matrix without row pivoting. size_t jl = jr; for (j = 0; j < ne; ++j) { size_t jj = orderVectorElements[j]; sm(j, jr) = mphase->nAtoms(kk,jj); } if (jl > 0) { // Compute the coefficients of JA column of the the upper // triangular R matrix, SS(J) = R_J_JR (this is slightly // different than Dalquist) R_JA_JA = 1 for (j = 0; j < jl; ++j) { ss[j] = 0.0; for (size_t i = 0; i < ne; ++i) { ss[j] += sm(i, jr) * sm(i, j); } ss[j] /= sa[j]; } // Now make the new column, (*,JR), orthogonal to the previous // columns for (j = 0; j < jl; ++j) { for (size_t i = 0; i < ne; ++i) { sm(i, jr) -= ss[j] * sm(i, j); } } } // Find the new length of the new column in Q. // It will be used in the denominator in future row calcs. sa[jr] = 0.0; for (size_t ml = 0; ml < ne; ++ml) { sa[jr] += pow(sm(ml, jr), 2); } // IF NORM OF NEW ROW .LT. 1E-3 REJECT if (sa[jr] > 1.0e-6) { break; } } // REARRANGE THE DATA if (jr != k) { if (BasisOptimize_print_lvl >= 1) { size_t kk = orderVectorSpecies[k]; writelogf(" --- %-12.12s", mphase->speciesName(kk)); size_t jj = orderVectorSpecies[jr]; writelogf("(%9.2g) replaces %-12.12s", molSave, mphase->speciesName(jj)); writelogf("(%9.2g) as component %3d\n", molNum[jj], jr); } std::swap(orderVectorSpecies[jr], orderVectorSpecies[k]); } // If we haven't found enough components, go back and find some more jr++; } if (! doFormRxn) { return nComponents; } // EVALUATE THE STOICHIOMETRY // // Formulate the matrix problem for the stoichiometric // coefficients. CX + B = 0 // // C will be an nc x nc matrix made up of the formula vectors for the // components. Each component's formula vector is a column. The rows are the // elements. // // n RHS's will be solved for. Thus, B is an nc x n matrix. // // BIG PROBLEM 1/21/99: // // This algorithm makes the assumption that the first nc rows of the formula // matrix aren't rank deficient. However, this might not be the case. For // example, assume that the first element in FormulaMatrix[] is argon. // Assume that no species in the matrix problem actually includes argon. // Then, the first row in sm[], below will be identically zero. bleh. // // What needs to be done is to perform a rearrangement of the ELEMENTS -> // i.e. rearrange, FormulaMatrix, sp, and gai, such that the first nc // elements form in combination with the nc components create an invertible // sm[]. not a small project, but very doable. // // An alternative would be to turn the matrix problem below into an ne x nc // problem, and do QR elimination instead of Gauss-Jordan elimination. // // Note the rearrangement of elements need only be done once in the problem. // It's actually very similar to the top of this program with ne being the // species and nc being the elements!! sm.resize(nComponents, nComponents); for (size_t k = 0; k < nComponents; ++k) { size_t kk = orderVectorSpecies[k]; for (size_t j = 0; j < nComponents; ++j) { size_t jj = orderVectorElements[j]; sm(j, k) = mphase->nAtoms(kk, jj); } } for (size_t i = 0; i < nNonComponents; ++i) { size_t k = nComponents + i; size_t kk = orderVectorSpecies[k]; for (size_t j = 0; j < nComponents; ++j) { size_t jj = orderVectorElements[j]; formRxnMatrix[j + i * ne] = - mphase->nAtoms(kk, jj); } } // // Use LU factorization to calculate the reaction matrix solve(sm, formRxnMatrix.data(), nNonComponents, ne); if (BasisOptimize_print_lvl >= 1) { writelog(" ---\n"); writelogf(" --- Number of Components = %d\n", nComponents); writelog(" --- Formula Matrix:\n"); writelog(" --- Components: "); for (size_t k = 0; k < nComponents; k++) { size_t kk = orderVectorSpecies[k]; writelogf(" %3d (%3d) ", k, kk); } writelog("\n --- Components Moles: "); for (size_t k = 0; k < nComponents; k++) { size_t kk = orderVectorSpecies[k]; writelogf("%-11.3g", molNumBase[kk]); } writelog("\n --- NonComponent | Moles | "); for (size_t i = 0; i < nComponents; i++) { size_t kk = orderVectorSpecies[i]; writelogf("%-11.10s", mphase->speciesName(kk)); } writelog("\n"); for (size_t i = 0; i < nNonComponents; i++) { size_t k = i + nComponents; size_t kk = orderVectorSpecies[k]; writelogf(" --- %3d (%3d) ", k, kk); writelogf("%-10.10s", mphase->speciesName(kk)); writelogf("|%10.3g|", molNumBase[kk]); // Print the negative of formRxnMatrix[]; it's easier to interpret. for (size_t j = 0; j < nComponents; j++) { writelogf(" %6.2f", - formRxnMatrix[j + i * ne]); } writelog("\n"); } writelog(" "); writeline('-', 77); } return nComponents; } // basopt()
void PeakPicker::findPeak() { int iOffset = ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2; // initialize iRightValley; for( iRightValley = ( iChroLength - 2 ) ; iRightValley > ProRataConfig::getPeakPickerWindowSize(); --iRightValley ) { if ( vfRetentionTime[ iRightValley ] < fRightMS2Time ) break; } ++iRightValley; // initialize iLeftValley for( iLeftValley = 1 ; iLeftValley < (iChroLength - ProRataConfig::getPeakPickerWindowSize() - 1); ++iLeftValley ) { if ( vfRetentionTime[ iLeftValley ] > fLeftMS2Time ) break; } --iLeftValley; // compute iLeftValley and iRightValley iRightValley = findNextRightValley( iRightValley ); iLeftValley = findNextLeftValley( iLeftValley ); double dCovarianceCutOff = median( vdCovarianceChro ); vector<double>::iterator itrBegin = vdCovarianceChro.begin(); double dHalfPeakIntensity = ( *(max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1 ) ) - dCovarianceCutOff ) * 0.5 ; double dLeftValleyIntensity = vdCovarianceChro.at( iLeftValley ) - dCovarianceCutOff; double dRightValleyIntensity = vdCovarianceChro.at( iRightValley ) - dCovarianceCutOff; bool bMoveLeftValley = ( (dLeftValleyIntensity > dHalfPeakIntensity) && iLeftValley > iOffset ); bool bMoveRightValley = ( (dRightValleyIntensity > dHalfPeakIntensity) && iRightValley < (iChroLength - iOffset - 1) ); bool bMoveLeftOrRight = ( vdCovarianceChro.at(iLeftValley) > vdCovarianceChro.at(iRightValley) ); while ( bMoveLeftValley || bMoveRightValley ) { if ( bMoveLeftValley && ( bMoveLeftOrRight || !bMoveRightValley ) ) iLeftValley = findNextLeftValley( iLeftValley ); if ( (!bMoveLeftValley || !bMoveLeftOrRight ) && bMoveRightValley ) iRightValley = findNextRightValley( iRightValley ); dHalfPeakIntensity = ( *(max_element(itrBegin + iLeftValley, itrBegin + iRightValley +1 ) ) - dCovarianceCutOff ) * 0.5 ; dLeftValleyIntensity = vdCovarianceChro.at( iLeftValley ) - dCovarianceCutOff; dRightValleyIntensity = vdCovarianceChro.at( iRightValley ) - dCovarianceCutOff; bMoveLeftValley = ( (dLeftValleyIntensity > dHalfPeakIntensity) && iLeftValley > iOffset ) ; bMoveRightValley = ( (dRightValleyIntensity > dHalfPeakIntensity) && iRightValley < (iChroLength - iOffset - 1) ) ; bMoveLeftOrRight = ( vdCovarianceChro.at(iLeftValley) > vdCovarianceChro.at(iRightValley) ); } // compute bPeakValidity bool bIsPeakBelowNoise = ( *( max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1 ) ) ) < dCovarianceCutOff; float fPeakWidth = vfRetentionTime[ iRightValley ] - vfRetentionTime[ iLeftValley ]; // float fChroDuration = vfRetentionTime.back() - vfRetentionTime.front() ; // minimal peak width = 0.1 min // maximal peak width = 8 min bool bIsPeakTooSmall = fPeakWidth < ( 0.1 ); bool bIsPeakTooBroad = fPeakWidth > ( 8 ); if ( bIsPeakBelowNoise || bIsPeakTooSmall || bIsPeakTooBroad ) bPeakValidity = false; else bPeakValidity = true; // compute dPeakHeightPPC dPeakHeightPPC = ( *( max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1) ) ) - ( ( vdCovarianceChro.at(iLeftValley) + vdCovarianceChro.at(iRightValley) )/2 ); }
bool CppArcInfo (vector < double >x, vector < double >y, vector < double >circle, vector < double >&ArcInfo) { // calculate the start and end angle of the arc formed by the input points, and also calculate the angle of arc. // circle: [yc, xc, r] // InSemiCircle: Np*1 bool vector, Np is the number of elements in x or y. It indicates whether points in the range of semicircle protruding to scan position. // ArcInfo: [StartAngle, EndAngle, ArcAngle], all the angles in unit of radian. // if ArcAngle is zero, it indicates that no valid arc is detected from the points, with the information about its corresponding circle center and scan position. if (circle.size () != 3) { #ifdef MATLABPRINT mexPrintf ("CppArcInfo ==> circle must be vector with 3 elements!\n"); #endif ArcInfo.clear (); return false; } if (x.size () != y.size () || x.size () < 2) { #ifdef MATLABPRINT mexPrintf ("CppArcInfo ==> x and y must be vectors with the same number of element, at least 2 elements!\n"); #endif ArcInfo.clear (); return false; } vector < double >angle (x.size (), -1.0); double minangle = 2 * PI, maxangle = 0.0, maxangleInPi = 0.0, minangleOutPi = 2 * PI; double arrow[2]; unsigned int pnum = 0; // count the number of points in semicircle protruding to scan position. // calculate the angle of vector (x-xc, y-yc) counterclockwise from x axis // estimate the arc angle by rasterizing the radius angle into equal divisions and counting the points within each division. double AngleResolution = 0.01 / 180.0 * PI; // the resolution of angle is 0.01 degree. int AngleNum = 36000; //static_cast<int>(2*PI/AngleResolution)+1; int tempind; vector < bool > GetPts (AngleNum, false); vector < double >MinAngleInDiv (AngleNum, 2 * PI); vector < double >MaxAngleInDiv (AngleNum, 0); for (unsigned int i = 0; i < x.size (); i++) { arrow[0] = x[i] - circle[1]; arrow[1] = y[i] - circle[0]; if (arrow[0] == 0) { if (arrow[1] == 0) { #ifdef MATLABPRINT mexPrintf ("CppArcInfo ==> circle center is at the same position with one point, wrong circle center!!\n"); #endif ArcInfo.clear (); return false; } } angle[i] = atan2 (arrow[1], arrow[0]); if (angle[i] < 0) { angle[i] += 2 * PI; } tempind = static_cast < int >(angle[i] / AngleResolution); GetPts[tempind] = true; if (angle[i] < MinAngleInDiv[tempind]) { MinAngleInDiv[tempind] = angle[i]; } if (angle[i] > MaxAngleInDiv[tempind]) { MaxAngleInDiv[tempind] = angle[i]; } } ArcInfo.clear (); ArcInfo.resize (3, 0.0); vector < int >StartAngleDiv, EndAngleDiv, BlankDivs; StartAngleDiv.clear (); EndAngleDiv.clear (); BlankDivs.clear (); bool blankflag = false; int blankdivnum = 0, blankblocknum = 0; int scancount = 0; // start from zero angle (counter-clockwise from x positive), search the consecutive blank angle divisions. for (int i = 0; i < 2 * AngleNum - 1 && scancount < AngleNum; i++) { if (!blankflag && GetPts[i % AngleNum] && !GetPts[(i + 1) % AngleNum]) { StartAngleDiv.push_back (i % AngleNum); blankflag = true; blankblocknum++; BlankDivs.push_back (0); scancount++; continue; } if (blankflag && !GetPts[i % AngleNum]) { BlankDivs[blankblocknum - 1]++; scancount++; if (GetPts[(i + 1) % AngleNum]) { EndAngleDiv.push_back ((i + 1) % AngleNum); blankflag = false; } continue; } if (GetPts[i % AngleNum]) { scancount++; } } if (BlankDivs.size () == 0) { if (!scancount) { ArcInfo[0] = 0; ArcInfo[1] = 0; ArcInfo[2] = mxGetInf (); } else { ArcInfo[0] = 0; ArcInfo[1] = 2 * PI; ArcInfo[2] = 2 * PI; } return true; } vector < int >::iterator MaxBlankDiv; MaxBlankDiv = max_element (BlankDivs.begin (), BlankDivs.end ()); int MaxInd = static_cast < int >(MaxBlankDiv - BlankDivs.begin ()); int MaxBlankDivCount = count (BlankDivs.begin (), BlankDivs.end (), *MaxBlankDiv); if (*MaxBlankDiv < 2) { ArcInfo[0] = 0; ArcInfo[1] = 2 * PI; ArcInfo[2] = 2 * PI; } else { if (MaxBlankDivCount > 1) { // This situation needs further processing to obtain more accurate arc angle. ArcInfo[0] = 0; ArcInfo[1] = 0; ArcInfo[2] = mxGetInf (); } else { ArcInfo[0] = MaxAngleInDiv[StartAngleDiv[MaxInd]]; ArcInfo[1] = MinAngleInDiv[EndAngleDiv[MaxInd]]; ArcInfo[2] = BlankDivs[MaxInd] * AngleResolution; ArcInfo[2] += AngleResolution * (StartAngleDiv[MaxInd] + 1) - ArcInfo[0]; ArcInfo[2] += ArcInfo[1] - AngleResolution * EndAngleDiv[MaxInd]; ArcInfo[2] = 2 * PI - ArcInfo[2]; } } return true; }
int maina(int argc, char** argv){ bool isLearning = false; int numberCluster = 3; double threshold = 0.3; std::string folderRecognition = "test/"; for (int i = 1; i < argc; i++) { const char* s = argv[i]; if (strcmp(s, "-learn") == 0) { isLearning = true; } else if (strcmp(s, "-folder") == 0) { folderRecognition = std::string(argv[++i]); } else if (strcmp(s, "-k") == 0) { numberCluster = atoi(argv[++i]); } else if (strcmp(s, "-thresh") == 0) { threshold = strtod(argv[++i], NULL); } else { std::cout << "not recognize command" << std::endl; return -1; } } std::vector<std::vector<double>> type1Des, type2Des, autreDes, autreCentroids; cv::Mat image, imageResized; std::vector<std::string> listFile; if (isLearning){ // read images of type 1 in folder and get list descriptors listFile = IO::getFilesInFolder(TYPE1_FOLDER); for(uint i = 0; i < listFile.size(); i++){ std::string fileName = TYPE1_FOLDER + listFile[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); type1Des.push_back(Utils::getDescriptors(image)); } listFile.clear(); // read images of type 2 in folder and get list descriptors listFile = IO::getFilesInFolder(TYPE2_FOLDER); for(uint i = 0; i < listFile.size(); i++){ std::string fileName = TYPE2_FOLDER + listFile[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); type2Des.push_back(Utils::getDescriptors(image)); } listFile.clear(); // read images of type autre in folder and get list descriptors listFile = IO::getFilesInFolder(AUTRE_FOLDER); for(uint i = 0; i < listFile.size(); i++){ std::string fileName = AUTRE_FOLDER + listFile[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); autreDes.push_back(Utils::getDescriptors(image)); } autreCentroids = Clustering::cluster(autreDes, numberCluster); // autreCentroids = Clustering::iterativeCluster(autreDes, threshold); // write descriptor to disk IO::writeDescriptors(type1Des, TYPE1_DESCRIPTOR); IO::writeDescriptors(type2Des, TYPE2_DESCRIPTOR); IO::writeDescriptors(autreCentroids, AUTRE_DESCRIPTOR); } else { type1Des = IO::getDescriptors(TYPE1_DESCRIPTOR); type2Des = IO::getDescriptors(TYPE2_DESCRIPTOR); autreCentroids = IO::getDescriptors(AUTRE_DESCRIPTOR); // list descriptors of image for classification std::vector<std::vector<double>> listDescriptors; // read image for recognition listFile = IO::getFilesInFolder(folderRecognition.c_str()); for (uint i = 0; i < listFile.size(); i++) { std::string fileName = folderRecognition + listFile[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); cv::resize(image, imageResized, cv::Size(), 0.1, 0.1); listDescriptors.push_back(Utils::getDescriptors(image)); } struct timeval tim; gettimeofday(&tim, NULL); double t1=tim.tv_sec+(tim.tv_usec/1000000.0); // classification std::vector<int> labels = Clustering::predict(type1Des, type2Des, autreCentroids, listDescriptors); gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); std::cout <<"time: " << t2 - t1 << " s" << std::endl; // // interative classification // std::vector<int> labels = Clustering::iterativeClustering(listDescriptors, threshold); // print result std::vector<int>::const_iterator it = max_element(labels.begin(), labels.end()); std::cout <<"number of cluster: " << *it + 1 << std::endl; for (int j = -1; j < *it + 1; j++){ for (uint i = 0; i < listFile.size(); i++){ if (labels[i]==j){ std::cout << listFile[i] << " " << labels[i] << std::endl; } } } // // write result // std::cout <<"number of cluster: " << *it + 1 << std::endl; // for (int j = -1; j < *it + 1; j++){ // for (uint i = 0; i < listFile.size(); i++){ // if (labels[i]==j){ // std::string fileName = folderRecognition + listFile[i]; // image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); // std::ostringstream convert; // stream used for the conversion // convert << labels[i]; // fileName = folderRecognition + convert.str() + listFile[i]; // cv::imwrite(fileName, image); // } // } // } } cv::waitKey(0); return 0; }
bool CppGridPts (vector < double >x, vector < double >y, double cellsize, unsigned int maxR, unsigned int minnumfit, vector < unsigned int >&img, vector < unsigned int >&dim_img, vector < double >&refmatrix, vector < unsigned int >&dim_refmatrix) { if (!(dim_img.size () == 2 && dim_refmatrix.size () == 2)) { #ifdef MATLABPRINT mexPrintf ("CppGridPts ==> inputs are invalid, failed!\n"); #endif return false; } if (x.size () < minnumfit) { // less than minnumfit points in given file, no image and refmatrix is generated. #ifdef DEBUG mexPrintf ("CppGridPts ==> less than minnumfit points in inputs!\n"); #endif img.clear (); dim_img[0] = 0; dim_img[1] = 0; refmatrix.clear (); dim_refmatrix[0] = 0; dim_refmatrix[1] = 0; return true; } // call CppCircleFitting to get preliminary circle center and raius. vector < double >precircle; CppCircleFitting (x, y, precircle); if (precircle.size () != 3) { // circle fitting failed possibly due to singular matrix. It means that all the points can't fit a circle. #ifdef DEBUG mexPrintf ("CppGridPts ==> CppCircleFitting return empty, circle fitting failed with all the points!\n"); #endif img.clear (); dim_img[0] = 0; dim_img[1] = 0; refmatrix.clear (); dim_refmatrix[0] = 0; dim_refmatrix[1] = 0; return true; } vector < double >::iterator Iter_minx, Iter_miny, Iter_maxx, Iter_maxy; double minx, miny, maxx, maxy; unsigned int colnum, rownum; Iter_minx = min_element (x.begin (), x.end ()); Iter_miny = min_element (y.begin (), y.end ()); Iter_maxx = max_element (x.begin (), x.end ()); Iter_maxy = max_element (y.begin (), y.end ()); //minx=min(*Iter_minx, precircle[1]-precircle[2]); //miny=min(*Iter_miny, precircle[0]-precircle[2]); //maxx=max(*Iter_maxx, precircle[1]+precircle[2]); //maxy=max(*Iter_maxy, precircle[0]+precircle[2]); minx = min (*Iter_minx, precircle[1] - maxR * cellsize); miny = min (*Iter_miny, precircle[0] - maxR * cellsize); maxx = max (*Iter_maxx, precircle[1] + maxR * cellsize); maxy = max (*Iter_maxy, precircle[0] + maxR * cellsize); colnum = static_cast < unsigned int >((maxx - minx) / cellsize + 0.5) + 1; rownum = static_cast < unsigned int >((maxy - miny) / cellsize + 0.5) + 1; dim_img[0] = rownum; dim_img[1] = colnum; img.clear (); img.resize (rownum * colnum, 0); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // It is important to notice that the center of // the first pixel, i.e. pixel at [1,1] locates at (minx, maxy) // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for (unsigned int i = 0, xpix, ypix; i < x.size (); i++) { xpix = static_cast < unsigned int >((x[i] - minx) / cellsize + 0.5); ypix = static_cast < unsigned int >((maxy - y[i]) / cellsize + 0.5); img[xpix * dim_img[0] + ypix] += 1; } mxArray *prhs[4], *plhs[1]; double *tempGetPr; prhs[0] = mxCreateDoubleScalar (minx); prhs[1] = mxCreateDoubleScalar (maxy); prhs[2] = mxCreateDoubleScalar (cellsize); prhs[3] = mxCreateDoubleScalar (-1 * cellsize); mexCallMATLAB (1, plhs, 4, prhs, "makerefmat"); tempGetPr = mxGetPr (plhs[0]); dim_refmatrix[0] = mxGetM (plhs[0]); dim_refmatrix[1] = mxGetN (plhs[0]); refmatrix.clear (); refmatrix.resize (dim_refmatrix[0] * dim_refmatrix[1], 0); for (unsigned int i = 0; i < refmatrix.size (); i++) { refmatrix[i] = tempGetPr[i]; } mxDestroyArray (prhs[0]); mxDestroyArray (prhs[1]); mxDestroyArray (prhs[2]); mxDestroyArray (prhs[3]); mxDestroyArray (plhs[0]); return true; }
void experiment( std::vector<std::string> listFile1Train, std::vector<std::string> listFile2Train, std::vector<std::string> listFile3Train, std::vector<std::string> listFileValidation, int numberCluster){ cv::Mat image; std::vector<std::vector<double>> type1Des, type2Des, autreDes, autreCentroids; //--------learning---------------------- //-------------------------------------- // read images of type 1 in folder and get list descriptors for(uint i = 0; i < listFile1Train.size(); i++){ std::string fileName = TYPE1_FOLDER + listFile1Train[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); type1Des.push_back(Utils::getDescriptors(image)); } // read images of type 2 in folder and get list descriptors for(uint i = 0; i < listFile2Train.size(); i++){ std::string fileName = TYPE2_FOLDER + listFile2Train[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); type2Des.push_back(Utils::getDescriptors(image)); } // read images of type autre in folder and get list descriptors for(uint i = 0; i < listFile3Train.size(); i++){ std::string fileName = AUTRE_FOLDER + listFile3Train[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); autreDes.push_back(Utils::getDescriptors(image)); } struct timeval tim; gettimeofday(&tim, NULL); double t1=tim.tv_sec+(tim.tv_usec/1000000.0); autreCentroids = Clustering::cluster(autreDes, numberCluster); gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); std::cout <<"learning time : " << t2 - t1 << "s" << std::endl; //--------Validation---------------------- //---------------------------------------- // list descriptors of image for classification std::vector<std::vector<double>> listValidationDes; // read image for recognition for (uint i = 0; i < listFileValidation.size(); i++) { std::string fileName = ALL_DATA_FOLDER + listFileValidation[i]; image = cv::imread(fileName, CV_LOAD_IMAGE_COLOR); listValidationDes.push_back(Utils::getDescriptors(image)); } gettimeofday(&tim, NULL); t2=tim.tv_sec+(tim.tv_usec/1000000.0); // classification std::vector<int> labels = Clustering::predict(type1Des, type2Des, autreCentroids, listValidationDes); gettimeofday(&tim, NULL); double t3=tim.tv_sec+(tim.tv_usec/1000000.0); std::cout <<"predict time : " << t3 - t2 << "s" << std::endl; // print result std::vector<int>::const_iterator it = max_element(labels.begin(), labels.end()); std::cout <<"number of cluster: " << *it + 1 << std::endl; for (int j = -1; j < *it + 1; j++){ for (uint i = 0; i < listFileValidation.size(); i++){ if (labels[i]==j){ std::cout << listFileValidation[i] << " " << labels[i] << std::endl; } } } }
void SysConf::GetSublattice(vector<double>& output, vector<double> & NSiteCount) { int idx; for(uint iii = 0; iii < output.size();++iii) { output[iii] = 0; } // Sublattice A for(int iii = 0; iii < SublatticeSize[0]; ++iii) { idx = SublatticeA[iii]; output[0] += NSiteCount[idx]; } // Sublattice B for(int iii = 0; iii < SublatticeSize[1]; ++iii) { idx = SublatticeB[iii]; output[1] += NSiteCount[idx]; } // Sublattice C for(int iii = 0; iii < SublatticeSize[2]; ++iii) { idx = SublatticeC[iii]; output[2] += NSiteCount[idx]; } for(uint iii = 0; iii < output.size();++iii) { output[iii] = output[iii]/SublatticeSize[iii]; } double SubAux = -1; vector<double>::iterator maxSub = max_element(output.begin(),output.end()); int distMax = distance(output.begin(),maxSub); vector<double>::iterator minSub = min_element(output.begin(),output.end()); int distMin = distance(output.begin(),minSub); if(*maxSub - 2 > 2 - *minSub) { // Then we're in the plaquette domain if(distMax == 1) // ( C A B ) -> ( A B C ) { SubAux = output[0]; output[0] = output[1]; // ( A A B ) | C output[1] = output[2]; // ( A B B ) | C output[2] = SubAux; // ( A B C ) | C } if(distMax == 2) // ( B C A ) -> ( A B C ) { SubAux = output[2]; // ( B C A ) | A output[2] = output[1]; // ( B C C ) | A output[1] = output[0]; // ( B B C ) | A output[0] = SubAux; // ( A B C ) | A } } else { // Then we're in the star domain if(distMin == 0) // ( C A B ) -> ( A B C ) { SubAux = output[0]; output[0] = output[1]; // ( A A B ) | C output[1] = output[2]; // ( A B B ) | C output[2] = SubAux; // ( A B C ) | C } if(distMin == 1) // ( B C A ) -> ( A B C ) { SubAux = output[2]; // ( B C A ) | A output[2] = output[1]; // ( B C C ) | A output[1] = output[0]; // ( B B C ) | A output[0] = SubAux; // ( A B C ) | A } } }
line NN2::max_line(const map<size_t,point> M){ return *max_element(M.begin(),M.end(), [](const line& p1, const line& p2){ return p1.second.second < p2.second.second; }); }
int main () { const unsigned namesCt = sizeof (names)/sizeof (names[0]); cout << *max_element (names, names + namesCt, str_compare) << endl; return 0; }
static void TestAlgorithms (void) { static const int c_TestNumbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 13, 14, 15, 16, 17, 18 }; const int* first = c_TestNumbers; const int* last = first + VectorSize(c_TestNumbers); intvec_t v, buf; v.assign (first, last); PrintVector (v); cout << "swap(1,2)\n"; swap (v[0], v[1]); PrintVector (v); v.assign (first, last); cout << "copy(0,8,9)\n"; copy (v.begin(), v.begin() + 8, v.begin() + 9); PrintVector (v); v.assign (first, last); cout << "copy with back_inserter\n"; v.clear(); copy (first, last, back_inserter(v)); PrintVector (v); v.assign (first, last); cout << "copy with inserter\n"; v.clear(); copy (first, first + 5, inserter(v, v.begin())); copy (first, first + 5, inserter(v, v.begin() + 3)); PrintVector (v); v.assign (first, last); cout << "copy_n(0,8,9)\n"; copy_n (v.begin(), 8, v.begin() + 9); PrintVector (v); v.assign (first, last); cout << "copy_if(is_even)\n"; intvec_t v_even; copy_if (v, back_inserter(v_even), &is_even); PrintVector (v_even); v.assign (first, last); cout << "for_each(printint)\n{ "; for_each (v, &printint); cout << "}\n"; cout << "for_each(reverse_iterator, printint)\n{ "; for_each (v.rbegin(), v.rend(), &printint); cout << "}\n"; cout << "find(10)\n"; cout.format ("10 found at offset %zd\n", abs_distance (v.begin(), find (v, 10))); cout << "count(13)\n"; cout.format ("%zu values of 13, %zu values of 18\n", count(v,13), count(v,18)); cout << "transform(sqr)\n"; transform (v, &sqr); PrintVector (v); v.assign (first, last); cout << "replace(13,666)\n"; replace (v, 13, 666); PrintVector (v); v.assign (first, last); cout << "fill(13)\n"; fill (v, 13); PrintVector (v); v.assign (first, last); cout << "fill_n(5, 13)\n"; fill_n (v.begin(), 5, 13); PrintVector (v); v.assign (first, last); cout << "fill 64083 uint8_t(0x41) "; TestBigFill<uint8_t> (64083, 0x41); cout << "fill 64083 uint16_t(0x4142) "; TestBigFill<uint16_t> (64083, 0x4142); cout << "fill 64083 uint32_t(0x41424344) "; TestBigFill<uint32_t> (64083, 0x41424344); cout << "fill 64083 float(0.4242) "; TestBigFill<float> (64083, 0x4242f); #if HAVE_INT64_T cout << "fill 64083 uint64_t(0x4142434445464748) "; TestBigFill<uint64_t> (64083, UINT64_C(0x4142434445464748)); #else cout << "No 64bit types available on this platform\n"; #endif cout << "copy 64083 uint8_t(0x41) "; TestBigCopy<uint8_t> (64083, 0x41); cout << "copy 64083 uint16_t(0x4142) "; TestBigCopy<uint16_t> (64083, 0x4142); cout << "copy 64083 uint32_t(0x41424344) "; TestBigCopy<uint32_t> (64083, 0x41424344); cout << "copy 64083 float(0.4242) "; TestBigCopy<float> (64083, 0.4242f); #if HAVE_INT64_T cout << "copy 64083 uint64_t(0x4142434445464748) "; TestBigCopy<uint64_t> (64083, UINT64_C(0x4142434445464748)); #else cout << "No 64bit types available on this platform\n"; #endif cout << "generate(genint)\n"; generate (v, &genint); PrintVector (v); v.assign (first, last); cout << "rotate(4)\n"; rotate (v, 7); rotate (v, -3); PrintVector (v); v.assign (first, last); cout << "merge with (3,5,10,11,11,14)\n"; const int c_MergeWith[] = { 3,5,10,11,11,14 }; intvec_t vmerged; merge (v.begin(), v.end(), VectorRange(c_MergeWith), back_inserter(vmerged)); PrintVector (vmerged); v.assign (first, last); cout << "inplace_merge with (3,5,10,11,11,14)\n"; v.insert (v.end(), VectorRange(c_MergeWith)); inplace_merge (v.begin(), v.end() - VectorSize(c_MergeWith), v.end()); PrintVector (v); v.assign (first, last); cout << "remove(13)\n"; remove (v, 13); PrintVector (v); v.assign (first, last); cout << "remove (elements 3, 4, 6, 15, and 45)\n"; vector<uoff_t> toRemove; toRemove.push_back (3); toRemove.push_back (4); toRemove.push_back (6); toRemove.push_back (15); toRemove.push_back (45); typedef index_iterate<intvec_t::iterator, vector<uoff_t>::iterator> riiter_t; riiter_t rfirst = index_iterator (v.begin(), toRemove.begin()); riiter_t rlast = index_iterator (v.begin(), toRemove.end()); remove (v, rfirst, rlast); PrintVector (v); v.assign (first, last); cout << "unique\n"; unique (v); PrintVector (v); v.assign (first, last); cout << "reverse\n"; reverse (v); PrintVector (v); v.assign (first, last); cout << "lower_bound(10)\n"; PrintVector (v); cout.format ("10 begins at position %zd\n", abs_distance (v.begin(), lower_bound (v, 10))); v.assign (first, last); cout << "upper_bound(10)\n"; PrintVector (v); cout.format ("10 ends at position %zd\n", abs_distance (v.begin(), upper_bound (v, 10))); v.assign (first, last); cout << "equal_range(10)\n"; PrintVector (v); TestEqualRange (v); v.assign (first, last); cout << "sort\n"; reverse (v); PrintVector (v); random_shuffle (v); sort (v); PrintVector (v); v.assign (first, last); cout << "stable_sort\n"; reverse (v); PrintVector (v); random_shuffle (v); stable_sort (v); PrintVector (v); v.assign (first, last); cout << "is_sorted\n"; random_shuffle (v); const bool bNotSorted = is_sorted (v.begin(), v.end()); sort (v); const bool bSorted = is_sorted (v.begin(), v.end()); cout << "unsorted=" << bNotSorted << ", sorted=" << bSorted << endl; v.assign (first, last); cout << "find_first_of\n"; static const int c_FFO[] = { 10000, -34, 14, 27 }; cout.format ("found 14 at position %zd\n", abs_distance (v.begin(), find_first_of (v.begin(), v.end(), VectorRange(c_FFO)))); v.assign (first, last); static const int LC1[] = { 3, 1, 4, 1, 5, 9, 3 }; static const int LC2[] = { 3, 1, 4, 2, 8, 5, 7 }; static const int LC3[] = { 1, 2, 3, 4 }; static const int LC4[] = { 1, 2, 3, 4, 5 }; cout << "lexicographical_compare"; cout << "\nLC1 < LC2 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC2)); cout << "\nLC2 < LC2 == " << lexicographical_compare (VectorRange(LC2), VectorRange(LC2)); cout << "\nLC3 < LC4 == " << lexicographical_compare (VectorRange(LC3), VectorRange(LC4)); cout << "\nLC4 < LC1 == " << lexicographical_compare (VectorRange(LC4), VectorRange(LC1)); cout << "\nLC1 < LC4 == " << lexicographical_compare (VectorRange(LC1), VectorRange(LC4)); cout << "\nmax_element\n"; cout.format ("max element is %d\n", *max_element (v.begin(), v.end())); v.assign (first, last); cout << "min_element\n"; cout.format ("min element is %d\n", *min_element (v.begin(), v.end())); v.assign (first, last); cout << "partial_sort\n"; reverse (v); partial_sort (v.begin(), v.iat(v.size() / 2), v.end()); PrintVector (v); v.assign (first, last); cout << "partial_sort_copy\n"; reverse (v); buf.resize (v.size()); partial_sort_copy (v.begin(), v.end(), buf.begin(), buf.end()); PrintVector (buf); v.assign (first, last); cout << "partition\n"; partition (v.begin(), v.end(), &is_even); PrintVector (v); v.assign (first, last); cout << "stable_partition\n"; stable_partition (v.begin(), v.end(), &is_even); PrintVector (v); v.assign (first, last); cout << "next_permutation\n"; buf.resize (3); iota (buf.begin(), buf.end(), 1); PrintVector (buf); while (next_permutation (buf.begin(), buf.end())) PrintVector (buf); cout << "prev_permutation\n"; reverse (buf); PrintVector (buf); while (prev_permutation (buf.begin(), buf.end())) PrintVector (buf); v.assign (first, last); cout << "reverse_copy\n"; buf.resize (v.size()); reverse_copy (v.begin(), v.end(), buf.begin()); PrintVector (buf); v.assign (first, last); cout << "rotate_copy\n"; buf.resize (v.size()); rotate_copy (v.begin(), v.iat (v.size() / 3), v.end(), buf.begin()); PrintVector (buf); v.assign (first, last); static const int c_Search1[] = { 5, 6, 7, 8, 9 }, c_Search2[] = { 10, 10, 11, 14 }; cout << "search\n"; cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search1)))); cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), search (v.begin(), v.end(), VectorRange(c_Search2)))); cout << "find_end\n"; cout.format ("{5,6,7,8,9} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search1)))); cout.format ("{10,10,11,14} at %zd\n", abs_distance (v.begin(), find_end (v.begin(), v.end(), VectorRange(c_Search2)))); cout << "search_n\n"; cout.format ("{14} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 1, 14))); cout.format ("{13,13} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 2, 13))); cout.format ("{10,10,10} at %zd\n", abs_distance (v.begin(), search_n (v.begin(), v.end(), 3, 10))); v.assign (first, last); cout << "includes\n"; static const int c_Includes[] = { 5, 14, 15, 18, 20 }; cout << "includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes)-1); cout << ", not includes=" << includes (v.begin(), v.end(), VectorRange(c_Includes)); cout << endl; static const int c_Set1[] = { 1, 2, 3, 4, 5, 6 }, c_Set2[] = { 4, 4, 6, 7, 8 }; intvec_t::iterator setEnd; cout << "set_difference\n"; v.resize (4); setEnd = set_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin()); PrintVector (v); assert (setEnd == v.end()); cout << "set_symmetric_difference\n"; v.resize (7); setEnd = set_symmetric_difference (VectorRange(c_Set1), VectorRange(c_Set2), v.begin()); PrintVector (v); assert (setEnd == v.end()); cout << "set_intersection\n"; v.resize (2); setEnd = set_intersection (VectorRange(c_Set1), VectorRange(c_Set2), v.begin()); PrintVector (v); assert (setEnd == v.end()); cout << "set_union\n"; v.resize (9); setEnd = set_union (VectorRange(c_Set1), VectorRange(c_Set2), v.begin()); PrintVector (v); assert (setEnd == v.end()); v.assign (first, last); }
int Pkmn::getMaxStat(){ return *max_element(c_stats.begin(),c_stats.end()); }
//----------------------------------------------------------------------- //체인 테이블 생성 및 PreProcessing //----------------------------------------------------------------------- Dvoid RenderModule::CreateChainTable(vector<Line>& vecLine, vector<ActiveLine>& activeTable) { assert(!vecLine.empty()); auto maxIter = max_element(begin(vecLine), end(vecLine), [](const Line& lhs, const Line& rhs) { return lhs.beginVertex.y < rhs.beginVertex.y; }); auto minIter = min_element(begin(vecLine), end(vecLine), [](const Line& lhs, const Line& rhs) { return lhs.beginVertex.y < rhs.beginVertex.y; }); Dint maxY = (Dint)maxIter->beginVertex.y; Dint minY = (Dint)minIter->beginVertex.y; vector<Line> currentLine; currentLine.reserve(3); for (Dint y = minY; y < maxY; ++y) { currentLine.clear(); for (auto lineIter = vecLine.begin(); lineIter != vecLine.end();) { ITER_CONVERT(pLine, &(*lineIter)); if (y == pLine->beginVertex.y || y == pLine->endVertex.y) //해당 y축에 정점이 걸치는지 검사 { currentLine.emplace_back( *pLine ); lineIter = vecLine.erase(lineIter); } else { ++lineIter; } } // 현재 라인에 포함가능한 엣지들 모두 포함 if( currentLine.empty() ) { continue; } for( auto chainIter = currentLine.begin(); chainIter != currentLine.end(); ) { auto checkOneCountIter = STD_FIND_IF(currentLine, [&] (const Line& line){ return CheckContinueLine(chainIter->lineKey, line.lineKey); }); if( checkOneCountIter == currentLine.end() ) //특정 정점이 연결되어 있지 않다 ( 1번만 카운트 됨 14_ScanLineFill.pdf 참조 ) { if( chainIter->isOneCount == false ) { chainIter->isOneCount = true; ++(chainIter->GetMinY()); //y축 값 1올리기 vecLine.emplace_back(*chainIter);//다시 검색하기 위해서 리스트에 넣어두자 chainIter = currentLine.erase(chainIter); } else { ++chainIter; } } else { ++chainIter; } } if( !currentLine.empty() ) { STD_ERASE(currentLine, STD_REMOVE_IF(currentLine, [] (const Line& l){ return l.beginVertex.y == l.endVertex.y; })); activeTable.emplace_back(y, currentLine); } } }
void FidoInterface::getFDR_MSE(const std::vector<double> &estFDR, const std::vector<double> &empFDR,double &mse) { /* Estimate MSE mse1 as : 1/N multiply by the SUM from k=1 to N of (estFDR(k) - empFDR(k))^2 */ /* Estimate MSE mse2 area as : sum trapezoid area of each segment (integral of the absolute value) * A_segment(i) = abs(X1-Xo) * abs((y1 + y2 ) / 2) * Where yo = estimated FDR at segment i * Where y1 = estimated FDR at segment i + 1 * Where Xo = empirical FDR at segment i * Where X1 = empirical FDR at segment i + 1 * Total Area = Total Area / range of X */ /* Estimate MSE mse3 area as : sum trapezoid area with antiderivatives of each segment (absolute value of the integral) * A_segment(i) = ((yo - m*Xo)*X1 + m/2 * X1^2) - ((yo - m*Xo)*Xo - m/2 * X2^2)) * Where yo = estimated FDR at segment i * Where y1 = estimated FDR at segment i + 1 * Where Xo = empirical FDR at segment i * Where X2 = empirical FDR at segment i + 1 * Where m = (y1 - y0) / (X1 - X0) * Total Area = abs(Total Area / range of X) */ /* Estimate MSE mse4 area as : sum trapezoid squared area with antiderivatives of each segment * A_segment(i) = ((yo - m*Xo)*X1 + m/2 * X1^2) - ((yo - m*Xo)*Xo - m/2 * X2^2)) * Where yo = estimated FDR at segment i * Where y1 = estimated FDR at segment i + 1 * Where Xo = empirical FDR at segment i * Where X2 = empirical FDR at segment i + 1 * Where m = (y1 - y0) / (X1 - X0) * Total Area = Total Area / range of X */ if( (*min_element(estFDR.begin(),estFDR.end()) >= mseThreshold_) || (estFDR.size() != empFDR.size()) || (estFDR.empty() || empFDR.empty()) || (((*max_element(estFDR.begin(),estFDR.end()) <= 0.0) && (*max_element(empFDR.begin(),empFDR.end()) <= 0.0))) ) { //no elements into the confidence interval or vectors empty //or different size or all zeroes //mse = mseThreshold_; mse = 1.0; //mse1 = mse2 = mse3 = mse4 = 1.0; return; } mse = 0.0; //mse1 = mse2 = mse3 = mse4 = 0.0; double x1,x2,y1,y2; for (unsigned k = 0; k < estFDR.size()-1; k++) { if (estFDR[k] <= mseThreshold_ && empFDR[k] <= mseThreshold_) { //empFDR and estFDR below threshold, y2,x2 are the diff of them x1 = estFDR[k]; x2 = estFDR[k+1]; y1 = x1 - empFDR[k]; y2 = x2 - empFDR[k+1]; } else if (estFDR[k] <= mseThreshold_) { //empFDR is above mseThreshold_, penalize the area positive x1 = estFDR[k]; x2 = estFDR[k+1]; y1 = x1; y2 = x2; } else { if (kUpdateRocN) { rocN_ = std::max(rocN_, (unsigned)std::max(50,std::min((int)k,500))); } break; } if ( x1 != x2 && x2 != 0 && y2 != 0 ) { //if there is an area x2 = min(x2,mseThreshold_); //in case x2 is above mseThreshold_ //mse2 += trapezoid_area(x1,x2,y1,y2); //mse3 += abs(area(x1, y1, x2, y2)); mse += areaSq(x1, y1, x2, y2); } //mse1 += pow(y1,2); } //mse1 += pow(y2,2); //last element of diff between vectors double normalizer1 = abs(std::min(estFDR.back(),mseThreshold_) - estFDR.front()); //normalize by x axis range (mseThreshold_ on top always) //double normalizer2 = (double)estFDR.size(); //normalize by the number of elements //std::cerr << estFDR[estFDR.size() - 2] << " " << estFDR.back() << std::endl; //std::cerr << empFDR[empFDR.size() - 2] << " " << empFDR.back() << std::endl; //mse1 /= normalizer2; //mse2 /= normalizer1; //mse3 /= normalizer1; mse /= (normalizer1*normalizer1*normalizer1)/3; return; }
ttl::pair<ForwardIt, ForwardIt> minmax_element(ForwardIt first, ForwardIt last) { // TODO: optimize return ttl::pair<ForwardIt, ForwardIt>(min_element(first, last), max_element(first, last)); }