void PolynomialFitting::Init(const std::string& file) { std::vector<double> x; std::vector<double> y; Load(file, x, y); MatrixData X(x.size(), std::vector<double>(mPower + 1, 0)); for(size_t i = 0;i < x.size(); ++i) { X[i][0] = 1; for(size_t j = 1; j <= mPower; ++j) X[i][j] = X[i][j - 1] * x[i]; } MatrixData Y(1, std::vector<double>(y)); Matrix xm(X), ym(Y); ym = ym.Transpose(); Matrix res = xm.Transpose() * xm; res = res.Inverse() * xm.Transpose() * ym; X = res.Transpose().GetData(); std::cout << "Value: " << std::endl; for(int i = 0;i < X[0].size(); ++i) std::cout << X[0][i] << " "; std::cout << std::endl; mCofficient = Polynomial(X[0]); }
/* Find inverse Matrix. * ARGUMENTS: None. * RETURNS: * - inversed matrix * Matrix &; */ Matrix &Matrix::Inverse( void ) { Matrix res; float Determ; if((Determ = this->Determinant()) == 0) return *this; res = Matrix(_Det3x3(M[1][1], M[1][2], M[1][3], M[2][1], M[2][2], M[2][3], M[3][1], M[3][2], M[3][3]) / Determ, -_Det3x3(M[1][0], M[1][2], M[1][3], M[2][0], M[2][2], M[2][3], M[3][0], M[3][2], M[3][3]) / Determ, _Det3x3(M[1][0], M[1][1], M[1][3], M[2][0], M[2][1], M[2][3], M[3][0], M[3][1], M[3][3]) / Determ, -_Det3x3(M[1][0], M[1][1], M[1][2], M[2][0], M[2][1], M[2][2], M[3][0], M[3][1], M[3][2]) / Determ, -_Det3x3(M[0][1], M[0][2], M[0][3], M[2][1], M[2][2], M[2][3], M[3][1], M[3][2], M[3][3]) / Determ, _Det3x3(M[0][0], M[0][2], M[0][3], M[2][0], M[2][2], M[2][3], M[3][0], M[3][2], M[3][3]) / Determ, -_Det3x3(M[0][0], M[0][1], M[0][3], M[2][0], M[2][1], M[2][3], M[3][0], M[3][1], M[3][3]) / Determ, _Det3x3(M[0][0], M[0][1], M[0][2], M[2][0], M[2][1], M[2][2], M[3][0], M[3][1], M[3][2]) / Determ, _Det3x3(M[0][1], M[0][2], M[0][3], M[1][1], M[1][2], M[1][3], M[3][1], M[3][2], M[3][3]) / Determ, -_Det3x3(M[0][0], M[0][2], M[0][3], M[1][0], M[1][2], M[1][3], M[3][0], M[3][2], M[3][3]) / Determ, _Det3x3(M[0][0], M[0][1], M[0][3], M[1][0], M[1][1], M[1][3], M[3][0], M[3][1], M[3][3]) / Determ, -_Det3x3(M[0][0], M[0][1], M[0][2], M[1][0], M[1][1], M[1][2], M[3][0], M[3][1], M[3][2]) / Determ, -_Det3x3(M[0][1], M[0][2], M[0][3], M[1][1], M[1][2], M[1][3], M[2][1], M[2][2], M[2][3]) / Determ, _Det3x3(M[0][0], M[0][2], M[0][3], M[1][0], M[1][2], M[1][3], M[2][0], M[2][2], M[2][3]) / Determ, -_Det3x3(M[0][0], M[0][1], M[0][3], M[1][0], M[1][1], M[1][3], M[2][0], M[2][1], M[2][3]) / Determ, _Det3x3(M[0][0], M[0][1], M[0][2], M[1][0], M[1][1], M[1][2], M[2][0], M[2][1], M[2][2]) / Determ); res.Transpose(); *this = res; return *this; } /* End of 'Inverse' function */
bool LinearRegression::FitLinearModel(Matrix & X, Vector & y){ Matrix Xt; Xt.Transpose(X); Matrix XtX; XtX.Product(Xt, X); if (!this->chol.TryDecompose(XtX)) return false; chol.Decompose(XtX); chol.Invert(); this->XtXinv = chol.inv; Vector tmp = y; tmp.Product(Xt, y); this->B.Product(this->XtXinv, tmp); // beta = (XtX)^{-1} Xt Y this->predict.Product(X, this->B); this->residuals = y; this->residuals.Subtract(this->predict); this->sigma2 = 0.0; for (int i = 0; i < this->residuals.Length(); i++){ sigma2 += (this->residuals[i]) * (this->residuals[i]); } sigma2 /= y.Length(); // MLE estimates of sigma2 this->covB = this->XtXinv; this->covB.Multiply(sigma2); return true; };
Matrix Matrix::operator * (const Matrix& m) { Matrix matrix = m.Transpose(); return Matrix( Vector3D(Rows[0].DotProduct(matrix.Rows[0]), Rows[0].DotProduct(matrix.Rows[1]), Rows[0].DotProduct(matrix.Rows[2])), Vector3D(Rows[1].DotProduct(matrix.Rows[0]), Rows[1].DotProduct(matrix.Rows[1]), Rows[1].DotProduct(matrix.Rows[2])), Vector3D(Rows[2].DotProduct(matrix.Rows[0]), Rows[2].DotProduct(matrix.Rows[1]), Rows[2].DotProduct(matrix.Rows[2]))); }
bool Matrix::Orthogonality() { Matrix temp; temp.A=this->A; if ((temp*temp.Transpose()).A==temp.SetIdentity().A) return true; else return false; }
void TerrainTextureShader::SetVertexBufferValues(ID3D11DeviceContext* context, const Matrix &wvpMatrix, const Matrix &worldMatrix) const { // set buffer values D3D11_MAPPED_SUBRESOURCE mappedResource; InputBufferVertex* dataPtr; // Lock the screen size constant buffer so it can be written to. HRESULT result = context->Map(mConstantVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(result)) { throw std::runtime_error(std::string("TerrainTextureShader: failed to map buffer in SetVertexBufferValues function")); } dataPtr = (InputBufferVertex*)mappedResource.pData; dataPtr->worldMatrix = worldMatrix.Transpose(); dataPtr->wvpMatrix = wvpMatrix.Transpose(); context->Unmap(mConstantVertexBuffer,0); }
void LineRenderer::RenderAll(RenderContext* rc) { ID3D11DeviceContext* d3dContext = rc->Context(); // update constant buffer Matrix viewProj = rc->Cam().View() * rc->Cam().Proj(); viewProj.Transpose(); UpdateConstantBuffer(d3dContext,m_perframeCB,&viewProj,sizeof(viewProj)); // set constant buffer to vertex shader ID3D11Buffer* cbuffers[1] = {m_perframeCB}; d3dContext->VSSetConstantBuffers(0,1,cbuffers); // set shaders d3dContext->VSSetShader(m_vsShader,NULL,0); d3dContext->GSSetShader( NULL, NULL, 0 ); d3dContext->PSSetShader(m_psShader,NULL,0); // set vertex layout and primitive topology d3dContext->IASetInputLayout(m_vertexLayoutPC); d3dContext->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_LINELIST ); RenderStateCache* rscache = rc->GetRenderStateCache(); // set state-blocks ( raster, depth, and blend states) d3dContext->RSSetState(rscache->GetRasterState(FillMode::Wireframe,CullMode::BACK)); d3dContext->OMSetDepthStencilState(NULL,0); d3dContext->OMSetBlendState( NULL, NULL, 0xFFFFFFFF ); ID3D11Buffer* vbuffers[1] = {m_vbPC->GetBuffer()}; uint32_t strides[1] = {m_vbPC->GetStride()}; uint32_t offsets[1] = {0}; d3dContext->IASetVertexBuffers( 0, 1, vbuffers, strides, offsets ); uint32_t bufSize = m_vbPC->GetCount(); uint32_t totalVertexCount = (uint32_t) m_vertsPC.size(); uint32_t start = 0; uint32_t count = (totalVertexCount < bufSize) ? totalVertexCount : bufSize; HRESULT hr; D3D11_MAPPED_SUBRESOURCE mappedResource; while(start < totalVertexCount) { hr = d3dContext->Map(m_vbPC->GetBuffer(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if(FAILED(hr)) break; CopyMemory(mappedResource.pData, &m_vertsPC[start], m_vbPC->GetStride() * count); d3dContext->Unmap(m_vbPC->GetBuffer(), 0); d3dContext->Draw(count,0); start += count; if( (start + count) > totalVertexCount) count = totalVertexCount - start; } m_vertsPC.clear(); }
/** * Get matrix representation of the transformation. * * @return Transformation matrix */ Matrix<4,4,float> TransformationNode::GetTransformationMatrix() { // get the rotation from the quaternion Matrix<4,4,float> m = rotation.GetMatrix().GetExpanded(); m.Transpose(); // write in the positional information m(3,0) = position[0]; m(3,1) = position[1]; m(3,2) = position[2]; return GetScaleMatrix() * m; }
void RotationConverter::R2AnglesRzInvRyInvRxInv(const Matrix &R, double &RzInv, double &RyInv, double &RxInv){ Matrix RTemp = R; RTemp.Transpose(); R2AnglesRxRyRz(RTemp, RxInv, RyInv, RzInv); }
void RotationConverter::R2AnglesRzRyRx(const Matrix &R, double &Rz, double &Ry, double &Rx){ Matrix RTemp = R; RTemp.Transpose(); R2AnglesRxInvRyInvRzInv(RTemp, Rx, Ry, Rz); }
bool ParticleShaderClass::SetShaderParameters(Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix, ID3D11ShaderResourceView* texture) { HRESULT result; D3D11_MAPPED_SUBRESOURCE mappedResource; MatrixBufferType* dataPtr; unsigned int bufferNumber; // Transpose the matrices to prepare them for the shader. worldMatrix = worldMatrix.Transpose(); viewMatrix = viewMatrix.Transpose(); projectionMatrix = projectionMatrix.Transpose(); // Lock the constant buffer so it can be written to. result = D3D_context->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr = (MatrixBufferType*)mappedResource.pData; // Copy the matrices into the constant buffer. dataPtr->world = worldMatrix; dataPtr->view = viewMatrix; dataPtr->projection = projectionMatrix; // Unlock the constant buffer. D3D_context->Unmap(m_matrixBuffer, 0); // Set the position of the constant buffer in the vertex shader. bufferNumber = 0; // Now set the constant buffer in the vertex shader with the updated values. D3D_context->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); // Set shader texture resource in the pixel shader. D3D_context->PSSetShaderResources(0, 1, &texture); return true; }
Transform Transform::RotateZ(float theta) { theta = DEG_2_RAD(theta); float sint = sinf(theta); float cost = cosf(theta); Matrix m ( cost, -sint, 0, 0, sint, cost, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return Transform(m, m.Transpose()); }
int LinAlgAux::LSSolve(Matrix &A, Matrix &b, Matrix &x, double &sigma, Matrix &Q) { int M = A.nCols(); int N = A.nRows(); if (!Matrix::LeastSQRSolve(A, b, x, Q)) return 0; Matrix V = A*x - b; Matrix vv = V.Transpose()*V; sigma = sqrt(vv(0, 0) / (N - M)); return 1; }
void Operations(Matrix m1,Matrix m2) { cout<<"[Умножение матриц]:"<<m1*m2<<endl; cout<<"[Транспонирование матрицы]:"<<endl<<m1.Transpose(); cout<<"[Матрица поворота]:"<<endl<<m1.Scale(2,3,4); cout<<"[Единичная матрица]:"<<endl<<m1.SetIdentity(); if(m1.Orthogonality()) cout<<"[Ортогональны]"<<endl; else cout<<"[Неортогональны]"<<endl; cout<<"[Поворот по Х]:"<<endl<<m1.RotateX(1.0)<<endl; cout<<"[Поворот по Y]:"<<endl<<m1.RotateY(2.0)<<endl; cout<<"[Поворот по Z]:"<<endl<<m1.RotateZ(3.0)<<endl; cout<<"[Сдвиг]:"<<endl<<m1.Translation(2,4,3)<<endl; }
bool Shader::SetConstants(ID3D11DeviceContext* context, Matrix world, Matrix view, Matrix projection) { //This method copies the provided matrices over to the constant buffer D3D11_MAPPED_SUBRESOURCE mappedResource; //To do this we us the Map method, this method gives us a "Mapped Subresource", that will end up here MatrixBuffer* inputData; //We call the Map method and pass in our Mapped Subresource struct, the method will fill it out for us if (FAILED(context->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))) { return false; } inputData = (MatrixBuffer*)mappedResource.pData; //The pData pointer in the Mapped Subresource points to the memory within the buffer, so we cast it to a MatrixBuffer inputData->world = world.Transpose(); //and fill it out! inputData->view = view.Transpose(); //The matrices we use a in row-major format, HLSL assumes column-major format so we transpose them inputData->projection = projection.Transpose(); //as we pass them into the matrix buffer context->Unmap(m_matrixBuffer, 0); //Unmapping the subresource frees it and finishes the process return true; }
Matrix Matrix::Reversed() const { Matrix result; double determinant = Determinant(); if (determinant != 0) { result = Adjoint(); result.Transpose(); result *= (1 / determinant); } return result; }
bool Transform::intersect(const Ray &r, Hit &h, float tmin) { Vec3f rTransOri = r.getOrigin(); Vec3f rTransDir = r.getDirection(); Matrix mInverse; m.Inverse(mInverse); mInverse.Transform(rTransOri); mInverse.TransformDirection(rTransDir); rTransDir.Normalize(); Ray rTrans(rTransDir,rTransOri); Hit hTrans(10000,NULL,Vec3f(0,0,0)); //need a new hit,because the x-y-z had changed 就因为这里没有使用一个新的hit导致了自己debug了两天 instance->intersect(rTrans,hTrans,tmin); if(hTrans.getT()<10000) { //world's t float t; //Vec3f hitPoint = rTransOri + rTransDir * hTrans.getT(); Vec3f hitPoint = rTrans.pointAtParameter(hTrans.getT()); m.Transform(hitPoint); Vec3f rOri = r.getOrigin(); Vec3f rDir = r.getDirection(); if((fabs(rDir[0])>=fabs(rDir[1]))&&(fabs(rDir[0])>=fabs(rDir[2]))){ t = (hitPoint[0] - rOri[0]) / rDir[0]; } else if((fabs(rDir[1])>=fabs(rDir[0]))&&(fabs(rDir[1])>=fabs(rDir[2]))){ t = (hitPoint[1] - rOri[1]) / rDir[1]; } else if((fabs(rDir[2])>=fabs(rDir[0]))&&(fabs(rDir[2])>=fabs(rDir[1]))){ t = (hitPoint[2] - rOri[2]) / rDir[2]; } //world's normal mInverse.Transpose(); Vec3f wNormal = hTrans.getNormal(); mInverse.TransformDirection(wNormal); wNormal.Normalize(); //need normalize //h.setNormal(wNormal); if(t>=tmin && t<=h.getT()) { h.set(t,hTrans.getMaterial(),wNormal,r); return 1; } } return 0; }
void Win32Polygon::_Draw() { // transform Matrix worldViewProj; T()->GetWorldViewProj(&worldViewProj); worldViewProj.Transpose(); d3d.context->UpdateSubresource(d3d.constantBufferVS, 0, NULL, &worldViewProj, 0, 0); d3d.context->UpdateSubresource(d3d.constantBufferPS, 0, 0, &color, 0, 0); d3d.context->PSSetShader(ps->ps, 0, 0); d3d.context->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP); d3d.context->RSSetState(d3d.rsWire); UINT stride = sizeof(Vertex); UINT offset = 0; d3d.context->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset); d3d.context->Draw(vertexCount, 0); }
Matrix<type> Matrix<type>::Productor ( const Matrix<type> & another) const { if(this->lineSize!=another.lineSize || this->columnSize!=another.columnSize) { throw SizeNotCompatible(); //return ; } Matrix<type> trans = another.Transpose();// Matrix<type>(another).Transpose();//another.Transpose(); //trans.PrintMatrix(std::cout); Matrix<type> result( this->lineSize , another.columnSize ); for( ty_size i =0 ; i < result.lineSize ; i++ ) { for( ty_size j = 0 ; j < result.columnSize ; j++ ) { result.matrix_data[i][j]=this->matrix_data[i].InnerProductor(trans.matrix_data[j]); } } return result; }
void SwarmWorld::Draw(shared_ptr<Renderer> renderer) { renderer->SetCameraLookAt(swarmCentre_); glDepthMask(GL_FALSE); renderer->Draw(skybox_); glDepthMask(GL_TRUE); for (int i = 0; i < NUM_BOIDS; ++i) { // Use our camera view transformation to align the 'mesh' to // its velocity vector Matrix align = Matrix::Camera(Vector(), boids_[i].velocity); bird_->transformation = Matrix::Translate(boids_[i].position) * align.Transpose() * Matrix::Scale(0.1f); bird_->colour[2] = anims_[i]; renderer->Draw(bird_); } }
int LinAlgAux::LSSolve(Matrix &A, Matrix &b, Matrix &x, double &sigma, Matrix &Q, float nsig, vector<int> &Outs) { int M = A.nCols(); int N = A.nRows(); if (!Matrix::LeastSQRSolve(A, b, x, Q)) return 0; Matrix V = A*x - b; Matrix vv = V.Transpose()*V; sigma = sqrt(vv(0, 0) / (N - M)); //Outliers search Outs.clear(); double tresh = sigma*nsig; for (size_t i = 0; i < V.nRows(); i++) { if (abs(V(i, 0)) >= tresh) Outs.push_back(i); } return 1; }
int main() { float a_data[2][3] = { {1, 2, 3}, {4, 5, 6}, }; Matrix<float, 2,3> a = Matrix<float,2,3>(a_data); std::cout << "a = \n" << a; std::cout << "a + a = \n" << a + a; std::cout << "a - a = \n" << a - a; std::cout << "3a = \n" << 3*a; Matrix<float, 2,3> z = a; z -= a; std::cout << "z = \n" << z; std::cout << "z == a: " << (z == a) << std::endl; std::cout << "z == z: " << (z == z) << std::endl; Matrix<float, 3,2> unity(1); std::cout << "unity = \n" << unity; std::cout << "a * unity = \n" << a * unity; std::cout << "a * aT = \n" << a * a.Transpose(); }
void Tri3::GetStiffnessMatrix(Matrix<FEdouble>* S) { Node* node1 = _model->GetNode(_node1); Node* node2 = _model->GetNode(_node2); Node* node3 = _model->GetNode(_node3); Matrix<FEdouble>* Fe = new Matrix<FEdouble>(3,6); (*Fe)(0,0) = (*Fe)(2,1) = node2->GetY()-node3->GetY(); (*Fe)(2,0) = (*Fe)(1,1) = -(node2->GetX()-node3->GetX()); (*Fe)(0,2) = (*Fe)(2,3) = node3->GetY()-node1->GetY(); (*Fe)(2,2) = (*Fe)(1,3) = -(node3->GetX()-node1->GetX()); (*Fe)(0,4) = (*Fe)(2,5) = node1->GetY()-node2->GetY(); (*Fe)(2,4) = (*Fe)(1,5) = -(node1->GetX()-node2->GetX()); FEdouble F = 0.5*static_cast<FEdouble>(fabs( node1->GetX()*(node2->GetY()-node3->GetY())+ node2->GetX()*(node3->GetY()-node1->GetY())+ node3->GetX()*(node1->GetY()-node2->GetY()) )); (*Fe)*=1/(2*F); Material* mat = _model->GetMaterial(_mat); FEdouble D = mat->GetEmodul()*_thickness/(1-(mat->GetNue()*mat->GetNue())); Matrix<FEdouble>* E = new Matrix<FEdouble>(3); (*E)(0,0) = (*E)(1,1) = D; (*E)(1,0) = (*E)(0,1) = D*mat->GetNue(); (*E)(2,2) = 0.5*D*(1-mat->GetNue()); Matrix<FEdouble> K = (*E)*(*Fe); Fe->Transpose(); (*S) = (*Fe)*K; (*S)*=F; }
bool Transform::intersect(const Ray & r, Hit & h, float tmin) { // Need to Transform Ray before do intersection Matrix reverseMat = transformMat; reverseMat.Inverse(); // cout << "Original Origin:\t" << r.getOrigin() << endl; // cout << "Original Direction:\t" << r.getDirection() << endl; Vec4f aug_origin(r.getOrigin(), 1); Vec3f aug_dir = r.getDirection(); reverseMat.Transform(aug_origin); reverseMat.TransformDirection(aug_dir); // cout << "Now Origin:\t" << r.getOrigin() << endl; // cout << "Now Direction:\t" << r.getDirection() << endl; // aug_dir.Normalize(); Ray transRay(aug_dir, Vec3f(aug_origin[0], aug_origin[1], aug_origin[2])); if ( !( object -> intersect(transRay, h, tmin) ) ) return false; // After transforming Ray, we need to transform Normal Matrix transposeRevMat = reverseMat; transposeRevMat.Transpose(); Vec3f hn = h.getNormal(); transposeRevMat.Transform(hn); hn.Normalize(); h.set(h.getT(), NULL, hn, r); return true; }
void ClassificationBiasMatrix::PerformAdjustmnts (const VectorDouble& classifiedCounts, VectorDouble& adjCounts, VectorDouble& stdErrors ) { // For description of calc's see the paper: // "Estimating the Taxonomic composition of a sample when individuals are classified with error" // by Andrew Solow, Cabll Davis, Qiao Hu // Woods Hole Oceanographic Institution, Woods Hole Massachusetts // Marine Ecology Progress Series // published 2006-july-06; vol 216:309-311 if (classifiedCounts.size () != (kkuint32)numClasses) { KKStr errMsg = "ClassificationBiasMatrix::PerformAdjustmnts ***ERROR*** Disagreement in length of classifiedCounts[" + StrFormatInt ((kkint32)classifiedCounts.size (), "ZZZ0") + "] and Prev Defined ClassList[" + StrFormatInt (numClasses, "ZZZ0") + "]."; runLog.Level (-1) << errMsg << endl; valid = false; throw KKException (errMsg); } kkint32 x = 0; kkint32 i, j, k; // We need to deal with the special case when one entry in the probability diagonal is zero. { for (x = 0; x < numClasses; x++) { if ((*probabilities)[x][x] == 0.0) { // This will cause the inversion of the diagonal matrix to fail. To deal // with this situation; I will steal some probability from other buckets on // same row. double totalAmtStolen = 0.0; double percentToSteal = 0.01; for (i = 0; i < numClasses; i++) { if ((*probabilities)[x][i] != 0.0) { double amtToSteal = (*probabilities)[x][i] * percentToSteal; (*probabilities)[x][i] = (*probabilities)[x][i] - amtToSteal; totalAmtStolen += amtToSteal; } } (*probabilities)[x][x] = totalAmtStolen; } } } Matrix m (numClasses, 1); for (x = 0; x < numClasses; x++) m[x][0] = classifiedCounts[x]; Matrix transposed = probabilities->Transpose (); Matrix Q = transposed.Inverse (); Matrix n = Q * m; Matrix varM (numClasses, numClasses); for (j = 0; j < numClasses; j++) { double varM_j = 0.0; for (i = 0; i < numClasses; i++) { double p = (*probabilities)[i][j]; varM_j += n[i][0] * p * (1.0 - p); } varM[j][j] = varM_j; } for (j = 0; j < numClasses; j++) { for (k = 0; k < numClasses; k++) { if (j != k) { double covM_jk = 0.0; for (i = 0; i < numClasses; i++) covM_jk -= n[i][0] * (*probabilities)[i][j] * (*probabilities)[j][k]; varM[j][k] = covM_jk; } } } Matrix varN = Q * varM * Q.Transpose (); adjCounts.clear (); stdErrors.clear (); for (x = 0; x < numClasses; x++) { adjCounts.push_back (n[x][0]); stdErrors.push_back (sqrt (varN[x][x])); } return; } /* PerformAdjustmnts */
int MultivariateVT::compute(Vector& freq, Matrix& U, Matrix& V) { if (freq.Length() != U.rows || freq.Length() != V.rows || U.cols != 1 || V.rows != V.cols) { return -1; } const int numFreq = freq.Length(); int numKeep = 0; std::set<int> skip; std::set<int> freqTable; // to avoid float numeric comparison, store maf * 1e6 maf.Dimension(numFreq); for (int i = 0; i < numFreq; ++i) { maf[i] = freq[i] < 0.5 ? freq[i] : 1.0 - freq[i]; if (maf[i] < 1e-10) { skip.insert(i); continue; } if (V[i][i] < 1e-10) { skip.insert(i); continue; } int mafInt = ceil(maf[i] * 1000000); if (freqTable.count(mafInt)) { continue; } freqTable.insert(mafInt); numKeep++; } #ifdef DEBUG fprintf(stderr, "numFreq = %d\n", numFreq); fprintf(stderr, "numKeep = %d\n", numKeep); #endif if (numKeep == 0) { return -1; } cutoff.Dimension(numKeep); // phi[i][j] = 1 means at maf[i] < cutoff[j] phi.Dimension(numFreq, numKeep); int j = 0; for (std::set<int>::const_iterator it = freqTable.begin(); it != freqTable.end(); ++it) { cutoff[j++] = 1.0 * (*it) / 1000000; } for (int i = 0; i < numFreq; ++i) { for (int j = 0; j < numKeep; ++j) { if (skip.count(i) > 0) { phi[i][j] = 0.; continue; } if (maf[i] <= cutoff[j]) { phi[i][j] = 1.; } else { phi[i][j] = 0.; } } } // u_phi = t(U) * phi Matrix tmp; tmp.Transpose(U); this->u_phi.Product(tmp, phi); // v_phi = t(phi) * v * phi Matrix phiT; phiT.Transpose(phi); tmp.Product(phiT, V); this->v_phi.Product(tmp, phi); int maxIdx = -1; double maxVal = -DBL_MAX; for (int i = 0; i < numKeep; ++i) { double t = fabs(u_phi[0][i] / sqrt(v_phi[i][i])); if (t > maxVal) { maxIdx = i; maxVal = t; } } #ifdef DEBUG dumpToFile(freq, "freq"); dumpToFile(cutoff, "cutoff"); dumpToFile(U, "U"); dumpToFile(V, "V"); dumpToFile(phi, "phi"); dumpToFile(u_phi, "u.phi"); dumpToFile(v_phi, "v.phi"); #endif this->minMAF = maf.Min(); this->maxMAF = maf.Max(); this->optimalMAF = cutoff[maxIdx]; this->optimalU = u_phi[0][maxIdx]; this->optimalV = v_phi[maxIdx][maxIdx]; this->stat = maxVal; this->optimalNumVar = 0; for (int i = 0; i < numFreq; ++i) { if (phi[i][maxIdx] > 0) ++this->optimalNumVar; } if (this->mvn.getBandProbFromCov(-maxVal, maxVal, this->v_phi, &this->pvalue)) { this->pvalue = -1; // failed return -1; } this->pvalue = 1.0 - this->pvalue; return 0; }
bool TextureShaderClass::SetShaderParameters(Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix, ID3D11ShaderResourceView** texture_array, int tipo_, int mouse_status_, Color color_, Vector3 lightPos_, float dimmed_) { HRESULT result; D3D11_MAPPED_SUBRESOURCE mappedResource; MatrixBufferType* dataPtr; unsigned int bufferNumber; Data_* dataPtr2; // Transpose the matrices to prepare them for the shader. worldMatrix = worldMatrix.Transpose(); viewMatrix = viewMatrix.Transpose(); projectionMatrix = projectionMatrix.Transpose(); // Lock the constant buffer so it can be written to. result = D3D_context->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr = (MatrixBufferType*)mappedResource.pData; // Copy the matrices into the constant buffer. dataPtr->world = worldMatrix; dataPtr->view = viewMatrix; dataPtr->projection = projectionMatrix; // Unlock the constant buffer. D3D_context->Unmap(m_matrixBuffer, 0); // Set the position of the constant buffer in the vertex shader. bufferNumber = 0; // Now set the constant buffer in the vertex shader with the updated values. D3D_context->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer); // Set shader texture resource in the pixel shader. D3D_context->PSSetShaderResources(0, 4, texture_array); // Lock the basic constant buffer so it can be written to. result = D3D_context->Map(texture_Buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr2 = (Data_*)mappedResource.pData; // Copy the lighting variables into the constant buffer. dataPtr2->color = color_; dataPtr2->lightPos = lightPos_; dataPtr2->extra1 = 0.0f; dataPtr2->type_ = float(tipo_); dataPtr2->mouse_status = float(mouse_status_); dataPtr2->dimmed = dimmed_; dataPtr2->extra2 = 0.0f; // Unlock the constant buffer. D3D_context->Unmap(texture_Buffer, 0); // Set the position of the light constant buffer in the pixel shader. bufferNumber = 0; // Finally set the light constant buffer in the pixel shader with the updated values. D3D_context->PSSetConstantBuffers(bufferNumber, 1, &texture_Buffer); return true; }
void IRWPCA(const Matrix<double>& data, Vector<double>& weights, Vector<double>& mu, Matrix<double>& trans, const double tol/*=1E-8*/, const int max_iter/*=1000*/, const bool quiet/* = true*/) { int d_in = data.nrows(); int d_out = trans.nrows(); int N = data.ncols(); //check on input data if (mu.size() != d_in) mu.reallocate(d_in); if (trans.ncols() != d_in) trans.reallocate(d_out,d_in); if (weights.size() != N) weights.reallocate(N,1.0); else weights.SetAllTo(1.0); if (max_iter<1) throw MatVecError("max_iter must be positive"); //data needed for procedure Matrix<double,SYM> transcov(d_in,d_in); Vector<double> V; Vector<double> weights_old; Vector<double> V_minus_mu; Matrix<double> trans_old; PCA(data,mu,trans); //Now we iterate and find the optimal weights, // mean, and transformation for(int count=1;count<max_iter;count++) { weights_old.deep_copy(weights); trans_old.deep_copy(trans); transcov = trans.Transpose() * trans; //find errors and new weights for(int i=0;i<N;i++) { V.deep_copy( data.col(i) ); V -= mu; V_minus_mu.deep_copy(V); V -= transcov * V_minus_mu; weights(i) = pow( blas_NRM2(V), 2 ); } make_weights(weights); WPCA(data,weights,mu,trans); //check for convergence using residuals between // new weights and old weights weights_old -= weights; double Wres = blas_NRM2(weights_old); // and new trans and old trans //trans_old -= trans; //double Tres = blas_NRM2(trans_old); if ( ( Wres/sqrt(N) <tol) ) { if (!quiet) std::cout << "IRWPCA: converged to tol = " << tol << " in " << count << " iterations\n"; return; } }//end for //if tolerance was not reached, return an error message throw IterException(max_iter,tol); }
bool Transform::intersect(const Ray &r, Hit &h, float tmin) { float scaler; Vec3f d, o, n_ws; Ray r1; Matrix m; r1 = r; m = matrix; // get the length of direction vector scaler = r.getDirection().Length(); // normalize the direction vector d = r1.getDirection(); d.Normalize(); // transform the ray o = r1.getOrigin(); m.Transform(o); m.TransformDirection(d); // Now, Ray origin and direction is transformed to Object Space // intersect at Object space if (object->intersect(r1, h, tmin) == false) return false; // transform the hit point and // normal vector back to world space // // In order to transform the normal vector, // let, // n_ws, normal vector in world space, // v_ws, perpendicular to normal in world space, // n_os, normal vector in object space // v_os, perpendicular to normal in object space, // // given, // n_os^T * v_os = 0 and v_ws^T * n_ws = 0 // // where, // ^T present transport of the vector(matrix) // ^-1 present inverse of the matrix // // n_os^T * v_os = 0 // ==> n_os^T * (M^-1 * M) * v_os = 0 // ==> (n_os^T * M^-1) * v_ws = 0 // and // n_ws * v_ws = 0 // thus // n_ws = (n_os^T) * M^-1 = (M^T)^-1 * n_os m.Transpose(); m.Inverse(); n_ws = h.getNormal(); m.Transform(n_ws); h.set(h.getT() * scaler, h.getMaterial(), n_ws, r); return true; }