void getEclipseProperty(Matrix& propertyFrames, const QString &hostName, quint16 port, QString caseName, QString propertyName) { QString serverName = hostName; quint16 serverPort = port; const int Timeout = 5 * 1000; QTcpSocket socket; socket.connectToHost(serverName, serverPort); if (!socket.waitForConnected(Timeout)) { error((("Connection: ") + socket.errorString()).toLatin1().data()); return; } // Create command and send it: QString command("GetProperty "); command += caseName + " " + propertyName; QByteArray cmdBytes = command.toLatin1(); QDataStream socketStream(&socket); socketStream.setVersion(QDataStream::Qt_4_0); socketStream << (qint64)(cmdBytes.size()); socket.write(cmdBytes); // Get response. First wait for the header while (socket.bytesAvailable() < (int)(2*sizeof(quint64))) { if (!socket.waitForReadyRead(Timeout)) { error((("Wating for header: ") + socket.errorString()).toLatin1().data()); return; } } // Read timestep count and blocksize quint64 timestepCount; quint64 byteCount; size_t activeCellCount; socketStream >> timestepCount; socketStream >> byteCount; activeCellCount = byteCount / sizeof(double); propertyFrames.resize(activeCellCount, timestepCount); if (!(byteCount && timestepCount)) { error ("Could not find the requested data in ResInsight"); return; } // Wait for available data for each timestep, then read data for each timestep for (size_t tIdx = 0; tIdx < timestepCount; ++tIdx) { while (socket.bytesAvailable() < (int)byteCount) { if (!socket.waitForReadyRead(Timeout)) { error((("Waiting for timestep data number: ") + QString::number(tIdx)+ ": " + socket.errorString()).toLatin1().data()); octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl; return ; } OCTAVE_QUIT; } qint64 bytesRead = 0; double * internalMatrixData = propertyFrames.fortran_vec(); #if 1 // Use raw data transfer. Faster. bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount); #else for (size_t cIdx = 0; cIdx < activeCellCount; ++cIdx) { socketStream >> internalMatrixData[tIdx * activeCellCount + cIdx]; if (socketStream.status() == QDataStream::Ok) bytesRead += sizeof(double); } #endif if ((int)byteCount != bytesRead) { error("Could not read binary double data properly from socket"); octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl; } OCTAVE_QUIT; } QString tmp = QString("riGetActiveCellProperty : Read %1").arg(propertyName); if (caseName.isEmpty()) { tmp += QString(" from active case."); } else { tmp += QString(" from %1.").arg(caseName); } octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl; return; }
// eigen-decomposition of a symmetric matrix void Matrix::eig(Matrix& U, Matrix& lambda, unsigned int iter, bool ignoreError) const { ASSERT(isValid() && isSquare()); Matrix basic = *this; Matrix eigenval(m_rows); // 1-dim case if (m_rows == 1) { basic(0, 0) = 1.0; eigenval(0) = m_data[0]; return; } std::vector<double> oD(m_rows); unsigned int i, j, k, l, m; double b, c, f, g, h, hh, p, r, s, scale; // reduction to tridiagonal form for (i=m_rows; i-- > 1;) { h = 0.0; scale = 0.0; if (i > 1) for (k = 0; k < i; k++) scale += fabs(basic(i, k)); if (scale == 0.0) oD[i] = basic(i, i-1); else { for (k = 0; k < i; k++) { basic(i, k) /= scale; h += basic(i, k) * basic(i, k); } f = basic(i, i-1); g = (f > 0.0) ? -::sqrt(h) : ::sqrt(h); oD[i] = scale * g; h -= f * g; basic(i, i-1) = f - g; f = 0.0; for (j = 0; j < i; j++) { basic(j, i) = basic(i, j) / (scale * h); g = 0.0; for (k=0; k <= j; k++) g += basic(j, k) * basic(i, k); for (k=j+1; k < i; k++) g += basic(k, j) * basic(i, k); f += (oD[j] = g / h) * basic(i, j); } hh = f / (2.0 * h); for (j=0; j < i; j++) { f = basic(i, j); g = oD[j] - hh * f; oD[j] = g; for (k=0; k <= j; k++) basic(j, k) -= f * oD[k] + g * basic(i, k); } for (k=i; k--;) basic(i, k) *= scale; } eigenval(i) = h; } eigenval(0) = oD[0] = 0.0; // accumulation of transformation matrices for (i=0; i < m_rows; i++) { if (eigenval(i) != 0.0) { for (j=0; j < i; j++) { g = 0.0; for (k = 0; k < i; k++) g += basic(i, k) * basic(k, j); for (k = 0; k < i; k++) basic(k, j) -= g * basic(k, i); } } eigenval(i) = basic(i, i); basic(i, i) = 1.0; for (j=0; j < i; j++) basic(i, j) = basic(j, i) = 0.0; } // eigenvalues from tridiagonal form for (i=1; i < m_rows; i++) oD[i-1] = oD[i]; oD[m_rows - 1] = 0.0; for (l=0; l < m_rows; l++) { j = 0; do { // look for small sub-diagonal element for (m=l; m < m_rows - 1; m++) { s = fabs(eigenval(m)) + fabs(eigenval(m + 1)); if (fabs(oD[m]) + s == s) break; } p = eigenval(l); if (m != l) { if (j++ == iter) { // Too many iterations --> numerical instability! if (ignoreError) break; else throw("[Matrix::eig] numerical problems"); } // form shift g = (eigenval(l+1) - p) / (2.0 * oD[l]); r = ::sqrt(g * g + 1.0); g = eigenval(m) - p + oD[l] / (g + ((g > 0.0) ? fabs(r) : -fabs(r))); s = 1.0; c = 1.0; p = 0.0; for (i=m; i-- > l;) { f = s * oD[i]; b = c * oD[i]; if (fabs(f) >= fabs(g)) { c = g / f; r = ::sqrt(c * c + 1.0); oD[i+1] = f * r; s = 1.0 / r; c *= s; } else { s = f / g; r = ::sqrt(s * s + 1.0); oD[i+1] = g * r; c = 1.0 / r; s *= c; } g = eigenval(i+1) - p; r = (eigenval(i) - g) * s + 2.0 * c * b; p = s * r; eigenval(i+1) = g + p; g = c * r - b; for (k=0; k < m_rows; k++) { f = basic(k, i+1); basic(k, i+1) = s * basic(k, i) + c * f; basic(k, i) = c * basic(k, i) - s * f; } } eigenval(l) -= p; oD[l] = g; oD[m] = 0.0; } } while (m != l); } // normalize eigenvectors for (j=m_rows; j--;) { s = 0.0; for (i=m_rows; i--;) s += basic(i, j) * basic(i, j); s = ::sqrt(s); for (i=m_rows; i--;) basic(i, j) /= s; } // sort by eigenvalues std::vector<unsigned int> index(m_rows); for (i=0; i<m_rows; i++) index[i] = i; CmpIndex cmpidx(eigenval, index); std::sort(index.begin(), index.end(), cmpidx); U.resize(m_rows, m_rows); lambda.resize(m_rows); for (i=0; i<m_rows; i++) { j = index[i]; lambda(i) = eigenval(j); for (k=0; k<m_rows; k++) U(k, i) = basic(k, j); } }
int main() { //Get Learning Dictionary GetLearningDictionary(RGBDic,LabDic); //LabDic[0].print("OK?"); //Do Saliency Detection for(int FileNode=1; FileNode<=MAXPIC; FileNode++) { //GetPic Mat SourceImage; Mat RGBImage; Mat LABImage; sprintf(FileName,"%s%d.jpg",IMGSAIM,FileNode); //get filename SourceImage=imread(FileName); //load picture from file resize(SourceImage,RGBImage,Size(PICSIZE,PICSIZE),0,0,INTER_LINEAR); cvtColor(RGBImage,LABImage,COLOR_BGR2Lab); //translate RGB into Lab imshow("Source",RGBImage); Matrix<double> RGBCannels[3]; Matrix<double> LabCanenls[3]; SpMatrix<double> SPRGB[3]; SpMatrix<double> SPLab[3]; Matrix<double> RGBSaliency; Matrix<double> LabSaliency; Matrix<double> FinalSaliency; Sparam sparam; for(int ColorSpace=1; ColorSpace<=2; ColorSpace++) { Matrix<double> *Cannels; Matrix<double> *Dic; SpMatrix<double> *Sparsecode; Matrix<double> * Saliency; //Choose Image Color Space if(ColorSpace==1) { Cannels=RGBCannels; Dic=RGBDic; Sparsecode=SPRGB; Saliency=&RGBSaliency; } else { Cannels=LabCanenls; Dic=LabDic; Sparsecode=SPLab; Saliency=&LabSaliency; } //Split picture into different cannels and transform Mat into Matrix<T> SplitCannel(RGBImage,Cannels[0],Cannels[1],Cannels[2]); //Split Picture into R,G,B cannel for(int Can=0; Can<3; Can++) { //Image into Row ImageToCol(Cannels[Can],PATCHSIZE,PATCHSIZE); //Represent picture by sparse coding Matrix<double> Result; lasso(Cannels[Can],Dic[Can],Sparsecode[Can],sparam); Dic->mult(Sparsecode[Can],Result); //Result into Image ColToImage(Result,PATCHSIZE,PATCHSIZE,PICSIZE,PICSIZE); } //Get cannnel's local saliency for(int Can=0; Can<3; Can++) { LocalSailency(Sparsecode[Can],Cannels[Can]); Normalization(Cannels[Can]); } //Composite cannels' saliency into space's saliency Saliency->resize(PATCHLEN,PATCHLEN); Saliency->setZeros(); for(int Can=0; Can<3; Can++) Saliency->add(Cannels[Can]); Normalization(*Saliency); } //Composite Lab's and RGB's saliency into finnal sailency FinalSaliency.resize(PATCHLEN,PATCHLEN); FinalSaliency.setZeros(); FinalSaliency.add(LabSaliency); FinalSaliency.add(RGBSaliency); Normalization(FinalSaliency); //transform saliency into image Mat SaliencyImage(PATCHLEN,PATCHLEN,CV_8UC1); MatrixtoMat(FinalSaliency,SaliencyImage); imshow("Final Saliency",SaliencyImage); waitKey(0); } return 0; }
void ColumnGenSolve::parDijkstra(ColumnGenSolve::parDijkstraParams ¶ms) { for(;;) { // params.mutex.lock(); if(params.exiting) return; if(params.finished) { // std::this_thread::sleep_for(std::chrono::microseconds(1)); // params.mutex.unlock(); continue; } const BitMatrix &base = *params.baseStar; const Matrix<double> &mapW = *params.mapWStar; int n = params.n, m = params.m; Matrix<Pair<double, Point>> &ans = *params.ansStar; // simple Dijkstra algorithm Matrix<Pair<double, Point>> dist; dist.resize(n, m); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(base.get(i, j)) dist[i][j].second = Point(-1, -1); else dist[i][j].first = 1e30; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; int EX = 1; while(n * m > EX) EX <<= 1; vector<double> sgt; sgt.resize(EX << 1, 1e30); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(base.get(i, j)) sgt[EX + i * m + j] = 0; for(int i = EX - 1; i >= 1; i--) sgt[i] = min(sgt[i << 1], sgt[i << 1 | 1]); for(;;) { if(sgt[1] >= 1e25) break; int sgtIdx = 1; while(sgtIdx < EX) if(sgt[sgtIdx] == sgt[sgtIdx << 1]) sgtIdx <<= 1; else sgtIdx = (sgtIdx << 1 | 1); sgtIdx -= EX; int cx = sgtIdx / m, cy = sgtIdx % m; sgt[sgtIdx += EX] = 1e30; for(sgtIdx >>= 1; sgtIdx; sgtIdx >>= 1) sgt[sgtIdx] = min(sgt[sgtIdx << 1], sgt[sgtIdx << 1 | 1]); const Pair<double, Point> &cd = dist[cx][cy]; for(int d = 0; d < 4; d++) { int tx = cx + dx[d], ty = cy + dy[d]; if(tx < 0 || tx >= n || ty < 0 || ty >= m) continue; double tdFirst = cd.first + mapW[tx][ty]; if(tdFirst < dist[tx][ty].first) { dist[tx][ty].first = tdFirst; dist[tx][ty].second = Point(cx, cy); sgt[sgtIdx = EX + tx * m + ty] = tdFirst; for(sgtIdx >>= 1; sgtIdx; sgtIdx >>= 1) sgt[sgtIdx] = min(sgt[sgtIdx << 1], sgt[sgtIdx << 1 | 1]); } } } ans = dist; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { for(int d = 3; d >= 0; d--) { int tx = i + dx[d], ty = j + dy[d]; if(tx < 0 || tx >= n || ty < 0 || ty >= m) continue; if(dist[tx][ty].first < ans[i][j].first) { ans[i][j].first = dist[tx][ty].first; ans[i][j].second = Point(tx, ty); } } } params.finished = true; }
IGL_INLINE void igl::cotmatrix( const Eigen::MatrixBase<DerivedV> & V, const Eigen::MatrixBase<DerivedF> & F, Eigen::SparseMatrix<Scalar>& L) { using namespace Eigen; using namespace std; L.resize(V.rows(),V.rows()); Matrix<int,Dynamic,2> edges; int simplex_size = F.cols(); // 3 for triangles, 4 for tets assert(simplex_size == 3 || simplex_size == 4); if(simplex_size == 3) { // This is important! it could decrease the comptuation time by a factor of 2 // Laplacian for a closed 2d manifold mesh will have on average 7 entries per // row L.reserve(10*V.rows()); edges.resize(3,2); edges << 1,2, 2,0, 0,1; }else if(simplex_size == 4) { L.reserve(17*V.rows()); edges.resize(6,2); edges << 1,2, 2,0, 0,1, 3,0, 3,1, 3,2; }else { return; } // Gather cotangents Matrix<Scalar,Dynamic,Dynamic> C; cotmatrix_entries(V,F,C); vector<Triplet<Scalar> > IJV; IJV.reserve(F.rows()*edges.rows()*4); // Loop over triangles for(int i = 0; i < F.rows(); i++) { // loop over edges of element for(int e = 0;e<edges.rows();e++) { int source = F(i,edges(e,0)); int dest = F(i,edges(e,1)); IJV.push_back(Triplet<Scalar>(source,dest,C(i,e))); IJV.push_back(Triplet<Scalar>(dest,source,C(i,e))); IJV.push_back(Triplet<Scalar>(source,source,-C(i,e))); IJV.push_back(Triplet<Scalar>(dest,dest,-C(i,e))); } } L.setFromTriplets(IJV.begin(),IJV.end()); }
bool ASMs1D::evalSolution (Matrix& sField, const IntegrandBase& integrand, const RealArray* gpar, bool) const { sField.resize(0,0); const int p1 = curv->order(); // Fetch nodal (control point) coordinates FiniteElement fe(p1,firstIp); this->getNodalCoordinates(fe.Xn); Vector solPt; Matrix dNdu, Jac, Xtmp; Matrix3D d2Ndu2, Hess; if (nsd > 1 && (integrand.getIntegrandType() & Integrand::SECOND_DERIVATIVES)) fe.G.resize(nsd,2); // For storing d{X}/du and d2{X}/du2 // Evaluate the secondary solution field at each point const RealArray& upar = *gpar; size_t nPoints = upar.size(); for (size_t i = 0; i < nPoints; i++, fe.iGP++) { fe.u = upar[i]; // Fetch basis function derivatives at current integration point if (integrand.getIntegrandType() & Integrand::NO_DERIVATIVES) this->extractBasis(fe.u,fe.N); else if (integrand.getIntegrandType() & Integrand::SECOND_DERIVATIVES) this->extractBasis(fe.u,fe.N,dNdu,d2Ndu2); else this->extractBasis(fe.u,fe.N,dNdu); // Fetch indices of the non-zero basis functions at this point IntVec ip; scatterInd(p1,curv->basis().lastKnotInterval(),ip); // Fetch associated control point coordinates utl::gather(ip,nsd,fe.Xn,Xtmp); if (!dNdu.empty()) { // Compute the Jacobian inverse and derivatives fe.detJxW = utl::Jacobian(Jac,fe.dNdX,Xtmp,dNdu); // Compute Hessian of coordinate mapping and 2nd order derivatives if (integrand.getIntegrandType() & Integrand::SECOND_DERIVATIVES) { if (!utl::Hessian(Hess,fe.d2NdX2,Jac,Xtmp,d2Ndu2,fe.dNdX)) continue; else if (fe.G.cols() == 2) { // Store the first and second derivatives of {X} w.r.t. // the parametric coordinate (xi), in the G-matrix fe.G.fillColumn(1,Jac.ptr()); fe.G.fillColumn(2,Hess.ptr()); } } } // Now evaluate the solution field if (!integrand.evalSol(solPt,fe,Xtmp*fe.N,ip)) return false; else if (sField.empty()) sField.resize(solPt.size(),nPoints,true); sField.fillColumn(1+i,solPt); } return true; }
void getActiveCellProperty(Matrix& propertyFrames, const QString &serverName, quint16 serverPort, const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel) { QTcpSocket socket; socket.connectToHost(serverName, serverPort); if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs)) { error((("Connection: ") + socket.errorString()).toLatin1().data()); return; } QDataStream socketStream(&socket); socketStream.setVersion(riOctavePlugin::qtDataStreamVersion); // Create command as a string with arguments , and send it: QString command; command += "GetActiveCellProperty " + QString::number(caseId) + " " + propertyName + " " + porosityModel; for (int i = 0; i < requestedTimeSteps.length(); ++i) { if (i == 0) command += " "; command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based if (i != requestedTimeSteps.length() -1) command += " "; } QByteArray cmdBytes = command.toLatin1(); socketStream << (qint64)(cmdBytes.size()); socket.write(cmdBytes); // Get response. First wait for the header while (socket.bytesAvailable() < (int)(2*sizeof(quint64))) { if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs)) { error((("Waiting for header: ") + socket.errorString()).toLatin1().data()); return; } } // Read timestep count and blocksize quint64 timestepCount; quint64 byteCount; size_t activeCellCount; socketStream >> timestepCount; socketStream >> byteCount; activeCellCount = byteCount / sizeof(double); propertyFrames.resize(activeCellCount, timestepCount); if (!(byteCount && timestepCount)) { error ("Could not find the requested data in ResInsight"); return; } // Wait for available data for each timestep, then read data for each timestep for (size_t tIdx = 0; tIdx < timestepCount; ++tIdx) { while (socket.bytesAvailable() < (int)byteCount) { if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs)) { error((("Waiting for timestep data number: ") + QString::number(tIdx)+ ": " + socket.errorString()).toLatin1().data()); octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl; return ; } OCTAVE_QUIT; } qint64 bytesRead = 0; double * internalMatrixData = propertyFrames.fortran_vec(); #if 0 // Raw data transfer. Faster. Not possible when dealing with coarsening // bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount); #else // Compatible transfer. Now the only one working for (size_t cIdx = 0; cIdx < activeCellCount; ++cIdx) { socketStream >> internalMatrixData[tIdx * activeCellCount + cIdx]; if (socketStream.status() == QDataStream::Ok) bytesRead += sizeof(double); } #endif if ((int)byteCount != bytesRead) { error("Could not read binary double data properly from socket"); octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl; } OCTAVE_QUIT; } QString tmp = QString("riGetActiveCellProperty : Read %1").arg(propertyName); if (caseId < 0) { tmp += QString(" from current case."); } else { tmp += QString(" from case with Id: %1.").arg(caseId); } octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl; return; }
bool Elasticity::formBmatrix (Matrix& Bmat, const Matrix& dNdX) const { const size_t nenod = dNdX.rows(); const size_t nstrc = nsd*(nsd+1)/2; Bmat.resize(nstrc*nsd,nenod,true); if (dNdX.cols() < nsd) { std::cerr <<" *** Elasticity::formBmatrix: Invalid dimension on dNdX, " << dNdX.rows() <<"x"<< dNdX.cols() <<"."<< std::endl; return false; } #define INDEX(i,j) i+nstrc*(j-1) switch (nsd) { case 1: // Strain-displacement matrix for 1D elements: // // [B] = | d/dx | * [N] for (size_t i = 1; i <= nenod; i++) Bmat(1,i) = dNdX(i,1); break; case 2: // Strain-displacement matrix for 2D elements: // // | d/dx 0 | // [B] = | 0 d/dy | * [N] // | d/dy d/dx | for (size_t i = 1; i <= nenod; i++) { // Normal strain part Bmat(INDEX(1,1),i) = dNdX(i,1); Bmat(INDEX(2,2),i) = dNdX(i,2); // Shear strain part Bmat(INDEX(3,1),i) = dNdX(i,2); Bmat(INDEX(3,2),i) = dNdX(i,1); } break; case 3: // Strain-displacement matrix for 3D elements: // // | d/dx 0 0 | // | 0 d/dy 0 | // [B] = | 0 0 d/dz | * [N] // | d/dy d/dx 0 | // | d/dz 0 d/dx | // | 0 d/dz d/dy | for (size_t i = 1; i <= nenod; i++) { // Normal strain part Bmat(INDEX(1,1),i) = dNdX(i,1); Bmat(INDEX(2,2),i) = dNdX(i,2); Bmat(INDEX(3,3),i) = dNdX(i,3); // Shear strain part Bmat(INDEX(4,1),i) = dNdX(i,2); Bmat(INDEX(4,2),i) = dNdX(i,1); Bmat(INDEX(5,2),i) = dNdX(i,3); Bmat(INDEX(5,3),i) = dNdX(i,2); Bmat(INDEX(6,1),i) = dNdX(i,3); Bmat(INDEX(6,3),i) = dNdX(i,1); } break; default: std::cerr <<" *** Elasticity::formBmatrix: nsd="<< nsd << std::endl; return false; } #undef INDEX Bmat.resize(nstrc,nsd*nenod); return true; }
virtual void Jacobian(const Vector& x,Matrix& J) { J.resize(1,x.n); Vector Ji = x; Ji *= 2; J.copyRow(0,Ji); }
/* * DataMatrix data encoding, implements Barcode2dBase::encode() */ bool BarcodeDataMatrix::encode( const std::string& cookedData, Matrix<bool>& encodedData ) { std::vector<uint8_t> codewords; /* * Encode data into codewords */ int nRawCw = ecc200Encode( cookedData, codewords ); /* * Determine parameters for "best size" */ const DMParameterEntry * p = ecc200BestSizeParams( nRawCw ); if ( p == nullptr ) { return false; } encodedData.resize( p->nXtotal, p->nYtotal ); /* * Fill any extra data codewords */ ecc200Fill( codewords, nRawCw, p->nDataTotal ); /* * Calculate Reed-Solomon correction codewords */ int nTotalBlocks = p->nBlocks1 + p->nBlocks2; std::vector<uint8_t> ecc( p->nEccBlock*nTotalBlocks, 0 ); for ( int iBlock = 0; iBlock < p->nBlocks1; iBlock++ ) { ecc200EccBlock( codewords, ecc, p->nDataBlock1, p->nEccBlock, p->aSelect, iBlock, nTotalBlocks ); } for ( int iBlock = p->nBlocks1; iBlock < nTotalBlocks; iBlock++ ) { ecc200EccBlock( codewords, ecc, p->nDataBlock2, p->nEccBlock, p->aSelect, iBlock, nTotalBlocks ); } codewords.insert( codewords.end(), ecc.begin(), ecc.end() ); /* Append to data */ /* * Create raw data matrix */ Matrix<bool> matrix( p->nXregions * p->nXregion, p->nYregions * p->nYregion ); ecc200FillMatrix( matrix, codewords ); /* * Construct by separating out regions and inserting finder patterns */ int xstride = p->nXregion + 2; int ystride = p->nYregion + 2; for ( int iXregion = 0; iXregion < p->nXregions; iXregion++ ) { for ( int iYregion = 0; iYregion < p->nYregions; iYregion++ ) { Matrix<bool> region = matrix.subMatrix( iXregion*p->nXregion, iYregion*p->nYregion, p->nXregion, p->nYregion ); encodedData.setSubMatrix( iXregion*xstride + 1, iYregion*ystride + 1, region ); finderPattern( encodedData, iXregion*xstride, iYregion*ystride, xstride, ystride ); } } return true; }
void draw_mesh( const Eigen::MatrixXd & V, const Eigen::MatrixXi & F, const Eigen::MatrixXd & N, const Eigen::VectorXf & S, const GLuint & S_loc) { using namespace Eigen; using namespace std; static Matrix<float,Dynamic,3,RowMajor> VR,NR; static Matrix<int,Dynamic,3,RowMajor> FR; static Matrix<float,Dynamic,1,ColMajor> SR; static GLuint ibo,vbo,sbo,nbo; static bool scene_dirty = true; if(scene_dirty) { VR.resize(F.rows()*3,3); NR.resize(F.rows()*3,3); SR.resize(F.rows()*3,1); FR.resize(F.rows(),3); for(int f = 0;f<F.rows();f++) { for(int c = 0;c<3;c++) { VR.row(3*f+c) = V.row(F(f,c)).cast<float>(); SR(3*f+c) = S(F(f,c)); NR.row(3*f+c) = N.row(f).cast<float>(); FR(f,c) = 3*f+c; } } glGenBuffers(1,&ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(GLuint)*FR.size(),FR.data(),GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); glGenBuffers(1,&vbo); glGenBuffers(1,&nbo); glGenBuffers(1,&sbo); glBindBuffer(GL_ARRAY_BUFFER,vbo); glBufferData(GL_ARRAY_BUFFER,sizeof(float)*VR.size(),VR.data(),GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,nbo); glBufferData(GL_ARRAY_BUFFER,sizeof(float)*NR.size(),NR.data(),GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,sbo); glBufferData(GL_ARRAY_BUFFER,sizeof(float)*SR.size(),SR.data(),GL_STATIC_DRAW); igl::report_gl_error("glBindBuffer: "); scene_dirty = false; } glEnableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER,vbo); glVertexPointer(3,GL_FLOAT,0,0); glEnableClientState(GL_NORMAL_ARRAY); glBindBuffer(GL_ARRAY_BUFFER,nbo); glNormalPointer(GL_FLOAT,0,0); glBindBuffer(GL_ARRAY_BUFFER,sbo); glVertexAttribPointer(S_loc, 1, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(S_loc); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,ibo); glDrawElements(GL_TRIANGLES,FR.size(),GL_UNSIGNED_INT,0); glBindBuffer(GL_ARRAY_BUFFER,0); }
// Exepectation Maximization. int Logit::EM(Matrix& beta, double tol, int max_iter) { // Preprocess. set_bP(); Matrix U; Matrix psi(N); Matrix w(N); double dist = tol + 1.0; // Proper size. beta.resize(P); beta.fill(0.0); int iter = 0; while (dist > tol && iter < max_iter) { // std::cout << beta; // w: posterior mean gemm(psi, tX, beta, 'T', 'N'); for (int i = 0; i < (int)N; ++i) { double hpsi = psi(i) * 0.5; // n * tanh(psi/2) / (psi/2) * 0.5 if ( fabs(hpsi) < 0.01 ) { w(i) = n(i) / cosh(hpsi) * (1 + hpsi*hpsi / 6.0 + pow(hpsi, 4.0) / 120.0 + pow(hpsi, 6) / 5040.0) * 0.25 ; } else w(i) = n(i) * tanh(hpsi) / hpsi * 0.25; } // beta: posterior mode Matrix old_beta(beta); // tXRtOm = tX sqrt(Om) Matrix tXRtOm(P, N); for(unsigned int j=0; j<tX.cols(); j++) { double rtw = sqrt(w(j)); for(unsigned int i=0; i<tX.rows(); i++) { tXRtOm(i,j) = tX(i,j) * rtw; } } // PP = X' Om X + P0. PP = P0; // syrk(PP, tXRtOm, 'N', 1.0, 1.0); gemm(PP, tXRtOm, tXRtOm, 'N', 'T', 1.0, 1.0); chol(U, PP, 'U'); beta.clone(bP); trsm(U, beta, 'U', 'L', 'T'); // U' y = bP trsm(U, beta, 'U', 'L', 'N'); // U beta = y // symsolve(PP, beta); // Check how much we improved. // Matrix diff = beta - old_beta; // dist = sqrt( dot(diff, diff) ); Matrix diff = fabs(beta - old_beta); dist = *std::max_element(diff.begin(), diff.end()); ++iter; } return iter; }
void Logit::compress() { // Push everything into a list. list<double> ylist; list<Matrix> xlist; list<double> nlist; // Our data should not have n_data(i)=0. for(uint i=0; i < N; ++i){ ylist.push_back(y(i)); xlist.push_back(tX.col(i)); nlist.push_back(n(i)); } // Merge data. list<double>::iterator y_i; list<Matrix>::iterator x_i; list<double>::iterator n_i; list<double>::iterator y_j; list<Matrix>::iterator x_j; list<double>::iterator n_j; x_i = xlist.begin(); y_i = ylist.begin(); n_i = nlist.begin(); while(x_i != xlist.end()){ x_j = x_i; y_j = y_i; n_j = n_i; ++x_j; ++y_j; ++n_j; while(x_j != xlist.end()){ if (*x_i == *x_j) { double sum = *n_i + *n_j; *y_i = (*n_i/sum) * *y_i + (*n_j/sum) * *y_j; *n_i = sum; // Increment THEN erase! // Actually, send pointer to erase, then increment, then erase. xlist.erase(x_j++); ylist.erase(y_j++); nlist.erase(n_j++); } else { ++x_j; ++y_j; ++n_j; } } ++x_i; ++y_i; ++n_i; } uint old_N = N; // Record to see if we have changed data. // Set up y, tX, n. N = xlist.size(); // cout << "Old N: " << old_N << " N: " << N << "\n"; // Warning... if (old_N != N) { printf("Warning: data was combined!\n"); printf("N: %i, P: %i \n", N, P); } // Matrix y(N); y.resize(N); tX.resize(P, N); n.resize(N); x_i = xlist.begin(); y_i = ylist.begin(); n_i = nlist.begin(); for(uint i = 0; i < N; ++i){ y(i) = *y_i++; tX.col(i) = *x_i++; n(i) = *n_i++; } // cout << "y:\n" << y; // cout << "tX:\n" << tX; // cout << "n:\n" << n; }
bool configure(ResourceFinder &rf) { string robot=rf.check("robot",Value("icub")).asString().c_str(); string name=rf.check("name",Value("karmaToolFinder")).asString().c_str(); arm=rf.check("arm",Value("right")).asString().c_str(); eye=rf.check("eye",Value("left")).asString().c_str(); if ((arm!="left") && (arm!="right")) { printf("Invalid arm requested!\n"); return false; } if ((eye!="left") && (eye!="right")) { printf("Invalid eye requested!\n"); return false; } Property optionArmL("(device cartesiancontrollerclient)"); optionArmL.put("remote",("/"+robot+"/cartesianController/left_arm").c_str()); optionArmL.put("local",("/"+name+"/left_arm").c_str()); if (!drvArmL.open(optionArmL)) { printf("Cartesian left_arm controller not available!\n"); terminate(); return false; } Property optionArmR("(device cartesiancontrollerclient)"); optionArmR.put("remote",("/"+robot+"/cartesianController/right_arm").c_str()); optionArmR.put("local",("/"+name+"/right_arm").c_str()); if (!drvArmR.open(optionArmR)) { printf("Cartesian right_arm controller not available!\n"); terminate(); return false; } if (arm=="left") drvArmL.view(iarm); else drvArmR.view(iarm); Property optionGaze("(device gazecontrollerclient)"); optionGaze.put("remote","/iKinGazeCtrl"); optionGaze.put("local",("/"+name+"/gaze").c_str()); if (drvGaze.open(optionGaze)) drvGaze.view(igaze); else { printf("Gaze controller not available!\n"); terminate(); return false; } Bottle info; igaze->getInfo(info); if (Bottle *pB=info.find(("camera_intrinsics_"+eye).c_str()).asList()) { int cnt=0; Prj.resize(3,4); for (int r=0; r<Prj.rows(); r++) for (int c=0; c<Prj.cols(); c++) Prj(r,c)=pB->get(cnt++).asDouble(); } else { printf("Camera intrinsic parameters not available!\n"); terminate(); return false; } imgInPort.open(("/"+name+"/img:i").c_str()); imgOutPort.open(("/"+name+"/img:o").c_str()); dataInPort.open(("/"+name+"/in").c_str()); logPort.open(("/"+name+"/log:o").c_str()); rpcPort.open(("/"+name+"/rpc").c_str()); attach(rpcPort); Vector min(3),max(3); min[0]=-1.0; max[0]=1.0; min[1]=-1.0; max[1]=1.0; min[2]=-1.0; max[2]=1.0; solver.setBounds(min,max); solution.resize(3,0.0); enabled=false; dataInPort.setReader(*this); return true; }
/** Return a matrix containing appropriate representation of an area of the board centred around the given move so it can be fed directly into a BPN network. The area size is determined by the value of PATTERNWIDTH and PATTERNHEIGHT. @param x The x coordinate to centre on. @param y The y coordinate to centre on. @param b The Board object from which to extract an area. @param input A return parameter to store the converted, NN ready input matrix. @param colour The colour whose point of view we are creating this input pattern for. I.e. which colour this move is being scored for. */ bool Safety1BPNGoAdapter::getInput(int x, int y, const BoardStruct& b, Matrix<float>& input, int colour) const { /** @todo This is the old contents, needs to be rewritten for Safety1 design. */ const BoardStruct::contentsType& t = b.getContents(); float act = 0; // board contents should be rotated so that nearest two board edges // are the top and left, this gets rid of all rotational symmetry int width = t.getWidth(); int height = t.getHeight(); int leftdist = x; int rightdist = width-x-1; int topdist = y; int bottomdist = height-y-1; bool topcloser = true; bool leftcloser = true; // top left sides always preferred if equidistant from two edges if(topdist>bottomdist) topcloser = false; if(leftdist>rightdist) leftcloser = false; // copy board into a matrix so we can rotate later BoardStruct::contentsType temp2(t); BoardStruct::contentsType temp(temp2.width, temp2.height); // if bottom right edges closer if(!topcloser && !leftcloser) { // rotate temp 180 clw temp2.doTransform(temp, Matrix_ROTATE180); // translate x and y now to match newly rotated board x = rightdist; y = bottomdist; } // if top right edges closer else if(topcloser && !leftcloser) { // rotate temp 270 clw temp2.doTransform(temp, Matrix_ROTATE270); x = topdist; y = rightdist; } // if bottom left edges closer else if(!topcloser && leftcloser) { // rotate temp 90 clw temp2.doTransform(temp, Matrix_ROTATE90); x = bottomdist; y = leftdist; } // no rotation else temp = temp2; // 3 units per point + 18 units for distance to nearest board edges input.resize(1, getBPN().getWeights()[0].getHeight()); // now extract contents of board around this point // values to work around area centred on x,y // extending as PATTERNWIDTHxPATTERNHEIGHT int pWidth = getPatternWidth(); int pHeight = getPatternHeight(); int topleftx = x-(pWidth/2); int toplefty = y-(pHeight/2); int offsetx = 0; int offsety = 0; int count = 0; vector<SpecialPoint> points; getInputFieldPoints(temp, points, x, y); vector<SpecialPoint>::const_iterator citer = points.begin(); for(;citer!=points.end();citer++) { if(citer->type==OFFBOARD) setPoint(input, count++, ACT_OFFBOARD); else setPoint(input, count++, getActivationValue(citer->type, colour)); } // add distance to edge values for last 18 neurons // 9 neurons for top edge distance // 9 neurons for left edge distance // use binary type system // all off except the nth neuron indicating the distance // the distance to top and left edges (now the nearest after rotation) // should now be x, y // top distance for(int i=0;i<9;i++) { if((i+1)==x) input.setValue(0, (count*4)+i, 1); else input.setValue(0, (count*4)+i, 0); } // left distance for(i=0;i<9;i++) { if((i+1)==y) input.setValue(0, ((count*4)+9)+i, 1); else input.setValue(0, ((count*4)+9)+i, 0); } //input.setValue(0, count*3, x); //input.setValue(0, (count*3)+1, y); return true; }
virtual void Jacobian(const Vector& x,Matrix& J) { J.resize(1,x.n); J(0,0) = -Cos(x[0]); J(0,1) = 1.0; }
IGL_INLINE void igl::massmatrix( const Eigen::MatrixBase<DerivedV> & V, const Eigen::MatrixBase<DerivedF> & F, const MassMatrixType type, Eigen::SparseMatrix<Scalar>& M) { using namespace Eigen; using namespace std; const int n = V.rows(); const int m = F.rows(); const int simplex_size = F.cols(); MassMatrixType eff_type = type; // Use voronoi of for triangles by default, otherwise barycentric if(type == MASSMATRIX_TYPE_DEFAULT) { eff_type = (simplex_size == 3?MASSMATRIX_TYPE_VORONOI:MASSMATRIX_TYPE_BARYCENTRIC); } // Not yet supported assert(type!=MASSMATRIX_TYPE_FULL); Matrix<int,Dynamic,1> MI; Matrix<int,Dynamic,1> MJ; Matrix<Scalar,Dynamic,1> MV; if(simplex_size == 3) { // Triangles // edge lengths numbered same as opposite vertices Matrix<Scalar,Dynamic,3> l(m,3); // loop over faces for(int i = 0;i<m;i++) { l(i,0) = (V.row(F(i,1))-V.row(F(i,2))).norm(); l(i,1) = (V.row(F(i,2))-V.row(F(i,0))).norm(); l(i,2) = (V.row(F(i,0))-V.row(F(i,1))).norm(); } Matrix<Scalar,Dynamic,1> dblA; doublearea(l,dblA); switch(eff_type) { case MASSMATRIX_TYPE_BARYCENTRIC: // diagonal entries for each face corner MI.resize(m*3,1); MJ.resize(m*3,1); MV.resize(m*3,1); MI.block(0*m,0,m,1) = F.col(0); MI.block(1*m,0,m,1) = F.col(1); MI.block(2*m,0,m,1) = F.col(2); MJ = MI; repmat(dblA,3,1,MV); MV.array() /= 6.0; break; case MASSMATRIX_TYPE_VORONOI: { // diagonal entries for each face corner // http://www.alecjacobson.com/weblog/?p=874 MI.resize(m*3,1); MJ.resize(m*3,1); MV.resize(m*3,1); MI.block(0*m,0,m,1) = F.col(0); MI.block(1*m,0,m,1) = F.col(1); MI.block(2*m,0,m,1) = F.col(2); MJ = MI; // Holy shit this needs to be cleaned up and optimized Matrix<Scalar,Dynamic,3> cosines(m,3); cosines.col(0) = (l.col(2).array().pow(2)+l.col(1).array().pow(2)-l.col(0).array().pow(2))/(l.col(1).array()*l.col(2).array()*2.0); cosines.col(1) = (l.col(0).array().pow(2)+l.col(2).array().pow(2)-l.col(1).array().pow(2))/(l.col(2).array()*l.col(0).array()*2.0); cosines.col(2) = (l.col(1).array().pow(2)+l.col(0).array().pow(2)-l.col(2).array().pow(2))/(l.col(0).array()*l.col(1).array()*2.0); Matrix<Scalar,Dynamic,3> barycentric = cosines.array() * l.array(); normalize_row_sums(barycentric,barycentric); Matrix<Scalar,Dynamic,3> partial = barycentric; partial.col(0).array() *= dblA.array() * 0.5; partial.col(1).array() *= dblA.array() * 0.5; partial.col(2).array() *= dblA.array() * 0.5; Matrix<Scalar,Dynamic,3> quads(partial.rows(),partial.cols()); quads.col(0) = (partial.col(1)+partial.col(2))*0.5; quads.col(1) = (partial.col(2)+partial.col(0))*0.5; quads.col(2) = (partial.col(0)+partial.col(1))*0.5; quads.col(0) = (cosines.col(0).array()<0).select( 0.25*dblA,quads.col(0)); quads.col(1) = (cosines.col(0).array()<0).select(0.125*dblA,quads.col(1)); quads.col(2) = (cosines.col(0).array()<0).select(0.125*dblA,quads.col(2)); quads.col(0) = (cosines.col(1).array()<0).select(0.125*dblA,quads.col(0)); quads.col(1) = (cosines.col(1).array()<0).select(0.25*dblA,quads.col(1)); quads.col(2) = (cosines.col(1).array()<0).select(0.125*dblA,quads.col(2)); quads.col(0) = (cosines.col(2).array()<0).select(0.125*dblA,quads.col(0)); quads.col(1) = (cosines.col(2).array()<0).select(0.125*dblA,quads.col(1)); quads.col(2) = (cosines.col(2).array()<0).select( 0.25*dblA,quads.col(2)); MV.block(0*m,0,m,1) = quads.col(0); MV.block(1*m,0,m,1) = quads.col(1); MV.block(2*m,0,m,1) = quads.col(2); break; } case MASSMATRIX_TYPE_FULL: assert(false && "Implementation incomplete"); break; default: assert(false && "Unknown Mass matrix eff_type"); } }else if(simplex_size == 4) { assert(V.cols() == 3); assert(eff_type == MASSMATRIX_TYPE_BARYCENTRIC); MI.resize(m*4,1); MJ.resize(m*4,1); MV.resize(m*4,1); MI.block(0*m,0,m,1) = F.col(0); MI.block(1*m,0,m,1) = F.col(1); MI.block(2*m,0,m,1) = F.col(2); MI.block(3*m,0,m,1) = F.col(3); MJ = MI; // loop over tets for(int i = 0;i<m;i++) { // http://en.wikipedia.org/wiki/Tetrahedron#Volume Matrix<Scalar,3,1> v0m3 = V.row(F(i,0)) - V.row(F(i,3)); Matrix<Scalar,3,1> v1m3 = V.row(F(i,1)) - V.row(F(i,3)); Matrix<Scalar,3,1> v2m3 = V.row(F(i,2)) - V.row(F(i,3)); Scalar v = fabs(v0m3.dot(v1m3.cross(v2m3)))/6.0; MV(i+0*m) = v/4.0; MV(i+1*m) = v/4.0; MV(i+2*m) = v/4.0; MV(i+3*m) = v/4.0; } }else { // Unsupported simplex size assert(false && "Unsupported simplex size"); } sparse(MI,MJ,MV,n,n,M); }
virtual void Jacobian(const Vector& dxddx,Matrix& J) { J.resize(3,6); J.setZero(); for(int i=0;i<3;i++) J(i,i+3) = 1.0; }
bool ASMs1D::globalL2projection (Matrix& sField, const IntegrandBase& integrand, bool continuous) const { if (!curv) return true; // silently ignore empty patches if (continuous) { std::cerr <<" *** ASMs1D::globalL2projection: Only discrete L2-projection" <<" is available in this method.\n " <<" Use ASMbase::L2projection instead."<< std::endl; } const int p1 = curv->order(); // Get Gaussian quadrature point coordinates const int ng1 = p1 - 1; const double* xg = GaussQuadrature::getCoord(ng1); if (!xg) return false; // Compute parameter values of the Gauss points over the whole patch Matrix gp; RealArray gpar = this->getGaussPointParameters(gp,ng1,xg); // Evaluate the secondary solution at all integration points if (!this->evalSolution(sField,integrand,&gpar)) return false; // Set up the projection matrices const size_t nnod = this->getNoNodes(); const size_t ncomp = sField.rows(); SparseMatrix A(SparseMatrix::SUPERLU); StdVector B(nnod*ncomp); A.redim(nnod,nnod); Vector phi(p1); // === Assembly loop over all elements in the patch ========================== int ip = 0; for (size_t iel = 0; iel < nel; iel++) { if (MLGE[iel] < 1) continue; // zero-area element // --- Integration loop over all Gauss points in current element ----------- for (int i = 1; i <= ng1; i++, ip++) { // Fetch basis function values at current integration point this->extractBasis(gp(i,1+iel),phi); // Integrate the linear system A*x=B for (size_t ii = 0; ii < phi.size(); ii++) { int inod = MNPC[iel][ii]+1; for (size_t jj = 0; jj < phi.size(); jj++) { int jnod = MNPC[iel][jj]+1; A(inod,jnod) += phi[ii]*phi[jj]; } for (size_t r = 1; r <= ncomp; r++) B(inod+(r-1)*nnod) += phi[ii]*sField(r,ip+1); } } } // Solve the patch-global equation system if (!A.solve(B)) return false; // Store the control-point values of the projected field sField.resize(ncomp,nnod); for (size_t i = 1; i <= nnod; i++) for (size_t j = 1; j <= ncomp; j++) sField(j,i) = B(i+(j-1)*nnod); return true; }
void Copy(Real m,Matrix& mat) { mat.resize(1,1); mat(0,0)=m; }
Vector<Tree *> ColumnGenSolve::route(int tim) const { // Open a console for output OFStream con("con"); auto clkStart = clock(); // Constant definition const Board *board = solver->board; const Vector<TerminalSet *> &termsets = board->terminalSets; const Matrix<int> &map = board->map; const int t = termsets.size() - 1; const int n = board->height; const int m = board->width; if(n * m >= 1250) cout << "solving subproblem " << n << " * " << m << "\n"; // Two useful Vectors /* Vector<Point> allPoints; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) allPoints.push_back(Point(i, j)); */ Matrix<double> all1; all1.resize(n, m); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) all1[i][j] = 1; // The tree set, initially empty Vector<Vector<Pair<Tree, GRBVar>>> treesets; for(int idx = 1; idx <= t; idx++) { // Current tree set Vector<Pair<Tree, GRBVar>> vec; // Add the set to the set list treesets.push_back(vec); } // Answer history Vector<double> tarAns; for(int T = 0;; T++){ // Solve the integer (binary) programming problem double curAns = solveLP(treesets, 1); tarAns.push_back(curAns); // Construct current best answer Vector<Tree *> ans; for(const auto &treeset: treesets) { for(const auto &treeVar: treeset) if(treeVar.second.get(GRB_DoubleAttr_X) > 0.5) { ans.push_back(new Tree(treeVar.first)); goto found; } ans.push_back(NULL); found:; } bool updated = false; // Build weight map for unrouted set Matrix<double> mapObs; mapObs.resize(n, m); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(map[i][j] == -1) mapObs[i][j] = M; else mapObs[i][j] = 1; for(int idx = 1; idx <= t; idx++) if(ans[idx - 1]) for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(ans[idx - 1]->map.get(i, j)) mapObs[i][j] = M; // Try to generate from each set for(int idx = 1; idx <= t; idx++) { if(termsets[idx]->points.empty()) continue; if(!ans[idx - 1]){ // If unrouted, try to generate from the map above if(suggestTree(termsets, treesets, mapObs, n, m, idx)) updated = true; }else{ // If routed { // Try to reroute current set Matrix<double> mapObs2 = mapObs; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if( mapObs2[i][j] >= M / 2 && ans[idx - 1]->map.get(i, j) ) mapObs2[i][j] = 1; if(suggestTree(termsets, treesets, mapObs2, n, m, idx)) updated = true; } { /* Try to reroute current set and try to route another tree rather than current tree */ Matrix<double> mapObs2 = mapObs; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if( mapObs2[i][j] >= M / 2 && !ans[idx - 1]->map.get(i, j) ) mapObs2[i][j] = M * M; if(suggestTree(termsets, treesets, mapObs2, n, m, idx)) updated = true; } { /* Try to solve integer programming without current set and try to avoid overlap between current tree and the solution above */ solveLP(treesets, 1, NULL, NULL, idx); Vector<Tree *> tmpAns; for(int i = 0; i < t; i++) if(i != idx - 1) { for(const auto &treeVar: treesets[i]) if(treeVar.second.get(GRB_DoubleAttr_X) > 0.5) { tmpAns.push_back(new Tree(treeVar.first)); goto found2; } tmpAns.push_back(NULL); found2:; } else tmpAns.push_back(NULL); // OK, let's construct weight map Matrix<double> mapObs2; mapObs2.resize(n, m); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(map[i][j] == -1) mapObs2[i][j] = M * M; else mapObs2[i][j] = 1; for(int nidx = 1; nidx <= t; nidx++) if(tmpAns[nidx - 1]) for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(tmpAns[nidx - 1]->map.get(i, j)) mapObs2[i][j] = M; if(suggestTree(termsets, treesets, mapObs2, n, m, idx)) updated = true; // clean up for(auto tree: tmpAns) delete tree; } } } auto clkNow = clock(); // If solution didn't improve recently, // cut! if(T >= 1 && fabs(tarAns[T - 1] - tarAns[T]) < 0.5) return ans; // Output current colution info if(n * m >= 20) { cout << "iteration " << T << "\n"; cout << "current time: " << (int) ((clkNow - clkStart) / CLOCKS_PER_SEC) << " seconds\n"; cout << "curAns " << curAns << endl; cout << "column sizes:\n"; for(const auto &treeset: treesets) cout << treeset.size() << " "; cout << "\n"; cout.flush(); if(n * m >= 80) { Solution solution; solution.board = solver->board; solution.trees.push_back(NULL); for(auto tree: ans) if(tree) solution.trees.push_back(new Tree(*tree)); else solution.trees.push_back(NULL); solution.computeMap(); con << solution; con.flush(); } } // Still cannot generate, cut if(!updated) return ans; // Clean up for(auto tree: ans) delete tree; } }
/** Calculate Constitutive Matrix, using the pertubation method */ void Hyperelastic2D::CalculateConstitutiveMatrix(const Vector& StrainVector, Matrix& rResult) { if( rResult.size1() != 3 ) // EBST { rResult.resize(3,3); } // Vector E1(6); Vector S1(6); Vector E2(6); Vector S2(6); // Vector E1; // array_1d<double,6> S1; // Vector E2; // array_1d<double,6> S2; ///////////// TANGENT MATRIX /////////// SERGIO OLLER + NELSON // PERTUBATION METHOD long double dE=0.00; // delta strain //double epsilon_real=std::numeric_limits<double>::epsilon(); //pertubation //KRATOS_WATCH(epsilon_real); long double epsilon=1E-9; // pertubation long double max=1E-14; E1.resize(6,false); //S1.resize(6,false); E2.resize(6,false); //S2.resize(6,false); // for EBST and Membrane mcurrentThickness=(mA0/mA)*mThickness; //KRATOS_WATCH(mA0); //KRATOS_WATCH(mA); //KRATOS_WATCH(mThickness); //KRATOS_WATCH(mcurrentThickness); double Ez = 0.0; // Uncomment below if you want to use Ez (uncomment the part related to y too! - line 587) Ez = (1.0/2.0)*((pow(mcurrentThickness,2.0)-pow(mThickness,2.0))/pow(mThickness,2.0)); //KRATOS_WATCH(Ez); Vector auxStrainVector(6); // 6 components auxStrainVector[0] = StrainVector[0]-mRetraction*(0.8*StrainVector[0]); // 0.8*StrainVector[0] represents E0 auxStrainVector[1] = StrainVector[1]-mRetraction*(0.8*StrainVector[1]); auxStrainVector[2] = Ez; auxStrainVector[3] = StrainVector[2]; auxStrainVector[4] = 0.0; auxStrainVector[5] = 0.0; //KRATOS_WATCH (auxStrainVector); Vector auxStressVector(6); // 6 components E1=auxStrainVector; //KRATOS_WATCH (E1); E2=auxStrainVector; //KRATOS_WATCH (E2); Matrix Ctot(6,6); // noalias(Ctot)=ZeroMatrix(6,6); // before Ctang //KRATOS_WATCH (Ctot); //// NEW FORM dE=(*std::min_element(auxStrainVector.begin(),auxStrainVector.end()))*epsilon; if (dE==0.00) { dE=epsilon; } if (dE<max) { dE=max; } for (unsigned int i=0; i<6; i++) { E2(i)+=dE; //pertubed Strain E2 Hyperelastic2D::CalculateStressVector(E1,S1); // computing stress S1 Hyperelastic2D::CalculateStressVector(E2,S2); // computing pertubed stress S2 noalias(S2)=S2-S1; noalias(S2)=S2/(dE); for (unsigned int j=0; j<6; j++) { Ctot(j,i)=S2(j); // Tangent Matrix } //E2.resize(6,false); //S2.resize(6,false); noalias(E2) = ZeroVector(6); noalias(S2) = ZeroVector(6); //noalias(E2) = StrainVector; } //noalias(rResult)=Ctang; // 2D //KRATOS_WATCH (Ctot); //noalias(rResult)=Ctang; // 2D // TEST !!! Matrix auxCtang2(4,4); for (unsigned int i=0; i<4; i++) { for (unsigned int j=0; j<4; j++) { auxCtang2(i,j)=Ctot(i,j); // aux Tangent Matrix 4X4 } } //KRATOS_WATCH (auxCtang2); // below putting zeros in last line and column Matrix auxCtang3(4,4); noalias(auxCtang3)=auxCtang2; for (unsigned int i=0; i<4; i++) { auxCtang3(2,i)=auxCtang2(3,i); auxCtang3(3,i)=auxCtang2(2,i); auxCtang3(i,2)=auxCtang2(i,3); auxCtang3(i,3)=auxCtang2(i,2); } //auxCtang3(2,2)=auxCtang2(3,3); //auxCtang3(2,3)=auxCtang2(3,2); //auxCtang3(3,2)=auxCtang2(2,3); //auxCtang3(3,3)=auxCtang2(2,2); //KRATOS_WATCH (auxCtang3(3,3)); // end - Matrix 4X4 with last line and column with zeros (ref Sigma_Z) Matrix v(3,3); for (unsigned int i=0; i<3; i++) { for (unsigned int j=0; j<3; j++) { v(i,j)=auxCtang3(i,j); } } //KRATOS_WATCH (v); Matrix w(3,1); for (unsigned int i=0; i<3; i++) { w(i,0)=auxCtang3(i,3); } //KRATOS_WATCH (w); Matrix x(1,3); for (unsigned int i=0; i<3; i++) { x(0,i)=auxCtang3(3,i); } //KRATOS_WATCH (x); double y=auxCtang3(3,3); //KRATOS_WATCH (y); Matrix auxCtang(3,3); noalias(auxCtang) += v; //KRATOS_WATCH (auxCtang); Matrix auxtest(3,3); noalias(auxtest) = prod(w,x); //KRATOS_WATCH (auxtest); // if (y != 0.0) // { // auxtest *= (1.0)/y; // } // else // { // y = 0.000000000000000000001; // auxtest *= (1.0)/y; // } // Uncomment below if considering Ez auxtest *= (1.0)/y; //KRATOS_WATCH (auxtest); noalias(auxCtang) -= auxtest; //KRATOS_WATCH (auxCtang); noalias(rResult)=auxCtang; //KRATOS_WATCH (rResult); }
double ColumnGenSolve::solveLP( Vector<Vector<Pair<Tree, GRBVar>>> &treesets, int mode, Matrix<double> *mapPi, Vector<double> *vecLambda, int ignoreIdx ) const { int t = (int) treesets.size(); const Board *board = solver->board; int n = board->height; int m = board->width; GRBModel &model = GRBFactory::createModel(); // Create variables for trees for(int i = 0; i < t; i++) if(i != ignoreIdx - 1) for(auto &treeVar: treesets[i]) treeVar.second = model.addVar( 0, 1, 0, mode ? GRB_BINARY : GRB_CONTINUOUS ); // Create variables for sets Vector<GRBVar> varCanRoute; for(int i = 0; i < t; i++) varCanRoute.push_back(model.addVar( 0, 1, 0, mode ? GRB_BINARY : GRB_CONTINUOUS )); model.update(); // Create target GRBLinExpr target; for(int i = 0; i < t; i++) { target += M * varCanRoute[i]; if(i != ignoreIdx - 1) for(const auto &treeVar: treesets[i]) target += treeVar.first.length * treeVar.second; } model.setObjective(target, GRB_MINIMIZE); // Create constraints for sets Vector<GRBConstr> constrCanRoute; for(int i = 0; i < t; i++) { GRBLinExpr consLeft; consLeft += varCanRoute[i]; if(i != ignoreIdx - 1) for(const auto &treeVar: treesets[i]) consLeft += treeVar.second; constrCanRoute.push_back(model.addConstr(consLeft == 1)); } // Create constraints for grids Matrix<GRBConstr> constrNode; constrNode.resize(n, m); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { GRBLinExpr consLeft; for(int idx = 0; idx < t; idx++) if(idx != ignoreIdx - 1) for(const auto &treeVar: treesets[idx]) if(treeVar.first.map.get(i, j)) consLeft += treeVar.second; if(board->map[i][j] == -1) constrNode[i][j] = model.addConstr(consLeft == 0); else constrNode[i][j] = model.addConstr(consLeft <= 1); } // Optimize! model.optimize(); double ans = model.get(GRB_DoubleAttr_ObjVal); // If mode is binary, dual values are not calculated, // we only return the answer. // if(mode) // return ans; // Get dual values of each grid if(mapPi != NULL) { mapPi->resize(n, m); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) (*mapPi)[i][j] = constrNode[i][j].get(GRB_DoubleAttr_Pi); } // Get dual values of each set if(vecLambda != NULL) { vecLambda->clear(); for(const auto &cons: constrCanRoute) vecLambda->push_back(cons.get(GRB_DoubleAttr_Pi)); } return ans; }
bool QMCSHLinearOptimize::run() { start(); //size of matrix numParams = optTarget->NumParams(); N = numParams + 1; // initialize our parameters vector<RealType> currentOvlp(N,0); vector<RealType> currentHOvlp(N,0); vector<RealType> currentParameters(numParams,0); RealType E_avg(0); vector<RealType> bestParameters(currentParameters); optdir.resize(numParams,0); optparm.resize(numParams,0); for (int i=0; i<numParams; i++) optparm[i] = currentParameters[i] = optTarget->Params(i); bool acceptedOneMove(false); int tooManyTries(20); int failedTries(0); RealType lastCost(0); RealType startCost(0); startCost = lastCost = optTarget->Cost(false); app_log()<<"Starting cost: "<<startCost<<endl; Matrix<RealType> OM; OM.resize(N,N); dmcEngine->fillVectors(currentOvlp,currentHOvlp,E_avg,OM); for (int i=0; i<numParams; i++) optdir[i]=currentOvlp[i]; std::vector<RealType> dP(N,1); for (int i=0; i<numParams; i++) dP[i+1]=optdir[i]; Lambda = getNonLinearRescale(dP,OM); app_log()<<"rescaling factor :"<<Lambda<<endl; RealType bigOptVec(std::abs(optdir[0])); for (int i=1; i<numParams; i++) bigOptVec =std::max(std::abs(optdir[i]),bigOptVec); // app_log()<<"currentOvlp"<<endl; // for (int i=0; i<numParams; i++) // app_log()<<optdir[i]<<" "; // app_log()<<endl; // // app_log()<<"optparam"<<endl; // for (int i=0; i<numParams; i++) // app_log()<<optparm[i]<<" "; // app_log()<<endl; if (MinMethod=="rescale") { if (bigOptVec*std::abs(Lambda)>bigChange) app_log()<<" Failed Step. Largest LM parameter change:"<<bigOptVec*std::abs(Lambda)<<endl; else { for (int i=0; i<numParams; i++) bestParameters[i] = optTarget->Params(i) = currentParameters[i] + Lambda*optdir[i]; acceptedOneMove = true; } } else if (MinMethod=="overlap") { orthoScale(optdir,OM); if (bigOptVec>bigChange) app_log()<<" Failed Step. Largest LM parameter change:"<<bigOptVec<<endl; else { for (int i=0; i<numParams; i++) bestParameters[i] = optTarget->Params(i) = currentParameters[i] + optdir[i]; acceptedOneMove = true; } } else if (MinMethod=="average") { for (int i=0; i<numParams; i++) bestParameters[i] = optTarget->Params(i) = currentParameters[i] + currentHOvlp[i]; acceptedOneMove = true; } else { TOL = param_tol/bigOptVec; AbsFuncTol=true; largeQuarticStep=bigChange/bigOptVec; quadstep = stepsize*Lambda; //bigOptVec; // initial guess for line min bracketing LambdaMax = quadstep; myTimers[3]->start(); if (MinMethod=="quartic") { int npts(7); lineoptimization3(npts,startCost); } else lineoptimization2(); myTimers[3]->stop(); RealType biggestParameterChange = bigOptVec*std::abs(Lambda); if (biggestParameterChange>bigChange) { app_log()<<" Failed Step. Largest LM parameter change:"<<biggestParameterChange<<endl; for (int i=0; i<numParams; i++) optTarget->Params(i) = bestParameters[i] = currentParameters[i]; } else { for (int i=0; i<numParams; i++) optTarget->Params(i) = optparm[i] + Lambda * optdir[i]; lastCost = optTarget->Cost(false); app_log()<<" Costs: "<<startCost<<" "<<lastCost<<endl; app_log()<<" Optimal rescaling factor :"<<Lambda<<endl; if (lastCost<startCost) acceptedOneMove = true; else { for (int i=0; i<numParams; i++) optTarget->Params(i) = currentParameters[i]; app_log()<<" Failed Step. Cost increase "<<endl; } } } // if (acceptedOneMove) // for (int i=0; i<numParams; i++) optTarget->Params(i) = bestParameters[i]; // else // for (int i=0; i<numParams; i++) optTarget->Params(i) = currentParameters[i]; // if (W.getActiveWalkers()>NumOfVMCWalkers) // { // W.destroyWalkers(W.getActiveWalkers()-NumOfVMCWalkers); // app_log() << " QMCLinearOptimize::generateSamples removed walkers." << endl; // app_log() << " Number of Walkers per node " << W.getActiveWalkers() << endl; // } finish(); return (optTarget->getReportCounter() > 0); }
Matrix Assignment::ImportAssignment(ifstream& input_file){ Matrix matrix; string line; vector<double> numstream; size_t num_rows = 0; size_t num_cols = 0; if (input_file.is_open()) { while (!input_file.eof() ) { getline (input_file,line); size_t local_num_cols=0; vector<double> local_numstream; local_numstream.clear(); string word; stringstream parse(line); while(parse >> word){ //if comment line, ignore it if(word[0] == '#') break; //numstream.push_back(atoi(word.c_str())); //if not number, then convert to zero numstream.push_back(atof(word.c_str())); //if not number, then convert to zero //local_numstream.push_back(atoi(word.c_str())); local_numstream.push_back(atof(word.c_str())); //matrix(num_rows, num_cols)= atoi(word.c_str()); local_num_cols++; } //end inner while //judge if the matrix format is correct or not if(num_cols && local_num_cols && num_cols!=local_num_cols){ cerr<<endl<<"Please input a correct matrix format!"<<endl<<endl; exit(-1); } //update column number if everything looks normal if(local_num_cols) num_cols = local_num_cols; //update row number if everything looks normal if(line.length()&&local_numstream.size()) num_rows++; } //end out layer while input_file.close(); //update class data members this->num_agents = num_rows; this->num_tasks = num_cols; //put elements into matrix //matrix.resize(num_rows, num_cols); matrix.resize(num_rows); for(unsigned int i=0; i<num_rows; i++) matrix[i].resize(num_cols); vector<double>::iterator itr = numstream.begin(); for(unsigned int i=0; i<num_rows; i++) for(unsigned int j=0; j<num_cols; j++) matrix[i][j].SetWeight(*itr++); } //end outmost if else{
IGL_INLINE void igl::cotmatrix( const Eigen::MatrixBase<DerivedV> & V, const Eigen::MatrixBase<DerivedF> & F, Eigen::SparseMatrix<Scalar>& L) { using namespace igl; using namespace Eigen; Eigen::DynamicSparseMatrix<double> foo; DynamicSparseMatrix<Scalar, RowMajor> dyn_L (V.rows(), V.rows()); Matrix<int,Dynamic,2> edges; int simplex_size = F.cols(); // 3 for triangles, 4 for tets assert(simplex_size == 3 || simplex_size == 4); if(simplex_size == 3) { // This is important! it could decrease the comptuation time by a factor of 2 // Laplacian for a closed 2d manifold mesh will have on average 7 entries per // row dyn_L.reserve(7*V.rows()); edges.resize(3,2); edges << 1,2, 2,0, 0,1; }else if(simplex_size == 4) { dyn_L.reserve(17*V.rows()); edges.resize(6,2); edges << 1,2, 2,0, 0,1, 3,0, 3,1, 3,2; }else { return; } // Gather cotangents Matrix<Scalar,Dynamic,Dynamic> C; cotangent(V,F,C); // Loop over triangles for(int i = 0; i < F.rows(); i++) { // loop over edges of element for(int e = 0;e<edges.rows();e++) { int source = F(i,edges(e,0)); int dest = F(i,edges(e,1)); dyn_L.coeffRef(source,dest) += C(i,e); dyn_L.coeffRef(dest,source) += C(i,e); dyn_L.coeffRef(source,source) += -C(i,e); dyn_L.coeffRef(dest,dest) += -C(i,e); } } // Corner indices of this triangle L = SparseMatrix<Scalar>(dyn_L); }
void getActiveCellProperty(Matrix& propertyFrames, const QString &serverName, quint16 serverPort, const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel) { QTcpSocket socket; socket.connectToHost(serverName, serverPort); if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs)) { error((("Connection: ") + socket.errorString()).toLatin1().data()); return; } QDataStream socketStream(&socket); socketStream.setVersion(riOctavePlugin::qtDataStreamVersion); // Create command as a string with arguments , and send it: QString command; command += "GetActiveCellProperty " + QString::number(caseId) + " " + propertyName + " " + porosityModel; for (int i = 0; i < requestedTimeSteps.length(); ++i) { if (i == 0) command += " "; command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based if (i != requestedTimeSteps.length() -1) command += " "; } QByteArray cmdBytes = command.toLatin1(); socketStream << (qint64)(cmdBytes.size()); socket.write(cmdBytes); // Get response. First wait for the header while (socket.bytesAvailable() < (int)(2*sizeof(quint64))) { if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs)) { error((("Waiting for header: ") + socket.errorString()).toLatin1().data()); return; } } // Read timestep count and blocksize quint64 timestepCount; quint64 byteCount; size_t activeCellCount; socketStream >> timestepCount; socketStream >> byteCount; activeCellCount = byteCount / sizeof(double); propertyFrames.resize(activeCellCount, timestepCount); if (!(byteCount && timestepCount)) { error ("Could not find the requested data in ResInsight"); return; } quint64 totalByteCount = byteCount * timestepCount; double* internalMatrixData = propertyFrames.fortran_vec(); QStringList errorMessages; if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), totalByteCount, errorMessages)) { for (int i = 0; i < errorMessages.size(); i++) { error(errorMessages[i].toLatin1().data()); } return; } QString tmp = QString("riGetActiveCellProperty : Read %1").arg(propertyName); if (caseId < 0) { tmp += QString(" from current case."); } else { tmp += QString(" from case with Id: %1.").arg(caseId); } octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl; return; }
/** Return a matrix containing appropriate representation of an area of the board centred around the given move so it can be fed directly into a BPN network. The area size is determined by the value of PATTERNWIDTH and PATTERNHEIGHT. @param x The x coordinate to centre on. @param y The y coordinate to centre on. @param b The Board object from which to extract an area. @param input A return parameter to store the converted, NN ready input matrix. @param colour The colour whose point of view we are creating this input pattern for. I.e. which colour this move is being scored for. */ bool newBPN4GoAdapter::getInput(int x, int y, const BoardStruct& b, Matrix<float>& input, int colour) const { const BoardStruct::contentsType& t = b.getContents(); float act = 0; // board contents should be rotated so that nearest two board edges // are the top and left, this gets rid of all rotational symmetry int width = t.getWidth(); int height = t.getHeight(); int leftdist = x; int rightdist = width-x-1; int topdist = y; int bottomdist = height-y-1; bool topcloser = true; bool leftcloser = true; // top left sides always preferred if equidistant from two edges if(topdist>bottomdist) topcloser = false; if(leftdist>rightdist) leftcloser = false; // copy board into a matrix so we can rotate later BoardStruct::contentsType temp2(t); BoardStruct::contentsType temp(temp2.width, temp2.height); // if bottom right edges closer if(!topcloser && !leftcloser) { // rotate temp 180 clw temp2.doTransform(temp, Matrix_ROTATE180); // translate x and y now to match newly rotated board x = rightdist; y = bottomdist; } // if top right edges closer else if(topcloser && !leftcloser) { // rotate temp 270 clw temp2.doTransform(temp, Matrix_ROTATE270); x = topdist; y = rightdist; } // if bottom left edges closer else if(!topcloser && leftcloser) { // rotate temp 90 clw temp2.doTransform(temp, Matrix_ROTATE90); x = bottomdist; y = leftdist; } // no rotation else temp = temp2; // 3 units per point + 18 units for distance to nearest board edges input.resize(1, getBPN().getWeights()[0].getHeight()); // now extract contents of board around this point // values to work around area centred on x,y // extending as PATTERNWIDTHxPATTERNHEIGHT int pWidth = getPatternWidth(); int pHeight = getPatternHeight(); int topleftx = x-(pWidth/2); int toplefty = y-(pHeight/2); int offsetx = 0; int offsety = 0; int count = 0; vector<SpecialPoint> points; getInputFieldPoints(temp, points, x, y); vector<SpecialPoint>::const_iterator citer = points.begin(); for(;citer!=points.end();citer++) { if(citer->type==OFFBOARD) setPoint(input, count++, ACT_OFFBOARD); else setPoint(input, count++, getActivationValue(citer->type, colour)); } /* // find equivalent input values for(int i=0;i<pHeight;i++) { offsety = i+toplefty; for(int j=0;j<pWidth;j++) { offsetx = j+topleftx; // check bounds to see if this point is off the board if(offsetx<0 || offsety<0 || offsetx>=width || offsety>=height) setPoint(input, count, ACT_OFFBOARD); else setPoint(input, count, getActivationValue(temp.getValue(offsetx, offsety), colour)); count++; } // end for j } // end for i */ // add distance to edge values for last 18 neurons // 9 neurons for top edge distance // 9 neurons for left edge distance // use binary type system // all off except the nth neuron indicating the distance // the distance to top and left edges (now the nearest after rotation) // should now be x, y int base = count*4; // top distance for(int i=0;i<9;i++) { if((i+1)==x) input.setValue(0, base+i, 1); else input.setValue(0, base+i, 0); } base = (count*4)+9; // left distance for(i=0;i<9;i++) { if((i+1)==y) input.setValue(0, base+i, 1); else input.setValue(0, base+i, 0); } // liberties neurons, 4 for each north, south, east and west // indicating one of 1,2,3>=4 liberties for string in that direction base = (count*4)+18; for(i=0;i<16;i++) input.setValue(0, base+i, 0); // north if((y-1)>=0) setLibertyNeurons(base, b, x, y-1, input); // south if((y+1)<b.getSize()) setLibertyNeurons(base+4, b, x, y+1, input); // east if((x+1)>=0) setLibertyNeurons(base+8, b, x+1, y, input); // west if((x-1)<b.getSize()) setLibertyNeurons(base+12, b, x-1, y, input); return true; }
/* * * Linear assignment problem solution * [modifies matrix in-place.] * matrix(row,col): row major format assumed. * * Assignments are remaining 0 values * (extra 0 values are replaced with -1) * */ void Munkres::solve(Matrix<double> &m) { const unsigned int rows = m.rows(), columns = m.columns(), size = std::max<unsigned int>(rows, columns); #ifdef DEBUG std::cout << "Munkres input matrix:" << std::endl; for ( unsigned int row = 0 ; row < rows ; row++ ) { for ( unsigned int col = 0 ; col < columns ; col++ ) { std::cout.width(8); std::cout << m(row, col) << ","; } std::cout << std::endl; } std::cout << std::endl; #endif bool notdone = true; int step = 1; // Copy input matrix this->matrix = m; if ( rows != columns ) { // If the input matrix isn't square, make it square // and fill the empty values with the largest value present // in the matrix. matrix.resize(size, size, matrix.max()); } // STAR == 1 == starred, PRIME == 2 == primed mask_matrix.resize(size, size); row_mask = new bool[size]; col_mask = new bool[columns]; for ( unsigned int i = 0 ; i < size ; i++ ) { row_mask[i] = false; } for ( unsigned int i = 0 ; i < size ; i++ ) { col_mask[i] = false; } // Prepare the matrix values... // If there were any infinities, replace them with a value greater // than the maximum value in the matrix. replace_infinites(matrix); minimize_along_direction(matrix, false); minimize_along_direction(matrix, true); // Follow the steps while ( notdone ) { switch ( step ) { case 0: notdone = false; // end the step flow break; case 1: step = step1(); // step is always 2 break; case 2: step = step2(); // step is always either 0 or 3 break; case 3: step = step3(); // step in [3, 4, 5] break; case 4: step = step4(); // step is always 2 break; case 5: step = step5(); // step is always 3 break; } } // Store results for ( unsigned int row = 0 ; row < size ; row++ ) { for ( unsigned int col = 0 ; col < size ; col++ ) { if ( mask_matrix(row, col) == STAR ) { matrix(row, col) = 0; } else { matrix(row, col) = -1; } } } #ifdef DEBUG std::cout << "Munkres output matrix:" << std::endl; for ( unsigned int row = 0 ; row < rows ; row++ ) { for ( unsigned int col = 0 ; col < columns ; col++ ) { std::cout.width(1); std::cout << matrix(row, col) << ","; } std::cout << std::endl; } std::cout << std::endl; #endif // Remove the excess rows or columns that we added to fit the // input to a square matrix. matrix.resize(rows, columns); m = matrix; delete [] row_mask; delete [] col_mask; }
// multiplies A*B^T and stores it in *this void multSEQ( Matrix& C, const Matrix& A, const Matrix& B, uint32 blocksize, int impose) { // assertion seems strange, but remember that we compute A*B^T uint32 l, m, n; if (impose == 1) { l = A.nRows(); m = B.nRows(); n = B.nCols(); } else { l = A.nRows(); m = B.nCols(); n = B.nRows(); } C.resize(l*m); std::cout << "Matrix Multiplication" << std::endl; timeval start, stop; clock_t cStart, cStop; mat sum = 0; #if __F4RT_DEBUG std::cout << std::endl; std::cout << "A => " << A.nRows() << "-" << A.nCols() << "-" << A.nEntries() << std::endl; std::cout << "B => " << A.nRows() << "-" << A.nCols() << "-" << A.nEntries() << std::endl; std::cout << "C => " << C.nRows() << "-" << C.nCols() << "-" << C.nEntries() << std::endl; #endif gettimeofday(&start, NULL); cStart = clock(); if (impose == 1) { for (uint32 i = 0; i < l; ++i) { for (uint32 j = 0; j < m; ++j) { sum = 0; for (uint32 k = 0; k < n; k++) { // sum += A(i,k) * B(j,k); sum += A.entries[k+i*n] * B.entries[k+j*n]; } //std::cout << j+i*m << ". " << sum << std::endl; C.entries[j+i*m] = (mat) (sum); } } } else { for (uint32 i = 0; i < l; ++i) { for (uint32 j = 0; j < m; ++j) { sum = 0; for (uint32 k = 0; k < n; k++) { // sum += A(i,k) * B(k,j); sum += A.entries[k+i*n] * B.entries[j+k*m]; } C.entries[j+i*m] = (mat) (sum); } } } gettimeofday(&stop, NULL); cStop = clock(); std::cout << "---------------------------------------------------" << std::endl; std::cout << "Method: Raw sequential" << std::endl; std::cout << "Cache improved: "; if (impose == 1) std::cout << "1" << std::endl; else std::cout << "0" << std::endl; // compute FLOPS: // assume addition and multiplication in the mult kernel are 2 operations // done A.nRows() * B.nRows() * B.nCols() double flops = 2 * A.nRows() * B.nRows() * B.nCols(); float epsilon = 0.0000000001; double realtime = ((stop.tv_sec - start.tv_sec) * 1e6 + (stop.tv_usec - start.tv_usec)) / 1e6; double cputime = (double)((cStop - cStart)) / CLOCKS_PER_SEC; char buffer[50]; // get digits before decimal point of cputime (the longest number) and setw // with it: digits + 1 (point) + 4 (precision) int digits = sprintf(buffer,"%.0f",cputime); double ratio = cputime/realtime; std::cout << "# Threads: " << 1 << std::endl; std::cout << "Block size: " << blocksize << std::endl; std::cout << "- - - - - - - - - - - - - - - - - - - - - - - - - -" << std::endl; std::cout << "Real time: " << std::setw(digits+1+4) << std::setprecision(4) << std::fixed << realtime << " sec" << std::endl; std::cout << "CPU time: " << std::setw(digits+1+4) << std::setprecision(4) << std::fixed << cputime << " sec" << std::endl; if (cputime > epsilon) std::cout << "CPU/real time: " << std::setw(digits+1+4) << std::setprecision(4) << std::fixed << ratio << std::endl; std::cout << "- - - - - - - - - - - - - - - - - - - - - - - - - -" << std::endl; std::cout << "GFLOPS/sec: " << std::setw(digits+1+4) << std::setprecision(4) << std::fixed << flops / (1000000000 * realtime) << std:: endl; std::cout << "---------------------------------------------------" << std::endl; }