void LCDMenu::display() { Menu * tmp; int i=scroll*prow; int maxi=((chary+scroll)*prow); lcd->clear(); if ((tmp=curMenu->getChild(i))) { do { lcd->setCursor(gx(i)+offset,gy(i)-scroll); lcd->print(tmp->name); i++; } while ((tmp=tmp->getSibling(1))&&i<maxi); if ((i<=maxi)&&showBack) //We stopped before the end of the lcd, so draw the back button if needed { lcd->setCursor(gx(i)+offset,gy(i)-scroll); lcd->print("Back"); } } else //Menu has no children { lcd->setCursor(0,0); lcd->print("No Children"); } setCursor(); }
void EdgePrewitt::prepareMatrices() { math::matrix<double> gx(3,3); math::matrix<double> gy(3,3); gx(0,0) = -1; gx(0,1) = 0; gx(0,2) = 1; gx(1,0) = -1; gx(1,1) = 0; gx(1,2) = 1; gx(2,0) = -1; gx(2,1) = 0; gx(2,2) = 1; gy(0,0) = -1; gy(0,1) = -1; gy(0,2) = -1; gy(1,0) = 0; gy(1,1) = 0; gy(1,2) = 0; gy(2,0) = 1; gy(2,1) = 1; gy(2,2) = 1; g_x = gx; g_y = gy; }
void setArrayDataToSinusoidalGradient( int dim , double** g_ptr , const int* lower , const int* upper , const double* xlo, const double* xhi, const double* h) { NULL_USE(xhi); NULL_USE(h); if (dim == 2) { double* gx_ptr = g_ptr[0]; MDA_Access<double, 2, MDA_OrderColMajor<2> > gx(gx_ptr, lower, upper); double* gy_ptr = g_ptr[1]; MDA_Access<double, 2, MDA_OrderColMajor<2> > gy(gy_ptr, lower, upper); for (int j = lower[1]; j <= upper[1]; ++j) { double y = xlo[1] + h[1] * (j - lower[1] + 0.5); double siny = sin(2 * M_PI * y); double cosy = cos(2 * M_PI * y); for (int i = lower[0]; i <= upper[0]; ++i) { double x = xlo[0] + h[0] * (i - lower[0] + 0.5); double sinx = sin(2 * M_PI * x); double cosx = cos(2 * M_PI * x); gx(i, j) = 2 * M_PI * cosx * siny; gy(i, j) = sinx * 2 * M_PI * cosy; } } } else if (dim == 3) { double* gx_ptr = g_ptr[0]; MDA_Access<double, 3, MDA_OrderColMajor<3> > gx(gx_ptr, lower, upper); double* gy_ptr = g_ptr[1]; MDA_Access<double, 3, MDA_OrderColMajor<3> > gy(gy_ptr, lower, upper); double* gz_ptr = g_ptr[2]; MDA_Access<double, 3, MDA_OrderColMajor<3> > gz(gz_ptr, lower, upper); for (int k = lower[2]; k <= upper[2]; ++k) { double z = xlo[2] + h[2] * (k - lower[2] + 0.5); double sinz = sin(2 * M_PI * z); double cosz = cos(2 * M_PI * z); for (int j = lower[1]; j <= upper[1]; ++j) { double y = xlo[1] + h[1] * (j - lower[1] + 0.5); double siny = sin(2 * M_PI * y); double cosy = cos(2 * M_PI * y); for (int i = lower[0]; i <= upper[0]; ++i) { double x = xlo[0] + h[0] * (i - lower[0] + 0.5); double sinx = sin(2 * M_PI * x); double cosx = cos(2 * M_PI * x); gx(i, j, k) = 2 * M_PI * cosx * siny * sinz; gy(i, j, k) = sinx * 2 * M_PI * cosy * sinz; gz(i, j, k) = sinx * cosy * 2 * M_PI * cosz; } } } } }
void tet_basis::proj2d_bdry(FLT *lin1, FLT *f1, int stride) { Array<FLT,2> wk0(gpy,3+em); const int be2 = em+3, be3 = 2*em+3; const int lgpx = gpx, lgpy = gpy, lnmodx = nmodx; int sign; FLT lcl0; #ifdef BZ_DEBUG Array<FLT,1> lin(lin1, shape(3+3*em+fm), neverDeleteData); Array<FLT,2> f(f1, shape(gpx,stride), neverDeleteData); #endif /* DETERMINE U VALUES, GRAD U VALUES AT COLLOCATION POINTS SUM HAT(U) FOR DU/DX AND DU/DY */ /* PART I - sum u*g_mn for each n, s_j */ for(int j = 0; j < lgpy; ++j ) { /* VERTEX 1 */ wk0(j,0) = lin(0)*gy(j,1); /* VERTEX 2, EDGE 3 */ sign = 1; lcl0 = lin(1)*gy(j,2); for(int i = 0; i < em; ++i){ lcl0 += sign*lin(be3+i)*gy(j,3+em+i); sign*=-1; } wk0(j,1) = lcl0; /* VERTEX 3, EDGE 2 */ lcl0 = lin(2)*gy(j,2); for(int i = 0; i < em; ++i){ lcl0 += lin(be2+i)*gy(j,3+em+i); } wk0(j,2) = lcl0; /* EDGE 1 */ for(int p = 3; p < em+3; ++p){ wk0(j,p)=lin(p)*gy(j,p); } } /* SUM OVER N AT EACH I,J POINT */ for (int i = 0; i < lgpx; ++i ) { for (int j = 0; j < lgpy; ++j) { lcl0 = wk0(j,0)*gx(i,0); for(int n = 1; n < lnmodx; ++n ) { lcl0 += wk0(j,n)*gx(i,n); } f(i,j) = lcl0; } } return; }
/* Get an 8 bit HEX number from the serial port */ unsigned char g2x(void) { unsigned char input_byte; input_byte=(gx()<<4); //get first nibble input_byte|=gx(); //get second nibble cksum+=input_byte; //compute checksum return (input_byte); }
void scan( int *pn ) { int sign = 1; int n = 0; char c = gx(); while( c < '0' || c > '9' ) { if( c == '-' ) sign = -1; c = gx(); } while( c >= '0' && c <= '9' ) n = (n<<3) + (n<<1) + c - '0', c = gx(); n = n * sign; *pn=n; }
void tet_basis::proj2d(FLT u1, FLT u2, FLT u3, FLT *f1, int stride) { const int lgpx = gpx, lgpy = gpy; #ifdef BZ_DEBUG Array<FLT,2> f(f1, shape(gpx,stride), neverDeleteData); #endif for (int i=0; i < lgpx; ++i ){ for (int j=0; j < lgpy; ++j ){ f(i,j) = u1*gx(i,0)*gy(j,1) +u2*gx(i,1)*gy(j,2) +u3*gx(i,2)*gy(j,2); } } return; }
void tst1() { ast_manager m; reg_decl_plugins(m); sort_ref s( m.mk_uninterpreted_sort(symbol("S")), m); func_decl_ref g( m.mk_func_decl(symbol("g"), s, s), m); func_decl_ref h( m.mk_func_decl(symbol("h"), s, s), m); sort * domain[2] = {s, s}; func_decl_ref f( m.mk_func_decl(symbol("f"), 2, domain, s), m); app_ref a( m.mk_const(symbol("a"), s), m); app_ref b( m.mk_const(symbol("b"), s), m); expr_ref x( m.mk_var(0, s), m); expr_ref y( m.mk_var(1, s), m); app_ref gx( m.mk_app(g, x), m); app_ref fgx_x( m.mk_app(f, gx.get(), x.get()), m); app_ref ha( m.mk_app(h, a.get()), m); app_ref gha( m.mk_app(g, ha.get()), m); app_ref fgha_ha( m.mk_app(f, gha.get(), ha.get()), m); tst_match(m, fgx_x, fgha_ha); app_ref fgha_gha( m.mk_app(f, gha.get(), gha.get()), m); tst_match(m, fgx_x, fgha_gha); app_ref fxy( m.mk_app(f, x.get(), y.get()), m); app_ref fyx( m.mk_app(f, y.get(), x.get()), m); tst_match(m, fxy, fyx); app_ref fygx( m.mk_app(f, y.get(), gx.get()), m); tst_match(m, fxy, fygx); tst_match(m, fygx, fxy); }
virtual BOOL on_draw(HELEMENT he, UINT draw_type, HDC hdc, const RECT &rc) { if ((DRAW_EVENTS)draw_type != where) return FALSE; // do default draw int w = rc.right - rc.left; int h = rc.bottom - rc.top; if (!surface) { surface = image::create(w, h); redraw = true; } else if (w != surface->width() || h != surface->height()) { delete surface; surface = image::create(w, h); redraw = true; } else if (redraw) surface->clear(); if (redraw) { graphics gx(surface); draw(he, gx, w, h); redraw = false; } surface->blit(hdc, rc.left, rc.top); return default_draw ? TRUE : FALSE; }
static void sweep(const std::vector<Vec3ui> &tri, const std::vector<Vec3f> &x, Array3f &phi, Array3i &closest_tri, const Vec3f &origin, float dx, float dy, float dz, int di, int dj, int dk) { int i0, i1; if(di>0){ i0=1; i1=phi.ni; } else{ i0=phi.ni-2; i1=-1; } int j0, j1; if(dj>0){ j0=1; j1=phi.nj; } else{ j0=phi.nj-2; j1=-1; } int k0, k1; if(dk>0){ k0=1; k1=phi.nk; } else{ k0=phi.nk-2; k1=-1; } for(int k=k0; k!=k1; k+=dk) for(int j=j0; j!=j1; j+=dj) for(int i=i0; i!=i1; i+=di){ Vec3f gx(i*dx+origin[0], j*dy+origin[1], k*dz+origin[2]); check_neighbour(tri, x, phi, closest_tri, gx, i, j, k, i-di, j, k); check_neighbour(tri, x, phi, closest_tri, gx, i, j, k, i, j-dj, k); check_neighbour(tri, x, phi, closest_tri, gx, i, j, k, i-di, j-dj, k); check_neighbour(tri, x, phi, closest_tri, gx, i, j, k, i, j, k-dk); check_neighbour(tri, x, phi, closest_tri, gx, i, j, k, i-di, j, k-dk); check_neighbour(tri, x, phi, closest_tri, gx, i, j, k, i, j-dj, k-dk); check_neighbour(tri, x, phi, closest_tri, gx, i, j, k, i-di, j-dj, k-dk); } }
QString SnumPlugin::extractnum(const QString &unicoded, int a) { int pos; QString tmp = ""; QString seriesnum = ""; QString season = ""; QString episode = ""; QRegExp rx("(\\d{1,2})[^\\d]{1}(\\d{1,3})"); pos = 0; pos = rx.indexIn(unicoded, pos); if (pos > -1) { season += rx.cap(1); episode += rx.cap(2); pos += rx.matchedLength(); } else { QRegExp px("(\\d{1,2})[^\\d]{2}(\\d{1,3})"); pos = 0; pos = px.indexIn(unicoded, pos); if (pos > -1) { season += px.cap(1); episode += px.cap(2); pos += px.matchedLength(); } else { QRegExp gx("(\\d{1,2})[^\\d]{0}(\\d{2})"); pos = 0; pos = gx.indexIn(unicoded, pos); if (pos > -1) { season += gx.cap(1); episode += gx.cap(2); pos += gx.matchedLength(); } } } if (season.length() == 1) { tmp = '0' + season; } else { tmp = season; } season = tmp; if (episode.length() == 1) { tmp = '0' + episode; } else { tmp = episode; } episode = tmp; seriesnum += season + 'e' + episode; if (a == 0) { return seriesnum; } else if (a == 1) { return season; } else { return episode; } }
void LCDMenu::setCursor() { if (cursor) { lcd->command(0x0F); } else { lcd->command(0x0E); } lcd->setCursor(gx(curloc),gy(curloc)-scroll); }
void Tri2dFCBlockSolver::gradSetup() { // set up averaged quadratic gradient coefficients if (gradMethod == 0 || gradMethod == 2){ gxQ.allocate(npsp1,2); gradSetupQuadratic(); } // set up fully cubic gradient coefficients gxC.allocate(npsp1,2); gradSetupCubic(); // copy the proper coefficients based on desired gradient method if (gradMethod == 0) for (int n=0; n<npsp1; n++) for (int k=0; k<2; k++) gx(n,k) = gxQ(n,k); else if (gradMethod == 1) for (int n=0; n<npsp1; n++) for (int k=0; k<2; k++) gx(n,k) = gxC(n,k); else if (gradMethod == 2){ for (int n=0; n<npsp1; n++) for (int k=0; k<2; k++) gx(n,k) = gxC(n,k); for (int n=nNode-nNodeBd; n<nNode; n++) for(int i=psp2(n); i<psp2(n+1); i++) for (int k=0; k<2; k++) gx(i,k) = gxQ(i,k); } else{ cout << "\ngradMethod not recognized in gradSetup.C" << endl; exit(0); } // deallocate work arrays gxQ.deallocate(); gxC.deallocate(); }
ColumnVector NLF1::evalG(const ColumnVector& x) // Evaluate the gradient at x { int result = 0 ; double fx; ColumnVector gx(dim); // *** CHANGE *** // if (!application.getGrad(x,gx)) { fcn_v(NLPGradient, dim, x, fx, gx, result, vptr); application.update(result,dim,x,fx,gx); ngevals++; } // *** CHANGE *** // return gx; }
ObsRngDev::ObsRngDev( const double prange, const SatID& svid, const DayTime& time, const ECEF& rxpos, const XvtStore<SatID>& eph, GeoidModel& gm, bool svTime) : obstime(time), svid(svid), ord(0), wonky(false) { computeOrd(prange, rxpos, eph, gm, svTime); Geodetic gx(rxpos, &gm); NBTropModel nb(gx.getAltitude(), gx.getLatitude(), time.DOYday()); computeTrop(nb); }
ObsRngDev::ObsRngDev( const double prange, const SatID& svid, const DayTime& time, const ECEF& rxpos, const XvtStore<SatID>& eph, GeoidModel& gm, const IonoModelStore& ion, IonoModel::Frequency fq, bool svTime) : obstime(time), svid(svid), ord(0), wonky(false) { computeOrd(prange, rxpos, eph, gm, svTime); Geodetic gx(rxpos, &gm); NBTropModel nb(gx.getAltitude(), gx.getLatitude(), time.DOYday()); computeTrop(nb); iono = ion.getCorrection(time, gx, elevation, azimuth, fq); ord -= iono; }
void CImgButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC dc; dc.Attach(lpDrawItemStruct->hDC); Graphics gx(dc); auto Img = m_imgStandart; auto state = lpDrawItemStruct->itemState; if ((state & ODS_SELECTED) && m_imgPressed != nullptr) Img = m_imgPressed; else if (m_Disabled && m_imgDisabled != nullptr) Img = m_imgDisabled; else if (m_Hovering && m_imgHovered != nullptr) Img = m_imgHovered; Rect rc(0, 0, Img->GetWidth(), Img->GetHeight()); gx.DrawImage(Img, rc); dc.Detach(); }
ObsRngDev::ObsRngDev( const double prange1, const double prange2, const SatID& svid, const DayTime& time, const ECEF& rxpos, const XvtStore<SatID>& eph, GeoidModel& gm, bool svTime) : obstime(time), svid(svid), ord(0), wonky(false) { // for dual frequency see ICD-GPS-211, section 20.3.3.3.3.3 double icpr = (prange2 - GAMMA * prange1)/IGAMMA; iono = prange1 - icpr; computeOrd(icpr, rxpos, eph, gm, svTime); Geodetic gx(rxpos, &gm); NBTropModel nb(gx.getAltitude(), gx.getLatitude(), time.DOYday()); computeTrop(nb); }
/*virtual*/ void InputEmulatorUInput::movePointer(const int32_t x, const int32_t y) const { struct input_event event; int32_t gx(x), gy(y); toScreen(&gx, &gy); memset(&event, 0, sizeof(event)); event.type = EV_ABS; event.code = ABS_X; event.value = gx; writeEvent(&event); event.type = EV_ABS; event.code = ABS_Y; event.value = gy; writeEvent(&event); event.type = EV_SYN; event.code = SYN_REPORT; event.value = 0; writeEvent(&event); }
Array3i make_level_set3(const std::vector<Vec3ui> &tri, const std::vector<Vec3f> &x, const Vec3f &origin, float dx, float dy, float dz, int ni, int nj, int nk, Array3f &phi, const int exact_band) { phi.resize(ni, nj, nk); phi.assign(ni*dx+nj*dy+nk*dz); // upper bound on distance Array3i closest_tri(ni, nj, nk, -1); Array3i intersection_count(ni, nj, nk, 0); // intersection_count(i,j,k) is # of tri intersections in (i-1,i]x{j}x{k} // we begin by initializing distances near the mesh, and figuring out intersection counts Vec3f ijkmin, ijkmax; for(unsigned int t=0; t<tri.size(); ++t){ unsigned int p, q, r; assign(tri[t], p, q, r); // coordinates in grid to high precision double fip=((double)x[p][0]-origin[0])/dx, fjp=((double)x[p][1]-origin[1])/dy, fkp=((double)x[p][2]-origin[2])/dz; double fiq=((double)x[q][0]-origin[0])/dx, fjq=((double)x[q][1]-origin[1])/dy, fkq=((double)x[q][2]-origin[2])/dz; double fir=((double)x[r][0]-origin[0])/dx, fjr=((double)x[r][1]-origin[1])/dy, fkr=((double)x[r][2]-origin[2])/dz; // do distances nearby int i0=clamp(int(min(fip,fiq,fir))-exact_band, 0, ni-1), i1=clamp(int(max(fip,fiq,fir))+exact_band+1, 0, ni-1); int j0=clamp(int(min(fjp,fjq,fjr))-exact_band, 0, nj-1), j1=clamp(int(max(fjp,fjq,fjr))+exact_band+1, 0, nj-1); int k0=clamp(int(min(fkp,fkq,fkr))-exact_band, 0, nk-1), k1=clamp(int(max(fkp,fkq,fkr))+exact_band+1, 0, nk-1); for(int k=k0; k<=k1; ++k) for(int j=j0; j<=j1; ++j) for(int i=i0; i<=i1; ++i){ Vec3f gx(i*dx+origin[0], j*dy+origin[1], k*dz+origin[2]); float d=point_triangle_distance(gx, x[p], x[q], x[r]); if(d<phi(i,j,k)){ phi(i,j,k)=d; closest_tri(i,j,k)=t; } } // and do intersection counts j0=clamp((int)std::ceil(min(fjp,fjq,fjr)), 0, nj-1); j1=clamp((int)std::floor(max(fjp,fjq,fjr)), 0, nj-1); k0=clamp((int)std::ceil(min(fkp,fkq,fkr)), 0, nk-1); k1=clamp((int)std::floor(max(fkp,fkq,fkr)), 0, nk-1); for(int k=k0; k<=k1; ++k) for(int j=j0; j<=j1; ++j){ double a, b, c; if(point_in_triangle_2d(j, k, fjp, fkp, fjq, fkq, fjr, fkr, a, b, c)){ double fi=a*fip+b*fiq+c*fir; // intersection i coordinate int i_interval=int(std::ceil(fi)); // intersection is in (i_interval-1,i_interval] if(i_interval<0) ++intersection_count(0, j, k); // we enlarge the first interval to include everything to the -x direction else if(i_interval<ni) ++intersection_count(i_interval,j,k); // we ignore intersections that are beyond the +x side of the grid } } } // and now we fill in the rest of the distances with fast sweeping for(unsigned int pass=0; pass<2; ++pass){ sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, +1, +1, +1); sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, -1, -1, -1); sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, +1, +1, -1); sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, -1, -1, +1); sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, +1, -1, +1); sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, -1, +1, -1); sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, +1, -1, -1); sweep(tri, x, phi, closest_tri, origin, dx, dy, dz, -1, +1, +1); } // then figure out signs (inside/outside) from intersection counts for(int k=0; k<nk; ++k) for(int j=0; j<nj; ++j){ int total_count=0; for(int i=0; i<ni; ++i){ total_count+=intersection_count(i,j,k); if(total_count%2==1){ // if parity of intersections so far is odd, phi(i,j,k)=-phi(i,j,k); // we are inside the mesh } } } return closest_tri; }
//-----------------------------------------------------------------------------------------// //--------------------------------DRAW NEW POINT TO THE GRAPHS-----------------------------// //-----------------------------------------------------------------------------------------// void RealTimePlotWindow::dataAvaible(QByteArray ext) { double przelicznik = 6103515625;//prescaler value double memory = 2; QVector<measurementData> data = ExtractData(ext);//extract data from dialogwinndow quint16 newDataSize = data.size(); QVector<double> key(newDataSize); QVector<double> ax(newDataSize); QVector<double> ay(newDataSize); QVector<double> az(newDataSize); QVector<double> gx(newDataSize); QVector<double> gy(newDataSize); QVector<double> gz(newDataSize); double keyPrescaler =0; keyPrescaler = keyCounter / 200; // qDebug()<<"znacznik"; for(double i = 0; i<newDataSize; i++) { key[i] = (double)keyPrescaler + (i/200); // key[i] = (double)keyCounter; ax[i] = ((double)data.at(i).ax.as_word)*przelicznik/100000000000; ay[i] = ((double)data.at(i).ay.as_word)*(-1)*przelicznik/100000000000; az[i] = ((double)data.at(i).az.as_word)*(-1)*przelicznik/100000000000; gx[i] = ((double)data.at(i).gx.as_word)*przelicznik/100000000000; gy[i] = ((double)data.at(i).gy.as_word)*(-1)*przelicznik/100000000000; gz[i] = ((double)data.at(i).gz.as_word)*(-1)*przelicznik/100000000000; } if((newDataSize>0)&(triger == true))//get instValues 5 times per secound(depend of timmer interval) { (*instValues)[0] = ax[0]; (*instValues)[1] = ay[0]; (*instValues)[2] = az[0]; (*instValues)[3] = gx[0]; (*instValues)[4] = gy[0]; (*instValues)[5] = gz[0]; triger = false; instValWindow->setInstValues(instValues); } // add new data to graphs ui->accPlot->graph(0)->addData(key, ax); ui->accPlot->graph(1)->addData(key, ay); ui->accPlot->graph(2)->addData(key, az); ui->gyroPlot->graph(0)->addData(key, gx); ui->gyroPlot->graph(1)->addData(key, gy); ui->gyroPlot->graph(2)->addData(key, gz); // remove data of lines that's outside visible range: ui->accPlot->graph(0)->removeDataBefore(keyPrescaler-memory); ui->accPlot->graph(1)->removeDataBefore(keyPrescaler-memory); ui->accPlot->graph(2)->removeDataBefore(keyPrescaler-memory); // qDebug()<<"znacznik 4\n"; // rescale value (vertical) axis to fit the current data: ui->accPlot->graph(0)->rescaleValueAxis(); ui->accPlot->graph(1)->rescaleValueAxis(true); ui->accPlot->graph(2)->rescaleValueAxis(true); // make key axis range scroll with the data (at a constant range size of 8): ui->accPlot->xAxis->setRange(keyPrescaler, memory, Qt::AlignRight); ui->accPlot->replot(); // remove data of lines that's outside visible range: ui->gyroPlot->graph(0)->removeDataBefore(keyPrescaler-memory); ui->gyroPlot->graph(1)->removeDataBefore(keyPrescaler-memory); ui->gyroPlot->graph(2)->removeDataBefore(keyPrescaler-memory); // rescale value (vertical) axis to fit the current data: ui->gyroPlot->graph(0)->rescaleValueAxis(); ui->gyroPlot->graph(1)->rescaleValueAxis(true); ui->gyroPlot->graph(2)->rescaleValueAxis(true); // make key axis range scroll with the data (at a constant range size of 8): ui->gyroPlot->xAxis->setRange(keyPrescaler, memory, Qt::AlignRight); ui->gyroPlot->replot(); keyCounter += newDataSize; MPS += newDataSize; qDebug()<<"keyCounter:"<<keyCounter; }
int opencv::CreateGeoMatchModel(const Mat& templateArr, double maxContrast, double minContrast) { if (CV_8UC1 != templateArr.type()) { return 0; } #if 0 Mat src = templateArr.clone(); CvSize Ssize; // Convert IplImage to Matrix for integer operations //CvMat srcstub, *src = (CvMat*)templateArr; // set width and height Ssize.width = src.cols; Ssize.height = src.rows; modelHeight = src.rows; //Save Template height modelWidth = src.cols; //Save Template width noOfCordinates = 0; //initialize if (cordinates) delete cordinates; cordinates = new Point[modelWidth *modelHeight]; //Allocate memory for coorinates of selected points in template image if (edgeMagnitude) delete edgeMagnitude; edgeMagnitude = new double[modelWidth *modelHeight]; //Allocate memory for edge magnitude for selected points if (edgeDerivativeX) delete edgeDerivativeX; edgeDerivativeX = new double[modelWidth *modelHeight]; //Allocate memory for edge X derivative for selected points if (edgeDerivativeY) delete edgeDerivativeY; edgeDerivativeY = new double[modelWidth *modelHeight]; ////Allocate memory for edge Y derivative for selected points // Calculate gradient of Template Mat gx(Ssize.height, Ssize.width, CV_16SC1); //create Matrix to store X derivative Mat gy(Ssize.height, Ssize.width, CV_16SC1); //create Matrix to store Y derivative cvSobel(src, gx, 1, 0, 3); //gradient in X direction cvSobel(src, gy, 0, 1, 3); //gradient in Y direction Mat nmsEdges(Ssize.height, Ssize.width, CV_32F); //create Matrix to store Final nmsEdges const short* _sdx; const short* _sdy; double fdx, fdy; double MagG, DirG; double MaxGradient = -99999.99; double direction; int *orients = new int[Ssize.height *Ssize.width]; int count = 0, i, j; // count variable; double **magMat; CreateDoubleMatrix(magMat, Ssize); for (i = 1; i < Ssize.height - 1; i++) { for (j = 1; j < Ssize.width - 1; j++) { _sdx = (short*)(gx->data.ptr + gx->step*i); _sdy = (short*)(gy->data.ptr + gy->step*i); fdx = _sdx[j]; fdy = _sdy[j]; // read x, y derivatives MagG = sqrt((float)(fdx*fdx) + (float)(fdy*fdy)); //Magnitude = Sqrt(gx^2 +gy^2) direction = cvFastArctan((float)fdy, (float)fdx); //Direction = invtan (Gy / Gx) magMat[i][j] = MagG; if (MagG > MaxGradient) MaxGradient = MagG; // get maximum gradient value for normalizing. // get closest angle from 0, 45, 90, 135 set if ((direction>0 && direction < 22.5) || (direction >157.5 && direction < 202.5) || (direction>337.5 && direction < 360)) direction = 0; else if ((direction > 22.5 && direction < 67.5) || (direction >202.5 && direction <247.5)) direction = 45; else if ((direction >67.5 && direction < 112.5) || (direction>247.5 && direction<292.5)) direction = 90; else if ((direction >112.5 && direction < 157.5) || (direction>292.5 && direction < 337.5)) direction = 135; else direction = 0; orients[count] = (int)direction; count++; } } count = 0; // init count // non maximum suppression double leftPixel, rightPixel; for (i = 1; i < Ssize.height - 1; i++) { for (j = 1; j < Ssize.width - 1; j++) { switch (orients[count]) { case 0: leftPixel = magMat[i][j - 1]; rightPixel = magMat[i][j + 1]; break; case 45: leftPixel = magMat[i - 1][j + 1]; rightPixel = magMat[i + 1][j - 1]; break; case 90: leftPixel = magMat[i - 1][j]; rightPixel = magMat[i + 1][j]; break; case 135: leftPixel = magMat[i - 1][j - 1]; rightPixel = magMat[i + 1][j + 1]; break; } // compare current pixels value with adjacent pixels if ((magMat[i][j] < leftPixel) || (magMat[i][j] < rightPixel)) (nmsEdges->data.ptr + nmsEdges->step*i)[j] = 0; else (nmsEdges->data.ptr + nmsEdges->step*i)[j] = (uchar)(magMat[i][j] / MaxGradient * 255); count++; } } int RSum = 0, CSum = 0; int curX, curY; int flag = 1; //Hysterisis threshold for (i = 1; i < Ssize.height - 1; i++) { for (j = 1; j < Ssize.width; j++) { _sdx = (short*)(gx->data.ptr + gx->step*i); _sdy = (short*)(gy->data.ptr + gy->step*i); fdx = _sdx[j]; fdy = _sdy[j]; MagG = sqrt(fdx*fdx + fdy*fdy); //Magnitude = Sqrt(gx^2 +gy^2) DirG = cvFastArctan((float)fdy, (float)fdx); //Direction = tan(y/x) ////((uchar*)(imgGDir->imageData + imgGDir->widthStep*i))[j]= MagG; flag = 1; if (((double)((nmsEdges->data.ptr + nmsEdges->step*i))[j]) < maxContrast) { if (((double)((nmsEdges->data.ptr + nmsEdges->step*i))[j]) < minContrast) { (nmsEdges->data.ptr + nmsEdges->step*i)[j] = 0; flag = 0; // remove from edge ////((uchar*)(imgGDir->imageData + imgGDir->widthStep*i))[j]=0; } else { // if any of 8 neighboring pixel is not greater than max contraxt remove from edge if ((((double)((nmsEdges->data.ptr + nmsEdges->step*(i - 1)))[j - 1]) < maxContrast) && (((double)((nmsEdges->data.ptr + nmsEdges->step*(i - 1)))[j]) < maxContrast) && (((double)((nmsEdges->data.ptr + nmsEdges->step*(i - 1)))[j + 1]) < maxContrast) && (((double)((nmsEdges->data.ptr + nmsEdges->step*i))[j - 1]) < maxContrast) && (((double)((nmsEdges->data.ptr + nmsEdges->step*i))[j + 1]) < maxContrast) && (((double)((nmsEdges->data.ptr + nmsEdges->step*(i + 1)))[j - 1]) < maxContrast) && (((double)((nmsEdges->data.ptr + nmsEdges->step*(i + 1)))[j]) < maxContrast) && (((double)((nmsEdges->data.ptr + nmsEdges->step*(i + 1)))[j + 1]) < maxContrast)) { (nmsEdges->data.ptr + nmsEdges->step*i)[j] = 0; flag = 0; ////((uchar*)(imgGDir->imageData + imgGDir->widthStep*i))[j]=0; } } } // save selected edge information curX = i; curY = j; if (flag != 0) { if (fdx != 0 || fdy != 0) { RSum = RSum + curX; CSum = CSum + curY; // Row sum and column sum for center of gravity cordinates[noOfCordinates].x = curX; cordinates[noOfCordinates].y = curY; edgeDerivativeX[noOfCordinates] = fdx; edgeDerivativeY[noOfCordinates] = fdy; //handle divide by zero if (MagG != 0) edgeMagnitude[noOfCordinates] = 1 / MagG; // gradient magnitude else edgeMagnitude[noOfCordinates] = 0; noOfCordinates++; } } } } centerOfGravity.x = RSum / noOfCordinates; // center of gravity centerOfGravity.y = CSum / noOfCordinates; // center of gravity // change coordinates to reflect center of gravity for (int m = 0; m < noOfCordinates; m++) { int temp; temp = cordinates[m].x; cordinates[m].x = temp - centerOfGravity.x; temp = cordinates[m].y; cordinates[m].y = temp - centerOfGravity.y; } ////cvSaveImage("Edges.bmp",imgGDir); // free alocated memories delete[] orients; ////cvReleaseImage(&imgGDir); cvReleaseMat(&gx); cvReleaseMat(&gy); cvReleaseMat(&nmsEdges); ReleaseDoubleMatrix(magMat, Ssize.height); modelDefined = true; #endif return 0; }
//--------------------------------------------------------- void NDG2D::OutputNodes_gauss() //--------------------------------------------------------- { static int count = 0; string output_dir = "."; string buf = umOFORM("%s/gauss_N%02d_%04d.vtk", output_dir.c_str(), m_gauss.NGauss, ++count); FILE *fp = fopen(buf.c_str(), "w"); if (!fp) { umLOG(1, "Could no open %s for output!\n", buf.c_str()); return; } // Set flags and totals int Npoints = 3*m_gauss.NGauss; // quadrature nodes per element // set totals for Vtk output #if (1) // FIXME: no connectivity int vtkTotalPoints = this->K * Npoints; int vtkTotalCells = vtkTotalPoints; int vtkTotalConns = vtkTotalPoints; int Ncells = Npoints; #else int vtkTotalPoints = this->K * Npoints; int vtkTotalCells = this->K * Ncells; int vtkTotalConns = (this->EToV.num_cols()+1) * this->K * Ncells; int Ncells = this->N * this->N; #endif //------------------------------------- // 1. Write the VTK header details //------------------------------------- fprintf(fp, "# vtk DataFile Version 2"); fprintf(fp, "\nNDGFem simulation nodes (surface quadrature)"); fprintf(fp, "\nASCII"); fprintf(fp, "\nDATASET UNSTRUCTURED_GRID\n"); fprintf(fp, "\nPOINTS %d double", vtkTotalPoints); int newNpts=0; //------------------------------------- // 2. Write the vertex data //------------------------------------- const DMat& gx=m_gauss.x; const DMat& gy=m_gauss.y; for (int k=1; k<=this->K; ++k) { for (int n=1; n<=Npoints; ++n) { fprintf(fp, "\n%20.12e %20.12e %6.1lf", gx(n,k), gy(n,k), 0.0); } } //------------------------------------- // 3. Write the element connectivity //------------------------------------- // Number of indices required to define connectivity fprintf(fp, "\n\nCELLS %d %d", vtkTotalCells, 2*vtkTotalConns); // TODO: write element connectivity to file // FIXME: out-putting as VTK_VERTEX int nodesk=0; for (int k=0; k<this->K; ++k) { // for each element for (int n=1; n<=Npoints; ++n) { fprintf(fp, "\n%d", 1); // for each triangle for (int i=1; i<=1; ++i) { // FIXME: no connectivity fprintf(fp, " %5d", nodesk); // nodes in nth triangle nodesk++; // indexed from 0 } } } //------------------------------------- // 4. Write the cell types //------------------------------------- // For each element (cell) write a single integer // identifying the cell type. The integer should // correspond to the enumeration in the vtk file: // /VTK/Filtering/vtkCellType.h fprintf(fp, "\n\nCELL_TYPES %d", vtkTotalCells); for (int k=0; k<this->K; ++k) { fprintf(fp, "\n"); for (int i=1; i<=Ncells; ++i) { //fprintf(fp, "5 "); // 5:VTK_TRIANGLE fprintf(fp, "1 "); // 1:VTK_VERTEX if (! (i%10)) fprintf(fp, "\n"); } } // add final newline to output fprintf(fp, "\n"); fclose(fp); }
// This does a tri-linear interpolation of the derivatives at each of the 8 // grid points around the given point. This avoids additional calls to the // function and speeds things up by a factor of 2 or so. GLvoid MarchingCubes::surfaceNormal(GLvector &norm, GLfloat const& x, GLfloat const& y, GLfloat const& z) { // needs offloading to the Grid class GLvector V000, V001, V010, V011, V100, V101, V110, V111; GLfloat gx(x/m_stepSize); GLfloat gy(y/m_stepSize); GLfloat gz(z/m_stepSize); GLint x0( std::floor(gx) ); GLint y0( std::floor(gy) ); GLint z0( std::floor(gz) ); GLint x1(x0+1); GLint y1(y0+1); GLint z1(z0+1); int i = x0; int j = y0; int k = z0; V000.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V000.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V000.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); i = x0; j = y0; k = z1; V001.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V001.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V001.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); i = x0; j = y1; k = z0; V010.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V010.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V010.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); i = x0; j = y1; k = z1; V011.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V011.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V011.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); i = x1; j = y0; k = z0; V100.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V100.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V100.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); i = x1; j = y0; k = z1; V101.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V101.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V101.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); i = x1; j = y1; k = z0; V110.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V110.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V110.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); i = x1; j = y1; k = z1; V111.fX = (*m_grid)(i+1, j, k ) - (*m_grid)(i-1, j, k ); V111.fY = (*m_grid)(i, j+1, k ) - (*m_grid)(i, j-1, k ); V111.fZ = (*m_grid)(i, j, k+1) - (*m_grid)(i, j, k-1); GLvector p0; p0.fX = gx - x0; p0.fY = gy - y0; p0.fZ = gz - z0; GLvector p1; p1.fX = x1 - gx; p1.fY = y1 - gy; p1.fZ = z1 - gz; GLfloat dX, dY, dZ; dX = V000.fX * p1.fX * p1.fY * p1.fZ + V001.fX * p1.fX * p1.fY * p0.fZ + V010.fX * p1.fX * p0.fY * p1.fZ + V011.fX * p1.fX * p0.fY * p0.fZ + V100.fX * p0.fX * p1.fY * p1.fZ + V101.fX * p0.fX * p1.fY * p0.fZ + V110.fX * p0.fX * p0.fY * p1.fZ + V111.fX * p0.fX * p0.fY * p0.fZ; dY = V000.fY * p1.fX * p1.fY * p1.fZ + V001.fY * p1.fX * p1.fY * p0.fZ + V010.fY * p1.fX * p0.fY * p1.fZ + V011.fY * p1.fX * p0.fY * p0.fZ + V100.fY * p0.fX * p1.fY * p1.fZ + V101.fY * p0.fX * p1.fY * p0.fZ + V110.fY * p0.fX * p0.fY * p1.fZ + V111.fY * p0.fX * p0.fY * p0.fZ; dZ = V000.fZ * p1.fX * p1.fY * p1.fZ + V001.fZ * p1.fX * p1.fY * p0.fZ + V010.fZ * p1.fX * p0.fY * p1.fZ + V011.fZ * p1.fX * p0.fY * p0.fZ + V100.fZ * p0.fX * p1.fY * p1.fZ + V101.fZ * p0.fX * p1.fY * p0.fZ + V110.fZ * p0.fX * p0.fY * p1.fZ + V111.fZ * p0.fX * p0.fY * p0.fZ; norm.fX = -dX; norm.fY = -dY; norm.fZ = -dZ; normalizeVector(norm, norm); }
int main(int argc, char* argv[]) { //init MPI MPI_Init( &argc, &argv); int rank, size; MPI_Comm_rank( MPI_COMM_WORLD, &rank); MPI_Comm_size( MPI_COMM_WORLD, &size); //create a grid and some data if( size != 4){ std::cerr << "Please run with 4 threads!\n"; return -1;} double Tmax=2.*M_PI; double NT = 10; double dt = Tmax/NT; dg::Grid1d<double> gx( 0, 2.*M_PI, 3, 10); dg::Grid1d<double> gy( 0, 2.*M_PI, 3, 10); dg::Grid1d<double> gz( 0, 2.*M_PI, 1, 20); dg::Grid3d<double> g( gx, gy, gz); std::string hello = "Hello world\n"; thrust::host_vector<double> data = dg::evaluate( function, g); //create NetCDF File int ncid; file::NC_Error_Handle err; MPI_Info info = MPI_INFO_NULL; err = nc_create_par( "testmpi.nc", NC_NETCDF4|NC_MPIIO|NC_CLOBBER, MPI_COMM_WORLD, info, &ncid); err = nc_put_att_text( ncid, NC_GLOBAL, "input", hello.size(), hello.data()); int dimids[4], tvarID; err = file::define_dimensions( ncid, dimids, &tvarID, g); int dataID; err = nc_def_var( ncid, "data", NC_DOUBLE, 4, dimids, &dataID); /* Write metadata to file. */ err = nc_enddef(ncid); //err = nc_enddef( ncid); size_t start[4] = {0, rank*g.Nz()/size, 0, 0}; size_t count[4] = {1, g.Nz()/size, g.Ny()*g.n(), g.Nx()*g.n()}; if( rank==0) std::cout<< "Write from "<< start[0]<< " "<<start[1]<<" "<<start[2]<<" "<<start[3]<<std::endl; if( rank==0) std::cout<< "Number of elements "<<count[0]<< " "<<count[1]<<" "<<count[2]<<" "<<count[3]<<std::endl; err = nc_var_par_access(ncid, dataID , NC_COLLECTIVE); err = nc_var_par_access(ncid, tvarID , NC_COLLECTIVE); size_t Tcount=1, Tstart=0; double time = 0; //err = nc_close(ncid); for(unsigned i=0; i<=NT; i++) { if(rank==0)std::cout<<"Write timestep "<<i<<"\n"; //err = nc_open_par( "testmpi.nc", NC_WRITE|NC_MPIIO, MPI_COMM_WORLD, info, &ncid); //doesn't work I don't know why time = i*dt; Tstart = i; data = dg::evaluate( function, g); dg::blas1::scal( data, cos( time)); start[0] = i; //write dataset (one timeslice) err = nc_put_vara_double( ncid, dataID, start, count, data.data() + start[1]*count[2]*count[3]); err = nc_put_vara_double( ncid, tvarID, &Tstart, &Tcount, &time); //err = nc_close(ncid); } err = nc_close(ncid); MPI_Finalize(); return 0; }
void Tri2dFCBlockSolver::rhsViscous() { if (order == 1 || order == 2){ // Galerkin int n1,n2,n3,nn; double xa,ya,xb,yb,xc,yc,vr,fv[nq],gv[nq]; Array2D<double> qc(3,nq),qac(3,nqa),cx(3,2); for (int n=0; n<nTri; n++){ n1 = tri(n,0); n2 = tri(n,1); n3 = tri(n,2); xa = x(n1,0); ya = x(n1,1); xb = x(n2,0); yb = x(n2,1); xc = x(n3,0); yc = x(n3,1); vr = xa*(yb-yc)+xb*(yc-ya)+xc*(ya-yb); vr = 2./vr; for (int i=0; i<3; i++){ for (int k=0; k<nq ; k++) qc (i,k) = q (n1,k); for (int k=0; k<nqa; k++) qac(i,k) = qa(n1,k); cx(i,0) = .5*(x(n3,1)-x(n2,1)); cx(i,1) = .5*(x(n2,0)-x(n3,0)); nn = n1; n1 = n2; n2 = n3; n3 = nn; } sys->rhsVisFluxGalerkin(1,&vr,&cx(0,0),&qc(0,0),&qac(0,0),&fv[0],&gv[0]); for (int k=0; k<nq ; k++) d(n1,k) -=(cx(0,0)*fv[k]+cx(0,1)*gv[k]); for (int k=0; k<nq ; k++) d(n2,k) -=(cx(1,0)*fv[k]+cx(1,1)*gv[k]); for (int k=0; k<nq ; k++) d(n3,k) -=(cx(2,0)*fv[k]+cx(2,1)*gv[k]); } qc.deallocate(); qac.deallocate(); cx.deallocate(); } else{// third-order scheme int m,l1,l2,n1,n2; double dx,dy,fk,Ax,Ay,cf,cg,a=.5; Array2D<double> qaxE(nne,nqaGradQa),qayE(nne,nqaGradQa); Array2D<double> f(nne,nq),g(nne,nq); Array2D<double> fx(nne,nq),gx(nne,nq),fy(nne,nq),gy(nne,nq); for (int n=0; n<nElem; n++){ qaxE.set(0.); qayE.set(0.); fx.set(0.); fy.set(0.); gx.set(0.); gy.set(0.); // compute local gradients at the nodes in this element for (int i=0; i<nne; i++) for (int j=0; j<nne; j++){ dx = dxg(n,i,j,0); dy = dxg(n,i,j,1); m = elem(n,j); for (int k=0; k<nqaGradQa; k++){ qaxE(i,k) += qa(m,iqagrad(k))*dx; qayE(i,k) += qa(m,iqagrad(k))*dy; }} // compute viscous fluxes at the nodes in this element for (int i=0; i<nne; i++){ m = elem(n,i); sys->rhsVisFlux(1,&q(m,0),&qa(m,0),&qaxE(i,0),&qayE(i,0), &f(i,0),&g(i,0)); } // compute gradients of viscous fluxes for (int i=0; i<nne; i++) for (int j=0; j<nne; j++){ dx = dxg(n,i,j,0); dy = dxg(n,i,j,1); for (int k=0; k<nq ; k++){ fx(i,k) += f(j,k)*dx; gx(i,k) += g(j,k)*dx; fy(i,k) += f(j,k)*dy; gy(i,k) += g(j,k)*dy; }} // compute directed viscous fluxes and corrections // at edges and distribute to nodes for (int i=0; i<nee; i++){ l1 = edgeE(i,0); l2 = edgeE(i,1); n1 = elem(n,l1); n2 = elem(n,l2); Ax = a*areaE(n,i,0); Ay = a*areaE(n,i,1); dx = .5*(x(n2,0)-x(n1,0)); dy = .5*(x(n2,1)-x(n1,1)); for (int k=0; k<nq; k++){ cf = dx*(fx(l2,k)-fx(l1,k))+ dy*(fy(l2,k)-fy(l1,k)); cg = dx*(gx(l2,k)-gx(l1,k))+ dy*(gy(l2,k)-gy(l1,k)); fk = Ax*(f(l1,k)+f(l2,k)-cf)+Ay*(g(l1,k)+g(l2,k)-cg); d(n1,k) -= fk; d(n2,k) += fk; }}} qaxE.deallocate(); qayE.deallocate(); f.deallocate(); g.deallocate(); fx.deallocate(); gx.deallocate(); fy.deallocate(); gy.deallocate(); } }
int LinearizerDuality::linearize(const IntervalVector& box, LPSolver& lp_solver, BoxProperties& prop) { // ========= get active constraints =========== /* Using system cache seems not interesting. */ //BxpSystemCache* cache=(BxpSystemCache*) prop[BxpSystemCache::get_id(sys)]; BxpSystemCache* cache=NULL; //-------------------------------------------------------------------------- BitSet* active; if (cache!=NULL) { active = &cache->active_ctrs(); } else { active = new BitSet(sys.active_ctrs(box)); } // ============================================ size_t n = sys.nb_var; size_t m = sys.f_ctrs.image_dim(); size_t n_total = n + m*n; int nb_ctr=0; // number of inequalities added in the LP solver // BxpLinearRelaxArgMin* argmin=(BxpLinearRelaxArgMin*) prop[BxpLinearRelaxArgMin::get_id(sys)]; // // if (argmin && argmin->argmin()) { // pt=*argmin->argmin(); // } else pt=box.mid(); if (!active->empty()) { //IntervalMatrix J=cache? cache->active_ctrs_jacobian() : sys.f_ctrs.jacobian(box,active); //IntervalMatrix J=sys.f_ctrs.jacobian(box,*active); IntervalMatrix J(active->size(),n); // derivatives over the box sys.f_ctrs.hansen_matrix(box,pt,J,*active); if (J.is_empty()) { if (cache==NULL) delete active; return -1; } // the evaluation of the constraints in the point IntervalVector gx(sys.f_ctrs.eval_vector(pt,*active)); if (gx.is_empty()) { if (cache==NULL) delete active; return 0; } int i=0; // counter of active constraints for (BitSet::iterator c=active->begin(); c!=active->end(); ++c, i++) { if (!sys.f_ctrs.deriv_calculator().is_linear[c]) { for (size_t j=0; j<n; j++) { Vector row(n_total,0.0); row[j]=1; row[n + c*n +j]=1; double rhs = pt[j] - lp_solver.get_epsilon(); lp_solver.add_constraint(row, LEQ, rhs); nb_ctr++; } } Vector row(n_total,0.0); row.put(0,J[i].lb()); IntervalVector gl(J[i].lb()); Vector diam_correctly_rounded = (IntervalVector(J[i].ub())-gl).lb(); for (size_t j=0; j<n; j++) { if (diam_correctly_rounded[j]<0) ibex_error("negative diameter"); } row.put(n + c*n,-diam_correctly_rounded); double rhs = (-gx[i] + (gl*pt)).lb()- lp_solver.get_epsilon(); lp_solver.add_constraint(row, LEQ, rhs); nb_ctr++; } } if (cache==NULL) delete active; return nb_ctr; }
void grid_eval(cl::program_t& prog, size_t block0, size_t block1, size_t refine) { const size_t Nx = px.size(); const size_t Ny = py.size(); const size_t Nz = pz.size(); cl::ctx_t ctx(prog.context()); cl::queue_t queue(ctx, ctx.device(0)); init_mesh(); { cl::kernel_t kern = prog.kernel("grid"); boost::scoped_array<uint8_t> out(new uint8_t[block0 * block0 * block0]); boost::scoped_array<float> gx(new float[block0]); boost::scoped_array<float> gy(new float[block0]); boost::scoped_array<float> gz(new float[block0]); cl::mem_t gx_mem = ctx.create_buffer(CL_MEM_READ_ONLY, block0 * sizeof(float), NULL); cl::mem_t gy_mem = ctx.create_buffer(CL_MEM_READ_ONLY, block0 * sizeof(float), NULL); cl::mem_t gz_mem = ctx.create_buffer(CL_MEM_READ_ONLY, block0 * sizeof(float), NULL); cl::mem_t out_mem = ctx.create_buffer(CL_MEM_READ_WRITE, block0 * block0 * block0, NULL); const size_t Py = block0; const size_t Pz = block0 * block0; kern.arg(0, gx_mem); kern.arg(1, gy_mem); kern.arg(2, gz_mem); kern.arg(3, out_mem); kern.arg(4, Py); kern.arg(5, Pz); for (size_t _z = 0; _z < Nz; _z += block0 - 1) { const size_t Wz = std::min(block0, Nz - _z); for (size_t i = 0; i < Wz; ++i) gz[i] = (float)pz[_z + i]; queue.sync(cl::cmd_write_buffer(gz_mem, CL_FALSE, 0, Wz * sizeof(float), gz.get())); for (size_t _y = 0; _y < Ny; _y += block0 - 1) { const size_t Wy = std::min(block0, Ny - _y); for (size_t i = 0; i < Wy; ++i) gy[i] = (float)py[_y + i]; queue.sync(cl::cmd_write_buffer(gy_mem, CL_FALSE, 0, Wy * sizeof(float), gy.get())); for (size_t _x = 0; _x < Nx; _x += block0 - 1) { std::cerr << "block: " << _x << "," << _y << "," << _z << std::endl; const size_t Wx = std::min(block0, Nx - _x); for (size_t i = 0; i < Wx; ++i) gx[i] = (float)px[_x + i]; queue.sync(cl::cmd_write_buffer(gx_mem, CL_FALSE, 0, Wx * sizeof(float), gx.get())); queue.sync(cl::cmd_task(kern).wrk_sz(Wx, Wy, Wz)); queue.sync(cl::cmd_read_buffer( out_mem, CL_FALSE, 0, block0 * block0 * block0, out.get())); for (size_t z = 0; z < Wz - 1; ++z) { for (size_t y = 0; y < Wy - 1; ++y) { for (size_t x = 0; x < Wx - 1; ++x) { size_t bits = 0; if (out[(x + 0) + (y + 0) * Py + (z + 0) * Pz]) bits |= 0x01; if (out[(x + 1) + (y + 0) * Py + (z + 0) * Pz]) bits |= 0x02; if (out[(x + 0) + (y + 1) * Py + (z + 0) * Pz]) bits |= 0x04; if (out[(x + 1) + (y + 1) * Py + (z + 0) * Pz]) bits |= 0x08; if (out[(x + 0) + (y + 0) * Py + (z + 1) * Pz]) bits |= 0x10; if (out[(x + 1) + (y + 0) * Py + (z + 1) * Pz]) bits |= 0x20; if (out[(x + 0) + (y + 1) * Py + (z + 1) * Pz]) bits |= 0x40; if (out[(x + 1) + (y + 1) * Py + (z + 1) * Pz]) bits |= 0x80; const uint8_t* row = mc_table[bits]; size_t n_tri = *row++; if (n_tri == 0) continue; { for (size_t t = 0; t < n_tri; ++t) { uint8_t ea, eb, ec; size_t va, vb, vc; ea = *row++; eb = *row++; ec = *row++; va = get_intersection( decode_edge(_x + x, _y + y, _z + z, ea)); vb = get_intersection( decode_edge(_x + x, _y + y, _z + z, eb)); vc = get_intersection( decode_edge(_x + x, _y + y, _z + z, ec)); mesh->add_tri(va, vb, vc); } } } } } } } } } std::vector<std::pair<edgeint_t, size_t> > vert_calc; vert_calc.reserve(int_idx.size()); for (typename edgeint_map_t::iterator i = int_idx.begin(); i != int_idx.end(); ++i) { vert_calc.push_back(std::make_pair((*i).first, (*i).second)); } { boost::scoped_array<cl_float3> a(new cl_float3[block1]); boost::scoped_array<cl_float3> b(new cl_float3[block1]); boost::scoped_array<cl_float3> c(new cl_float3[block1]); cl::mem_t a_mem = ctx.create_buffer(CL_MEM_READ_ONLY, block1 * sizeof(cl_float3), NULL); cl::mem_t b_mem = ctx.create_buffer(CL_MEM_READ_ONLY, block1 * sizeof(cl_float3), NULL); cl::mem_t c_mem = ctx.create_buffer(CL_MEM_READ_WRITE, block1 * sizeof(cl_float3), NULL); cl::kernel_t kern = prog.kernel("chop"); kern.arg(0, a_mem); kern.arg(1, b_mem); kern.arg(2, c_mem); kern.arg(3, refine); for (size_t i = 0; i < vert_calc.size(); i += block1) { const size_t N = std::min(vert_calc.size() - i, block1); for (size_t j = 0; j < N; ++j) { edgeint_t& e = vert_calc[i + j].first; v3d_t a_pos = position_of_vertex(e.a[0], e.a[1], e.a[2]); v3d_t b_pos = position_of_vertex(e.b[0], e.b[1], e.b[2]); a[j].x = (float)a_pos.x; a[j].y = (float)a_pos.y; a[j].z = (float)a_pos.z; b[j].x = (float)b_pos.x; b[j].y = (float)b_pos.y; b[j].z = (float)b_pos.z; } queue.sync(cl::cmd_write_buffer(a_mem, CL_FALSE, 0, N * sizeof(cl_float3), a.get())); queue.sync(cl::cmd_write_buffer(b_mem, CL_FALSE, 0, N * sizeof(cl_float3), b.get())); queue.sync(cl::cmd_task(kern).wrk_sz(N)); queue.sync(cl::cmd_read_buffer(c_mem, CL_FALSE, 0, N * sizeof(cl_float3), c.get())); for (size_t j = 0; j < N; ++j) { mesh->vertices[vert_calc[i + j].second].pos = v3d_t::init(c[j].x, c[j].y, c[j].z); } } } }
void Terrain::loadFromFile(std::string path, std::string sectionName) { res::openArchive(path); int width,height,channels; unsigned char* heightmap = res::getTexture2DBuffer(sectionName, "heightmap", &width, &height, &channels); for(int i = 0; i < width*height; i++) heightmap[i] /= 2; float* tmpArray = new float[width * height * 3]; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { tmpArray[ coord(i, j)*3 ] = (float)i; tmpArray[ coord(i, j)*3 +1] = (float)heightmap[ coord(i, j) ]; tmpArray[ coord(i, j)*3 +2] = (float)j; } } mVertices.bind(); mVertices.alloc(width * height * 3); mVertices.sendData(0, tmpArray, width * height * 3); if(res::fileExists(sectionName, "normalmap")) { mNormalMap = res::getTexture2D(sectionName, "normalmap"); } else { // Sobel operator mat3 gx(-1.0, -2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 1.0); mat3 gy(-1.0, 0.0, 1.0, -2.0, 0.0, 2.0, -1.0, 0.0, 1.0); for(int i = 1; i < height-1; i++) { for(int j = 1; j < width-1; j++) { /*vec3 v1 = vec3( 0.0, ((float)heightmap[ coord(i-1, j) ] -(float)heightmap[ coord(i, j) ])/2, 1.0); v1.normalize(); vec3 v2 = vec3( 1.0, ((float)heightmap[ coord(i, j-1) ] -(float)heightmap[ coord(i, j) ])/2, 0.0); v2.normalize(); vec3 v3 = vec3( 0.0, ((float)heightmap[ coord(i+1, j) ] -(float)heightmap[ coord(i, j) ])/2, -1.0); v3.normalize(); vec3 v4 = vec3(-1.0, ((float)heightmap[ coord(i, j+1) ] -(float)heightmap[ coord(i, j) ])/2, 0.0); v4.normalize(); vec3 n = normalized( normalized(cross(v1, v2)) + normalized(cross(v2, v3)) + normalized(cross(v3, v4)) + normalized(cross(v4, v1)) ); float sx = coord(i < height-1 ? i+1 : i, j) - coord(i != 0 ? i-1 : i, j); if (i == 0 || i == height -1) sx *= 2; float sy = coord(i, j < width-1 ? j+1 : j) - coord(i, j != 0 ? j-1 : j); if (j == 0 || j == width -1) sy *= 2; n = normalized(vec3(-sx, 1, -sy));*/ mat3 img( HeightMacro(i+1, j-1)/5, HeightMacro(i+1, j)/5, HeightMacro(i+1, j+1)/5, HeightMacro(i , j-1)/5, HeightMacro(i , j)/5, HeightMacro(i , j+1)/5, HeightMacro(i-1, j-1)/5, HeightMacro(i-1, j)/5, HeightMacro(i-1, j+1)/5); float cx = img.convolution( gx ); float cy = img.convolution( gy ); /*mat3 fx = gx * img; mat3 fy = gy * img; float cx = fx[0] + fx[1] + fx[2] + fx[6] + fx[7] + fx[8]; float cy = fx[0] + fx[2] + fx[3] + fx[5] + fx[6] + fx[8];*/ float cz = 0.5 + sqrt((cx*cx, cy*cy)); vec3 n(cx, cz, cy); n.normalize(); tmpArray[ coord(i, j)*3 ] = n.x; tmpArray[ coord(i, j)*3 +1] = n.y; tmpArray[ coord(i, j)*3 +2] = n.z; } } /*mNormals.bind(); mNormals.alloc(width * height * 3); mNormals.sendData(0, tmpArray, width * height * 3);*/ } std::vector<unsigned int> indicesVec; mRoot->build(0, 0, width, height, 5, ChunkInfo(width, height, 16, 16, &indicesVec)); unsigned int indices[indicesVec.size()]; for(int i = 0; i < indicesVec.size(); i++) indices[i] = indicesVec[i]; mIndices.bind(); mIndices.alloc(indicesVec.size()); mIndices.sendData(0, indices, indicesVec.size()); mAlphaMap = res::getTexture2D(sectionName, "alphamap"); mDetailMaps = res::getTextureArray( res::getConf(sectionName, "detailtexturearray") ); res::closeArchive(); }
void LogBarrier::optimize() { Printer::getInstance().printStatusBegin("Optimizing (Log Barrier)..."); const size_t d = f.getNumberOfParameters(); xOpt.resize(0); fOpt = NAN; xHist.resize(0, d); fHist.resize(0); kHist.clear(); base::DataVector x(x0); float_t fx = f.eval(x); xHist.appendRow(x); fHist.append(fx); base::DataVector xNew(d); base::DataVector gx(g.getNumberOfComponents()); float_t mu = mu0; size_t breakIterationCounter = 0; const size_t BREAK_ITERATION_COUNTER_MAX = 10; size_t k = 1; const size_t unconstrainedN = N / 20; PenalizedObjectiveFunction fPenalized(f, g, mu); PenalizedObjectiveGradient fPenalizedGradient(fGradient, gGradient, mu); while (k < N) { fPenalized.setMu(mu); fPenalizedGradient.setMu(mu); AdaptiveGradientDescent unconstrainedOptimizer(fPenalized, fPenalizedGradient, unconstrainedN, 10.0 * theta); unconstrainedOptimizer.setStartingPoint(x); unconstrainedOptimizer.optimize(); xNew = unconstrainedOptimizer.getOptimalPoint(); const size_t numberInnerEvaluations = unconstrainedOptimizer.getHistoryOfOptimalPoints().getNrows(); k += numberInnerEvaluations; x = xNew; fx = f.eval(x); g.eval(x, gx); k++; xHist.appendRow(x); fHist.append(fx); kHist.push_back(numberInnerEvaluations); // status printing Printer::getInstance().printStatusUpdate(std::to_string(k) + " evaluations, x = " + x.toString() + ", f(x) = " + std::to_string(fx) + ", g(x) = " + gx.toString()); mu *= rhoMuMinus; xNew.sub(x); if (xNew.l2Norm() < theta) { breakIterationCounter++; if (breakIterationCounter >= BREAK_ITERATION_COUNTER_MAX) { break; } } else { breakIterationCounter = 0; } } xOpt.resize(d); xOpt = x; fOpt = fx; Printer::getInstance().printStatusEnd(); }