m multiply(m m1, m m2) { m A, B, C, D, E, F, G, H; m P1, P2, P3, P4, P5, P6, P7; m Q1, Q2, Q3, Q4; m result; int m1_i, m1_j; int i, j; int n = m1.re - m1.rs + 1; /* base case */ /* if the incoming matrix is 2x2 */ if (n <= 2) { int a, b, c, d, e, f, g, h; m m3 = m1; a = m1.a[m1.rs][m1.cs]; b = m1.a[m1.rs][m1.cs+1]; c = m1.a[m1.rs+1][m1.cs]; d = m1.a[m1.rs+1][m1.cs+1]; e = m2.a[m2.rs][m2.cs]; f = m2.a[m2.rs][m2.cs+1]; g = m2.a[m2.rs+1][m2.cs]; h = m2.a[m2.rs+1][m2.cs+1]; m3.a[m3.rs][m3.cs] = a*e + b*g; m3.a[m3.rs][m3.cs+1] = a*f + b*h; m3.a[m3.rs+1][m3.cs] = c*e + d*g; m3.a[m3.rs+1][m3.cs+1] = c*f + d*h; return m3; } result.rs = result.cs = 0; result.ce = result.re = n-1; A = B = C = D = m1; E = F = G = H = m2; A.rs = m1.rs; A.re = m1.re/2; A.cs = m1.cs; A.ce = m1.ce/2; B.rs = m1.rs; B.re = m1.re/2; B.cs = m1.ce/2 + 1; B.ce = m1.ce; C.rs = m1.re/2 + 1; C.re = m1.re; C.cs = m1.cs; C.ce = m1.ce/2; D.rs = m1.re/2 + 1; D.re = m1.re; D.cs = m1.ce/2 + 1; D.ce = m1.ce; E.rs = m2.rs; E.re = m2.re/2; E.cs = m2.cs; E.ce = m2.ce/2; F.rs = m2.rs; F.re = m2.re/2; F.cs = m2.ce/2 + 1; F.ce = m2.ce; G.rs = m2.re/2 + 1; G.re = m2.re; G.cs = m2.cs; G.ce = m2.ce/2; H.rs = m2.re/2 + 1; H.re = m2.re; H.cs = m2.ce/2 + 1; H.ce = m2.ce; P1 = multiply(A, minus(F, H)); P2 = multiply(plus(A, B), H); P3 = multiply(plus(C, D), E); P4 = multiply(D, minus(G, E)); P5 = multiply(plus(A, D), plus(E, H)); P6 = multiply(minus(B, D), plus(G, H)); P7 = multiply(minus(A, C), plus(E, F)); Q1 = plus(minus(plus(P5, P4), P2), P6); Q2 = plus(P1, P2); Q3 = plus(P3, P4); Q4 = minus(minus(plus(P1, P5), P3), P7); for (m1_i=Q1.rs, i=0 ; m1_i<=Q1.re ; m1_i++, i++) for (m1_j=Q1.cs, j=0 ; m1_j<=Q1.ce ; m1_j++, j++) result.a[i][j] = Q1.a[m1_i][m1_j]; for (m1_i=Q2.rs, i=0 ; m1_i<=Q2.re ; m1_i++, i++) for (m1_j=Q2.cs, j=n/2 ; m1_j<=Q2.ce ; m1_j++, j++) result.a[i][j] = Q2.a[m1_i][m1_j]; for (m1_i=Q3.rs, i=n/2 ; m1_i<=Q3.re ; m1_i++, i++) for (m1_j=Q3.cs, j=0 ; m1_j<=Q3.ce ; m1_j++, j++) result.a[i][j] = Q3.a[m1_i][m1_j]; for (m1_i=Q4.rs, i=n/2 ; m1_i<=Q4.re ; m1_i++, i++) for (m1_j=Q4.cs, j=n/2 ; m1_j<=Q4.ce ; m1_j++, j++) result.a[i][j] = Q4.a[m1_i][m1_j]; return result; }
void Matrix::scale(float xScale, float yScale, float zScale, Matrix* dst) const { Matrix s; createScale(xScale, yScale, zScale, &s); multiply(*this, s, dst); }
//argc is the number of arguments, and argv is the array containing those arguments int main(int argc, char *argv[]) { // declaring area for variables int here; int amountComplex, mRoot, nPower, form, i, j; double tempRealorMag, tempImagorPhase, userInput1, userInput2; complex secondnumber, atemp, stemp, mtemp, dtemp, ptemp, rtemp, ctemp; FILE *inputf; //Pointer to the input filepath FILE *outputf; //Pointer to the output filepath // check to see that there are 2 command line arguments for input-file // and output-file switch (argc) { case 2: fprintf(stderr,"Error: Please also provide an output filename\n"); return(1); case 3: break; // have input file and output file; all is OK default: fprintf(stderr,"Error: Please provide input and output filenames respectively as command line arguments\n"); return(1); } // make sure the input file opens if((inputf=fopen(argv[1],"r"))==NULL) { fprintf(stderr,"Error opening input file file. Check permissions.\n"); return(1); } // make sure the output file opens if((outputf=fopen(argv[2],"w"))==NULL) { fprintf(stderr,"Error opening output file. Check permissions.\n"); return(1); } // reading the first four numbers from the text file fscanf(inputf, "%d", &amountComplex); fscanf(inputf, "%d", &form); fscanf(inputf, "%d", &nPower); fscanf(inputf, "%d", &mRoot); // error checking is missing in the program: // 1) number of complex numbers should be a positive integer // 2) format should be 0 for Cartesian or 1 for Polar, any other number is wrong // 3) can power be any number??? // 4) can root be any number??? // dynamically creates one array of type complex complex myCarray[amountComplex]; // reads the numbers and puts them into an array; closes inputfile for (i = 0; i < amountComplex; i++) { fscanf(inputf, "%lf", &tempRealorMag); fscanf(inputf, "%lf", &tempImagorPhase); myCarray[i].real = tempRealorMag; myCarray[i].imaginary = tempImagorPhase; } fclose(inputf); // enters the second the number to be added, can be in // cartesian (0) or polar (1) formats // cartesian format if (form == 0) { printf("\nEnter real part: "); scanf("%lf", &userInput1); printf("\nEnter imaginary part: "); scanf("%lf", &userInput2); secondnumber.real = userInput1; secondnumber.imaginary = userInput2; } // polar format if (form == 1) { printf("\nEnter Magnitude: "); scanf("%lf", &userInput1); printf("\nEnter Phase: "); scanf("%lf", &userInput2); secondnumber.real = userInput1; secondnumber.imaginary = userInput2; } // for debugging purposes /* printf("\a\a\n\tI am here!!!!\n\n"); printf("Number of complex numbers = %d\n", amountComplex); printf("Format is (0) Cartesian or (1) Polar = %d\n", form); printf("Power is = %d\n", nPower); printf("Root is = %d\n", mRoot); printf("Real or Magnitude of 2nd number is = %lf\n", secondnumber.real); printf("Imaginary of Phase of 2nd number is = %lf\n", secondnumber.imaginary); printf ("Enter an integer number to continue = "); scanf("%d", &here); */ // writes the results to the output file in either Cartesian or Polar formats // cartesian format if(form == 0) { fprintf(outputf, "This will be in Cartesian format, the order of results are:\n"); fprintf(outputf, "Real part\n"); fprintf(outputf, "Imaginary part\n"); fprintf(outputf, "Magnitude\n"); fprintf(outputf, "Phase\n"); fprintf(outputf, "Power\n"); fprintf(outputf, "Root\n"); fprintf(outputf, "Conjugate\n"); fprintf(outputf, "Addition\n"); fprintf(outputf, "Subtraction\n"); fprintf(outputf, "Multiplication\n"); fprintf(outputf, "Division\n\n"); } // polar format if(form == 1) { fprintf(outputf, "This will be in Polar format, the order of results are:\n"); fprintf(outputf, "Real part\n"); fprintf(outputf, "Imaginary part\n"); fprintf(outputf, "Magnitude\n"); fprintf(outputf, "Phase\n"); fprintf(outputf, "Power\n"); fprintf(outputf, "Root\n"); fprintf(outputf, "Conjugate\n"); fprintf(outputf, "Addition\n"); fprintf(outputf, "Subtraction\n"); fprintf(outputf, "Multiplication\n"); fprintf(outputf, "Division\n\n"); } // number crunching part of code for(j = 0; j < amountComplex; j++) { // Real part, Imaginary part, Magnitude, Phase, Power, Root, // and Conjugate of complex number input array fprintf(outputf, "%lf\n", getReal(myCarray[j], form)); fprintf(outputf, "%lf\n", getImaginary(myCarray[j], form)); fprintf(outputf, "%lf\n", getMagnitude(myCarray[j], form)); fprintf(outputf, "%lf\n", getPhase(myCarray[j], form)); ptemp = getPower(nPower, myCarray[j], form); rtemp = getRoot(mRoot, myCarray[j], form); ctemp = getConjugate(myCarray[j]); fprintf(outputf, "%lf %lf \n", ptemp.real, ptemp.imaginary); fprintf(outputf, "%lf %lf \n", rtemp.real, rtemp.imaginary); fprintf(outputf, "%lf %lf \n", ctemp.real, ctemp.imaginary); // Addition, Subtraction, Multiplication, Division with Second Number entered by user atemp = add(myCarray[j], secondnumber, form); stemp = subtract(myCarray[j], secondnumber, form); mtemp = multiply(myCarray[j], secondnumber, form); dtemp = divide(myCarray[j], secondnumber, form); fprintf(outputf, "%lf %lf \n", atemp.real, atemp.imaginary); fprintf(outputf, "%lf %lf \n", stemp.real, stemp.imaginary); fprintf(outputf, "%lf %lf \n", mtemp.real, mtemp.imaginary); fprintf(outputf, "%lf %lf \n", dtemp.real, dtemp.imaginary); fprintf(outputf, "\n\tNext Complex Number\n"); } fclose(outputf); return(0); } //end of main function
void Matrix::multiply(const Matrix& m) { multiply(*this, m, this); }
void Matrix::rotate(const Vector3& axis, float angle, Matrix* dst) const { Matrix r; createRotation(axis, angle, &r); multiply(*this, r, dst); }
void solve(BIT sp[], BIT p1[], BIT p2[], BIT z[], int &n, int current_position, BIT carry, int &sp_n){ //n is number of bits in p1,p2 //if(current_position == 0) solve(sp, p1, p2, z, n, current_position+1, 0); //std::cout << sp_cp << "\n"; //std::string pause; getline(std::cin, pause); //reverse(p1, n);printPrime(p1,n);reverse(p1, n); //reverse(p2, n);printPrime(p2,n);reverse(p2, n); //std::cout << "current pos: " << current_position << "\n"; if(current_position == n){ std::vector<BIT> product; multiply(p1,p2,product,n); trim(product); /* std::cout << "p1\n"; reverse(p1, n);printPrime(p1,n);reverse(p1, n); std::cout << "p2\n"; reverse(p2, n);printPrime(p2,n);reverse(p2, n); std::cout << "p1*p2\n"; reverse(product);printPrime(product);reverse(product); std::cout << "sp\n"; reverse(sp,sp_n);printPrime(sp,sp_n);reverse(sp,sp_n); */ if( areEqual(product,sp,sp_n) ){ reverse(p1, n); reverse(p2, n); reverse(product); reverse(sp,sp_n); std::cout << "Hooray!\n"; printPrime(p1,n); printPrime(p2,n); printPrime(product); printPrime(sp,sp_n); std::cout << "------\n"; std::cout << "TIME: " << float( clock () - begin_time ) / CLOCKS_PER_SEC << "\n"; exit(0); } return; } BIT sum_of_carry_and_known = carry; for(int i = 1; i < current_position; i++){ sum_of_carry_and_known += p2[i]*p1[current_position-i]; } //std::cout << sum_of_carry_and_known << "\n"; //std::cout << sp[current_position] << "\n"; if(sp[current_position] == 0){ if(sum_of_carry_and_known % 2 == 0){ p1[current_position] = 0; p2[current_position] = 0; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); p1[current_position] = 1; p2[current_position] = 1; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); } else if(sum_of_carry_and_known % 2 == 1){ p1[current_position] = 0; p2[current_position] = 1; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); p1[current_position] = 1; p2[current_position] = 0; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); } }else if(sp[current_position] == 1){ if(sum_of_carry_and_known % 2 == 0){ p1[current_position] = 0; p2[current_position] = 1; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); p1[current_position] = 1; p2[current_position] = 0; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); } else if(sum_of_carry_and_known % 2 == 1){ p1[current_position] = 0; p2[current_position] = 0; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); p1[current_position] = 1; p2[current_position] = 1; carry = (sum_of_carry_and_known+p1[current_position]+p2[current_position])/2; solve(sp,p1,p2,z,n,current_position+1,carry,sp_n); } } }
void Matrix::multiply(float scalar) { multiply(scalar, this); }
vec3& vec3::operator*=(const vec3& other) { return multiply(other); }
void yybesselj(void) { double d; int n; N = pop(); X = pop(); push(N); n = pop_integer(); // numerical result if (isdouble(X) && n != (int) 0x80000000) { //d = jn(n, X->u.d); push_double(d); return; } // bessej(0,0) = 1 if (iszero(X) && iszero(N)) { push_integer(1); return; } // besselj(0,n) = 0 if (iszero(X) && n != (int) 0x80000000) { push_integer(0); return; } // half arguments if (N->k == NUM && MEQUAL(N->u.q.b, 2)) { // n = 1/2 if (MEQUAL(N->u.q.a, 1)) { push_integer(2); push_symbol(PI); divide(); push(X); divide(); push_rational(1, 2); power(); push(X); sine(); multiply(); return; } // n = -1/2 if (MEQUAL(N->u.q.a, -1)) { push_integer(2); push_symbol(PI); divide(); push(X); divide(); push_rational(1, 2); power(); push(X); cosine(); multiply(); return; } // besselj(x,n) = (2/x) (n-sgn(n)) besselj(x,n-sgn(n)) - besselj(x,n-2*sgn(n)) push_integer(MSIGN(N->u.q.a)); SGN = pop(); push_integer(2); push(X); divide(); push(N); push(SGN); subtract(); multiply(); push(X); push(N); push(SGN); subtract(); besselj(); multiply(); push(X); push(N); push_integer(2); push(SGN); multiply(); subtract(); besselj(); subtract(); return; } push(symbol(BESSELJ)); push(X); push(N); list(3); }
static bool matchTemplate_CCOEFF_NORMED(InputArray _image, InputArray _templ, OutputArray _result) { matchTemplate(_image, _templ, _result, CV_TM_CCORR); UMat temp, image_sums, image_sqsums; integral(_image, image_sums, image_sqsums, CV_32F, CV_32F); int type = image_sums.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); ocl::Kernel k("matchTemplate_CCOEFF_NORMED", ocl::imgproc::match_template_oclsrc, format("-D CCOEFF_NORMED -D type=%s -D elem_type=%s -D cn=%d", ocl::typeToStr(type), ocl::typeToStr(depth), cn)); if (k.empty()) return false; UMat templ = _templ.getUMat(); Size size = _image.size(), tsize = templ.size(); _result.create(size.height - templ.rows + 1, size.width - templ.cols + 1, CV_32F); UMat result = _result.getUMat(); float scale = 1.f / tsize.area(); if (cn == 1) { float templ_sum = (float)sum(templ)[0]; multiply(templ, templ, temp, 1, CV_32F); float templ_sqsum = (float)sum(temp)[0]; templ_sqsum -= scale * templ_sum * templ_sum; templ_sum *= scale; if (templ_sqsum < DBL_EPSILON) { result = Scalar::all(1); return true; } k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadOnlyNoSize(image_sqsums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, scale, templ_sum, templ_sqsum); } else { Vec4f templ_sum = Vec4f::all(0), templ_sqsum = Vec4f::all(0); templ_sum = sum(templ); multiply(templ, templ, temp, 1, CV_32F); templ_sqsum = sum(temp); float templ_sqsum_sum = 0; for (int i = 0; i < cn; i ++) templ_sqsum_sum += templ_sqsum[i] - scale * templ_sum[i] * templ_sum[i]; templ_sum *= scale; if (templ_sqsum_sum < DBL_EPSILON) { result = Scalar::all(1); return true; } if (cn == 2) k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadOnlyNoSize(image_sqsums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, scale, templ_sum[0], templ_sum[1], templ_sqsum_sum); else k.args(ocl::KernelArg::ReadOnlyNoSize(image_sums), ocl::KernelArg::ReadOnlyNoSize(image_sqsums), ocl::KernelArg::ReadWrite(result), templ.rows, templ.cols, scale, templ_sum[0], templ_sum[1], templ_sum[2], templ_sum[3], templ_sqsum_sum); } size_t globalsize[2] = { result.cols, result.rows }; return k.run(2, globalsize, NULL, false); }
//TODO remove pModel CEvaluationNode* CDerive::deriveBranch(const CEvaluationNode* node, const CCopasiObject * pObject, std::vector<const CEvaluationNode*>& env, //std::vector<const CCopasiObject*>& objenv, const CEvaluationTree* pTree, bool simplify) { CEvaluationNode * newNode = NULL; const CEvaluationNodeOperator * pENO = dynamic_cast<const CEvaluationNodeOperator*>(node); if (pENO) { if (!pENO->getLeft() || !pENO->getRight()) return NULL; CEvaluationNode * pLeftDeriv = deriveBranch(pENO->getLeft(), pObject, env, pTree, simplify); if (!pLeftDeriv) return NULL; CEvaluationNode * pRightDeriv = deriveBranch(pENO->getRight(), pObject, env, pTree, simplify); if (!pRightDeriv) {delete pLeftDeriv; return NULL;} // we now know that derivations of the left and right branch exist switch ((CEvaluationNodeOperator::SubType) CEvaluationNode::subType(pENO->getType())) { case CEvaluationNodeOperator::MULTIPLY: { CEvaluationNode * pLeftCopy = copyBranch_var2obj(pENO->getLeft(), env); CEvaluationNode * pRightCopy = copyBranch_var2obj(pENO->getRight(), env); CEvaluationNode * tmpNode1 = multiply(pRightCopy, pLeftDeriv, simplify); CEvaluationNode * tmpNode2 = multiply(pRightDeriv, pLeftCopy, simplify); return add(tmpNode1, tmpNode2, simplify); } break; case CEvaluationNodeOperator::DIVIDE: { CEvaluationNode * pLeftCopy = copyBranch_var2obj(pENO->getLeft(), env); CEvaluationNode * pRightCopy = copyBranch_var2obj(pENO->getRight(), env); //numerator CEvaluationNode * tmpNode1 = multiply(pRightCopy, pLeftDeriv, simplify); CEvaluationNode * tmpNode2 = multiply(pRightDeriv, pLeftCopy, simplify); CEvaluationNode * minusNode = subtract(tmpNode1, tmpNode2, simplify); minusNode->compile(NULL); //denominator CEvaluationNode * powerNode = power(copyBranch_var2obj(pENO->getRight(), env), new CEvaluationNodeNumber(CEvaluationNodeNumber::INTEGER, "2"), simplify); return divide(minusNode, powerNode, simplify); } break; case CEvaluationNodeOperator::PLUS: return add(pLeftDeriv, pRightDeriv, simplify); break; case CEvaluationNodeOperator::MINUS: return subtract(pLeftDeriv, pRightDeriv, simplify); break; case CEvaluationNodeOperator::POWER: { // b-1 CEvaluationNode * tmpNode = subtract(copyBranch_var2obj(pENO->getRight(), env), new CEvaluationNodeNumber(CEvaluationNodeNumber::INTEGER, "1"), simplify); // a^(b-1) CEvaluationNode * powerNode = power(copyBranch_var2obj(pENO->getLeft(), env), tmpNode, simplify); // b*a' tmpNode = multiply(copyBranch_var2obj(pENO->getRight(), env), pLeftDeriv, simplify); // ln a CEvaluationNodeFunction * funcNode = new CEvaluationNodeFunction(CEvaluationNodeFunction::LOG, "ln"); funcNode->addChild(copyBranch_var2obj(pENO->getLeft(), env)); // add a // a * b' * ln a CEvaluationNode * tmpNode2 = multiply(copyBranch_var2obj(pENO->getLeft(), env), multiply(pRightDeriv, funcNode, simplify), simplify); // b*a + a*b * ln a CEvaluationNode * plusNode = add(tmpNode, tmpNode2, simplify); // a^(b-1)*(b*a + a*b * ln a) return multiply(powerNode, plusNode, simplify); } break; default: break; } } const CEvaluationNodeVariable * pENV = dynamic_cast<const CEvaluationNodeVariable*>(node); if (pENV) { if (!env[pENV->getIndex()]) return NULL; //basically just expand the tree. return deriveBranch(env[pENV->getIndex()], pObject, env, pTree, simplify); } const CEvaluationNodeNumber * pENN = dynamic_cast<const CEvaluationNodeNumber*>(node); if (pENN) { newNode = new CEvaluationNodeNumber(CEvaluationNodeNumber::INTEGER, "0"); return newNode; } const CEvaluationNodeObject *pENObj = dynamic_cast<const CEvaluationNodeObject*>(node); if (pENObj) { //first check whether the object is the derivation variable if (pObject->getCN() == pENObj->getObjectCN()) { //std::cout << "*"; return new CEvaluationNodeNumber(CEvaluationNodeNumber::INTEGER, "1"); } //now we need to check if we know something about the object so that it needs to be expanded const CCopasiObject * tmpObj = (const CCopasiObject *)pENObj->getObjectInterfacePtr(); if (!tmpObj) return NULL; //object is a concentration? if (tmpObj->getObjectName() == "Concentration") { //std::cout << "Concentration found" << std::endl; //In this context, the concentration is expanded as "amount of substance/volume" std::string tmpstr = tmpObj->getObjectParent() ? "<" + tmpObj->getObjectParent()->getCN() + ",Reference=ParticleNumber>" : "<>"; CEvaluationNodeObject* amount = new CEvaluationNodeObject(CEvaluationNodeObject::CN, tmpstr); amount->compile(pTree); tmpstr = tmpObj->getObjectAncestor("Compartment") ? "<" + tmpObj->getObjectAncestor("Compartment")->getCN() + ",Reference=Volume>" : "<>"; CEvaluationNodeObject* volume = new CEvaluationNodeObject(CEvaluationNodeObject::CN, tmpstr); volume->compile(pTree); CEvaluationNodeObject* volume2 = new CEvaluationNodeObject(CEvaluationNodeObject::CN, tmpstr); //we need this node twice volume2->compile(pTree); CEvaluationNode* damount = deriveBranch(amount, pObject, env, pTree, simplify); CEvaluationNode* dvolume = deriveBranch(volume, pObject, env, pTree, simplify); // A / V - A*V /V^2 return subtract(divide(damount, volume, simplify), divide(multiply(amount, dvolume, simplify), power(volume2, new CEvaluationNodeNumber(CEvaluationNodeNumber::INTEGER, "2"), simplify), simplify), simplify); } //TODO: //object is an object with an assignment //object is dependent species //object is a reaction rate // otherwise return 0. return new CEvaluationNodeNumber(CEvaluationNodeNumber::INTEGER, "0"); } const CEvaluationNodeCall *pENCall = dynamic_cast<const CEvaluationNodeCall*>(node); if (pENCall) { //is it a function? const CFunction * tmpFunction = dynamic_cast<const CFunction*>(pENCall->getCalledTree()); // const std::vector<CEvaluationNode *> getListOfChildNodes() const {return mCallNodes;} //create call environment for the called function std::vector<const CEvaluationNode*> subenv; size_t i, imax = pENCall->getListOfChildNodes().size(); subenv.resize(imax); for (i = 0; i < imax; ++i) { CEvaluationNode* tmpnode = copyBranch_var2obj(pENCall->getListOfChildNodes()[i], env); compileTree(tmpnode, pTree); subenv[i] = tmpnode; } return deriveBranch(pENCall->getCalledTree()->getRoot(), pObject, subenv, pTree, simplify); } return newNode; }
TransformationData SharedManipulationMerger::calculateResult() { TransformationData result; unsigned temp; unsigned short objectType; unsigned short objectId; unsigned entityId; unsigned tempObjectType, tempObjectId; bool tempBool; uint64_t pipeId = inputPipeList[0].pipe->getPipeId(); TransformationManager::unpackPipeId(pipeId, &temp, &temp, &temp, &temp, &tempObjectType, &tempObjectId, &tempBool); objectType = (unsigned short)tempObjectType; objectId = (unsigned short)tempObjectId; entityId = join(objectType, objectId); Entity* ent; if (inputPipeList.size() == 1) { // do what offset modifier does TransformationData resultLastStage; User* user = inputPipeList[0].pipe->getOwner(); TransformationData offset = user->getAssociatedEntityOffset(entityId); resultLastStage = inputPipeList[0].transf; multiply(result, resultLastStage, offset); // dumpVec(resultLastStage.position, "SharedManipulationMerger: cursor transf"); // dumpVec(offset.position, "SharedManipulationMerger: picking offset"); // assert(false); singleUser = true; } else if (singleUser) { // got two users the first time assert(inputPipeList.size() == 2); gmtl::Vec3f center; gmtl::Vec3f cursor[2]; TransformationData entTransf; int i; for (i = 0; i < 2; i++) cursor[i] = inputPipeList[i].transf.position; center = (cursor[0] + cursor[1]) * 0.5f; ent = WorldDatabase::getEntityWithTypeInstanceId(objectType, objectId); assert(ent); entTransf = ent->getWorldTransformation(); scale = entTransf.scale; dumpTransformation(entTransf); dEntityOrigin = entTransf.position - center; axis = cursor[1] - cursor[0]; gmtl::normalize(axis); orientation = entTransf.orientation; if (gmtl::length(cursor[0]) < 0.001f || gmtl::length(cursor[1]) < 0.001f) { assert(false); } singleUser = false; result = entTransf; } else { // multiuser gmtl::Vec3f center; gmtl::Vec3f cursor[2]; gmtl::Vec3f axisNew; gmtl::Vec3f normal; gmtl::AxisAnglef rotAngle; gmtl::Quatf rotq; TransformationData entTransf; float dotProduct; float angle; int i; for (i = 0; i < 2; i++) cursor[i] = inputPipeList[i].transf.position; center = (cursor[0] + cursor[1]) * 0.5f; axisNew = cursor[1] - cursor[0]; gmtl::normalize(axisNew); // printd("Normal = %f %f %f\n", normal[0], normal[1], normal[2]); // printd("angle = %f\n", angle); dotProduct = gmtl::dot(axis, axisNew); // if(fabs(dotProduct) > 1) // { // printd("axis are very similar\n"); // // gmtl::Vec3f li = axis + gmtl::Vec3f(1, 0, 0); // gmtl::Vec3f li; // gmtl::Quatf invOri; // gmtl::Matrix44f rotm; // // invOri = orientation; // invert(invOri); // li = invOri * gmtl::Vec3f(1, 0, 0); // normalize(li); // if(fabs(gmtl::dot(li, axis)) >= 0.99999) // { // printd("ohoh right and axis are not linear independent\n"); // li = invOri * gmtl::Vec3f(0, 0, 1); // normalize(li); // assert(fabs(gmtl::dot(li, axis)) < 1); // } // // // normalize(li); // gmtl::cross(normal, axis, li); // normalize(normal); // gmtl::cross(li, normal, axis); // normalize(li); // // rotm.set( li[0], li[1], li[2], 0, // normal[0], normal[1], normal[2], 0, // axis[0], axis[1], axis[2], 0, // 0, 0, 0, 1); // // assert(gmtl::length(li) < 1.01); // assert(gmtl::length(normal) < 1.01); // assert(gmtl::length(axis) < 1.01); // // printd("det of rotm: %0.03f\n", gmtlDet3(rotm)); // gmtl::set(rotq, rotm); // // } else // { // gmtl::cross(normal, axis, axisNew); // gmtl::normalize(normal); // angle = acos(dotProduct); // rotAngle = gmtl::AxisAnglef(angle, normal); // gmtl::set(rotq, rotAngle); // } gmtl::cross(normal, axis, axisNew); gmtl::normalize(normal); if (gmtl::length(normal) < 0.99999) { printd("bad normal: %0.04f\n", gmtl::length(normal)); normal = gmtl::Vec3f(1, 0, 0); angle = 0; rotq = gmtl::QUAT_IDENTITYF; } // if else { dotProduct = gmtl::dot(axis, axisNew); if (dotProduct > 1) dotProduct = 1; if (dotProduct < -1) dotProduct = -1; angle = acos(dotProduct); // printd("Normal length = %f\n", gmtl::length(normal)); // printd("Angle = %f\n", angle); rotAngle = gmtl::AxisAnglef(angle, normal); gmtl::set(rotq, rotAngle); // printd("Quaternion = %f %f %f %f\n", rotq[0], rotq[1], rotq[2], rotq[3]); } // else dEntityOrigin = rotq * dEntityOrigin; orientation = rotq * orientation; axis = axisNew; result = identityTransformation(); result.position = center + dEntityOrigin; result.orientation = orientation; result.scale = scale; // dumpTransformation(result); #if not defined(MACOS_X) && not defined(__APPLE_CC__) if (isnan(result.position[0])) { dumpTransformation(result); assert(false); } #endif } // else return result; }
int main() { // Height of the capillary interface for the grid CpuPtr_2D height_distribution(nx, ny, 0, true); computeRandomHeights(0, H, height_distribution); // Density difference between brine and CO2 float delta_rho = 500; // Gravitational acceleration float g = 9.87; // Non-dimensional constant that scales the strength of the capillary forces float c_cap = 1.0/6.0; // Permeability data (In real simulations this will be a table based on rock data, here we use a random distribution ) float k_data[10] = {0.9352, 1.0444, 0.9947, 0.9305, 0.9682, 1.0215, 0.9383, 1.0477, 0.9486, 1.0835}; float k_heights[10] = {10, 20, 25, 100, 155, 193, 205, 245, 267, 300}; //Inside Kernel // Converting the permeability data into a table of even subintervals in the z-directions //float k_values[n+1]; //kDistribution(dz, h, k_heights, k_data, k_values); // MOBILITY // The mobility is a function of the saturation, which is directly related to the capillary pressure // Pressure at capillary interface, which is known float p_ci = 1; // Table of capillary pressure values for our subintervals along the z-axis ranging from 0 to h float resolution = 0.01; int size = 1/resolution + 1; float p_cap_ref_table[size]; float s_b_ref_table[size]; createReferenceTable(g, H, delta_rho, c_cap, resolution, p_cap_ref_table, s_b_ref_table); // Set block and grid sizes and initialize gpu pointer dim3 grid; dim3 block; computeGridBlock(dim3& grid, dim3& block, nx, ny, block_x, block_y); // Allocate and set data on the GPU GpuPtr_2D Lambda_device(nx, ny, 0, NULL); GpuPtr_1D k_data_device(10, k_data); GpuPtr_1D k_heights_device(10, k_heights); GpuPtr_1D p_cap_ref_table_device(size, p_cap_ref_table); GpuPtr_1D s_b_ref_table_device(size, s_b_ref_table); cudaHostAlloc(&args, sizeof(CoarsePermIntegrationKernelArgs), cudaHostAllocWriteCombined); // Set arguments and run coarse integration kernel CoarsePermIntegrationArgs coarse_perm_int_args; setCoarsePermIntegrationArgs(coarse_perm_int_args,\ Lambda_device.getRawPtr(),\ k_data_device.getRawPtr(),\ k_heights_device.getRawPtr(),\ p_cap_ref_table_device.getRawPtr(),\ s_b_ref_table_device.getRawPtr(),\ nx, ny, 0); callCoarseIntegrationKernel(grid, block, coarse_perm_int_args); float p_cap_values[n+1]; computeCapillaryPressure(p_ci, g, delta_rho, h, dz, n, p_cap_values); float s_b_values[n+1]; inverseCapillaryPressure(n, g, h, delta_rho, c_cap, p_cap_values, s_b_values); printArray(n+1, s_b_values); // End point mobility lambda'_b, a known quantity float lambda_end_point = 1; float lambda_values[n+1]; computeMobility(n, s_b_values, lambda_end_point, lambda_values); // Multiply permeability values with lambda values float f_values[n+1]; multiply(n+1, lambda_values, k_values, f_values); //Numerical integral with trapezoidal float K = trapezoidal(dz, n, k_values); float L = trapezoidal(dz, n, f_values)/K; printf("Value of integral K. %.4f", K); printf("Value of integral L. %.4f", L); }
int performMaths() { cout << "\nHi! You again, choosing deeper and deeper. Is seems you like maths so here is what you can do:" << endl; cout << "'1' additions" << endl; cout << "'2' subtractions" << endl; cout << "'3' multiplications" << endl; cout << "'4' dicisions" << endl; int choice = SafeCinNum(); if(choice < 0 || choice > 4) cout << "Choice non available, you'll have to start again." << endl; else { cout << "\n***********************\n\n Ok, enter two numbers now a and b and I'll perform the operation you requested" << endl; cout << "\na = "; double a = SafeCinDouble(); cout << "\nb = "; double b = SafeCinDouble(); switch(choice) { case 1: { double res = add(a,b); cout << "\na + b = " << res << endl; return 0; } case 2: { double res = subtract(a,b); cout << "\na - b = " << res << endl; return 0; } case 3: { double res = multiply(a,b); cout << "\na * b = " << res << endl; return 0; } case 4: { double res = divide(a,b); cout << "\na / b = " << res << endl; return 0; } default: return 1; } } }
int main() { printf("Start...."); start: printf("\n(input) "); //계산기 프로그램 시작 scanf("%s", in1); str_in1 = strlen(in1); c_hoice(); if (chosen != 1){ scanf("%s", in2); str_in2 = strlen(in2); scanf("%s", in3); str_in3 = strlen(in3); check_sign_in1(); check_sign_in3(); re_array_in1(); re_array_in3(); separate(); if(in2[0] == '-'){ if(minus_sign_count == 0) in2[0] = '-'; else if(minus_sign_count == 1){ if(if_minus_first == 1){ in2[0] = '+'; when_put_minus =1;} if(if_minus_last == 1) in2[0] = '+';} else{ in2[0] = '-'; when_remove_minus =1;}} else if(in2[0] == '+'){ if(minus_sign_count == 0) in2[0] = '+'; else if(minus_sign_count == 1){ if(if_minus_first == 1) in2[0] = '-'; if(if_minus_last == 1) in2[0] = '-';} else{ in2[0] = '+'; when_put_minus=1;}} else if(in2[0] == '*'){ if(minus_sign_count == 0 || minus_sign_count == 2) in2[0] = '*'; else if(minus_sign_count == 1){ in2[0] = '*'; when_put_minus=1;}} else if(in2[0] == '/'){ if(minus_sign_count == 0 || minus_sign_count == 2) in2[0] = '/'; else if(minus_sign_count == 1){ in2[0] = '/'; when_put_minus=1;}} else if(in2[0] == '%'){ if(minus_sign_count == 0 || minus_sign_count == 2) in2[0] = '%'; else if(minus_sign_count == 1){ in2[0] = '%'; when_put_minus=1;}} switch (in2[0]) { case '+' : { invert1(); convert1(); plus(); convert2(); invert2(); break; } case '-' : { invert1(); compare(); convert1(); minus(); convert2(); invert2(); break; } case '*' : { invert1(); invert1_mul_s(); multiply(); invert2(); invert2_mul_s(); break; } case '/' : { invert1(); compare(); convert1(); divide(); convert2(); invert2(); break; } case '%' : { invert1(); compare(); convert1(); remain(); convert2(); invert2(); break; } default: ; } printf(" = "); if(when_put_minus == 1) printf("-"); // if(when_remove_minus == 1) //여기서 - 부호 하나를 배열에서 빼주는 명령어 쓸 수 없을까? if (daeso == 1) printf("-"); comma(res_j); if (p != 0) {printf("."); comma(res_s);} } initialization(); goto start; return 0; }
MatrixAlias& MatrixAlias::operator*=(const MatrixAliasConstant& operand) { equals(multiply(operand)); return *this; }
vec4 & vec4::operator*=(const float & other) { return multiply(other); }
MatrixAlias& MatrixAlias::operator*=(const double& operand) { equals(multiply(operand)); return *this; }
SparseMatrix& SparseMatrix::operator *= (const double rhs) { *this = multiply(rhs); return *this; }
void yypower(void) { int n; p2 = pop(); p1 = pop(); // both base and exponent are rational numbers? if (isrational(p1) && isrational(p2)) { push(p1); push(p2); qpow(); return; } // both base and exponent are either rational or double? if (isnum(p1) && isnum(p2)) { push(p1); push(p2); dpow(); return; } if (istensor(p1)) { power_tensor(); return; } if (p1 == symbol(E) && car(p2) == symbol(LOG)) { push(cadr(p2)); return; } if ((p1 == symbol(MINFTY) || p1 == symbol(INFTY)) && isnegativeterm(p2)) { push_integer(0); return; } if (iszero(p1) && isnegativeterm(p2)) { push_symbol(INFTY); return; } if (p1 == symbol(E) && p2 == symbol(MINFTY)) { push_integer(0); return; } if (p1 == symbol(E) && isdouble(p2)) { push_double(exp(p2->u.d)); return; } // 1 ^ a -> 1 // a ^ 0 -> 1 if (equal(p1, one) || iszero(p2)) { push(one); return; } // a ^ 1 -> a if (equal(p2, one)) { push(p1); return; } // (a * b) ^ c -> (a ^ c) * (b ^ c) if (car(p1) == symbol(MULTIPLY)) { p1 = cdr(p1); push(car(p1)); push(p2); power(); p1 = cdr(p1); while (iscons(p1)) { push(car(p1)); push(p2); power(); multiply(); p1 = cdr(p1); } return; } // (a ^ b) ^ c -> a ^ (b * c) if (car(p1) == symbol(POWER)) { push(cadr(p1)); push(caddr(p1)); push(p2); multiply(); power(); return; } // (a + b) ^ n -> (a + b) * (a + b) ... if (expanding && isadd(p1) && isnum(p2)) { push(p2); n = pop_integer(); if (n > 1) { power_sum(n); return; } } // sin(x) ^ 2n -> (1 - cos(x) ^ 2) ^ n if (trigmode == 1 && car(p1) == symbol(SIN) && iseveninteger(p2)) { push_integer(1); push(cadr(p1)); cosine(); push_integer(2); power(); subtract(); push(p2); push_rational(1, 2); multiply(); power(); return; } // cos(x) ^ 2n -> (1 - sin(x) ^ 2) ^ n if (trigmode == 2 && car(p1) == symbol(COS) && iseveninteger(p2)) { push_integer(1); push(cadr(p1)); sine(); push_integer(2); power(); subtract(); push(p2); push_rational(1, 2); multiply(); power(); return; } // complex number? (just number, not expression) if (iscomplexnumber(p1)) { // integer power? // n will be negative here, positive n already handled if (isinteger(p2)) { // / \ n // -n | a - ib | // (a + ib) = | -------- | // | 2 2 | // \ a + b / push(p1); conjugate(); p3 = pop(); push(p3); push(p3); push(p1); multiply(); divide(); push(p2); negate(); power(); return; } // noninteger or floating power? if (isnum(p2)) { #if 1 // use polar form push(p1); mag(); push(p2); power(); push_integer(-1); push(p1); arg(); push(p2); multiply(); push(symbol(PI)); divide(); power(); multiply(); #else // use exponential form push(p1); mag(); push(p2); power(); push(symbol(E)); push(p1); arg(); push(p2); multiply(); push(imaginaryunit); multiply(); power(); multiply(); #endif return; } } if (simplify_polar()) return; push_symbol(POWER); push(p1); push(p2); list(3); }
void Matrix::multiply(float scalar, Matrix* dst) const { multiply(*this, scalar, dst); }
static int cvt_by_tile( TIFF *in, TIFF *out ) { uint32* raster; /* retrieve RGBA image */ uint32 width, height; /* image width & height */ uint32 tile_width, tile_height; uint32 row, col; uint32 *wrk_line; tsize_t raster_size; int ok = 1; TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height); if( !TIFFGetField(in, TIFFTAG_TILEWIDTH, &tile_width) || !TIFFGetField(in, TIFFTAG_TILELENGTH, &tile_height) ) { TIFFError(TIFFFileName(in), "Source image not tiled"); return (0); } TIFFSetField(out, TIFFTAG_TILEWIDTH, tile_width ); TIFFSetField(out, TIFFTAG_TILELENGTH, tile_height ); /* * Allocate tile buffer */ raster_size = multiply(multiply(tile_width, tile_height), sizeof (uint32)); if (!raster_size) { TIFFError(TIFFFileName(in), "Can't allocate buffer for raster of size %lux%lu", (unsigned long) tile_width, (unsigned long) tile_height); return (0); } raster = (uint32*)_TIFFmalloc(raster_size); if (raster == 0) { TIFFError(TIFFFileName(in), "No space for raster buffer"); return (0); } /* * Allocate a scanline buffer for swapping during the vertical * mirroring pass. (Request can't overflow given prior checks.) */ wrk_line = (uint32*)_TIFFmalloc(tile_width * sizeof (uint32)); if (!wrk_line) { TIFFError(TIFFFileName(in), "No space for raster scanline buffer"); ok = 0; } /* * Loop over the tiles. */ for( row = 0; ok && row < height; row += tile_height ) { for( col = 0; ok && col < width; col += tile_width ) { uint32 i_row; /* Read the tile into an RGBA array */ if (!TIFFReadRGBATile(in, col, row, raster)) { ok = 0; break; } /* * XXX: raster array has 4-byte unsigned integer type, that is why * we should rearrange it here. */ #if HOST_BIGENDIAN TIFFSwabArrayOfLong(raster, tile_width * tile_height); #endif /* * For some reason the TIFFReadRGBATile() function chooses the * lower left corner as the origin. Vertically mirror scanlines. */ for( i_row = 0; i_row < tile_height / 2; i_row++ ) { uint32 *top_line, *bottom_line; top_line = raster + tile_width * i_row; bottom_line = raster + tile_width * (tile_height-i_row-1); _TIFFmemcpy(wrk_line, top_line, 4*tile_width); _TIFFmemcpy(top_line, bottom_line, 4*tile_width); _TIFFmemcpy(bottom_line, wrk_line, 4*tile_width); } /* * Write out the result in a tile. */ if( TIFFWriteEncodedTile( out, TIFFComputeTile( out, col, row, 0, 0), raster, 4 * tile_width * tile_height ) == -1 ) { ok = 0; break; } } } _TIFFfree( raster ); _TIFFfree( wrk_line ); return ok; }
void Matrix::rotate(const Quaternion& q, Matrix* dst) const { Matrix r; createRotation(q, &r); multiply(*this, r, dst); }
static int cvt_by_strip( TIFF *in, TIFF *out ) { uint32* raster; /* retrieve RGBA image */ uint32 width, height; /* image width & height */ uint32 row; uint32 *wrk_line; tsize_t raster_size; int ok = 1; TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height); if( !TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip) ) { TIFFError(TIFFFileName(in), "Source image not in strips"); return (0); } TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); /* * Allocate strip buffer */ raster_size = multiply(multiply(width, rowsperstrip), sizeof (uint32)); if (!raster_size) { TIFFError(TIFFFileName(in), "Can't allocate buffer for raster of size %lux%lu", (unsigned long) width, (unsigned long) rowsperstrip); return (0); } raster = (uint32*)_TIFFmalloc(raster_size); if (raster == 0) { TIFFError(TIFFFileName(in), "No space for raster buffer"); return (0); } /* * Allocate a scanline buffer for swapping during the vertical * mirroring pass. (Request can't overflow given prior checks.) */ wrk_line = (uint32*)_TIFFmalloc(width * sizeof (uint32)); if (!wrk_line) { TIFFError(TIFFFileName(in), "No space for raster scanline buffer"); ok = 0; } /* * Loop over the strips. */ for( row = 0; ok && row < height; row += rowsperstrip ) { int rows_to_write, i_row; /* Read the strip into an RGBA array */ if (!TIFFReadRGBAStrip(in, row, raster)) { ok = 0; break; } /* * XXX: raster array has 4-byte unsigned integer type, that is why * we should rearrange it here. */ #if HOST_BIGENDIAN TIFFSwabArrayOfLong(raster, width * rowsperstrip); #endif /* * Figure out the number of scanlines actually in this strip. */ if( row + rowsperstrip > height ) rows_to_write = height - row; else rows_to_write = rowsperstrip; /* * For some reason the TIFFReadRGBAStrip() function chooses the * lower left corner as the origin. Vertically mirror scanlines. */ for( i_row = 0; i_row < rows_to_write / 2; i_row++ ) { uint32 *top_line, *bottom_line; top_line = raster + width * i_row; bottom_line = raster + width * (rows_to_write-i_row-1); _TIFFmemcpy(wrk_line, top_line, 4*width); _TIFFmemcpy(top_line, bottom_line, 4*width); _TIFFmemcpy(bottom_line, wrk_line, 4*width); } /* * Write out the result in a strip */ if( TIFFWriteEncodedStrip( out, row / rowsperstrip, raster, 4 * rows_to_write * width ) == -1 ) { ok = 0; break; } } _TIFFfree( raster ); _TIFFfree( wrk_line ); return ok; }
void Matrix::rotateZ(float angle, Matrix* dst) const { Matrix r; createRotationZ(angle, &r); multiply(*this, r, dst); }
double calculate(int numInputTokens, char **inputString){ int i; double result = 0.0; char *s; struct DynArr *stack; double num; //set up the stack stack = createDynArr(20); // start at 1 to skip the name of the calculator calc for(i=1;i < numInputTokens;i++) { s = inputString[i]; // Hint: General algorithm: // (1) Check if the string s is in the list of operators. // (1a) If it is, perform corresponding operations. // (1b) Otherwise, check if s is a number. // (1b - I) If s is not a number, produce an error. // (1b - II) If s is a number, push it onto the stack if(strcmp(s, "+") == 0){ add(stack); printf("Adding\n"); } else if(strcmp(s,"-") == 0){ subtract(stack); printf("Subtracting\n"); } else if(strcmp(s, "/") == 0){ divide(stack); printf("Dividing\n"); } else if(strcmp(s, "x") == 0){ multiply(stack); printf("Multiplying\n"); } else if(strcmp(s,"^") == 0){ power(stack); printf("Power\n"); } else if(strcmp(s, "^2") == 0){ squared(stack); printf("Squaring\n"); } else if(strcmp(s, "^3") == 0){ cubed(stack); printf("Cubing\n"); } else if(strcmp(s, "abs") == 0){ absoluteValue(stack); printf("Absolute value\n"); } else if(strcmp(s, "sqrt") == 0){ squareRoot(stack); printf("Square root\n"); } else if(strcmp(s, "exp") == 0){ exponential(stack); printf("Exponential\n"); } else if(strcmp(s, "ln") == 0){ naturalLog(stack); printf("Natural Log\n"); } else if(strcmp(s, "log") == 0){ logBase10(stack); printf("Log\n"); } else{ // FIXME: You need to develop the code here (when s is not an operator) // Remember to deal with special values ("pi" and "e") //check if not a number if (isNumber(s, &num) == 0){ if (strcmp(s, "pi") == 0){ num = 3.14159265; } else if (strcmp(s, "e") == 0){ num = 2.7182818; } else{ //wrong printf("%s is not valid (number or operator) \n", s); break; } } pushDynArr(stack, num); } } //end for /* FIXME: You will write this part of the function (2 steps below) * (1) Check if everything looks OK and produce an error if needed. * (2) Store the final value in result and print it out. */ if (sizeDynArr(stack) != 1) { printf("Incorrect count of numbers is detected! Calculations CANNOT be preformed. "); return 0; } else { result = topDynArr(stack); } return result; }
void Matrix::translate(float x, float y, float z, Matrix* dst) const { Matrix t; createTranslation(x, y, z, &t); multiply(*this, t, dst); }
int square(int num) { return multiply(num, num); }
Point2d phaseCorrelate(InputArray _src1, InputArray _src2, InputArray _window, double* response) { Mat src1 = _src1.getMat(); Mat src2 = _src2.getMat(); Mat window = _window.getMat(); CV_Assert( src1.type() == src2.type()); CV_Assert( src1.type() == CV_32FC1 || src1.type() == CV_64FC1 ); CV_Assert( src1.size == src2.size); if(!window.empty()) { CV_Assert( src1.type() == window.type()); CV_Assert( src1.size == window.size); } int M = getOptimalDFTSize(src1.rows); int N = getOptimalDFTSize(src1.cols); Mat padded1, padded2, paddedWin; if(M != src1.rows || N != src1.cols) { copyMakeBorder(src1, padded1, 0, M - src1.rows, 0, N - src1.cols, BORDER_CONSTANT, Scalar::all(0)); copyMakeBorder(src2, padded2, 0, M - src2.rows, 0, N - src2.cols, BORDER_CONSTANT, Scalar::all(0)); if(!window.empty()) { copyMakeBorder(window, paddedWin, 0, M - window.rows, 0, N - window.cols, BORDER_CONSTANT, Scalar::all(0)); } } else { padded1 = src1; padded2 = src2; paddedWin = window; } // perform window multiplication if available if(!paddedWin.empty()) { // apply window to both images before proceeding... multiply(paddedWin, padded1, padded1); multiply(paddedWin, padded2, padded2); } // execute phase correlation equation // Reference: http://en.wikipedia.org/wiki/Phase_correlation cv::Mat FFT1, FFT2; dft(padded1, FFT1, DFT_COMPLEX_OUTPUT); dft(padded2, FFT2, DFT_COMPLEX_OUTPUT); // // high-pass filter // cv::Mat hpFilter = 1-paddedWin; // phasecorrelation::fftShift(hpFilter); // for(int i=0; i<paddedWin.rows; i++){ // for(int j=0; j<paddedWin.cols; j++){ // FFT1.at<cv::Vec2f>(i,j) *= hpFilter.at<float>(i,j); // FFT2.at<cv::Vec2f>(i,j) *= hpFilter.at<float>(i,j); // } // } cv::Mat P; cv::mulSpectrums(FFT1, FFT2, P, DFT_COMPLEX_OUTPUT, true); cv::Mat Pm(P.size(), CV_32F); // NOTE: memleak in magSpectrums when using it with complex output! //phasecorrelation::magSpectrums(P, Pm); for(int i=0; i<P.rows; i++){ for(int j=0; j<P.cols; j++){ cv::Vec2f e = P.at<cv::Vec2f>(i, j); Pm.at<float>(i, j) = cv::sqrt(e[0]*e[0] + e[1]*e[1]); } } //phasecorrelation::divSpectrums(P, Pm, C, 0, false); // FF* / |FF*| (phase correlation equation completed here...) for(int i=0; i<P.rows; i++){ for(int j=0; j<P.cols; j++){ P.at<cv::Vec2f>(i, j) /= (Pm.at<float>(i, j) + DBL_EPSILON); } } cv::Mat C(P.size(), CV_32F); cv::dft(P, C, cv::DFT_INVERSE + cv::DFT_REAL_OUTPUT); phasecorrelation::fftShift(C); // shift the energy to the center of the frame. //cvtools::writeMat(C, "C.mat", "C"); // locate the highest peak Point peakLoc; minMaxLoc(C, NULL, NULL, NULL, &peakLoc); // get the phase shift with sub-pixel accuracy, 5x5 window seems about right here... Point2d t = phasecorrelation::weightedCentroid(C, peakLoc, Size(3, 3), response); // max response is M*N (not exactly, might be slightly larger due to rounding errors) if(response) *response /= M*N; // adjust shift relative to image center... Point2d center((double)padded1.cols / 2.0, (double)padded1.rows / 2.0); return (center - t); }
int main(){ return multiply(42,24); }