Exemplo n.º 1
0
int TclExpCPCommand(ClientData clientData, Tcl_Interp *interp,
    int argc, TCL_Char **argv, Domain *theDomain)
{
    if (theExperimentalCPs == 0)
        theExperimentalCPs = new ArrayOfTaggedObjects(32);
    
    // make sure there is a minimum number of arguments
    if (argc < 4)  {
        opserr << "WARNING invalid number of arguments\n";
        printCommand(argc,argv);
        opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
        return TCL_ERROR;
    }
    
    int tag, i, argi = 1;
    int nodeTag = 0, ndf = 0, ndm = 0;
    Node *theNode = 0;
    int numSignals = 0, numLim = 0, numRefType = 0;
    double f, lim;
    ExperimentalCP *theCP = 0;
    
    if (Tcl_GetInt(interp, argv[argi], &tag) != TCL_OK)  {
        opserr << "WARNING invalid expControlPoint tag\n";
        return TCL_ERROR;
    }
    argi++;
    if (strcmp(argv[argi],"-node") == 0)  {
        argi++;
        if (Tcl_GetInt(interp, argv[argi], &nodeTag) != TCL_OK)  {
            opserr << "WARNING invalid nodeTag for control point: " << tag << endln;
            printCommand(argc,argv);
            opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
            return TCL_ERROR;
        }
        theNode = theDomain->getNode(nodeTag);
        ndf = theNode->getNumberDOF();
        ndm = OPS_GetNDM();
        argi++;
    }
    // count number of signals
    i = argi;
    while (i < argc)  {
        if (strcmp(argv[i],"-fact") == 0 || strcmp(argv[i],"-factor") == 0)
            i += 2;
        else if (strcmp(argv[i],"-isRel") == 0 || strcmp(argv[i],"-isRelative") == 0)
            i++;
        else if (strcmp(argv[i],"-lim") == 0 || strcmp(argv[i],"-limit") == 0)  {
            i += 3;
            numLim++;
        }
        else  {
            i += 2;
            numSignals++;
        }
    }
    if (numSignals == 0)  {
        opserr << "WARNING invalid number of arguments for control point: " << tag << endln;
        printCommand(argc,argv);
        opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
        return TCL_ERROR;
    }
    if (numLim > 0 && numLim != numSignals)  {
        opserr << "WARNING invalid number of limits for control point: " << tag << endln;
        printCommand(argc,argv);
        opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
        return TCL_ERROR;
    }
    ID dof(numSignals);
    ID rspType(numSignals);
    Vector factor(numSignals);
    Vector lowerLim(numSignals);
    Vector upperLim(numSignals);
    ID isRelative(numSignals);
    for (i=0; i<numSignals; i++)  {
        if (ndf == 0)  {
            int dofID = 0;
            if (sscanf(argv[argi],"%d",&dofID) != 1)  {
                if (sscanf(argv[argi],"%*[dfouDFOU]%d",&dofID) != 1)  {
                    opserr << "WARNING invalid dof for control point: " << tag << endln;
                    printCommand(argc,argv);
                    opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                    return TCL_ERROR;
                }
            }
            dof(i) = dofID - 1;
        }
        else if (ndm == 1 && ndf == 1)  {
            if (strcmp(argv[argi],"1") == 0 || 
                strcmp(argv[argi],"dof1") == 0 || strcmp(argv[argi],"DOF1") == 0 ||
                strcmp(argv[argi],"u1") == 0 || strcmp(argv[argi],"U1") == 0 ||
                strcmp(argv[argi],"ux") == 0 || strcmp(argv[argi],"UX") == 0)
                dof(i) = 0;
            else  {
                opserr << "WARNING invalid dof for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                return TCL_ERROR;
            }
        }
        else if (ndm == 2 && ndf == 2)  {
            if (strcmp(argv[argi],"1") == 0 ||
                strcmp(argv[argi],"dof1") == 0 || strcmp(argv[argi],"DOF1") == 0 ||
                strcmp(argv[argi],"u1") == 0 || strcmp(argv[argi],"U1") == 0 ||
                strcmp(argv[argi],"ux") == 0 || strcmp(argv[argi],"UX") == 0)
                dof(i) = 0;
            else if (strcmp(argv[argi],"2") == 0 ||
                strcmp(argv[argi],"dof2") == 0 || strcmp(argv[argi],"DOF2") == 0 ||
                strcmp(argv[argi],"u2") == 0 || strcmp(argv[argi],"U2") == 0 ||
                strcmp(argv[argi],"uy") == 0 || strcmp(argv[argi],"UY") == 0)
                dof(i) = 1;
            else  {
                opserr << "WARNING invalid dof for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                return TCL_ERROR;
            }
        }
        else if (ndm == 2 && ndf == 3)  {
            if (strcmp(argv[argi],"1") == 0 ||
                strcmp(argv[argi],"dof1") == 0 || strcmp(argv[argi],"DOF1") == 0 ||
                strcmp(argv[argi],"u1") == 0 || strcmp(argv[argi],"U1") == 0 ||
                strcmp(argv[argi],"ux") == 0 || strcmp(argv[argi],"UX") == 0)
                dof(i) = 0;
            else if (strcmp(argv[argi],"2") == 0 ||
                strcmp(argv[argi],"dof2") == 0 || strcmp(argv[argi],"DOF2") == 0 ||
                strcmp(argv[argi],"u2") == 0 || strcmp(argv[argi],"U2") == 0 ||
                strcmp(argv[argi],"uy") == 0 || strcmp(argv[argi],"UY") == 0)
                dof(i) = 1;
            else if (strcmp(argv[argi],"3") == 0 ||
                strcmp(argv[argi],"dof3") == 0 || strcmp(argv[argi],"DOF3") == 0 ||
                strcmp(argv[argi],"r3") == 0 || strcmp(argv[argi],"R3") == 0 ||
                strcmp(argv[argi],"rz") == 0 || strcmp(argv[argi],"RZ") == 0)
                dof(i) = 2;
            else  {
                opserr << "WARNING invalid dof for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                return TCL_ERROR;
            }
        }
        else if (ndm == 3 && ndf == 3)  {
            if (strcmp(argv[argi],"1") == 0 ||
                strcmp(argv[argi],"dof1") == 0 || strcmp(argv[argi],"DOF1") == 0 ||
                strcmp(argv[argi],"u1") == 0 || strcmp(argv[argi],"U1") == 0 ||
                strcmp(argv[argi],"ux") == 0 || strcmp(argv[argi],"UX") == 0)
                dof(i) = 0;
            else if (strcmp(argv[argi],"2") == 0 ||
                strcmp(argv[argi],"dof2") == 0 || strcmp(argv[argi],"DOF2") == 0 ||
                strcmp(argv[argi],"u2") == 0 || strcmp(argv[argi],"U2") == 0 ||
                strcmp(argv[argi],"uy") == 0 || strcmp(argv[argi],"UY") == 0)
                dof(i) = 1;
            else if (strcmp(argv[argi],"3") == 0 ||
                strcmp(argv[argi],"dof3") == 0 || strcmp(argv[argi],"DOF3") == 0 ||
                strcmp(argv[argi],"u3") == 0 || strcmp(argv[argi],"U3") == 0 ||
                strcmp(argv[argi],"uz") == 0 || strcmp(argv[argi],"UZ") == 0)
                dof(i) = 2;
            else  {
                opserr << "WARNING invalid dof for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                return TCL_ERROR;
            }
        }
        else if (ndm == 3 && ndf == 6)  {
            if (strcmp(argv[argi],"1") == 0 ||
                strcmp(argv[argi],"dof1") == 0 || strcmp(argv[argi],"DOF1") == 0 ||
                strcmp(argv[argi],"u1") == 0 || strcmp(argv[argi],"U1") == 0 ||
                strcmp(argv[argi],"ux") == 0 || strcmp(argv[argi],"UX") == 0)
                dof(i) = 0;
            else if (strcmp(argv[argi],"2") == 0 ||
                strcmp(argv[argi],"dof2") == 0 || strcmp(argv[argi],"DOF2") == 0 ||
                strcmp(argv[argi],"u2") == 0 || strcmp(argv[argi],"U2") == 0 ||
                strcmp(argv[argi],"uy") == 0 || strcmp(argv[argi],"UY") == 0)
                dof(i) = 1;
            else if (strcmp(argv[argi],"3") == 0 ||
                strcmp(argv[argi],"dof3") == 0 || strcmp(argv[argi],"DOF3") == 0 ||
                strcmp(argv[argi],"u3") == 0 || strcmp(argv[argi],"U3") == 0 ||
                strcmp(argv[argi],"uz") == 0 || strcmp(argv[argi],"UZ") == 0)
                dof(i) = 2;
            else if (strcmp(argv[argi],"4") == 0 ||
                strcmp(argv[argi],"dof4") == 0 || strcmp(argv[argi],"DOF4") == 0 ||
                strcmp(argv[argi],"r1") == 0 || strcmp(argv[argi],"R1") == 0 ||
                strcmp(argv[argi],"rx") == 0 || strcmp(argv[argi],"RX") == 0)
                dof(i) = 3;
            else if (strcmp(argv[argi],"5") == 0 ||
                strcmp(argv[argi],"dof5") == 0 || strcmp(argv[argi],"DOF5") == 0 ||
                strcmp(argv[argi],"r2") == 0 || strcmp(argv[argi],"R2") == 0 ||
                strcmp(argv[argi],"ry") == 0 || strcmp(argv[argi],"RY") == 0)
                dof(i) = 4;
            else if (strcmp(argv[argi],"6") == 0 ||
                strcmp(argv[argi],"dof6") == 0 || strcmp(argv[argi],"DOF6") == 0 ||
                strcmp(argv[argi],"r3") == 0 || strcmp(argv[argi],"R3") == 0 ||
                strcmp(argv[argi],"rz") == 0 || strcmp(argv[argi],"RZ") == 0)
                dof(i) = 5;
            else  {
                opserr << "WARNING invalid dof for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
               return TCL_ERROR;
            }
        }
        argi++;
        if (strcmp(argv[argi],"1") == 0 || strcmp(argv[argi],"dsp") == 0 ||
            strcmp(argv[argi],"disp") == 0 || strcmp(argv[argi],"displacement") == 0)
            rspType(i) = OF_Resp_Disp;
        else if (strcmp(argv[argi],"2") == 0 || strcmp(argv[argi],"vel") == 0 ||
            strcmp(argv[argi],"velocity") == 0)
            rspType(i) = OF_Resp_Vel;
        else if (strcmp(argv[argi],"3") == 0 || strcmp(argv[argi],"acc") == 0 ||
            strcmp(argv[argi],"accel") == 0 || strcmp(argv[argi],"acceleration") == 0)
            rspType(i) = OF_Resp_Accel;
        else if (strcmp(argv[argi],"4") == 0 || strcmp(argv[argi],"frc") == 0 ||
            strcmp(argv[argi],"force") == 0)
            rspType(i) = OF_Resp_Force;
        else if (strcmp(argv[argi],"5") == 0 ||  strcmp(argv[argi],"t") == 0 ||
            strcmp(argv[argi],"tme") == 0 || strcmp(argv[argi],"time") == 0)
            rspType(i) = OF_Resp_Time;
        else  {
            opserr << "WARNING invalid rspType for control point: " << tag << endln;
            printCommand(argc,argv);
            opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
            return TCL_ERROR;
        }
        argi++;
        if (argi<argc && (strcmp(argv[argi],"-fact") == 0 || strcmp(argv[argi],"-factor") == 0))  {
            argi++;
            if (Tcl_GetDouble(interp, argv[argi], &f) != TCL_OK)  {
                opserr << "WARNING invalid factor for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                return TCL_ERROR;
            }
            factor(i) = f;
            argi++;
        } else  {
            factor(i) = 1.0;
        }
        if (argi<argc && (strcmp(argv[argi],"-lim") == 0 || strcmp(argv[argi],"-limit") == 0))  {
            argi++;
            if (Tcl_GetDouble(interp, argv[argi], &lim) != TCL_OK)  {
                opserr << "WARNING invalid lower limit for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                return TCL_ERROR;
            }
            lowerLim(i) = lim;
            argi++;
            if (Tcl_GetDouble(interp, argv[argi], &lim) != TCL_OK)  {
                opserr << "WARNING invalid upper limit for control point: " << tag << endln;
                printCommand(argc,argv);
                opserr << "Want: expControlPoint tag <-node nodeTag> dof rspType <-fact f> <-lim l u> <-isRel> ...\n";
                return TCL_ERROR;
            }
            upperLim(i) = lim;
            argi++;
        }
        if (argi<argc && (strcmp(argv[argi],"-isRel") == 0 || strcmp(argv[argi],"-isRelative") == 0))  {
            isRelative(i) = 1;
            numRefType++;
            argi++;
        }
    }
    
    // parsing was successful, allocate the control point
    theCP = new ExperimentalCP(tag, dof, rspType, factor);
    
    if (theCP == 0)  {
        opserr << "WARNING could not create experimental control point " << argv[1] << endln;
        return TCL_ERROR;
    }
    
    // add limits if available
    if (numLim > 0)
        theCP->setLimits(lowerLim, upperLim);
    
    // add signal reference types if available
    if (numRefType > 0)
        theCP->setSigRefType(isRelative);
    
    // add node if available
    if (theNode != 0)
        theCP->setNode(theNode);
    
    // now add the control point to the modelBuilder
    if (addExperimentalCP(*theCP) < 0)  {
        delete theCP; // invoke the destructor, otherwise mem leak
        return TCL_ERROR;
    }
    
    return TCL_OK;
}
Exemplo n.º 2
0
void GaussianFactorization(void)
{
  BigInteger prime, q, r, M1, M2, Tmp;
  struct sFactors *pstFactor;

  BigIntMultiply(&ReValue, &ReValue, &tofactor);
  BigIntMultiply(&ImValue, &ImValue, &Tmp);
  BigIntAdd(&tofactor, &Tmp, &tofactor);
  NbrFactorsNorm = 0;
#ifdef __EMSCRIPTEN__
  originalTenthSecond = tenths();
#endif
  if (tofactor.nbrLimbs == 1 && tofactor.limbs[0].x == 0)
  {                // Norm is zero.
    showText("<ul><li>Any gaussian prime divides this number</li></ul>");
    return;
  }
  showText("<ul>");
  if (tofactor.nbrLimbs > 1 || tofactor.limbs[0].x > 1)
  {           // norm greater than 1. Factor norm.
    int index, index2;
    char *ptrFactorDec = tofactorDec;
    NumberLength = tofactor.nbrLimbs;
    CompressBigInteger(nbrToFactor, &tofactor);
    strcpy(ptrFactorDec, "Re&sup2; + Im&sup2; = ");
    ptrFactorDec += strlen(ptrFactorDec);
    Bin2Dec(ReValue.limbs, ptrFactorDec, ReValue.nbrLimbs, groupLen);
    ptrFactorDec += strlen(ptrFactorDec);
    strcpy(ptrFactorDec, "&sup2; + ");
    ptrFactorDec += strlen(ptrFactorDec);
    Bin2Dec(ImValue.limbs, ptrFactorDec, ImValue.nbrLimbs, groupLen);
    ptrFactorDec += strlen(ptrFactorDec);
    strcpy(ptrFactorDec, "&sup2;");
    ptrFactorDec += strlen(ptrFactorDec);
    factor(&tofactor, nbrToFactor, factorsNorm, astFactorsNorm);
    NbrFactorsNorm = astFactorsNorm[0].multiplicity;
    pstFactor = &astFactorsNorm[1];
    for (index = 0; index < NbrFactorsNorm; index++)
    {
      int *ptrPrime = pstFactor->ptrFactor;
      NumberLength = *ptrPrime;
      UncompressBigInteger(ptrPrime, &prime);
      if (prime.nbrLimbs == 1 && prime.limbs[0].x == 2)
      {             // Prime factor is 2.
        for (index2 = 0; index2 < pstFactor->multiplicity; index2++)
        {
          M1.nbrLimbs = M2.nbrLimbs = 1;
          M1.limbs[0].x = M2.limbs[0].x = 1;
          M1.sign = SIGN_POSITIVE;
          M2.sign = SIGN_NEGATIVE;
          DivideGaussian(&M1, &M1);           // Divide by 1+i
          DivideGaussian(&M1, &M2);           // Divide by 1-i
        }
      }
      if ((prime.limbs[0].x & 2) == 0)
      {                               // Prime is congruent to 1 (mod 4)
        CopyBigInt(&q, &prime);
        NumberLength = prime.nbrLimbs;
        memcpy(&TestNbr, prime.limbs, NumberLength * sizeof(limb));
        TestNbr[NumberLength].x = 0;
        GetMontgomeryParms(NumberLength);
        subtractdivide(&q, 1, 4);     // q = (prime-1)/4
        memset(&K, 0, NumberLength * sizeof(limb));
        memset(minusOneMont, 0, NumberLength * sizeof(limb));
        SubtBigNbrModN(minusOneMont, MontgomeryMultR1, minusOneMont, TestNbr, NumberLength);
        K[0].x = 1;
        do
        {    // Loop that finds mult1 = sqrt(-1) mod prime in Montgomery notation.
          K[0].x++;
          modPow(K, q.limbs, q.nbrLimbs, mult1.limbs);
        } while (!memcmp(mult1.limbs, MontgomeryMultR1, NumberLength * sizeof(limb)) ||
                 !memcmp(mult1.limbs, minusOneMont, NumberLength * sizeof(limb)));
        K[0].x = 1;
        modmult(mult1.limbs, K, mult1.limbs);       // Convert mult1 to standard notation.
        UncompressLimbsBigInteger(mult1.limbs, &mult1);  // Convert to Big Integer.
        mult2.nbrLimbs = 1;                // mult2 <- 1
        mult2.limbs[0].x = 1;
        mult2.sign = SIGN_POSITIVE;
        for (;;)
        {
          // norm <- (mult1^2 + mult2^2) / prime
          BigIntMultiply(&mult1, &mult1, &tofactor);
          BigIntMultiply(&mult2, &mult2, &Tmp);
          BigIntAdd(&tofactor, &Tmp, &Tmp);
          BigIntDivide(&Tmp, &prime, &tofactor);
          if (tofactor.nbrLimbs == 1 && tofactor.limbs[0].x == 1)
          {        // norm equals 1.
            break;
          }
          BigIntRemainder(&mult1, &tofactor, &M1);
          BigIntRemainder(&mult2, &tofactor, &M2);
          BigIntAdd(&M1, &M1, &Tmp);
          BigIntSubt(&tofactor, &Tmp, &Tmp);
          if (Tmp.sign == SIGN_NEGATIVE)
          {
            BigIntSubt(&M1, &tofactor, &M1);
          }
          BigIntAdd(&M2, &M2, &Tmp);
          BigIntSubt(&tofactor, &Tmp, &Tmp);
          if (Tmp.sign == SIGN_NEGATIVE)
          {
            BigIntSubt(&M2, &tofactor, &M2);
          }
          // Compute q <- (mult1*M1 + mult2*M2) / norm
          BigIntMultiply(&mult1, &M1, &q);
          BigIntMultiply(&mult2, &M2, &Tmp);
          BigIntAdd(&q, &Tmp, &Tmp);
          BigIntDivide(&Tmp, &tofactor, &q);
          // Compute Mult2 <- (mult1*M2 - mult2*M1) / tofactor
          BigIntMultiply(&mult1, &M2, &r);
          BigIntMultiply(&mult2, &M1, &Tmp);
          BigIntSubt(&r, &Tmp, &Tmp);
          BigIntDivide(&Tmp, &tofactor, &mult2);
          CopyBigInt(&mult1, &q);
          mult1.sign = SIGN_POSITIVE;    // mult1 <- abs(mult1)
          mult2.sign = SIGN_POSITIVE;    // mult2 <- abs(mult2)
        }            /* end while */
        CopyBigInt(&M1, &mult1);
        CopyBigInt(&M2, &mult2);
        BigIntSubt(&M1, &M2, &Tmp);
        if (Tmp.sign == SIGN_NEGATIVE)
        {
          CopyBigInt(&Tmp, &mult1);
          CopyBigInt(&mult1, &mult2);
          CopyBigInt(&mult2, &Tmp);
        }
        for (index2 = 0; index2 < pstFactor->multiplicity; index2++)
        {
          DivideGaussian(&mult1, &mult2);
          BigIntNegate(&mult2, &Tmp);
          DivideGaussian(&mult1, &Tmp);
        }
      }              // end p = 1 (mod 4)
      else
      {              // if p = 3 (mod 4)
        q.nbrLimbs = 1;    // q <- 0
        q.limbs[0].x = 0;
        q.sign = SIGN_POSITIVE;
        for (index2 = 0; index2 < pstFactor->multiplicity; index2++)
        {
          DivideGaussian(&prime, &q);
        }            // end p = 3 (mod 4)
      }
      pstFactor++;
    }
  }
  // Process units: 1, -1, i, -i.
  if (ReValue.nbrLimbs == 1 && ReValue.limbs[0].x == 1)
  {
    if (ReValue.sign == SIGN_POSITIVE)
    {             // Value is 1.
      if (NbrFactorsNorm == 0)
      {
        showText("No gaussian prime divides this number");
      }
    }
    else
    {            // Value is -1.
      showText("<li>-1</li>");
    }
  }
  else if (ImValue.sign == SIGN_POSITIVE)
  {
    showText("<li>i</li>");
  }
  else
  {
    showText("<li>-i</li>");
  }
  showText("</ul>");
}
Exemplo n.º 3
0
int main(int argc, const char *argv[])
{
	int res;
	char *str;
	mpz_t largenum;

	if (argc <= 0) {
		fprintf(stderr, "usage: %s\n", argv[0]);
		exit(EXIT_SUCCESS);
	}

	fprintf(stderr, "setting pitch\n");
	orient_range.orient.pitch   = 180;
	orient_range.pitch_range    = 10;

	fprintf(stderr, "setting roll\n");
	orient_range.orient.roll    = 0;
	orient_range.roll_range     = 10;

	fprintf(stderr, "setting azimuth\n");
	orient_range.orient.azimuth = 0;
	orient_range.azimuth_range  = 0;

	mpz_init_set_str(one, "1", 10);
	mpz_init_set_str(two, "2", 10);

	gmp_randinit_default(randstate);

	sleep(1);

	if (syscall(__NR_orientlock_read, &orient_range) == -1) {
		fprintf(stderr, "error: Unable to obtain lock\n");
		exit(EXIT_FAILURE);
	}

	fp = fopen("./integer", "r");

	if ((fgets(integer, INTEGER_BUF_SIZE, fp)) == NULL) {
			fprintf(stderr, "error: Unable to read from file");
			exit(EXIT_FAILURE);
	}
	chomp_line(integer);

	mpz_init(largenum);
	mpz_init_set_str(largenum, integer, 10);

	str = mpz_to_str(largenum);
	if (!str)
		return EXIT_FAILURE;

	/*
	 * We simply return the prime number itself if the base is prime.
	 * (We use the GMP probabilistic function with 10 repetitions).
	 */
	res = mpz_probab_prime_p(largenum, 10);
	if (res) {
		printf("%s is a prime number\n", str);
		free(str);
		mpz_add(largenum, largenum, one);
	}

	printf("Prime factors for %s are:  ", str);
	free(str);

	factor(largenum);
	printf("\n");

	fclose(fp);

	if (syscall(__NR_orientunlock_read, &orient_range) == -1) {
		fprintf(stderr, "error: Unable to unlock\n");
		exit(EXIT_FAILURE);
	}

	return EXIT_SUCCESS;
}
Exemplo n.º 4
0
template<class Real> int
Triangulation<Real>::flipMinimize (const int& eIndex)
{
  double oldArea, newArea;
  int oldP[3], oldQ[3], newP[3], newQ[3];
  TriangulationEdge newEdge;

  if (edges[eIndex].tIndex[0] < 0 || edges[eIndex].tIndex[1] < 0)
  {
    return 0;
  }

  if (!factor (edges[eIndex].tIndex[0], oldP[0], oldP[1], oldP[2]))
  {
    return 0;
  }
  if (!factor (edges[eIndex].tIndex[1], oldQ[0], oldQ[1], oldQ[2]))
  {
    return 0;
  }

  oldArea = area (oldP[0], oldP[1], oldP[2]) + area (oldQ[0], oldQ[1], oldQ[2]);
  int idxP, idxQ;
  for (idxP = 0; idxP < 3; idxP++)
  {
    int i;
    for (i = 0; i < 3; i++)
    {
      if (oldP[idxP] == oldQ[i])
      {
        break;
      }
    }
    if (i == 3)
    {
      break;
    }
  }
  for (idxQ = 0; idxQ < 3; idxQ++)
  {
    int i;
    for (i = 0; i < 3; i++)
    {
      if (oldP[i] == oldQ[idxQ])
      {
        break;
      }
    }
    if (i == 3)
    {
      break;
    }
  }
  if (idxP == 3 || idxQ == 3)
  {
    return 0;
  }
  newP[0] = oldP[idxP];
  newP[1] = oldP[(idxP + 1) % 3];
  newP[2] = oldQ[idxQ];
  newQ[0] = oldQ[idxQ];
  newQ[1] = oldP[(idxP + 2) % 3];
  newQ[2] = oldP[idxP];

  newArea = area (newP[0], newP[1], newP[2]) + area (newQ[0], newQ[1], newQ[2]);
  if (oldArea <= newArea)
  {
    return 0;
  }

  // Remove the entry in the hash_table for the old edge
  edgeMap.erase (EdgeIndex (edges[eIndex].pIndex[0], edges[eIndex].pIndex[1]));
  // Set the new edge so that the zero-side is newQ
  edges[eIndex].pIndex[0] = newP[0];
  edges[eIndex].pIndex[1] = newQ[0];
  // Insert the entry into the hash_table for the new edge
  edgeMap[EdgeIndex (newP[0], newQ[0])] = eIndex;
  // Update the triangle information
  for (int i = 0; i < 3; i++)
  {
    int idx;
    idx = edgeMap[EdgeIndex (newQ[i], newQ[(i + 1) % 3])];
    triangles[edges[eIndex].tIndex[0]].eIndex[i] = idx;
    if (idx != eIndex)
    {
      if (edges[idx].tIndex[0] == edges[eIndex].tIndex[1])
      {
        edges[idx].tIndex[0] = edges[eIndex].tIndex[0];
      }
      if (edges[idx].tIndex[1] == edges[eIndex].tIndex[1])
      {
        edges[idx].tIndex[1] = edges[eIndex].tIndex[0];
      }
    }

    idx = edgeMap[EdgeIndex (newP[i], newP[(i + 1) % 3])];
    triangles[edges[eIndex].tIndex[1]].eIndex[i] = idx;
    if (idx != eIndex)
    {
      if (edges[idx].tIndex[0] == edges[eIndex].tIndex[0])
      {
        edges[idx].tIndex[0] = edges[eIndex].tIndex[1];
      }
      if (edges[idx].tIndex[1] == edges[eIndex].tIndex[0])
      {
        edges[idx].tIndex[1] = edges[eIndex].tIndex[1];
      }
    }
  }
  return 1;
}
Exemplo n.º 5
0
/* true if n prime */
int ei_isprime(int n)
{
  return (n == factor(n));
}
Exemplo n.º 6
0
int main(int argc, char **argv)
{
    char num[100000] = {0};
    factor(num, 100000, atoi(argv[1]));
    return 0;
}
Exemplo n.º 7
0
url
descendance (url u) {
  // Utility for style and package menus in tm_server.cpp
  // Compute and merge subdirectories of directories in path
  return factor (descendance_sub (u));
}
int main(int argc, char** argv) {
  global_logger().set_log_level(LOG_INFO);
  global_logger().set_log_to_console(true);

  // Parse command line options -----------------------------------------------
  const std::string description = 
    "Creates a folder with synthetic training data";
  graphlab::command_line_options clopts(description, false);
  std::string output_folder = "synthetic_data";
  size_t nfiles            = 5;
  size_t D                 = 20;
  size_t nusers            = 1000;
  size_t nmovies           = 10000;
  size_t nvalidate       = 2;
  size_t npredict          = 1;
  double noise             = 0.1;
  double stdev             = 2;
  double alpha             = 1.8;


  clopts.attach_option("dir", output_folder,
                       "Location to create the data files");
  clopts.attach_option("nfiles", nfiles,
                       "The number of files to generate.");
  clopts.attach_option("D", D, "Number of latent dimensions.");
  clopts.attach_option("nusers", nusers,
                       "The number of users.");
  clopts.attach_option("nmovies", nmovies,
                       "The number of movies.");
  clopts.attach_option("alpha", alpha,
                       "The power-law constant.");
  clopts.attach_option("nvalidate", nvalidate,
                       "The validate ratings pers user");
  clopts.attach_option("npredict", npredict,
                       "The predict ratings pers user");

  clopts.attach_option("noise", noise,
                       "The standard deviation noise parameter");
  clopts.attach_option("stdev", stdev,
                       "The standard deviation in latent factor values");

  if(!clopts.parse(argc, argv)) {
    std::cout << "Error in parsing command line arguments." << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Creating data directory: " << output_folder << std::endl;
  boost::filesystem::path directory(output_folder);
  if(!boost::filesystem::create_directory(output_folder)) {
    logstream(LOG_ERROR) 
      << "Error creating directory: " << directory << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "Opening files:" << std::endl;
  std::vector< std::ofstream* > train_files(nfiles);
  std::vector< std::ofstream* > validate_files(nfiles);
  std::vector< std::ofstream* > predict_files(nfiles);
  for(size_t i = 0; i < nfiles; ++i) {
    const std::string train_fname = 
      output_folder + "/graph_" + graphlab::tostr(i) + ".tsv";
    train_files[i] = new std::ofstream(train_fname.c_str());
    if(!train_files[i]->good()) {
      logstream(LOG_ERROR) 
        << "Error creating file: " << train_fname;
    }

    const std::string validate_fname = 
      output_folder + "/graph_" + graphlab::tostr(i) + ".tsv.validate";
    validate_files[i] = new std::ofstream(validate_fname.c_str());
    if(!validate_files[i]->good()){
      logstream(LOG_ERROR) 
        << "Error creating file: " << train_fname;
    }       

    const std::string predict_fname = 
      output_folder + "/graph_" + graphlab::tostr(i) + ".tsv.predict";
    predict_files[i] = new std::ofstream(predict_fname.c_str());
    if(!predict_files[i]->good()){
      logstream(LOG_ERROR) 
        << "Error creating file: " << train_fname;
    }       
  }
  



  // Make synthetic latent factors
  std::vector< vec_type > user_factors(nusers);
  std::vector< vec_type > movie_factors(nmovies);
  // Create a shared random number generator
  graphlab::random::generator gen; gen.seed(31413);
  
  std::cout << "Constructing latent user factors" << std::endl;
  foreach(vec_type& factor, user_factors) {
    factor.resize(D);
    // Randomize the factor
    for(size_t d = 0; d < D; ++d) 
      factor(d) = gen.gaussian(0, stdev);
  }
Exemplo n.º 9
0
main (int argc, char *argv[])
{
      while ( --argc )
            factor(atof(*++argv));
      return 0;
}
Exemplo n.º 10
0
void KEndingBalanceDlg::slotUpdateBalances()
{
  MYMONEYTRACER(tracer);

  // determine the beginning balance and ending balance based on the following
  // forumulas:
  //
  // end balance   = current balance - sum(all non cleared transactions)
  //                                 - sum(all cleared transactions posted
  //                                        after statement date)
  // start balance = end balance - sum(all cleared transactions
  //                                        up to statement date)
  MyMoneyTransactionFilter filter(d->m_account.id());
  filter.addState(MyMoneyTransactionFilter::notReconciled);
  filter.setReportAllSplits(true);

  QList<QPair<MyMoneyTransaction, MyMoneySplit> > transactionList;
  QList<QPair<MyMoneyTransaction, MyMoneySplit> >::const_iterator it;

  // retrieve the list from the engine
  MyMoneyFile::instance()->transactionList(transactionList, filter);

  //first retrieve the oldest not reconciled transaction
  QDate oldestTransactionDate;
  it = transactionList.constBegin();
  if (it != transactionList.constEnd()) {
    oldestTransactionDate = (*it).first.postDate();
    m_statementInfoPageCheckings->m_oldestTransactionDate->setText(i18n("Oldest unmarked transaction: %1", QLocale().toString(oldestTransactionDate)));
  }

  filter.addState(MyMoneyTransactionFilter::cleared);

  // retrieve the list from the engine to calculate the starting and ending balance
  MyMoneyFile::instance()->transactionList(transactionList, filter);

  MyMoneyMoney balance = MyMoneyFile::instance()->balance(d->m_account.id());
  MyMoneyMoney factor(1, 1);
  if (d->m_account.accountGroup() == MyMoneyAccount::Liability)
    factor = -factor;

  MyMoneyMoney endBalance, startBalance;
  balance = balance * factor;
  endBalance = startBalance = balance;

  tracer.printf("total balance = %s", qPrintable(endBalance.formatMoney("", 2)));

  for (it = transactionList.constBegin(); it != transactionList.constEnd(); ++it) {
    const MyMoneySplit& split = (*it).second;
    balance -= split.shares() * factor;
    if ((*it).first.postDate() > field("statementDate").toDate()) {
      tracer.printf("Reducing balances by %s because postdate of %s/%s(%s) is past statement date", qPrintable((split.shares() * factor).formatMoney("", 2)), qPrintable((*it).first.id()), qPrintable(split.id()), qPrintable((*it).first.postDate().toString(Qt::ISODate)));
      endBalance -= split.shares() * factor;
      startBalance -= split.shares() * factor;
    } else {
      switch (split.reconcileFlag()) {
        case MyMoneySplit::NotReconciled:
          tracer.printf("Reducing balances by %s because %s/%s(%s) is not reconciled", qPrintable((split.shares() * factor).formatMoney("", 2)), qPrintable((*it).first.id()), qPrintable(split.id()), qPrintable((*it).first.postDate().toString(Qt::ISODate)));
          endBalance -= split.shares() * factor;
          startBalance -= split.shares() * factor;
          break;
        case MyMoneySplit::Cleared:
          tracer.printf("Reducing start balance by %s because %s/%s(%s) is cleared", qPrintable((split.shares() * factor).formatMoney("", 2)), qPrintable((*it).first.id()), qPrintable(split.id()), qPrintable((*it).first.postDate().toString(Qt::ISODate)));
          startBalance -= split.shares() * factor;
          break;
        default:
          break;
      }
    }
  }
  //FIXME: port
  m_statementInfoPageCheckings->m_previousBalance->setValue(startBalance);
  m_statementInfoPageCheckings->m_endingBalance->setValue(endBalance);
  tracer.printf("total balance = %s", qPrintable(endBalance.formatMoney("", 2)));
  tracer.printf("start balance = %s", qPrintable(startBalance.formatMoney("", 2)));

  setField("interestDateEdit", field("statementDate").toDate());
  setField("chargesDateEdit", field("statementDate").toDate());
}
Exemplo n.º 11
0
KEndingBalanceDlg::KEndingBalanceDlg(const MyMoneyAccount& account, QWidget *parent) :
    KEndingBalanceDlgDecl(parent),
    d(new Private(Page_InterestChargeCheckings + 1))
{
  setModal(true);
  QString value;
  MyMoneyMoney endBalance, startBalance;

  d->m_account = account;

  MyMoneySecurity currency = MyMoneyFile::instance()->security(account.currencyId());
  //FIXME: port
  m_statementInfoPageCheckings->m_enterInformationLabel->setText(QString("<qt>") + i18n("Please enter the following fields with the information as you find them on your statement. Make sure to enter all values in <b>%1</b>.", currency.name()) + QString("</qt>"));

  // If the previous reconciliation was postponed,
  // we show a different first page
  value = account.value("lastReconciledBalance");
  if (value.isEmpty()) {
    // if the last statement has been entered long enough ago (more than one month),
    // then take the last statement date and add one month and use that as statement
    // date.
    QDate lastStatementDate = account.lastReconciliationDate();
    if (lastStatementDate.addMonths(1) < QDate::currentDate()) {
      setField("statementDate", lastStatementDate.addMonths(1));
    }

    slotUpdateBalances();

    d->m_pages.clearBit(Page_PreviousPostpone);
  } else {
    d->m_pages.clearBit(Page_CheckingStart);
    d->m_pages.clearBit(Page_InterestChargeCheckings);
    //removePage(m_interestChargeCheckings);
    // make sure, we show the correct start page
    setStartId(Page_PreviousPostpone);

    MyMoneyMoney factor(1, 1);
    if (d->m_account.accountGroup() == MyMoneyAccount::Liability)
      factor = -factor;

    startBalance = MyMoneyMoney(value) * factor;
    value = account.value("statementBalance");
    endBalance = MyMoneyMoney(value) * factor;

    //FIXME: port
    m_statementInfoPageCheckings->m_previousBalance->setValue(startBalance);
    m_statementInfoPageCheckings->m_endingBalance->setValue(endBalance);
  }

  // We don't need to add the default into the list (see ::help() why)
  // m_helpAnchor[m_startPageCheckings] = QString("");
  d->m_helpAnchor[m_interestChargeCheckings] = QString("details.reconcile.wizard.interest");
  d->m_helpAnchor[m_statementInfoPageCheckings] = QString("details.reconcile.wizard.statement");

  value = account.value("statementDate");
  if (!value.isEmpty())
    setField("statementDate", QDate::fromString(value, Qt::ISODate));

  //FIXME: port
  m_statementInfoPageCheckings->m_lastStatementDate->setText(QString());
  if (account.lastReconciliationDate().isValid()) {
    m_statementInfoPageCheckings->m_lastStatementDate->setText(i18n("Last reconciled statement: %1", QLocale().toString(account.lastReconciliationDate())));
  }

  // connect the signals with the slots
  connect(MyMoneyFile::instance(), SIGNAL(dataChanged()), this, SLOT(slotReloadEditWidgets()));
  connect(m_statementInfoPageCheckings->m_statementDate, SIGNAL(dateChanged(QDate)), this, SLOT(slotUpdateBalances()));
  connect(m_interestChargeCheckings->m_interestCategoryEdit, SIGNAL(createItem(QString,QString&)), this, SLOT(slotCreateInterestCategory(QString,QString&)));
  connect(m_interestChargeCheckings->m_chargesCategoryEdit, SIGNAL(createItem(QString,QString&)), this, SLOT(slotCreateChargesCategory(QString,QString&)));
  connect(m_interestChargeCheckings->m_payeeEdit, SIGNAL(createItem(QString,QString&)), this, SIGNAL(createPayee(QString,QString&)));

  KMyMoneyMVCCombo::setSubstringSearchForChildren(m_interestChargeCheckings, !KMyMoneySettings::stringMatchFromStart());

  slotReloadEditWidgets();

  // preset payee if possible
  try {
    // if we find a payee with the same name as the institution,
    // than this is what we use as payee.
    if (!d->m_account.institutionId().isEmpty()) {
      MyMoneyInstitution inst = MyMoneyFile::instance()->institution(d->m_account.institutionId());
      MyMoneyPayee payee = MyMoneyFile::instance()->payeeByName(inst.name());
      setField("payeeEdit", payee.id());
    }
  } catch (const MyMoneyException &) {
  }

  KMyMoneyUtils::updateWizardButtons(this);

  // setup different text and icon on finish button
  setButtonText(QWizard::FinishButton, KStandardGuiItem::cont().text());
  button(QWizard::FinishButton)->setIcon(KStandardGuiItem::cont().icon());
}
Exemplo n.º 12
0
Arquivo: common.hpp Projeto: rhl-/diy2
 RegularPartners(int dim, int nblocks, int k, bool contiguous = true):
   divisions_(dim, 0),
   contiguous_(contiguous)                       { Decomposer::fill_divisions(dim, nblocks, divisions_); factor(k, divisions_, kvs_); fill_steps(); }
Exemplo n.º 13
0
	Emitter *getElement(size_t i) {
		if (i != 0)
			return NULL;

		ref<Timer> timer = new Timer();
		Log(EDebug, "Rasterizing skylight emitter to an %ix%i environment map ..",
				m_resolution, m_resolution/2);
		ref<Bitmap> bitmap = new Bitmap(SKY_PIXELFORMAT, Bitmap::EFloat,
			Vector2i(m_resolution, m_resolution/2));

		Point2 factor((2*M_PI) / bitmap->getWidth(),
			M_PI / bitmap->getHeight());

		#if defined(MTS_OPENMP)
			#pragma omp parallel for
		#endif
		for (int y=0; y<bitmap->getHeight(); ++y) {
			Float theta = (y+.5f) * factor.y;
			Spectrum *target = (Spectrum *) bitmap->getFloatData()
				+ y * bitmap->getWidth();

			for (int x=0; x<bitmap->getWidth(); ++x) {
				Float phi = (x+.5f) * factor.x;

				*target++ = getSkyRadiance(SphericalCoordinates(theta, phi));
			}
		}

		Log(EDebug, "Done (took %i ms)", timer->getMilliseconds());

		#if defined(MTS_DEBUG_SUNSKY)
		/* Write a debug image for inspection */
		{
			int size = 513 /* odd-sized */, border = 2;
			int fsize = size+2*border, hsize = size/2;
			ref<Bitmap> debugBitmap = new Bitmap(Bitmap::ERGB, Bitmap::EFloat32, Vector2i(fsize));
			debugBitmap->clear();

			#if defined(MTS_OPENMP)
				#pragma omp parallel for
			#endif
			for (int y=0; y<size; ++y) {
				float *target = debugBitmap->getFloat32Data() + ((y + border) * fsize + border) * 3;

				for (int x=0; x<size; ++x) {
					Float xp = -(x - hsize) / (Float) hsize;
					Float yp = -(y - hsize) / (Float) hsize;

					Float radius = std::sqrt(xp*xp + yp*yp);

					Spectrum result(0.0f);
					if (radius < 1) {
						Float theta = radius * 0.5f * M_PI;
						Float phi = std::atan2(xp, yp);
						result = getSkyRadiance(SphericalCoordinates(theta, phi));
					}

					Float r, g, b;
					result.toLinearRGB(r, g, b);

					*target++ = (float) r;
					*target++ = (float) g;
					*target++ = (float) b;
				}
			}

			ref<FileStream> fs = new FileStream("sky.exr", FileStream::ETruncReadWrite);
			debugBitmap->write(Bitmap::EOpenEXR, fs);
		}
		#endif

		/* Instantiate a nested environment map plugin */
		Properties props("envmap");
		Properties::Data bitmapData;
		bitmapData.ptr = (uint8_t *) bitmap.get();
		bitmapData.size = sizeof(Bitmap);
		props.setData("bitmap", bitmapData);
		props.setAnimatedTransform("toWorld", m_worldTransform);
		props.setFloat("samplingWeight", m_samplingWeight);
		Emitter *emitter = static_cast<Emitter *>(
			PluginManager::getInstance()->createObject(
			MTS_CLASS(Emitter), props));
		emitter->configure();
		return emitter;
	}
Exemplo n.º 14
0
int main(){
factor(10,10);
}
Exemplo n.º 15
0
int main()
{

    const int cmx = 120000;
    long long sm = 0;

    std::vector<std::vector<int> > gcdtb;

    //    gcdtb.resize(cmx);
    //for(int i=0; i < cmx; ++i)
    //    gcdtb[i].resize(cmx);

    //for(int i = 0; i < cmx; i++)
    //{
    //    if(i%1000 == 0)
    //        std::cout << i << std::endl;
        
    //    for(int j = 0; j < cmx; j++)
    //    {
    //        gcdtb[i][j] = boost::math::gcd(i,j);
    //    }
    //}
        
    clock_t t1,t2;

    t1 = clock();

    std::vector<std::vector<int> > fcts;
    
    for(int i=0; i < cmx; ++i)
        fcts.push_back(factor(i));    

    for(int a=1; a < cmx-1; ++a)
    {
        if(a%100 == 0)
            std::cout << a << std::endl;

        for(int b=a+1;b<cmx-a;++b)
        {
            int c = a + b;
            if(boost::math::gcd(a,b)==1 && boost::math::gcd(a,c)==1 && boost::math::gcd(b,c)==1)
            {
                std::vector<int> fac1,fac2,fac3,fac;
                //fac1 = factor(a);
                //fac2 = factor(b);
                //fac3 = factor(c);
                fac1 = fcts[a];
                fac2 = fcts[b];
                fac3 = fcts[c];
                fac1.insert(fac1.end(),fac2.begin(),fac2.end());
                fac1.insert(fac1.end(),fac3.begin(),fac3.end());

                sort(fac1.begin(),fac1.end());
                fac1.erase(std::unique(fac1.begin(), fac1.end()), fac1.end());

                if(prod(fac1) < c)
                   sm += c;
                }
            }
    }

    t2 = clock();

    std::cout << sm << std::endl;

    float diff = ((float)t2-(float)t1);
    std::cout << "Time was: " << diff/CLOCKS_PER_SEC << std::endl;

    //int val = boost::math::gcd(6,15); 

    //std::cout << val << std::endl;

    //std::vector<int> tstvec;
    
    //int tstint = 4*4*5*5*6;
    //tstvec = factor(tstint);

    //sort(tstvec.begin(), tstvec.end());
    //tstvec.erase(unique(tstvec.begin(), tstvec.end()), tstvec.end());

    //    for(int i=0; i<tstvec.size();i++)
    //{
    //    std::cout << tstvec[i] << std::endl;
    // }

    //long long mxvl = 120000;
    //long long outvl = mxvl*mxvl*mxvl;

    //std::cout << mxvl*mxvl << std::endl;
    //std::cout << outvl << std::endl;

    return 0;
}
Exemplo n.º 16
0
int main(int argc, char** argv) {
  std::cout << "make the image denoising alchemy problem"
            << std::endl;

  std::string model_filename = "image";
  std::string drawing = "sunset";
  std::string corruption = "gaussian";
  std::string smoothing = "square";
  double lambda = 3;
  double sigma = 1;
  size_t rows = 200;
  size_t rings = 7;
  


  

  // Command line parsing
  graphlab::command_line_options clopts("Make the alchemy image", true);
  clopts.attach_option("model", 
                       &model_filename, model_filename,
                       "Alchemy formatted model file");
  clopts.attach_option("drawing", 
                       &drawing, drawing,
                       "drawing type");
  clopts.attach_option("corruption", 
                       &corruption, corruption,
                       "corruption type");
  clopts.attach_option("smoothing", 
                       &smoothing, smoothing,
                       "smoothing type");
  clopts.attach_option("lambda", 
                       &lambda, lambda,
                       "edge parameter");
  clopts.attach_option("sigma", 
                       &sigma, sigma,
                       "noise parameter");
  clopts.attach_option("rows", 
                       &rows, rows,
                       "number of rows and cols");
  clopts.attach_option("rings", 
                       &rings, rings,
                       "number of rings");

  if( !clopts.parse(argc, argv) ) { 
    std::cout << "Error parsing command line arguments!"
              << std::endl;
    return EXIT_FAILURE;
  }


  
  std::cout << "Creating a synethic image." << std::endl;
  image original(rows, rows);
  if(drawing == "sunset") 
    original.paint_sunset(rings);
  else if(drawing == "checkerboard")
    original.paint_checkerboard(rings);
  else {
    std::cout << "Invalid drawing type!" << std::endl;
    exit(1);
  }
  std::cout << "Saving original image. " << std::endl;
  original.save("original.pgm");    

    
  std::cout << "Corrupting Image. " << std::endl;
  image noisy = original;
  if(corruption == "gaussian") 
    noisy.gaussian_corrupt(sigma);
  else if(corruption == "flip")
    noisy.flip_corrupt(rings, 0.75);
  else if(corruption == "ising") 
    noisy = image(rows, rows);
  else {
    std::cout << "Invalid corruption type!" << std::endl;
    exit(1);
  }
  std::cout << "Saving corrupted image. " << std::endl;
  noisy.save("corrupted.pgm");
  

  // dummy variables 0 and 1 and num_rings by num_rings
  std::cout << "Creating edge factor" << std::endl;
  factor_t edge_factor(domain_t(variable_t(0, rings), variable_t(1, rings)));
  // Set the smoothing type
  if(smoothing == "square") {
    edge_factor.set_as_agreement(lambda);
  } else if (smoothing == "laplace") {
    edge_factor.set_as_laplace(lambda);
  } else  {
    std::cout << "Invalid smoothing stype!" << std::endl;
    assert(false);
  }
  std::cout << edge_factor << std::endl;
  
  std::cout << "Constructing factor graph." << std::endl;
  factorized_model model;
  // Add all the node factors
  double sigmaSq = sigma*sigma;
  for(size_t i = 0; i < noisy.rows(); ++i) {
    for(size_t j = 0; j < noisy.cols(); ++j) {
      // initialize the potential and belief
      uint32_t pixel_id = noisy.vertid(i, j);
      variable_t var(pixel_id, rings);
      factor_t factor(var);
      // Set the node potential
      double obs = noisy.pixel(i, j);
      if(corruption == "gaussian") {
        for(size_t pred = 0; pred < rings; ++pred) {
          factor.logP(pred) = 
            -(obs - pred)*(obs - pred) / (2.0 * sigmaSq);
        }
      } else if(corruption == "flip") {
        for(size_t pred = 0; pred < rings; ++pred) {
          factor.logP(pred) = obs == pred? 0 : -sigma;
        }
      } else if(corruption == "ising") {
        // Do nothing since we want a uniform node potential
        factor.uniform();
      } else {
        std::cout << "Invalid corruption!" << std::endl;
        exit(1);
      }
      factor.normalize();
      model.add_factor(factor);
    } // end of for j in cols
  } // end of for i in rows

  // Construct edge_factors  
  for(size_t i = 0; i < noisy.rows(); ++i) {
    for(size_t j = 0; j < noisy.cols(); ++j) {
      size_t source = noisy.vertid(i,j);
      variable_t source_var(source, rings);
      if(i+1 < noisy.rows()) {
        vertex_id_t target = noisy.vertid(i+1, j);
        variable_t target_var(target, rings);
        domain_t dom(source_var, target_var);
        edge_factor.set_args(dom);
        model.add_factor(edge_factor);
      }
      if(j+1 < noisy.cols()) {
        vertex_id_t target = noisy.vertid(i, j+1);
        variable_t target_var(target, rings);
        domain_t dom(source_var, target_var);
        edge_factor.set_args(dom);
        model.add_factor(edge_factor);
      }
    } // end of for j in cols
  } // end of for i in rows

  std::cout << "Saving model in alchemy format" << std::endl;
  model.save_alchemy(model_filename + ".alchemy");


  return EXIT_SUCCESS;
} // end of main
Exemplo n.º 17
0
 IExprNode* mul(const std::vector<Token>& tokens, int &curToken)
 {
     IExprNode *left = factor(tokens, curToken); 
     return rmul(tokens, curToken, left);
 }
Exemplo n.º 18
0
void *spooles_factor(long *row, long *col, double *data,
                    long neq, long nnz, int symmetryflag)
{
	InpMtx *mtxA;
    struct factorinfo *pfi_ = (struct factorinfo *)malloc(sizeof(struct factorinfo));
    
	//printf(" Factoring the system of equations using the symmetric spooles solver\n");
 
	if ((msgFile = fopen("spooles.out", "a")) == NULL) {
		fprintf(stderr, "\n fatal error in spooles.c"
			"\n unable to open file spooles.out\n");
	}

	/*
	 * Create the InpMtx object from the CalculiX matrix
	 *      representation
	 */
    mtxA = InpMtx_new();
    InpMtx_init(mtxA, INPMTX_BY_ROWS, SPOOLES_REAL, nnz, neq);
	
    long i;
    for(i = 0 ; i<nnz ; i++) {
        InpMtx_inputRealEntry(mtxA, row[i], col[i], data[i]);
    }
        
	/* solve it! */


#ifdef USE_MT
	/* Rules for parallel solve:
           a. determining the maximum number of cpus:
              - if NUMBER_OF_CPUS>0 this is taken as the number of
                cpus in the system
              - else it is taken from _SC_NPROCESSORS_CONF, if strictly
                positive
              - else 1 cpu is assumed (default)
           b. determining the number of cpus to use
              - if CCX_NPROC_EQUATION_SOLVER>0 then use
                CCX_NPROC_EQUATION_SOLVER cpus
              - else if CCX_NPROC>0 use CCX_NPROC cpus
              - else use the maximum number of cpus
	 */
	if (num_cpus < 0) {
	    int sys_cpus;
	    char *env,*envloc,*envsys;
	    
	    num_cpus = 0;
	    sys_cpus=0;
	    
	    /* explicit user declaration prevails */
	    
	    envsys=getenv("NUMBER_OF_CPUS");
	    if(envsys){
		sys_cpus=atoi(envsys);
		if(sys_cpus<0) sys_cpus=0;
	    }
	    
	    /* automatic detection of available number of processors */
	    
	    if(sys_cpus==0){
		sys_cpus = sysconf(_SC_NPROCESSORS_CONF);
		if(sys_cpus<1) sys_cpus=1;
	    }
	    
	    /* local declaration prevails, if strictly positive */
	    
	    envloc = getenv("CCX_NPROC_EQUATION_SOLVER");
	    if(envloc){
		num_cpus=atoi(envloc);
		if(num_cpus<0){
		    num_cpus=0;
		}else if(num_cpus>sys_cpus){
		    num_cpus=sys_cpus;
		}
	    }
	    
	    /* else global declaration, if any, applies */
	    
	    env = getenv("OMP_NUM_THREADS");
	    if(num_cpus==0){
		if (env)
		    num_cpus = atoi(env);
		if (num_cpus < 1) {
		    num_cpus=1;
		}else if(num_cpus>sys_cpus){
		    num_cpus=sys_cpus;
		}
	    }
	    
	}
	//printf(" Using up to %d cpu(s) for spooles.\n\n", num_cpus);
	if (num_cpus > 1) {
	    /* do not use the multithreaded solver unless
	     * we have multiple threads - avoid the
		 * locking overhead
		 */
		factor_MT(pfi_, mtxA, neq, msgFile,symmetryflag);
	} else {
		factor(pfi_, mtxA, neq, msgFile,symmetryflag);
	}
#else
	//printf(" Using 1 cpu for spooles.\n\n");
	factor(pfi_, mtxA, neq, msgFile,symmetryflag);
#endif

    return (void *)pfi_;
}
Exemplo n.º 19
0
static url
factor_sub (url u) {
  if (is_concat (u)) return u[1] * factor (u[2]);
  if (is_or (u)) return factor_sub (u[1]) | factor_sub (u[2]);
  return u;
}
Exemplo n.º 21
0
	Emitter *getElement(size_t i) {
		if (i != 0)
			return NULL;

		if (m_sunRadiusScale == 0) {
			Properties props("directional");
			const Transform &trafo = m_worldTransform->eval(0);
			props.setVector("direction", -trafo(m_sunDir));
			props.setFloat("samplingWeight", m_samplingWeight);

			props.setSpectrum("irradiance", m_radiance * m_solidAngle);

			Emitter *emitter = static_cast<Emitter *>(
				PluginManager::getInstance()->createObject(
				MTS_CLASS(Emitter), props));

			emitter->configure();
			return emitter;
		}

		/* Rasterizing the sphere to an environment map and checking the
		   individual pixels for coverage (which is what Mitsuba 0.3.0 did)
		   was slow and not very effective; for instance the power varied
		   dramatically with resolution changes. Since the sphere generally
		   just covers a few pixels, the code below rasterizes it much more
		   efficiently by generating a few thousand QMC samples.

		   Step 1: compute a *very* rough estimate of how many
		   pixel in the output environment map will be covered
		   by the sun */
		size_t pixelCount = m_resolution*m_resolution/2;
		Float cosTheta = std::cos(m_theta * m_sunRadiusScale);

		/* Ratio of the sphere that is covered by the sun */
		Float coveredPortion = 0.5f * (1 - cosTheta);

		/* Approx. number of samples that need to be generated,
		   be very conservative */
		size_t nSamples = (size_t) std::max((Float) 100,
			(pixelCount * coveredPortion * 1000));

		ref<Bitmap> bitmap = new Bitmap(SUN_PIXELFORMAT, Bitmap::EFloat,
			Vector2i(m_resolution, m_resolution/2));
		bitmap->clear();
		Frame frame(m_sunDir);

		Point2 factor(bitmap->getWidth() / (2*M_PI),
			bitmap->getHeight() / M_PI);

		Spectrum *target = (Spectrum *) bitmap->getFloatData();
		Spectrum value =
			m_radiance * (2 * M_PI * (1-std::cos(m_theta))) *
			static_cast<Float>(bitmap->getWidth() * bitmap->getHeight())
			/ (2 * M_PI * M_PI * nSamples);

		for (size_t i=0; i<nSamples; ++i) {
			Vector dir = frame.toWorld(
				Warp::squareToUniformCone(cosTheta, sample02(i)));

			Float sinTheta = math::safe_sqrt(1-dir.y*dir.y);
			SphericalCoordinates sphCoords = fromSphere(dir);

			Point2i pos(
				std::min(std::max(0, (int) (sphCoords.azimuth * factor.x)), bitmap->getWidth()-1),
				std::min(std::max(0, (int) (sphCoords.elevation * factor.y)), bitmap->getHeight()-1));

			target[pos.x + pos.y * bitmap->getWidth()] += value / std::max((Float) 1e-3f, sinTheta);
		}

		/* Instantiate a nested envmap plugin */
		Properties props("envmap");
		Properties::Data bitmapData;
		bitmapData.ptr = (uint8_t *) bitmap.get();
		bitmapData.size = sizeof(Bitmap);
		props.setData("bitmap", bitmapData);
		props.setAnimatedTransform("toWorld", m_worldTransform);
		props.setFloat("samplingWeight", m_samplingWeight);
		Emitter *emitter = static_cast<Emitter *>(
			PluginManager::getInstance()->createObject(
			MTS_CLASS(Emitter), props));
		emitter->configure();
		return emitter;
	}
Exemplo n.º 22
0
GraphAndValues Masseuse::LoadPoseGraphAndLCC(
    const string& pose_graph_file, bool read_lcc) {


  FILE *fp = (FILE *)fopen(pose_graph_file.c_str(), "rb");

  if (fp == NULL) {
    fprintf(stderr, "Could not open file %s\n",
            pose_graph_file.c_str());
  }


  if (fread(&origin, sizeof(Eigen::Vector6d), 1, fp) != 1) {
    throw invalid_argument("LoadPoseGraphAndLCC:  Cannot load the origin!");
  }

  //  std::cerr << "read origin: " << origin.transpose() << std::endl;

  unsigned numRelPoses = 0;
  unsigned numLCC = 0;

  if (fread(&numRelPoses, sizeof(unsigned), 1, fp) != 1) {
    printf("error! Cannot load num of relative poses.\n");
    throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
  }

  if(read_lcc){
    if (fread(&numLCC, sizeof(unsigned), 1, fp) != 1) {
      printf("error! Cannot load num of loop closure constraints.\n");
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
  }

  std::cerr << "Will load " << numRelPoses << " rel poses, "
            << numLCC << " loop closure constranits." << std::endl;

  relative_poses.clear();
  // save all rel poses
  for (unsigned i = 0; i != numRelPoses; i++) {
    RelPose rPos;
    if (fread(&rPos.ref_id, sizeof(unsigned), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
    if (fread(&rPos.live_id, sizeof(unsigned), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
    if (fread(&rPos.rel_pose, sizeof(Eigen::Vector6d), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
    if (fread(&rPos.cov, sizeof(Eigen::Matrix6d), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }

    relative_poses.push_back(rPos);
  }

  if(read_lcc){
    loop_closure_constraints.clear();
    // save all lcc here
    for (unsigned i = 0; i != numLCC; i++) {
      RelPose rPos;
      if (fread(&rPos.ref_id, sizeof(unsigned), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }
      if (fread(&rPos.live_id, sizeof(unsigned), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }
      if (fread(&rPos.rel_pose, sizeof(Eigen::Vector6d), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }
      if (fread(&rPos.cov, sizeof(Eigen::Matrix6d), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }

      loop_closure_constraints.push_back(rPos);
    }
  }
  fclose(fp);

  std::cerr << "Finished loading Pose Graph from  " << pose_graph_file
            << std::endl;

  std::shared_ptr<Values> initial(new Values);
  std::shared_ptr<Graph> graph(new Graph);
  Pose3 prev_pose;

  unsigned numICPfailed = 0;
  for (size_t ii = 0; ii < relative_poses.size(); ++ii){
    RelPose curr_pose = relative_poses[ii];
    if(ii == 0){
      // first relative pose, initialize graph at origin
      unsigned id = curr_pose.ref_id;
      Rot3 R(origin[3], origin[4], origin[5]);
      Point3 t = origin.head<3>();
      Pose3 orig(R, t);
      (*initial)[id] = orig;
      prev_pose = orig;

      //            std::cerr << "inserting origin: Rot: " << orig.rotationMatrix().eulerAngles
      //                         (0,1,2).transpose() << " Trans: " << orig.translation().transpose() <<
      //                         " at index:  " << id <<
      //                         std::endl;
    }

    // Build the next vertex using the relative contstraint
    Rot3 R(curr_pose.rel_pose[3], curr_pose.rel_pose[4],
        curr_pose.rel_pose[5]);
    Point3 t = curr_pose.rel_pose.head<3>();
    Pose3 rel(R, t);

    Pose3 new_pose = prev_pose*rel;
    (*initial)[curr_pose.live_id] = new_pose;

    //    std::cerr << "inserting pose: Rot: " << new_pose.rotationMatrix().eulerAngles
    //                 (0,1,2).transpose() << " Trans: " << new_pose.translation().transpose() <<
    //                 " at index:  " << curr_pose.live_id <<
    //                 std::endl;

    prev_pose = new_pose;

    // Also insert a factor for the binary pose constraint
    unsigned id1 = curr_pose.ref_id;
    unsigned id2 = curr_pose.live_id;

    Matrix m = curr_pose.cov;
    if(m.sum() == 0 || m.determinant() <= 0 || std::isnan(m.determinant())
       /*|| m.determinant() > options.cov_det_thresh*/){
      //      std::cerr << "ICP failed for rel pose between " << id1 << " and " << id2 <<
      //                   "Setting fixed covaraince..." <<
      //                   std::endl;
      Eigen::Vector6d cov_vec;
      // TODO: Improve handling of cases where the frame-to-frame ICP failed
      cov_vec << 7e-8, 7e-8, 7e-8, 8e-11, 8e-11, 8e-11;
      m = cov_vec.asDiagonal();
      numICPfailed++;
    }

    //        std::cerr <<  "Adding binary constraint between id: " << id1 << " and " <<
    //                      id2 << std::endl << "with cov: \n" << m << std::endl;

    // Create a new factor between poses
    if(options.use_identity_covariance){
      m.setIdentity();
    }

    m = m * options.rel_covariance_mult;

    Factor factor(id1, id2, rel, m);
    graph->push_back(factor);

  }

  std::cerr << std::setprecision(3) << std::fixed <<"ICP failed " << numICPfailed << " times " <<
               "out of " << relative_poses.size() << " ( " << (double)numICPfailed/(double)relative_poses.size() * 100 <<
               "% )" << std::endl;


  if( read_lcc ){
    std::cerr << "Reading LLC." << std::endl;

    int discarded_lcc = 0;
    for(size_t ii = 0; ii < loop_closure_constraints.size(); ++ii){
      RelPose curr_lcc = loop_closure_constraints[ii];
      unsigned id1 = curr_lcc.ref_id;
      unsigned id2 = curr_lcc.live_id;

      Rot3 R(curr_lcc.rel_pose[3], curr_lcc.rel_pose[4],
          curr_lcc.rel_pose[5]);
      Point3 t = curr_lcc.rel_pose.head<3>();
      Pose3 lcc(R, t);

      Matrix m = curr_lcc.cov;

      if(m.sum() == 0 ||
         m.determinant() > options.cov_det_thresh ||
         m.determinant() <= 0 ||
         std::isnan(m.determinant()))
      {
        // ICP failed or something went wrong for this loop closure, ignoring
        // The determinant of the cov. matrix may also be larger than the
        // specified threshold.
        discarded_lcc++;
        continue;
      }

      // check if the lcc is between far away poses. If so, downweight it's
      // covariance.

      //      const Pose3* lcc_0 = dynamic_cast<const Pose3*>(&initial->at(id1));
      //      const Pose3* lcc_1 = dynamic_cast<const Pose3*>(&initial->at(id2));

      //      Pose3 lcc_diff = lcc_0->compose(lcc).inverse().compose(*lcc_1);
      //            std::cerr << "distance between poses for lcc: " << ii <<
      //                         " between poses " <<  id1 << " and " << id2 << ": "
      //                      << lcc_diff.translation().norm() << std::endl;
      //      Pose3 diff = (*lcc_0).inverse().compose(*lcc_1);
      //      std::cerr << "distance between poses for lcc: " << ii <<
      //                   " between poses " <<  id1 << " and " << id2 << ": "
      //                << lcc.translation().norm() << std::endl;

      // Create a new factor between poses
      if(options.use_identity_covariance){
        m.setIdentity();
      }

      Factor lcc_factor(id1, id2, lcc, m);
      lcc_factor.isLCC = true;

      graph->push_back(lcc_factor);
      curr_lcc.ext_id = graph->size()-1;


      //      std::cerr << std::scientific <<
      //                   "Adding lcc between id: " << id1 << " and " <<
      //                    id2 << std::endl << "with cov: \n" << lcc_factor.cov << std::endl;

      //m_addedLCC[keyFromId(id2)] = curr_lcc;

      /*

      // If we already have a constraint between poses i and j, only use the one
      // with the highest degree of certainty (lowest cov. determinant)
      if(m_addedLCC.count(keyFromId(id2)) == 0){
        // LCC has not been added yet, just add
        graph->push_back(factor);
        curr_lcc.m_nExtId = graph->size()-1;
        m_addedLCC[keyFromId(id2)] = curr_lcc;
      }else{
        // Check if the covariance of the new lcc for poses i and j
        // is smaller than what we are currently using
        EstPose old_lcc = m_addedLCC[keyFromId(id2)];
        if(old_lcc.m_Cov.determinant() > curr_lcc.m_Cov.determinant()){
          // new det is smaller, replace
          curr_lcc.m_nExtId = old_lcc.m_nExtId;
          graph->replace(old_lcc.m_nExtId, factor);
          m_addedLCC[keyFromId(id2)] = curr_lcc;
//          std::cerr << "determinant for new lcc between " << id1 << " and " <<
//                       id2 << " is: " << curr_lcc.m_Cov.determinant() << " < "
//                    << old_lcc.m_Cov.determinant() << std::endl;

        }else{
          // Determinant for new constraint is larger, skip it
          continue;
        }

      }
      */

    }

    //    //ZZZZZZZZZZZZZ Temp, add wrong LCC to test switchable constraints
    //    unsigned id1 = 480;
    //    unsigned id2 = 870;
    //    Pose3& T2 = initial->at(id2);

    //    Pose3& T1 = initial->at(id1);

    //    Pose3 T12 = T1.inverse() * T2;


    //    // Add random values to the translation
    //    T12.translation()[0] += 5;
    //    T12.translation()[1] -= 2;
    //    T12.translation()[3] += 7;

    //    // Rotate the pose by an arbitrary amount
    //    Sophus::SO3d rot(0.5, 0.7, 0.1);

    //    T12.rotationMatrix() *= rot.matrix();
    //    Factor wrong_lcc(id1, id2, T12, Eigen::Matrix6d::Identity());
    //    wrong_lcc.isLCC = true;
    //    // now add the wrong LCC to the graph
    //    graph->push_back(wrong_lcc);


    std::cerr << std::setprecision(3) << std::fixed <<"Did not use " << discarded_lcc << " LCC " <<
                 "out of " << numLCC << " ( " << (double)discarded_lcc/(double)numLCC * 100 <<
                 "% )" << std::endl;

  }

  return make_pair(graph, initial);
}
void ATMSP<T>::factor(ATMSB<T> &bc) {

	/// Check available memory
	if ( numInd>=ATMSP_MAXNUM || valInd>=ATMSP_SIZE || opCnt>=ATMSP_SIZE ) longjmp(errJmp, memErr);

	/// Handle open parenthesis and unary operators first
	if ( *cp == '(' ) {
		++cp; expression(bc);
		if ( *cp++ != ')' ) longjmp(errJmp, parErr);
	}
	else if ( *cp == '+' ) {
		++cp; factor(bc);
	}
	else if ( *cp == '-' ) {
		++cp; factor(bc);
		bc.fun[opCnt++] = &ATMSB<T>::pchs;
	}

	/// Extract numbers starting with digit or dot
	else if ( isdigit(*cp) || *cp=='.' ) {
		char *end;
		bc.num[numInd] = (T)strtod(cp, &end);
		bc.val[valInd++] = &bc.num[numInd++];
		bc.fun[opCnt++] = &ATMSB<T>::ppush;
		cp = end;
	}

	/// Extract constants starting with $
	else if ( *cp == '$' ) {
		if ( !conLst.find(skipAlphaNum(), conInd) ) longjmp(errJmp, conErr);
		bc.con[conInd] = conLst[conInd].val;
		bc.val[valInd++] = &bc.con[conInd];
		bc.fun[opCnt++] = &ATMSB<T>::ppush;
	}

	/// Extract variables
	else if ( isVar(cp) ) {
		if ( varLst.find(skipAlphaNum(), varInd) ) varCnt++; else longjmp(errJmp, varErr);
		bc.val[valInd++] = &bc.var[varInd];
		bc.fun[opCnt++] = &ATMSB<T>::ppush;
	}

	/// Extract functions
	else {

		// Search function and advance cp behind open parenthesis
		if ( funLst.find(skipAlphaNum(), funInd) ) ++cp; else longjmp(errJmp, funErr);

		// Set operator function and advance cp
		switch ( funInd ) {
			case  0: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pabs;    break;
			case  1: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pcos;    break;
			case  2: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pcosh;   break;
			case  3: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pexp;    break;
			case  4: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::plog;    break;
			case  5: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::plog10;  break;
			case  6: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::plog2;   break;
			case  7: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::psin;    break;
			case  8: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::psinh;   break;
			case  9: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::psqrt;   break;
			case 10: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::ptan;    break;
			case 11: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::ptanh;   break;
			#if !defined(COMPLEX)
			case 12: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pasin;   break;
			case 13: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pacos;   break;
			case 14: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::patan;   break;
			case 15: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::patan2;  break;
			case 16: expression(bc); ++cp; expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pmax; break;
			case 17: expression(bc); ++cp; expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pmin; break;
			case 18: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::psig;    break;
			case 19: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pfloor;  break;
			case 20: expression(bc); bc.fun[opCnt++] = &ATMSB<T>::pround;  break;
			#endif
		}
		++cp;
	}

	/// At last handle univalent operators like ^ or % (not implemented here)
	if ( *cp == '^' ) {

		// Exponent a positive number? Try to optimize later
		bool optPow = isdigit( *++cp ) ? true : false;
		if ( *(cp+1) == '^' ) optPow = false;
		factor(bc);

		// Speed up bytecode for 2^2, x^3 ...
		if ( optPow ) {
			if ( *bc.val[valInd-1] == (T)2.0 ) {
				--valInd;
				bc.fun[opCnt-1] = &ATMSB<T>::ppow2;
			}
			else if ( *bc.val[valInd-1] == (T)3.0 ) {
				--valInd;
				bc.fun[opCnt-1] = &ATMSB<T>::ppow3;
			}
			else if ( *bc.val[valInd-1] == (T)4.0 ) {
				--valInd;
				bc.fun[opCnt-1] = &ATMSB<T>::ppow4;
			}
			// Exponent is a positive number, but not 2-4. Proceed with standard pow()
			else
				bc.fun[opCnt++] = &ATMSB<T>::ppow;
		}
		// Exponent is a not a number or negative. Proceed with standard pow()
		else
			bc.fun[opCnt++] = &ATMSB<T>::ppow;
	}

} // End of factor(bc)
Exemplo n.º 24
0
int main() {
	if(-1 == SDL_Init(SDL_INIT_VIDEO)) {
		std::cerr << "Unable to initialize SDL" << std::endl;
		return EXIT_FAILURE;
	}

	if(NULL == SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BPP, SDL_OPENGL)) {
		std::cerr << "Unable to open the window and get an OpenGL context" << std::endl;
		return EXIT_FAILURE;
	}

	SDL_WM_SetCaption("OpenGL4Imacs", NULL);

	GLenum glewCode = glewInit();
	if(GLEW_OK != glewCode) {
		std::cerr << "Unable to initialize GLEW : " << glewGetErrorString(glewCode) << std::endl;
		return EXIT_FAILURE;
	}

	//initialisation

	glimac::TrackballCamera trackballCamera;

	glimac::VBO vbo;
	vbo.bind();

	glimac::gcaVertex vertexs;

//////////////////*******demo/********///////////////////////////////////////////////////////////////////////////////////////
	std::vector<gca::K_blade> grassmann;
	gca::GCA_vector x(1, 0, 0, 1.0);
	gca::GCA_vector y;
	y << 0, 1, 0, 1.0;
	gca::GCA_vector z(0, 0, 1, 1.0);
	gca::GCA_vector o(0, 0, 0, 1.0);

	vertexs.getBlade(x^o, glm::vec3(1, 0, 0)); //le balde, puis la couleur
	vertexs.getBlade(y^o, glm::vec3(0, 1, 0));
	vertexs.getBlade(z^o, glm::vec3(0, 0, 1));

	plop();

	gca::GCA_vector a (3, 5, -1, 1.);
	gca::GCA_vector b(1.2, -2.7, -0.1, 1.);
	gca::GCA_vector c;
	c<< -4.1, 0.2, 2.8, 1.; 

	gca::GCA_scalar factor(3);

	a = factor^a;

	gca::GCA_bivector l = a ^ b;
	gca::GCA_antibivector antil = ~l;

	gca::GCA_trivector p = l^c;
	gca::GCA_trivector copyP(-p);
	gca::GCA_trivector otherPlan(1, 1, 1, 1);

	gca::GCA_bivector croisementPlan = ~p^~otherPlan;

	std::cout<<"point a :"<< a<<std::endl;
	std::cout<<"~a :"<< ~a<<std::endl;
	std::cout<<"point b :"<< b<<std::endl;
	std::cout<<"point c :"<< c<<std::endl;
	std::cout<<"droite l (a^b) "<< l<<std::endl;
	std::cout<<"antibivector de l"<< antil<<std::endl;
	std::cout<<"plan p (l^c)"<< p<<std::endl;
	std::cout<<"copyP = -p"<<copyP<<std::endl;
	std::cout<<"~copyP"<<~copyP<<std::endl;
	std::cout<<"otherPlan"<<otherPlan<<std::endl;
	std::cout<<"~p^~otherPlan"<<croisementPlan<<std::endl;
	std::cout<<"~(~p^~otherPlan)"<<~croisementPlan<<std::endl;

	vertexs.getBlade(a, glm::vec3(1, 0, 0));
	vertexs.getBlade(b, glm::vec3(1, 0, 0));
	vertexs.getBlade(c, glm::vec3(1, 0, 0));
	vertexs.getBlade(l, glm::vec3(1, 1, 0));
	vertexs.getBlade(p, glm::vec3(1, 1, 1));
	vertexs.getBlade(otherPlan, glm::vec3(0, 1, 1));
	vertexs.getBlade(~croisementPlan, glm::vec3(0.5, 0.5, 0.));


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	glBufferData(GL_ARRAY_BUFFER, vertexs.getVertexCount() * sizeof(glimac::ShapeVertex), vertexs.getDataPointer(), GL_STATIC_DRAW);
	
	glBindBuffer(GL_ARRAY_BUFFER, 0); //on debind le vbo

	glimac::VAO vao;
	vao.bind();
	vbo.bind();
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(	 0, // Index de l'attribut: 0 dans notre cas, l'index de la position
							 3, // Nombre de composantes de l'attribut: 2 car on à 2 float par position
							 GL_FLOAT, // Type des composantes de l'attribut: GL_FLOAT pour les float
							 GL_FALSE, // A mettre à GL_TRUE
							 sizeof(glimac::ShapeVertex), // nombre de float à parcourire depuis la position initiale pour atteintre les prochaine coordonnées (2 de position + 3 de couleurs=5)
							 (const GLvoid*) (0 * sizeof(GLfloat))); // A mettre à 0 ou NULL pour l'instant	
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(	 1, // Index de l'attribut: 0 dans notre cas, l'index de la position
							 3, // Nombre de composantes de l'attribut: 3 car on à 3 float par couleur
							 GL_FLOAT, // Type des composantes de l'attribut: GL_FLOAT pour les float
							 GL_FALSE, // la normailsation est faite par la carte graphique
							 sizeof(glimac::ShapeVertex), // nombre de float à parcourire depuis la position initiale pour atteintre les prochaine coordonnées (2 de position + 3 de couleurs=5)
							 (const GLvoid*) (3 * sizeof(GLfloat))); // Un sommet est stocké dans le VBO sous la forme x y r g b. Le décalage est donc de 2 flottants car il y x y juste avant la couleur. Il faut donc passer à la fonction la valeur (const GLvoid*) (2 * sizeof(GLfloat))	
	
	glBindBuffer(GL_ARRAY_BUFFER, 0); //on debind le vbo
	glBindVertexArray(0);			//on debind le vao


	//shader
	
	glimac::Program programShader = glimac::loadProgram( "../shader/3D.vs.glsl", "../shader/color3D.fs.glsl");
	
	programShader.use();

	GLint location1 = glGetUniformLocation(programShader.getGLId(), "uMVPMatrix");
	GLint location2 = glGetUniformLocation(programShader.getGLId(), "uMVMatrix");
	GLint location3 = glGetUniformLocation(programShader.getGLId(), "uNormalMatrix");

	glEnable(GL_DEPTH_TEST); //permet d'activer le test de profondeur du GPU.


	int sourisX, sourisY;
	bool done = false;
	while(!done) {
		Uint32 tStart = SDL_GetTicks();

		// Rendering code goes here

		glm::mat4 ProjMatrix = glm::perspective(70.f, (float)WINDOW_WIDTH/(float)WINDOW_HEIGHT, 0.1f, 100.f);
		glm::mat4 MVMatrix = glm::translate(glm::mat4(1.f), glm::vec3(0,0,-5));
		MVMatrix *= trackballCamera.getViewMatrix();
		glm::mat4 NormalMatrix = glm::transpose(glm::inverse(MVMatrix));



		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		vao.bind();

			glUniformMatrix4fv(location1, 1, 0, glm::value_ptr(ProjMatrix * MVMatrix /* RotateTerre*/));
			glUniformMatrix4fv(location2, 1, 0, glm::value_ptr(MVMatrix /* RotateTerre*/));
			glUniformMatrix4fv(location3, 1, 0, glm::value_ptr(NormalMatrix));

			glDrawArrays(GL_LINES, 0, vertexs.getVertexCount());
			

		glBindVertexArray(0);			//on debind le vao

		// Application code goes here

		SDL_Event e;
		while(SDL_PollEvent(&e)) {
			switch(e.type) {
				default:
				break;

				case SDL_MOUSEBUTTONDOWN:
					switch(e.button.button){
						case SDL_BUTTON_WHEELDOWN:
							trackballCamera.moveFront(-0.1);
						break;

						case SDL_BUTTON_WHEELUP:
							trackballCamera.moveFront(0.1);
						break;

						case SDL_BUTTON_RIGHT:
							sourisX = e.button.x;
							sourisY = e.button.y;
						break;
					}
				break;

				case SDL_QUIT:
					done = true;
				break;
			}
		}

		int x, y;
		if(SDL_GetMouseState(&x, &y) & SDL_BUTTON(3))
		{	
			trackballCamera.rotateLeft(y - sourisY);
			trackballCamera.rotateUp(x - sourisX);

			sourisX = x;
			sourisY = y;
		}

		

		// Mise à jour de la fenêtre (synchronisation implicite avec OpenGL)
		SDL_GL_SwapBuffers();

		Uint32 tEnd = SDL_GetTicks();
		Uint32 d = tEnd - tStart;
		if(d < FRAME_DURATION) {
			SDL_Delay(FRAME_DURATION - d);
		}
	}

	SDL_Quit();

	return EXIT_SUCCESS;
}
Exemplo n.º 25
0
int term2(big_int *a)
{
    int n;
    int result = 0;
    int sign = 0;

    while (1) {
        switch ((int) curr_lex.token) {
            case '+' :
                /* Unary plus. Just skip it. */
                match('+');
                continue;
            case '-' :
                /* Unary minus. Invert following operand */
                match('-');
                sign ^= 1;
                continue;
            default :
                /* just call factor() */
                if (factor(a)) {
                    result = 1;
                    goto done;
                }
                if (sign) {
                    /* invert the sign of number */
                    if (big_int_neg(a, a)) {
                        printf("error when inverting the sign of number [a]\n");
                        result = 2;
                        goto done;
                    }
                }
                if (curr_lex.token == '!') {
                    /* factorial */
                    match('!');
                    if (is_mod) {
                        /* modular arithmetic */
                        if (big_int_factmod(a, module, a)) {
                            printf("error in big_int_factmod()\n");
                            result = 3;
                            goto done;
                        }
                    } else {
                        /* ordinary arithmetic */
                        if (big_int_to_int(a, &n)) {
                            printf("error when converting number [a] to int [n]\n");
                            result = 4;
                            goto done;
                        }
                        if (big_int_fact(n, a)) {
                            printf("error in big_int_fact(%d)\n", n);
                            result = 5;
                            goto done;
                        }
                    }
                }
                goto done;
        }
    }

done:
    return result;
}
Exemplo n.º 26
0
struct fft_plan_3d *fft_3d_create_plan(
    MPI_Comm comm, int nfast, int nmid, int nslow,
    int in_ilo, int in_ihi, int in_jlo, int in_jhi,
    int in_klo, int in_khi,
    int out_ilo, int out_ihi, int out_jlo, int out_jhi,
    int out_klo, int out_khi,
    int scaled, int permute, int *nbuf)

{
    struct fft_plan_3d *plan;
    int me,nprocs;
    int i,num,flag,remapflag,fftflag;
    int first_ilo,first_ihi,first_jlo,first_jhi,first_klo,first_khi;
    int second_ilo,second_ihi,second_jlo,second_jhi,second_klo,second_khi;
    int third_ilo,third_ihi,third_jlo,third_jhi,third_klo,third_khi;
    int out_size,first_size,second_size,third_size,copy_size,scratch_size;
    int np1,np2,ip1,ip2;
    int list[50];

    /* system specific variables */

#ifdef FFT_INTEL
    FFT_DATA dummy;
#endif
#ifdef FFT_T3E
    FFT_DATA dummy[5];
    int isign,isys;
    double scalef;
#endif

    /* query MPI info */

    MPI_Comm_rank(comm,&me);
    MPI_Comm_size(comm,&nprocs);

    /* compute division of procs in 2 dimensions not on-processor */

    bifactor(nprocs,&np1,&np2);
    ip1 = me % np1;
    ip2 = me/np1;

    /* allocate memory for plan data struct */

    plan = (struct fft_plan_3d *) malloc(sizeof(struct fft_plan_3d));
    if (plan == NULL) return NULL;

    /* remap from initial distribution to layout needed for 1st set of 1d FFTs
       not needed if all procs own entire fast axis initially
       first indices = distribution after 1st set of FFTs */

    if (in_ilo == 0 && in_ihi == nfast-1)
        flag = 0;
    else
        flag = 1;

    MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);

    if (remapflag == 0) {
        first_ilo = in_ilo;
        first_ihi = in_ihi;
        first_jlo = in_jlo;
        first_jhi = in_jhi;
        first_klo = in_klo;
        first_khi = in_khi;
        plan->pre_plan = NULL;
    }
    else {
        first_ilo = 0;
        first_ihi = nfast - 1;
        first_jlo = ip1*nmid/np1;
        first_jhi = (ip1+1)*nmid/np1 - 1;
        first_klo = ip2*nslow/np2;
        first_khi = (ip2+1)*nslow/np2 - 1;
        plan->pre_plan =
            remap_3d_create_plan(comm,in_ilo,in_ihi,in_jlo,in_jhi,in_klo,in_khi,
                                 first_ilo,first_ihi,first_jlo,first_jhi,
                                 first_klo,first_khi,
                                 FFT_PRECISION,0,0,2);
        if (plan->pre_plan == NULL) return NULL;
    }

    /* 1d FFTs along fast axis */

    plan->length1 = nfast;
    plan->total1 = nfast * (first_jhi-first_jlo+1) * (first_khi-first_klo+1);

    /* remap from 1st to 2nd FFT
       choose which axis is split over np1 vs np2 to minimize communication
       second indices = distribution after 2nd set of FFTs */

    second_ilo = ip1*nfast/np1;
    second_ihi = (ip1+1)*nfast/np1 - 1;
    second_jlo = 0;
    second_jhi = nmid - 1;
    second_klo = ip2*nslow/np2;
    second_khi = (ip2+1)*nslow/np2 - 1;
    plan->mid1_plan =
        remap_3d_create_plan(comm,
                             first_ilo,first_ihi,first_jlo,first_jhi,
                             first_klo,first_khi,
                             second_ilo,second_ihi,second_jlo,second_jhi,
                             second_klo,second_khi,
                             FFT_PRECISION,1,0,2);
    if (plan->mid1_plan == NULL) return NULL;

    /* 1d FFTs along mid axis */

    plan->length2 = nmid;
    plan->total2 = (second_ihi-second_ilo+1) * nmid * (second_khi-second_klo+1);

    /* remap from 2nd to 3rd FFT
       if final distribution is permute=2 with all procs owning entire slow axis
         then this remapping goes directly to final distribution
       third indices = distribution after 3rd set of FFTs */

    if (permute == 2 && out_klo == 0 && out_khi == nslow-1)
        flag = 0;
    else
        flag = 1;

    MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);

    if (remapflag == 0) {
        third_ilo = out_ilo;
        third_ihi = out_ihi;
        third_jlo = out_jlo;
        third_jhi = out_jhi;
        third_klo = out_klo;
        third_khi = out_khi;
    }
    else {
        third_ilo = ip1*nfast/np1;
        third_ihi = (ip1+1)*nfast/np1 - 1;
        third_jlo = ip2*nmid/np2;
        third_jhi = (ip2+1)*nmid/np2 - 1;
        third_klo = 0;
        third_khi = nslow - 1;
    }

    plan->mid2_plan =
        remap_3d_create_plan(comm,
                             second_jlo,second_jhi,second_klo,second_khi,
                             second_ilo,second_ihi,
                             third_jlo,third_jhi,third_klo,third_khi,
                             third_ilo,third_ihi,
                             FFT_PRECISION,1,0,2);
    if (plan->mid2_plan == NULL) return NULL;

    /* 1d FFTs along slow axis */

    plan->length3 = nslow;
    plan->total3 = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) * nslow;

    /* remap from 3rd FFT to final distribution
       not needed if permute = 2 and third indices = out indices on all procs */

    if (permute == 2 &&
            out_ilo == third_ilo && out_ihi == third_ihi &&
            out_jlo == third_jlo && out_jhi == third_jhi &&
            out_klo == third_klo && out_khi == third_khi)
        flag = 0;
    else
        flag = 1;

    MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);

    if (remapflag == 0)
        plan->post_plan = NULL;
    else {
        plan->post_plan =
            remap_3d_create_plan(comm,
                                 third_klo,third_khi,third_ilo,third_ihi,
                                 third_jlo,third_jhi,
                                 out_klo,out_khi,out_ilo,out_ihi,
                                 out_jlo,out_jhi,
                                 FFT_PRECISION,(permute+1)%3,0,2);
        if (plan->post_plan == NULL) return NULL;
    }

    /* configure plan memory pointers and allocate work space
       out_size = amount of memory given to FFT by user
       first/second/third_size = amount of memory needed after pre,mid1,mid2 remaps
       copy_size = amount needed internally for extra copy of data
       scratch_size = amount needed internally for remap scratch space
       for each remap:
         use out space for result if big enough, else require copy buffer
         accumulate largest required remap scratch space */

    out_size = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) * (out_khi-out_klo+1);
    first_size = (first_ihi-first_ilo+1) * (first_jhi-first_jlo+1) *
                 (first_khi-first_klo+1);
    second_size = (second_ihi-second_ilo+1) * (second_jhi-second_jlo+1) *
                  (second_khi-second_klo+1);
    third_size = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) *
                 (third_khi-third_klo+1);

    copy_size = 0;
    scratch_size = 0;

    if (plan->pre_plan) {
        if (first_size <= out_size)
            plan->pre_target = 0;
        else {
            plan->pre_target = 1;
            copy_size = MAX(copy_size,first_size);
        }
        scratch_size = MAX(scratch_size,first_size);
    }

    if (plan->mid1_plan) {
        if (second_size <= out_size)
            plan->mid1_target = 0;
        else {
            plan->mid1_target = 1;
            copy_size = MAX(copy_size,second_size);
        }
        scratch_size = MAX(scratch_size,second_size);
    }

    if (plan->mid2_plan) {
        if (third_size <= out_size)
            plan->mid2_target = 0;
        else {
            plan->mid2_target = 1;
            copy_size = MAX(copy_size,third_size);
        }
        scratch_size = MAX(scratch_size,third_size);
    }

    if (plan->post_plan)
        scratch_size = MAX(scratch_size,out_size);

    *nbuf = copy_size + scratch_size;

    if (copy_size) {
        plan->copy = (FFT_DATA *) malloc(copy_size*sizeof(FFT_DATA));
        if (plan->copy == NULL) return NULL;
    }
    else plan->copy = NULL;

    if (scratch_size) {
        plan->scratch = (FFT_DATA *) malloc(scratch_size*sizeof(FFT_DATA));
        if (plan->scratch == NULL) return NULL;
    }
    else plan->scratch = NULL;

    /* system specific pre-computation of 1d FFT coeffs
       and scaling normalization */

#ifdef FFT_SGI

    plan->coeff1 = (FFT_DATA *) malloc((nfast+15)*sizeof(FFT_DATA));
    plan->coeff2 = (FFT_DATA *) malloc((nmid+15)*sizeof(FFT_DATA));
    plan->coeff3 = (FFT_DATA *) malloc((nslow+15)*sizeof(FFT_DATA));

    if (plan->coeff1 == NULL || plan->coeff2 == NULL ||
            plan->coeff3 == NULL) return NULL;

    FFT_1D_INIT(nfast,plan->coeff1);
    FFT_1D_INIT(nmid,plan->coeff2);
    FFT_1D_INIT(nslow,plan->coeff3);

    if (scaled == 0)
        plan->scaled = 0;
    else {
        plan->scaled = 1;
        plan->norm = 1.0/(nfast*nmid*nslow);
        plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
                        (out_khi-out_klo+1);
    }

#endif

#ifdef FFT_INTEL

    flag = 0;

    num = 0;
    factor(nfast,&num,list);
    for (i = 0; i < num; i++)
        if (list[i] != 2 && list[i] != 3 && list[i] != 5) flag = 1;
    num = 0;
    factor(nmid,&num,list);
    for (i = 0; i < num; i++)
        if (list[i] != 2 && list[i] != 3 && list[i] != 5) flag = 1;
    num = 0;
    factor(nslow,&num,list);
    for (i = 0; i < num; i++)
        if (list[i] != 2 && list[i] != 3 && list[i] != 5) flag = 1;

    MPI_Allreduce(&flag,&fftflag,1,MPI_INT,MPI_MAX,comm);
    if (fftflag) {
        if (me == 0) printf("ERROR: FFTs are not power of 2,3,5\n");
        return NULL;
    }

    plan->coeff1 = (FFT_DATA *) malloc((3*nfast/2+1)*sizeof(FFT_DATA));
    plan->coeff2 = (FFT_DATA *) malloc((3*nmid/2+1)*sizeof(FFT_DATA));
    plan->coeff3 = (FFT_DATA *) malloc((3*nslow/2+1)*sizeof(FFT_DATA));

    if (plan->coeff1 == NULL || plan->coeff2 == NULL ||
            plan->coeff3 == NULL) return NULL;

    flag = 0;
    FFT_1D_INIT(&dummy,&nfast,&flag,plan->coeff1);
    FFT_1D_INIT(&dummy,&nmid,&flag,plan->coeff2);
    FFT_1D_INIT(&dummy,&nslow,&flag,plan->coeff3);

    if (scaled == 0) {
        plan->scaled = 1;
        plan->norm = nfast*nmid*nslow;
        plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
                        (out_khi-out_klo+1);
    }
    else
        plan->scaled = 0;

#endif

#ifdef FFT_DEC

    if (scaled == 0) {
        plan->scaled = 1;
        plan->norm = nfast*nmid*nslow;
        plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
                        (out_khi-out_klo+1);
    }
    else
        plan->scaled = 0;

#endif

#ifdef FFT_T3E

    plan->coeff1 = (double *) malloc((12*nfast)*sizeof(double));
    plan->coeff2 = (double *) malloc((12*nmid)*sizeof(double));
    plan->coeff3 = (double *) malloc((12*nslow)*sizeof(double));

    if (plan->coeff1 == NULL || plan->coeff2 == NULL ||
            plan->coeff3 == NULL) return NULL;

    plan->work1 = (double *) malloc((8*nfast)*sizeof(double));
    plan->work2 = (double *) malloc((8*nmid)*sizeof(double));
    plan->work3 = (double *) malloc((8*nslow)*sizeof(double));

    if (plan->work1 == NULL || plan->work2 == NULL ||
            plan->work3 == NULL) return NULL;

    isign = 0;
    scalef = 1.0;
    isys = 0;

    FFT_1D_INIT(&isign,&nfast,&scalef,dummy,dummy,plan->coeff1,dummy,&isys);
    FFT_1D_INIT(&isign,&nmid,&scalef,dummy,dummy,plan->coeff2,dummy,&isys);
    FFT_1D_INIT(&isign,&nslow,&scalef,dummy,dummy,plan->coeff3,dummy,&isys);

    if (scaled == 0)
        plan->scaled = 0;
    else {
        plan->scaled = 1;
        plan->norm = 1.0/(nfast*nmid*nslow);
        plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
                        (out_khi-out_klo+1);
    }

#endif

#ifdef FFT_FFTW

    plan->plan_fast_forward =
        fftw_create_plan(nfast,FFTW_FORWARD,FFTW_ESTIMATE | FFTW_IN_PLACE);
    plan->plan_fast_backward =
        fftw_create_plan(nfast,FFTW_BACKWARD,FFTW_ESTIMATE | FFTW_IN_PLACE);

    if (nmid == nfast) {
        plan->plan_mid_forward = plan->plan_fast_forward;
        plan->plan_mid_backward = plan->plan_fast_backward;
    }
    else {
        plan->plan_mid_forward =
            fftw_create_plan(nmid,FFTW_FORWARD,FFTW_ESTIMATE | FFTW_IN_PLACE);
        plan->plan_mid_backward =
            fftw_create_plan(nmid,FFTW_BACKWARD,FFTW_ESTIMATE | FFTW_IN_PLACE);
    }

    if (nslow == nfast) {
        plan->plan_slow_forward = plan->plan_fast_forward;
        plan->plan_slow_backward = plan->plan_fast_backward;
    }
    else if (nslow == nmid) {
        plan->plan_slow_forward = plan->plan_mid_forward;
        plan->plan_slow_backward = plan->plan_mid_backward;
    }
    else {
        plan->plan_slow_forward =
            fftw_create_plan(nslow,FFTW_FORWARD,FFTW_ESTIMATE | FFTW_IN_PLACE);
        plan->plan_slow_backward =
            fftw_create_plan(nslow,FFTW_BACKWARD,FFTW_ESTIMATE | FFTW_IN_PLACE);
    }

    if (scaled == 0)
        plan->scaled = 0;
    else {
        plan->scaled = 1;
        plan->norm = 1.0/(nfast*nmid*nslow);
        plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
                        (out_khi-out_klo+1);
    }

#endif

    return plan;
}
Exemplo n.º 27
0
Arquivo: prover.c Projeto: ombt/ombt
// resolve two clauses, if possible.
int
resolveClauses(Array<BinaryTree_AVL<Clause> > &clausesArray, 
	Clause &cl1, Clause &cl2, int &clausesAdded, unsigned int currentDepth)
{
	// check if any of the clauses are empty
	statistics[ResolutionsAttempted] += 1;
	totalstatistics[TotalResolutionsAttempted] += 1;
	if (cl1.isEmpty() || cl2.isEmpty())
	{
		return(VALID);
	}

	// check if clauses can be resolved
	if (!cl1.getSOS() && !cl2.getSOS())
	{
		// one clause must be in the set-of-support
		return(NOMATCH);
	}
	if ((cl1.getType() == Clause::Negative && 
	     cl2.getType() == Clause::Negative) ||
	    (cl1.getType() == Clause::Positive && 
	     cl2.getType() == Clause::Positive))
	{
		// two positive clauses or two negative clauses
		// can not be resolved.
		return(NOMATCH);
	}

	// attempt to resolve two clauses. use A-ordering resolution,
	// try to resolve maximal literals.
	//
	Literal maxlit1;
	if (cl1.getMaximalLiteral(maxlit1) != OK)
	{
		ERROR("getMaximalLiteral failed.", errno);
		return(NOTOK);
	}
	Literal maxlit2;
	if (cl2.getMaximalLiteral(maxlit2) != OK)
	{
		ERROR("getMaximalLiteral failed.", errno);
		return(NOTOK);
	}
	if ((cl1.getTotalMembers() > maxliterals) ||
	    (cl2.getTotalMembers() > maxliterals))
	{
		statistics[MaximumLiteralsClausesRejected] += 1;
		totalstatistics[TotalMaximumLiteralsClausesRejected] += 1;
		return(NOMATCH);
	}
	if (maxlit1.unify_ne(~maxlit2))
	{
		return(NOMATCH);
	}

	// factor clauses
	Substitutions subs;
	if (factor(maxlit1, cl1, subs) == NOTOK)
	{
		ERROR("factor failed.", errno);
		return(NOTOK);
	}
	if (factor(maxlit2, cl2, subs) == NOTOK)
	{
		ERROR("factor failed.", errno);
		return(NOTOK);
	}

	// attempt to unify the clauses
	subs.clear();
	int status = unify(maxlit1, ~maxlit2, subs);
	switch (status)
	{
	case OK:
		if (verbose)
		{
			cout << endl;
			Literal ml1(maxlit1);
			cout << "max literal 1 (before subs): " << ml1 << endl;
			subs.applyTo(ml1);
			cout << "max literal 1 (after subs): " << ml1 << endl;
			Literal ml2(maxlit2);
			cout << "max literal 2 (before subs): " << ml2 << endl;
			subs.applyTo(ml2);
			cout << "max literal 2 (after subs): " << ml2 << endl;
			MustBeTrue(equal(ml1, ~ml2));
		}
		break;
	case NOMATCH:
		return(NOMATCH);
	default:
		ERROR("unify failed.", errno);
		return(status);
	}

	// can resolve, remove literals from clauses
	Clause newcl1(cl1);
	if (newcl1.remove(maxlit1) != OK)
	{
		ERROR("remove failed.", errno);
		return(NOTOK);
	}
	if (subs.applyTo(newcl1) != OK)
	{
		ERROR("applyTo failed.", errno);
		return(NOTOK);
	}
	Clause newcl2(cl2);
	if (newcl2.remove(maxlit2) != OK)
	{
		ERROR("remove failed.", errno);
		return(NOTOK);
	}
	if (subs.applyTo(newcl2) != OK)
	{
		ERROR("applyTo failed.", errno);
		return(NOTOK);
	}

	// store new clause and update flag
	Clause newcl = newcl1+newcl2;
	if (newcl.renameVariables() != OK)
	{
		ERROR("renameVariables failed.", errno);
		return(NOTOK);
	}
	newcl.setDepth(currentDepth+1);
	newcl.setNumber(nextClause++);
	if (clausesArray[currentDepth+1].insert(newcl) != OK)
	{
		ERROR("insert failed.", errno);
		return(NOTOK);
	}
	clausesAdded = 1;

	// indicate the clauses that were resolved
	statistics[ClausesGenerated] += 1;
	totalstatistics[TotalClausesGenerated] += 1;
	dumpnewclause(cl1, cl2, newcl);

	// check if we found an empty clause
	if (newcl.isEmpty())
	{
		return(VALID);
	}
	else
	{
		return(OK);
	}
}
Exemplo n.º 28
0
Arquivo: prime.c Projeto: pbos/optimus
int main()
{
	// generate B first primes
	sieve_gen(B, primes);

	first_cands = malloc(sizeof(mpz_t)*primes[B-1]);

	for(size_t i = 0; i < primes[B-1]; ++i)
		mpz_init(first_cands[i]);

	for(size_t i = 0; i < B; ++i)
		mpz_init(candidates[i]);

	for(int i = 0; i < B; ++i)
		fprintf(stderr, "%d, ", primes[i]);

	fputs("\n", stderr);

	// generate logarithms of them (used when sieving for number candidates)
	for(int i = 0; i < B; ++i)
	{
		log_primes[i] = log(primes[i]);
	//	fprintf(stderr, "log(%d) = %f\n", primes[i], log_primes[i]);
	}

	mpz_t num;
	mpz_init(num);

	mpz_init(q);

	for(size_t i = 0; i < MAX_BITS; ++i)
		mpz_init(factors[i]);

	while(1)
	{
		char buf[128];
		if(fgets(buf, sizeof(buf), stdin) == NULL)
			break;
		if(mpz_set_str(num, buf, 10) == -1)
			continue;

		mpz_out_str(stderr, 10, num);
		fputs(":\n", stderr);
		// All numbers less than or equal to 3 are already prime factored.
		// This handles the special cases for '1' and '0'.
		if(mpz_cmp_ui(num, 3) <= 0)
		{
			mpz_out_str(stdout, 10, num);
			putchar('\n');
			putchar('\n');
			continue;
		}

		num_factors = 0;
		fail = false;
		factor(num);
		if(fail)
		{
			num_factors = 0;
			puts("fail");
		}
		for(size_t i = 0; i < num_factors; ++i)
		{
			mpz_out_str(stdout, 10, factors[i]);
			putchar('\n');
		}
		putchar('\n');
	}

	for(size_t i = 0; i < MAX_BITS; ++i)
		mpz_clear(factors[i]);

	for(size_t i = 0; i < primes[B-1]; ++i)
		mpz_clear(first_cands[i]);

	for(size_t i = 0; i < B; ++i)
		mpz_clear(candidates[i]);

	mpz_clear(q);
	mpz_clear(num);

	return 0;
}
Exemplo n.º 29
0
void factor(int number, int n, int j) {

    int                i;

    /*****************************************************************************
    *                                                                            *
    *  1 is neither prime nor composite.                                         *
    *                                                                            *
    *****************************************************************************/

    if (n == 1) {

        printf("1 is a unit\n");
        return;

    }

    /*****************************************************************************
    *                                                                            *
    *  Determine the prime factors of n.                                         *
    *                                                                            *
    *****************************************************************************/

    i = j;

    while (i <= (int)(sqrt((double)n))) {

        if (n % i == 0) {

            /***********************************************************************
            *                                                                      *
            *  We have found a prime factor of n. Print it and factor n / i.       *
            *                                                                      *
            ***********************************************************************/

            fprintf(stdout, "%d\n", i);
            factor(number, (int)(n / i), i);
            return;

        }

        else {

            i++;

        }

    }

    /*****************************************************************************
    *                                                                            *
    *  If this point is reached, n is prime.                                     *
    *                                                                            *
    *****************************************************************************/

    if (n == number)
        printf("%d is prime\n", number);
    else
        printf("%d\n", n);

    return;

}
Exemplo n.º 30
0
void KInstitutionsView::loadSubAccounts(KMyMoneyAccountTreeItem* parent, const QString& institutionId)
{
  MyMoneyFile* file = MyMoneyFile::instance();

  QMap<QString, MyMoneyAccount>::const_iterator it_a;
  MyMoneyMoney  value;
  bool showClosedAccounts = kmymoney2->toggleAction("view_show_all_accounts")->isChecked()
      || !KMyMoneyGlobalSettings::hideClosedAccounts();

  for(it_a = m_accountMap.begin(); it_a != m_accountMap.end(); ++it_a) {
    const MyMoneyAccount& acc = *it_a;
    MyMoneyMoney factor(1,1);
    switch(acc.accountGroup()) {
      case MyMoneyAccount::Liability:
        factor = MyMoneyMoney(-1,1);
        // tricky fall through here

      case MyMoneyAccount::Asset:
        if(acc.institutionId() == institutionId
        && !acc.isInvest()
        && (!acc.isClosed() || showClosedAccounts)) {
          QValueList<MyMoneyPrice> prices;
          MyMoneySecurity security = file->baseCurrency();
          try {
            if(acc.currencyId() != file->baseCurrency().id()) {
              security = m_securityMap[acc.currencyId()];
              prices += file->price(acc.currencyId(), file->baseCurrency().id());
            }

          } catch(MyMoneyException *e) {
            kdDebug(2) << __PRETTY_FUNCTION__ << " caught exception while adding " << acc.name() << "[" << acc.id() << "]: " << e->what();
            delete e;
          }

          KMyMoneyAccountTreeItem* item = new KMyMoneyAccountTreeItem(parent, acc, prices, security);
          if(acc.id() == m_reconciliationAccount.id())
            item->setReconciliation(true);

          if(acc.accountType() == MyMoneyAccount::Investment)
            loadSubAccounts(item);
          value += (item->totalValue() * factor);
        }
        break;

      default:
        break;
    }
  }

  // the calulated value for the institution is not correct as
  // it does not take the negative sign for liability accounts
  // into account. So we correct this here with the value we
  // have calculated while filling the list
  parent->adjustTotalValue(-parent->totalValue());  // load a 0
  parent->adjustTotalValue(value);                  // now store the new value

  // we need to call slotUpdateNetWorth() here manually, because
  // KMyMoneyAccountTreeItem::adjustTotalValue() does not send out
  // the valueChanged() signal
  slotUpdateNetWorth();
}