int minCut(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int len = s.size(); if(!len) return 0; vector<vector<bool>> dp1(len, vector<bool>(len, false)); for(int l = 1; l <= len; l++) { for(int i = 0; i <= len-l; i++) { if(l == 1) dp1[i][i] = true; else if(l == 2) dp1[i][i+1] = (s[i] == s[i+1]); else dp1[i][i+l-1] = (s[i] == s[i+l-1] && dp1[i+1][i+l-2]); } } vector<int> dp2(len, 0); for(int i = 1; i < len; i++) { dp2[i] = dp2[i-1]+1; for(int j = i-1; j >= 0; j--) { if(dp1[j][i]) dp2[i] = (j == 0)?0:min(dp2[i],dp2[j-1]+1); } } return dp2[len-1]; }
int _dp1(int x) { int ans = 0; if (col[x]) { edge *tmp = chi[x].next; if (not tmp) { ans = 1; } else { int mul = 1; while (tmp) { mul *= dp1(tmp->v); tmp = tmp->next; } tmp = chi[x].next; while (tmp) { if (dp1(tmp->v)) ans += dp2(tmp->v) * mul / dp1(tmp->v); tmp = tmp->next; } ans += mul; } } else { edge *tmp = chi[x].next; int cnt = 0; int mul = 1; while (tmp) { ++ cnt; mul *= dp1(tmp->v); tmp = tmp->next; } ans = cnt * mul; } return momo1[x] = ans; }
NS_IMETHODIMP GTKEmbedDirectoryProvider::GetFiles(const char *aKey, nsISimpleEnumerator* *aResult) { nsCOMPtr<nsIDirectoryServiceProvider2> dp2(do_QueryInterface(EmbedPrivate::sAppFileLocProvider)); if (!dp2) return NS_ERROR_FAILURE; return dp2->GetFiles(aKey, aResult); }
int rob(vector<int>& nums) { if (nums.size() == 0) return 0; vector<int> dp1(nums.size()); // Rob current vector<int> dp2(nums.size()); // No rob current dp1[0] = nums[0]; dp2[0] = 0; for (int i = 1; i < nums.size(); ++i) { dp1[i] = dp2[i - 1] + nums[i]; dp2[i] = max(dp1[i - 1], dp2[i - 1]); // Can skip 2 houses max } return max(dp1[nums.size() - 1], dp2[nums.size() - 1]); }
int countNumbersWithUniqueDigits(int n) { // start coding at 11:09 vector<int> dp1(1, 0); vector<int> dp2(1, 1); dp1.push_back(9); dp2.push_back(10); if (n < 2) return dp2[n]; while (dp2.size() <= n) { dp1.push_back(dp1.back() * (10-dp1.size()+1)); dp2.push_back(dp2.back() + dp1.back()); } return dp2.back(); }
int rob(vector<int>& nums){ int n = nums.size(); if(n == 0) return 0; if(n == 1) return nums[0]; //dp1: dp without the last one, dp2: dp without the first one vector<int> dp1(n - 1), dp2(n - 1); dp1[0] = nums[0]; dp1[1] = max(nums[0], nums[1]); for(int i = 2; i < n - 1; i++){ dp1[i] = max(dp1[i - 1], dp1[i - 2] + nums[i]); } dp2[0] = nums[1]; dp2[1] = max(nums[1], nums[2]); for(int i = 2; i < n - 1; i++){ dp2[i] = max(dp2[i - 1], dp2[i - 2] + nums[i + 1]); } return max(dp1.back(), dp2.back()); }
double vtTin::GetArea3D() { double area = 0.0; uint tris = NumTris(); for (uint i = 0; i < tris; i++) { const int v0 = m_tri[i*3]; const int v1 = m_tri[i*3+1]; const int v2 = m_tri[i*3+2]; const DPoint2 &p1 = m_vert[v0]; const DPoint2 &p2 = m_vert[v1]; const DPoint2 &p3 = m_vert[v2]; DPoint3 dp1(p1.x, p1.y, m_z[v0]); DPoint3 dp2(p2.x, p2.y, m_z[v1]); DPoint3 dp3(p3.x, p3.y, m_z[v2]); area += AreaOfTriangle(dp1, dp2, dp3); } return area; }
int rob(vector<int>& nums) { int n = nums.size(); if (n == 0) return 0; if (n == 1) return nums[0]; int ans = 0; vector<int> dp1(n, 0); vector<int> dp2(n, 0); dp1[0] = nums[0]; for (int i = 1; i < n - 1; i++) { dp1[i] = nums[i]; if (i - 1 >= 0) dp1[i] = max(dp1[i], dp1[i - 1]); if (i - 2 >= 0) dp1[i] = max(dp1[i], dp1[i - 2] + nums[i]); } ans = max(ans, dp1[n - 2]); dp2[n - 1] = nums[n - 1]; for (int i = n - 2; i > 0; i--) { dp2[i] = nums[i]; if (i + 1 < n) dp2[i] = max(dp2[i], dp2[i + 1]); if (i + 2 < n) dp2[i] = max(dp2[i], dp2[i + 2] + nums[i]); } ans = max(ans, dp2[1]); return ans; }
int maxProfit(vector<int> &prices) { if (prices.size() < 2) { return 0; } int n = prices.size(); vector<int> dp1(n, 0); vector<int> dp2(n, 0); int minval = prices[0]; for (int i = 1; i < n; i++) { minval = min(minval, prices[i]); dp1[i] = max(dp1[i-1], prices[i] - minval); } int maxval = prices[n-1]; for (int i = n - 2; i >= 0; i--) { maxval = max(maxval, prices[i]); dp2[i] = max(dp2[i+1], maxval - prices[i]); } int result = 0; for (int i = 0; i < n; i++) { result = max(result, dp1[i] + dp2[i]); } return result; }
int main() { atexit(count_check); { DP dp; assert(null(dp)); DP dp2(std::move(dp)); assert(null(dp2)); dp = std::move(dp2); assert(null(dp)); dp2.reset(nullptr); assert(null(dp2)); assert(equal(dp, dp2)); } { DP dp{new Derived}; assert(not_null(dp)); assert(val_equal(dp, 1, 1)); dp.reset(new Derived{2}); assert(not_null(dp)); assert(val_equal(dp, 2, 2)); dp.reset(nullptr); assert(null(dp)); dp = DP{new Derived{3}}; assert(not_null(dp)); assert(val_equal(dp, 3, 3)); dp = std::move(dp); dp = DP{new Derived}; assert(not_null(dp)); assert(val_equal(dp, 1, 1)); } { BP bp{new Base}, dp{new Derived}; assert(not_null(bp)); assert(not_null(dp)); assert(val_equal(bp)); assert(val_equal(dp, 1, 1)); assert(val_not_equal(bp, dp)); { BP mp{std::move(bp)}; assert(val_equal(mp)); mp = std::move(dp); assert(val_equal(mp, 1, 1)); } bp.reset(new Base); dp.reset(new Derived); DP dp2{new Derived}; assert(val_not_equal(bp, dp)); assert(val_not_equal(bp, dp2)); assert(not_equal(dp, dp2)); } { CP<0> cp0{new Chain<2>}; assert(val_equal(cp0, 2, 2)); cp0 = CP<3>{new Chain<5>}; assert(val_equal(cp0, 5, 5)); cp0 = CP<2>{CP<5>{CP<8>{new Chain<12>}}}; assert(val_equal(cp0, 12, 12)); } { CP<0> cp0; CP<2> cp2; CP<5> cp5; cp5.reset(new Chain<10>); assert(val_equal(cp5, 10, 10)); cp2 = std::move(cp5); assert(val_equal(cp2, 10, 10)); cp0 = std::move(cp2); assert(val_equal(cp0, 10, 10)); } { GP<0, 0> gp00{GP<0,3>{GP<4,3>{GP<4,4>{GP<4,5>{new Grid<5, 5>}}}}}; assert(val_equal(gp00, 5, 5)); } { GP<0, 0> gp00; GP<1, 0> gp10; GP<1, 1> gp11; GP<1, 2> gp12; GP<2, 2> gp22; gp22.reset(new Grid<2, 5>); gp12 = std::move(gp22); gp11 = std::move(gp12); gp10 = std::move(gp11); gp00 = std::move(gp10); assert(val_equal(gp00, 2, 5)); } }
void MomentumCorrFunc::correlateFrames(int frame1, int frame2) { SimInfo::MoleculeIterator mi1; SimInfo::MoleculeIterator mi2; Molecule* mol1; Molecule* mol2; Molecule::AtomIterator ai1; Molecule::AtomIterator ai2; Atom* atom1; Atom* atom2; std::vector<Vector3d> atomPositions1; std::vector<Vector3d> atomPositions2; std::vector<Vector3d> atomVelocity1; std::vector<Vector3d> atomVelocity2; int thisAtom1, thisAtom2; Snapshot* snapshot1 = bsMan_->getSnapshot(frame1); Snapshot* snapshot2 = bsMan_->getSnapshot(frame2); assert(snapshot1 && snapshot2); RealType time1 = snapshot1->getTime(); RealType time2 = snapshot2->getTime(); int timeBin = int ((time2 - time1) /deltaTime_ + 0.5); updateFrame(frame1); atomPositions1.clear(); for (mol1 = info_->beginMolecule(mi1); mol1 != NULL; mol1 = info_->nextMolecule(mi1)) { for(atom1 = mol1->beginAtom(ai1); atom1 != NULL; atom1 = mol1->nextAtom(ai1)) { atomPositions1.push_back(atom1->getPos(frame1)); atomVelocity1.push_back(atom1->getVel(frame1)); } } updateFrame(frame2); atomPositions2.clear(); for (mol2 = info_->beginMolecule(mi2); mol2 != NULL; mol2 = info_->nextMolecule(mi2)) { for(atom2 = mol2->beginAtom(ai2); atom2 != NULL; atom2 = mol2->nextAtom(ai2)) { atomPositions2.push_back(atom2->getPos(frame2)); atomVelocity2.push_back(atom2->getVel(frame2)); } } thisAtom1 = 0; for (mol1 = info_->beginMolecule(mi1); mol1 != NULL; mol1 = info_->nextMolecule(mi1)) { for(atom1 = mol1->beginAtom(ai1); atom1 != NULL; atom1 = mol1->nextAtom(ai1)) { Vector3d r1 = atomPositions1[thisAtom1]; Vector3d p1 = atom1->getMass() * atomVelocity1[thisAtom1]; thisAtom2 = 0; for (mol2 = info_->beginMolecule(mi2); mol2 != NULL; mol2 = info_->nextMolecule(mi2)) { for(atom2 = mol2->beginAtom(ai2); atom2 != NULL; atom2 = mol2->nextAtom(ai2)) { Vector3d r2 = atomPositions2[thisAtom2]; Vector3d p2 = atom2->getMass() * atomVelocity1[thisAtom1]; Vector3d deltaPos = (r2-r1); Vector3d dp2( deltaPos.x() * deltaPos.x(), deltaPos.y() * deltaPos.y(), deltaPos.z() * deltaPos.z()); Vector3d pprod( p1.x() * p2.x(), p1.y() * p2.y(), p1.z() * p2.z()); histogram_[timeBin] += outProduct(dp2, pprod); thisAtom2++; } } thisAtom1++; } } count_[timeBin]++; }
CObject* build() { sys::info << "ogl::CBoxObjectBuilder::build()" << sys::endl; float dmax = hasOption(CObjectBuilder::NORMALIZED) ? math::max(mWidth, math::max(mHeight, mDepth)) : 1.0f; float hwidth = (mWidth / 2.0f) / dmax; float hheight = (mHeight / 2.0f) / dmax; float hdepth = (mDepth / 2.0f) / dmax; const size_t nNumVertices = 24; const size_t nNumIndices = 36; // bool bFlatface = hasOption(CObjectBuilder::FLATFACE); math::vec3* positions = new math::vec3[nNumVertices]; positions[ 0] = math::vec3(-hwidth,-hheight, hdepth); positions[ 1] = math::vec3(-hwidth,-hheight, hdepth); positions[ 2] = math::vec3(-hwidth,-hheight, hdepth); positions[ 3] = math::vec3( hwidth,-hheight, hdepth); positions[ 4] = math::vec3( hwidth,-hheight, hdepth); positions[ 5] = math::vec3( hwidth,-hheight, hdepth); positions[ 6] = math::vec3( hwidth, hheight, hdepth); positions[ 7] = math::vec3( hwidth, hheight, hdepth); positions[ 8] = math::vec3( hwidth, hheight, hdepth); positions[ 9] = math::vec3(-hwidth, hheight, hdepth); positions[10] = math::vec3(-hwidth, hheight, hdepth); positions[11] = math::vec3(-hwidth, hheight, hdepth); positions[12] = math::vec3(-hwidth,-hheight,-hdepth); positions[13] = math::vec3(-hwidth,-hheight,-hdepth); positions[14] = math::vec3(-hwidth,-hheight,-hdepth); positions[15] = math::vec3( hwidth,-hheight,-hdepth); positions[16] = math::vec3( hwidth,-hheight,-hdepth); positions[17] = math::vec3( hwidth,-hheight,-hdepth); positions[18] = math::vec3( hwidth, hheight,-hdepth); positions[19] = math::vec3( hwidth, hheight,-hdepth); positions[20] = math::vec3( hwidth, hheight,-hdepth); positions[21] = math::vec3(-hwidth, hheight,-hdepth); positions[22] = math::vec3(-hwidth, hheight,-hdepth); positions[23] = math::vec3(-hwidth, hheight,-hdepth); math::vec2* texcoords = new math::vec2[nNumVertices]; texcoords[ 0] = math::vec2(1.0f, 1.0f); texcoords[ 1] = math::vec2(0.0f, 1.0f); texcoords[ 2] = math::vec2(0.0f, 1.0f); texcoords[ 3] = math::vec2(0.0f, 1.0f); texcoords[ 4] = math::vec2(1.0f, 1.0f); texcoords[ 5] = math::vec2(1.0f, 1.0f); texcoords[ 6] = math::vec2(0.0f, 0.0f); texcoords[ 7] = math::vec2(1.0f, 0.0f); texcoords[ 8] = math::vec2(1.0f, 0.0f); texcoords[ 9] = math::vec2(1.0f, 0.0f); texcoords[10] = math::vec2(0.0f, 0.0f); texcoords[11] = math::vec2(0.0f, 0.0f); texcoords[12] = math::vec2(0.0f, 1.0f); texcoords[13] = math::vec2(1.0f, 1.0f); texcoords[14] = math::vec2(0.0f, 0.0f); texcoords[15] = math::vec2(1.0f, 1.0f); texcoords[16] = math::vec2(0.0f, 1.0f); texcoords[17] = math::vec2(1.0f, 0.0f); texcoords[18] = math::vec2(1.0f, 0.0f); texcoords[19] = math::vec2(0.0f, 0.0f); texcoords[20] = math::vec2(1.0f, 1.0f); texcoords[21] = math::vec2(0.0f, 0.0f); texcoords[22] = math::vec2(1.0f, 0.0f); texcoords[23] = math::vec2(0.0f, 1.0f); math::vec3* normals = new math::vec3[nNumVertices]; normals[ 0] = math::vec3( 0.0f, 0.0f, 1.0f); normals[ 1] = math::vec3(-1.0f, 0.0f, 0.0f); normals[ 2] = math::vec3( 0.0f,-1.0f, 0.0f); normals[ 3] = math::vec3( 0.0f, 0.0f, 1.0f); normals[ 4] = math::vec3( 1.0f, 0.0f, 0.0f); normals[ 5] = math::vec3( 0.0f,-1.0f, 0.0f); normals[ 6] = math::vec3( 0.0f, 0.0f, 1.0f); normals[ 7] = math::vec3( 1.0f, 0.0f, 0.0f); normals[ 8] = math::vec3( 0.0f, 1.0f, 0.0f); normals[ 9] = math::vec3( 0.0f, 0.0f, 1.0f); normals[10] = math::vec3(-1.0f, 0.0f, 0.0f); normals[11] = math::vec3( 0.0f, 1.0f, 0.0f); normals[12] = math::vec3( 0.0f, 0.0f,-1.0f); normals[13] = math::vec3(-1.0f, 0.0f, 0.0f); normals[14] = math::vec3( 0.0f,-1.0f, 0.0f); normals[15] = math::vec3( 0.0f, 0.0f,-1.0f); normals[16] = math::vec3( 1.0f, 0.0f, 0.0f); normals[17] = math::vec3( 0.0f,-1.0f, 0.0f); normals[18] = math::vec3( 0.0f, 0.0f,-1.0f); normals[19] = math::vec3( 1.0f, 0.0f, 0.0f); normals[20] = math::vec3( 0.0f, 1.0f, 0.0f); normals[21] = math::vec3( 0.0f, 0.0f,-1.0f); normals[22] = math::vec3(-1.0f, 0.0f, 0.0f); normals[23] = math::vec3( 0.0f, 1.0f, 0.0f); static GLushort indices[] = { 3, 0, 9, // triangle 0 // face 0 // +z 3, 9, 6, // triangle 1 // face 0 12, 15, 18, // triangle 2 // face 1 // -z 12, 18, 21, // triangle 3 // face 1 1, 13, 22, // triangle 4 // face 2 // -x 1, 22, 10, // triangle 5 // face 2 16, 4, 7, // triangle 6 // face 3 // +x 16, 7, 19, // triangle 7 // face 4 2, 5, 17, // triangle 8 // face 5 // -y 2, 17, 14, // triangle 9 // face 5 23, 20, 8, // triangle 10 // face 6 // +y 23, 8, 11 // triangle 11 // face 7 }; math::vec3* tangents = new math::vec3[nNumVertices]; math::vec3* binormals = new math::vec3[nNumVertices]; for(size_t i = 0; i < nNumIndices; i+=3) // for every triangle { ushort i0 = indices[i+0]; ushort i1 = indices[i+1]; ushort i2 = indices[i+2]; math::vec3& p0 = positions[i0]; math::vec3& p1 = positions[i1]; math::vec3& p2 = positions[i2]; math::vec2& t0 = texcoords[i0]; math::vec2& t1 = texcoords[i1]; math::vec2& t2 = texcoords[i2]; math::vec3 dp1(p1 - p0); // e1 math::vec3 dp2(p2 - p0); // e2 math::vec3 normal = math::normalize(math::cross(dp2, dp1)); normals[i0] += normal; // avarage the normals normals[i0] = math::normalize(normals[i0]); normals[i1] += normal; normals[i1] = math::normalize(normals[i1]); normals[i2] += normal; normals[i2] = math::normalize(normals[i2]); math::vec2 dt1 = t1 - t0; math::vec2 dt2 = t2 - t0; float r = 1.0f / (dt1.x * dt2.y - dt1.y * dt2.x); math::vec3 ta = (dp1 * dt2.y - dp2 * dt1.y) * r; // tangent math::vec3 bi = (dp2 * dt1.x - dp1 * dt2.x) * r; // binormal tangents[i0] = ta; tangents[i1] = ta; tangents[i2] = ta; binormals[i0] = bi; binormals[i1] = bi; binormals[i2] = bi; } if(hasOption(CObjectBuilder::INVERTED)) { for(size_t i = 0; i < nNumVertices; ++i) { normals[i] *= -1.0f; tangents[i] *= -1.0f; binormals[i] *= -1.0f; } for(ushort i = 0; i < nNumIndices; i+=3) { GLushort tmp = indices[i+1]; indices[i+1] = indices[i+2]; indices[i+2] = tmp; } } if(mTextureScale != 1.0f) { for(size_t i = 0; i < nNumVertices; ++i) texcoords[i] = texcoords[i] / mTextureScale; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// CObject* pObject = new CObject; pObject->mNumVertices = nNumVertices; pObject->mNumIndices = nNumIndices; pObject->setDrawStrategy(mDrawStrategy == nullptr ? new CDrawStrategy : mDrawStrategy); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// { // shapes CShape* pShape = new CShape; pShape->setVertexBufferRange(0, pObject->mNumVertices, GL_FLOAT); pShape->setIndexBufferRange(0, pObject->mNumIndices, GL_UNSIGNED_SHORT); CMaterial* pMaterial = new CMaterial; CDdsTextureBuilder* pTextureBuilder = new CDdsTextureBuilder; pTextureBuilder->setFile("notfound.dds"); CTexture* pTexture = pTextureBuilder->build(); pTexture->setFiltering(CTexture::EFiltering::TRILINEAR); delete pTextureBuilder; pMaterial->setTexture(CTexture::EScope::DIFFUSE, pTexture); pShape->setMaterial(pMaterial); pObject->addShape(pShape); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// pObject->mBuffers.resize(5); glGenVertexArrays(1, &(pObject->mVAO)); glBindVertexArray(pObject->mVAO); // indices glGenBuffers(1, &(pObject->mBuffers[INDEX_BUFFER_INDEX])); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pObject->mBuffers[INDEX_BUFFER_INDEX]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, nNumIndices * sizeof(GLushort), indices, GL_STATIC_DRAW); // positions glGenBuffers(1, &(pObject->mBuffers[POSITION_BUFFER_INDEX])); glBindBuffer(GL_ARRAY_BUFFER, pObject->mBuffers[POSITION_BUFFER_INDEX]); glBufferData(GL_ARRAY_BUFFER, nNumVertices * sizeof(math::vec3), positions, GL_STATIC_DRAW); glVertexAttribPointer(POSITION_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, sizeof(math::vec3), (const GLvoid*)(0)); glEnableVertexAttribArray(POSITION_ATTRIBUTE); // positions // texcoords glGenBuffers(1, &(pObject->mBuffers[TEXCOORD_BUFFER_INDEX])); glBindBuffer(GL_ARRAY_BUFFER, pObject->mBuffers[TEXCOORD_BUFFER_INDEX]); glBufferData(GL_ARRAY_BUFFER, nNumVertices * sizeof(math::vec2), texcoords, GL_STATIC_DRAW); glVertexAttribPointer(TEXCOORD_ATTRIBUTE, 2, GL_FLOAT, GL_FALSE, sizeof(math::vec2), (const GLvoid*)(0)); //(GLvoid*)((0 + 3) * sizeof(GLfloat))); glEnableVertexAttribArray(TEXCOORD_ATTRIBUTE); // texcoords // normals glGenBuffers(1, &(pObject->mBuffers[NORMAL_BUFFER_INDEX])); glBindBuffer(GL_ARRAY_BUFFER, pObject->mBuffers[NORMAL_BUFFER_INDEX]); glBufferData(GL_ARRAY_BUFFER, nNumVertices * sizeof(math::vec3), normals, GL_STATIC_DRAW); glVertexAttribPointer(NORMAL_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, sizeof(math::vec3), (const GLvoid*)(0)); //(GLvoid*)((0 + 3 + 2) * sizeof(GLfloat))); glEnableVertexAttribArray(NORMAL_ATTRIBUTE); // normals // tangents glGenBuffers(1, &(pObject->mBuffers[TANGENT_BUFFER_INDEX])); glBindBuffer(GL_ARRAY_BUFFER, pObject->mBuffers[TANGENT_BUFFER_INDEX]); glBufferData(GL_ARRAY_BUFFER, nNumVertices * sizeof(math::vec3), tangents, GL_STATIC_DRAW); glVertexAttribPointer(TANGENT_ATTRIBUTE, 3, GL_FLOAT, GL_FALSE, sizeof(math::vec3), (const GLvoid*)(0)); //(GLvoid*)((0 + 3 + 2) * sizeof(GLfloat))); glEnableVertexAttribArray(TANGENT_ATTRIBUTE); // tangents // clean glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); delete [] positions; delete [] texcoords; delete [] normals; delete [] tangents; delete [] binormals; //////////////////////////////////////////////////////////////////////////////////////////////////////////////// return pObject; }
int main(int argc, char *argv[]) { int n = 10; int ierr = 0; double reltol = 1.0e-14; double abstol = 1.0e-14; int MyPID = 0; try { // Initialize MPI #ifdef HAVE_MPI MPI_Init(&argc,&argv); #endif // Create a communicator for Epetra objects #ifdef HAVE_MPI Epetra_MpiComm Comm( MPI_COMM_WORLD ); #else Epetra_SerialComm Comm; #endif MyPID = Comm.MyPID(); // Create the map Epetra_Map map(n, 0, Comm); bool verbose = false; // Check for verbose output if (argc>1) if (argv[1][0]=='-' && argv[1][1]=='v') verbose = true; // Seed the random number generator in Teuchos. We create random // bordering matrices and it is possible different processors might generate // different matrices. By setting the seed, this shouldn't happen. Teuchos::ScalarTraits<double>::seedrandom(12345); // Create and initialize the parameter vector LOCA::ParameterVector pVector; pVector.addParameter("Param 1", 1.69); pVector.addParameter("Param 2", -9.7); pVector.addParameter("Param 3", 0.35); pVector.addParameter("Param 4", -0.78); pVector.addParameter("Param 5", 2.53); // Create parameter list Teuchos::RCP<Teuchos::ParameterList> paramList = Teuchos::rcp(new Teuchos::ParameterList); Teuchos::ParameterList& nlParams = paramList->sublist("NOX"); Teuchos::ParameterList& nlPrintParams = nlParams.sublist("Printing"); nlPrintParams.set("MyPID", MyPID); if (verbose) nlPrintParams.set("Output Information", NOX::Utils::Error + NOX::Utils::Details + NOX::Utils::OuterIteration + NOX::Utils::InnerIteration + NOX::Utils::Warning + NOX::Utils::TestDetails + NOX::Utils::StepperIteration + NOX::Utils::StepperDetails); else nlPrintParams.set("Output Information", NOX::Utils::Error); // Create global data object Teuchos::RCP<LOCA::GlobalData> globalData = LOCA::createGlobalData(paramList); Epetra_Vector clone_vec(map); NOX::Epetra::Vector nox_clone_vec(clone_vec); Teuchos::RCP<NOX::Abstract::Vector> x = nox_clone_vec.clone(NOX::ShapeCopy); x->random(); Teuchos::RCP<NOX::Abstract::MultiVector> dx1 = nox_clone_vec.createMultiVector(3); Teuchos::RCP<NOX::Abstract::MultiVector> dx2 = nox_clone_vec.createMultiVector(1); Teuchos::RCP<NOX::Abstract::MultiVector> dx3 = nox_clone_vec.createMultiVector(2); Teuchos::RCP<NOX::Abstract::MultiVector> dx4 = nox_clone_vec.createMultiVector(2); dx1->random(); dx2->random(); dx3->init(0.0); dx4->random(); Teuchos::RCP<NOX::Abstract::MultiVector> dx_all = dx1->clone(NOX::DeepCopy); dx_all->augment(*dx2); dx_all->augment(*dx3); dx_all->augment(*dx4); NOX::Abstract::MultiVector::DenseMatrix dp1(dx1->numVectors(), pVector.length()); NOX::Abstract::MultiVector::DenseMatrix dp2(dx2->numVectors(), pVector.length()); NOX::Abstract::MultiVector::DenseMatrix dp3(dx3->numVectors(), pVector.length()); NOX::Abstract::MultiVector::DenseMatrix dp4(dx4->numVectors(), pVector.length()); dp1.random(); dp2.random(); dp3.random(); dp4.random(); NOX::Abstract::MultiVector::DenseMatrix dp_all(dx_all->numVectors(), pVector.length()); for (int j=0; j<dp_all.numCols(); j++) { for (int i=0; i<dp1.numRows(); i++) dp_all(i,j) = dp1(i,j); for (int i=0; i<dp2.numRows(); i++) dp_all(dp1.numRows()+i,j) = dp2(i,j); for (int i=0; i<dp3.numRows(); i++) dp_all(dp1.numRows()+dp2.numRows()+i,j) = dp3(i,j); for (int i=0; i<dp4.numRows(); i++) dp_all(dp1.numRows()+dp2.numRows()+dp3.numRows()+i,j) = dp4(i,j); } std::vector< Teuchos::RCP<LOCA::MultiContinuation::ConstraintInterface> > constraintObjs(4); Teuchos::RCP<LinearConstraint> linear_constraint; linear_constraint = Teuchos::rcp(new LinearConstraint(dx1->numVectors(), pVector, nox_clone_vec)); linear_constraint->setDgDx(*dx1); linear_constraint->setDgDp(dp1); linear_constraint->setIsZeroDX(false); constraintObjs[0] = linear_constraint; linear_constraint = Teuchos::rcp(new LinearConstraint(dx2->numVectors(), pVector, nox_clone_vec)); linear_constraint->setDgDx(*dx2); linear_constraint->setDgDp(dp2); linear_constraint->setIsZeroDX(false); constraintObjs[1] = linear_constraint; linear_constraint = Teuchos::rcp(new LinearConstraint(dx3->numVectors(), pVector, nox_clone_vec)); linear_constraint->setDgDx(*dx3); linear_constraint->setDgDp(dp3); linear_constraint->setIsZeroDX(true); constraintObjs[2] = linear_constraint; linear_constraint = Teuchos::rcp(new LinearConstraint(dx4->numVectors(), pVector, nox_clone_vec)); linear_constraint->setDgDx(*dx4); linear_constraint->setDgDp(dp4); linear_constraint->setIsZeroDX(false); constraintObjs[3] = linear_constraint; // Check some statistics on the solution NOX::TestCompare testCompare(globalData->locaUtils->out(), *(globalData->locaUtils)); LOCA::MultiContinuation::CompositeConstraint composite(globalData, constraintObjs); composite.setX(*x); LinearConstraint combined(dx_all->numVectors(), pVector, nox_clone_vec); combined.setDgDx(*dx_all); combined.setDgDp(dp_all); combined.setX(*x); // // test computeConstraints() // composite.computeConstraints(); combined.computeConstraints(); int numConstraints = dx_all->numVectors(); const NOX::Abstract::MultiVector::DenseMatrix& g_composite = composite.getConstraints(); const NOX::Abstract::MultiVector::DenseMatrix& g_combined = combined.getConstraints(); ierr += testCompare.testMatrix( g_composite, g_combined, reltol, abstol, "CompositeConstraint::computeConstraints()"); // // test computeDP() // std::vector<int> paramIDs(3); paramIDs[0] = 1; paramIDs[1] = 2; paramIDs[2] = 4; NOX::Abstract::MultiVector::DenseMatrix dgdp_composite( numConstraints, paramIDs.size()+1); NOX::Abstract::MultiVector::DenseMatrix dgdp_combined( numConstraints, paramIDs.size()+1); dgdp_composite.putScalar(0.0); dgdp_combined.putScalar(0.0); composite.computeDP(paramIDs, dgdp_composite, false); combined.computeDP(paramIDs, dgdp_combined, false); ierr += testCompare.testMatrix( dgdp_composite, dgdp_combined, reltol, abstol, "CompositeConstraint::computeDP()"); // // test multiplyDX() // composite.computeDX(); combined.computeDX(); int numMultiply = 5; Teuchos::RCP<NOX::Abstract::MultiVector> A = nox_clone_vec.createMultiVector(numMultiply); A->random(); NOX::Abstract::MultiVector::DenseMatrix composite_multiply(numConstraints, numMultiply); NOX::Abstract::MultiVector::DenseMatrix combined_multiply(numConstraints, numMultiply); composite.multiplyDX(2.65, *A, composite_multiply); combined.multiplyDX(2.65, *A, combined_multiply); ierr += testCompare.testMatrix(composite_multiply, combined_multiply, reltol, abstol, "CompositeConstraint::multiplyDX()"); // // test addDX() (No Trans) // int numAdd = 5; NOX::Abstract::MultiVector::DenseMatrix B1(numConstraints, numAdd); B1.random(); NOX::Abstract::MultiVector::DenseMatrix B2(numAdd, numConstraints); B2.random(); Teuchos::RCP<NOX::Abstract::MultiVector> composite_add1 = nox_clone_vec.createMultiVector(numAdd); composite_add1->random(); Teuchos::RCP<NOX::Abstract::MultiVector> composite_add2 = nox_clone_vec.createMultiVector(numAdd); composite_add2->random(); Teuchos::RCP<NOX::Abstract::MultiVector> combined_add1 = composite_add1->clone(NOX::DeepCopy); Teuchos::RCP<NOX::Abstract::MultiVector> combined_add2 = composite_add2->clone(NOX::DeepCopy); composite.addDX(Teuchos::NO_TRANS, 1.45, B1, 2.78, *composite_add1); combined.addDX(Teuchos::NO_TRANS, 1.45, B1, 2.78, *combined_add1); ierr += testCompare.testMultiVector( *composite_add1, *combined_add1, reltol, abstol, "CompositeConstraint::addDX() (No Trans)"); // // test addDX() (Trans) // composite.addDX(Teuchos::TRANS, 1.45, B2, 2.78, *composite_add2); combined.addDX(Teuchos::TRANS, 1.45, B2, 2.78, *combined_add2); ierr += testCompare.testMultiVector( *composite_add2, *combined_add2, reltol, abstol, "CompositeConstraint::addDX() (Trans)"); LOCA::destroyGlobalData(globalData); } catch (std::exception& e) { std::cout << e.what() << std::endl; ierr = 1; } catch (const char *s) { std::cout << s << std::endl; ierr = 1; } catch (...) { std::cout << "Caught unknown exception!" << std::endl; ierr = 1; } if (MyPID == 0) { if (ierr == 0) std::cout << "All tests passed!" << std::endl; else std::cout << ierr << " test(s) failed!" << std::endl; } #ifdef HAVE_MPI MPI_Finalize() ; #endif return ierr; }
int main(int argc, char **argv) { // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Load the mesh. Mesh mesh; MeshReaderH2D mloader; mloader.load("square.mesh", &mesh); // Perform initial mesh refinemets. for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Set exact solution. CustomExactSolution exact(&mesh); // Initialize boundary conditions DefaultEssentialBCNonConst<double> bc_essential("Bdy", &exact); EssentialBCs<double> bcs(&bc_essential); // Initialize the weak formulation. CustomWeakFormPoisson wf1; // Create an H1 space with default shapeset. H1Space<double> space(&mesh, &bcs, P_INIT); int ndof = Space<double>::get_num_dofs(&space); info("ndof: %d", ndof); info("---- Assembling by DiscreteProblem, solving by %s:", MatrixSolverNames[matrix_solver].c_str()); // Initialize the linear discrete problem. DiscreteProblem<double> dp1(&wf1, &space); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix<double>* matrix = create_matrix<double>(matrix_solver); Vector<double>* rhs = create_vector<double>(matrix_solver); LinearSolver<double>* solver = create_linear_solver<double>(matrix_solver, matrix, rhs); #ifdef HAVE_AZTECOO if (matrix_solver == SOLVER_AZTECOO) { (dynamic_cast<AztecOOSolver<double>*>(solver))->set_solver(iterative_method); (dynamic_cast<AztecOOSolver<double>*>(solver))->set_precond(preconditioner); // Using default iteration parameters (see solver/aztecoo.h). } #endif // Begin time measurement of assembly. cpu_time.tick(HERMES_SKIP); // Initial coefficient vector for the Newton's method. double* coeff_vec = new double[ndof]; memset(coeff_vec, 0, ndof*sizeof(double)); // Initialize the Newton solver. Hermes::Hermes2D::NewtonSolver<double> newton(&dp1, matrix_solver); // Perform Newton's iteration and translate the resulting coefficient vector into a Solution. Hermes::Hermes2D::Solution<double> sln1; try { newton.solve(coeff_vec); } catch(Hermes::Exceptions::Exception e) { e.printMsg(); error("Newton's iteration failed."); } Hermes::Hermes2D::Solution<double>::vector_to_solution(newton.get_sln_vector(), &space, &sln1); // CPU time measurement. double time = cpu_time.tick().last(); // Calculate errors. double rel_err_1 = Global<double>::calc_rel_error(&sln1, &exact, HERMES_H1_NORM) * 100; info("CPU time: %g s.", time); info("Exact H1 error: %g%%.", rel_err_1); delete(matrix); delete(rhs); delete(solver); // View the solution and mesh. ScalarView sview("Solution", new WinGeom(0, 0, 440, 350)); sview.show(&sln1); //OrderView oview("Polynomial orders", new WinGeom(450, 0, 400, 350)); //oview.show(&space); // TRILINOS PART: info("---- Assembling by DiscreteProblem, solving by NOX:"); // Initialize the weak formulation for Trilinos. CustomWeakFormPoisson wf2(TRILINOS_JFNK); // Initialize DiscreteProblem. DiscreteProblem<double> dp2(&wf2, &space); // Time measurement. cpu_time.tick(HERMES_SKIP); // Set initial vector for NOX. // NOTE: Using zero vector was causing convergence problems. info("Projecting to obtain initial vector for the Newton's method."); ZeroSolution init_sln(&mesh); // Initialize the NOX solver with the vector "coeff_vec". info("Initializing NOX."); NewtonSolverNOX<double> nox_solver(&dp2); nox_solver.set_output_flags(message_type); nox_solver.set_ls_type(iterative_method); nox_solver.set_ls_tolerance(ls_tolerance); nox_solver.set_conv_iters(max_iters); if (flag_absresid) nox_solver.set_conv_abs_resid(abs_resid); if (flag_relresid) nox_solver.set_conv_rel_resid(rel_resid); // Choose preconditioning. MlPrecond<double> pc("sa"); if (PRECOND) { if (TRILINOS_JFNK) nox_solver.set_precond(pc); else nox_solver.set_precond(preconditioner); } // Assemble and solve using NOX. Solution<double> sln2; OGProjection<double>::project_global(&space, &init_sln, coeff_vec); try { nox_solver.solve(coeff_vec); } catch(Hermes::Exceptions::Exception e) { e.printMsg(); error("NOX failed."); } Solution<double>::vector_to_solution(nox_solver.get_sln_vector(), &space, &sln2); info("Number of nonlin iterations: %d (norm of residual: %g)", nox_solver.get_num_iters(), nox_solver.get_residual()); info("Total number of iterations in linsolver: %d (achieved tolerance in the last step: %g)", nox_solver.get_num_lin_iters(), nox_solver.get_achieved_tol()); // CPU time needed by NOX. time = cpu_time.tick().last(); // Show the NOX solution. ScalarView view2("Solution<double> 2", new WinGeom(450, 0, 460, 350)); view2.show(&sln2); //view2.show(&exact); // Calculate errors. double rel_err_2 = Global<double>::calc_rel_error(&sln2, &exact, HERMES_H1_NORM) * 100; info("CPU time: %g s.", time); info("Exact H1 error: %g%%.", rel_err_2); // Wait for all views to be closed. View::wait(); return 0; }
UINT __stdcall IOToElevator2(void *args) { CDataPool dp2("Ele2", sizeof(struct myDpData)) ; struct myDpData *Ele2DP = (struct myDpData *)(dp2.LinkDataPool()) ; while(flag) { if (ps3.Read()>0) { ps3.Wait(); m1->Wait(); Ele2Status = *Ele2DP; m1->Signal(); cs3.Signal(); } m1->Wait(); //FLOOR 9 MOVE_CURSOR(29,1); printf(" |"); if (Ele2Status.floor == 9) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,2); printf(" |"); if (Ele2Status.floor == 9) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,3); printf(" |"); if (Ele2Status.floor == 9) printf("^-^"); else printf(" "); printf("| "); //FLOOR 8 MOVE_CURSOR(29,5); printf(" |"); if (Ele2Status.floor == 8) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,6); printf(" |"); if (Ele2Status.floor == 8) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,7); printf(" |"); if (Ele2Status.floor == 8) printf("^-^"); else printf(" "); printf("| "); //FLOOR 7 MOVE_CURSOR(29,9); printf(" |"); if (Ele2Status.floor == 7) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,10); printf(" |"); if (Ele2Status.floor == 7) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,11); printf(" |"); if (Ele2Status.floor == 7) printf("^-^"); else printf(" "); printf("| "); //FLOOR 6 MOVE_CURSOR(29,13); printf(" |"); if (Ele2Status.floor == 6) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,14); printf(" |"); if (Ele2Status.floor == 6) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,15); printf(" |"); if (Ele2Status.floor == 6) printf("^-^"); else printf(" "); printf("| "); //FLOOR 5 MOVE_CURSOR(29,17); printf(" |"); if (Ele2Status.floor == 5) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,18); printf(" |"); if (Ele2Status.floor == 5) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,19); printf(" |"); if (Ele2Status.floor == 5) printf("^-^"); else printf(" "); printf("| "); //FLOOR 4 MOVE_CURSOR(29,21); printf(" |"); if (Ele2Status.floor == 4) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,22); printf(" |"); if (Ele2Status.floor == 4) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,23); printf(" |"); if (Ele2Status.floor == 4) printf("^-^"); else printf(" "); printf("| "); //FLOOR 3 MOVE_CURSOR(29,25); printf(" |"); if (Ele2Status.floor == 3) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,26); printf(" |"); if (Ele2Status.floor == 3) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,27); printf(" |"); if (Ele2Status.floor == 3) printf("^-^"); else printf(" "); printf("| "); //FLOOR 2 MOVE_CURSOR(29,29); printf(" |"); if (Ele2Status.floor == 2) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,30); printf(" |"); if (Ele2Status.floor == 2) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,31); printf(" |"); if (Ele2Status.floor == 2) printf("^-^"); else printf(" "); printf("| "); //FLOOR 1 MOVE_CURSOR(29,33); printf(" |"); if (Ele2Status.floor == 1) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,34); printf(" |"); if (Ele2Status.floor == 1) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,35); printf(" |"); if (Ele2Status.floor == 1) printf("^-^"); else printf(" "); printf("| "); //FLOOR 0 MOVE_CURSOR(29,37); printf(" |"); if (Ele2Status.floor == 0) printf("._."); else printf(" "); printf("| "); MOVE_CURSOR(29,38); printf(" |"); if (Ele2Status.floor == 0) { printf("|"); if (Ele2Status.door == OPEN) printf("O"); else printf("-"); printf("|"); } else printf(" "); printf("| "); MOVE_CURSOR(29,39); printf(" |"); if (Ele2Status.floor == 0) printf("^-^"); else printf(" "); printf("| "); MOVE_CURSOR(29,41); printf(" Ele2"); MOVE_CURSOR(36,42); for (int i = 7; i < 10; i++) { if (Ele2Status.lights[i] == 1) { TEXT_COLOUR(14); } printf("[%d] ", i); TEXT_COLOUR(7); } MOVE_CURSOR(36,43); for (int i = 4; i < 7; i++) { if (Ele2Status.lights[i] == 1) { TEXT_COLOUR(14); } printf("[%d] ", i); TEXT_COLOUR(7); } MOVE_CURSOR(36,44); for (int i = 1; i < 4; i++) { if (Ele2Status.lights[i] == 1) { TEXT_COLOUR(14); } printf("[%d] ", i); TEXT_COLOUR(7); } MOVE_CURSOR(40,45); if (Ele2Status.lights[0] == 1) { TEXT_COLOUR(14); } printf("[0]"); TEXT_COLOUR(7); fflush(stdout); MOVE_CURSOR(0,50); fflush(stdout); m1->Signal(); SLEEP(1); } return 0 ; }