/// Construct a rational object, given a numerator and a denominator
 /// Always reduce to normal form
 /// @param n numerator
 /// @param d denominator
 /// @pre denominator > 0
 rational(int n, int d) : numerator_{n}, denominator_{d} {
     reduce();
 }
Esempio n. 2
0
//----------------------------------------------------------------
QVariant AbifReader::fromDir(const AbifDir &dir)
{
    // Try to unserialize all data ! Not sure if all is working
    // Check specification from http://www6.appliedbiosystems.com/support/software_community/ABIF_File_Format.pdf

    //debugDir(dir);
    QByteArray part;


    if (dir.dataSize<=4){

        int val = dir.dataOffset;
        val = __bswap_32(val);
        char * data = (char*)&val;
        part.setRawData(data,dir.dataSize);

    }
    else {
        mDevice->seek(dir.dataOffset);
        part = mDevice->read(dir.dataSize);

    }

    QDataStream stream(part);
    stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
    stream.setByteOrder(QDataStream::BigEndian);



    //-----------------------------------------------
    if (Type(dir.elementType) == CString ) // 19
    {
        part.chop(1);
        return QString(part);
    }
    //-----------------------------------------------

    if (Type(dir.elementType) == PString ) // 18
    {
        part.remove(0,1);
        return QString(part);
    }

    //-----------------------------------------------

    if (Type(dir.elementType) == Word ) // 3
        return QString(part);
    //-----------------------------------------------

    if (Type(dir.elementType) == Char ) // 2
        return QString(part);
    //-----------------------------------------------

    if (Type(dir.elementType) == Short ) // 4
    {
        QVariantList list;
        qint16 v;

        if (dir.name == "Scal")
        {
            qDebug()<<dir.elementsize;
        }

        while (!stream.atEnd())
        {

            stream >> v;
            list.append(v);
        }

        return reduce(list);
    }
 void radix_shift(std::size_t n){
     numerator.radix_shift(n);
     reduce();
 }
Esempio n. 4
0
//private:
void fraction::copy(const fraction &other)
{
    num = other.num;
    denom = other.denom;
    reduce();
}
Esempio n. 5
0
//Mutator functions
void fraction::setNum(int n)
{
    num = n;
    reduce();
}
Esempio n. 6
0
/* returns intersection type of wall1 with wall2.  Returns intersection point
 * if FirstEndpoint, SecondEndpoint, or Middle is returned.  Return approximate
 * intersection point if Inexpressible.  Returned point is guaranteed to be
 * on wall1.
 */
IntersectionType BSPWallIntersection(WallData *wall1, WallData *wall2, int *x, int *y)
{
   int a,b,c;
   int x0,y0,x1,y1;
   int side0,side1;
   int num,denom;
   int dx,dy;
   
   /* first, get line equation from first wall */
   BSPGetLineEquationFromWall(wall1, &a, &b, &c);
   
   /* work with second wall */
   x0 = wall2->x0;
   y0 = wall2->y0;
   x1 = wall2->x1;
   y1 = wall2->y1;
   
   side0 = a*x0 + b*y0 + c;
   side1 = a*x1 + b*y1 + c;

   if (side0 == 0 && side1 == 0)
      return Coincide;
   if (side0 == 0)
   {
      *x = x0; *y = y0;
      return FirstEndpoint;
   }
   if (side1 == 0)
   {
      *x = x1; *y = y1;
      return SecondEndpoint;
   }

   if ((side0 > 0 && side1 > 0) || (side0 < 0 && side1 < 0))
      return NoIntersection;
   
   if (side0 > 0)
   {
      num = side0;
      denom = side0 - side1;
   }
   else
   {
      num = -side0;
      denom = side1 - side0;
   }
   reduce(&num, &denom);
   /* num/denom is between 0 and 1, exclusive */
   
   dx = x1 - x0;
   dy = y1 - y0;
   
   if (dx % denom != 0 || dy % denom != 0)
   {
      /* prevent overflow! */
      while(ABS(num) > 65536)
      {
	 num >>= 1;
	 denom >>= 1;
      }
      
      *x = x0 + num * dx / denom;
      *y = y0 + num * dy / denom;
      return Inexpressible;
   }
   
   *x = x0 + num * (dx / denom);
   *y = y0 + num * (dy / denom);
   return Middle;
}
Esempio n. 7
0
inline
void parallel_reduce( const size_t        work_count ,
                      const FunctorType & functor )
{
  Impl::ParallelReduce< FunctorType , size_t > reduce( functor , work_count );
}
Esempio n. 8
0
void drawbmp (char * filename) {

    unsigned int headers[13];
    FILE * outfile;
    int extrabytes;
    int paddedsize;
    int x;
    int y;
    int n;
    int red, green, blue;

    extrabytes = 4 - ((WIDTH * 3) % 4);                 // How many bytes of padding to add to each
    // horizontal line - the size of which must
    // be a multiple of 4 bytes.
    if (extrabytes == 4)
        extrabytes = 0;

    paddedsize = ((WIDTH * 3) + extrabytes) * HEIGHT;

// Headers...
// Note that the "BM" identifier in bytes 0 and 1 is NOT included in these "headers".

    headers[0]  = paddedsize + 54;      // bfSize (whole file size)
    headers[1]  = 0;                    // bfReserved (both)
    headers[2]  = 54;                   // bfOffbits
    headers[3]  = 40;                   // biSize
    headers[4]  = WIDTH;  // biWidth
    headers[5]  = HEIGHT; // biHeight

// Would have biPlanes and biBitCount in position 6, but they're shorts.
// It's easier to write them out separately (see below) than pretend
// they're a single int, especially with endian issues...

    headers[7]  = 0;                    // biCompression
    headers[8]  = paddedsize;           // biSizeImage
    headers[9]  = 0;                    // biXPelsPerMeter
    headers[10] = 0;                    // biYPelsPerMeter
    headers[11] = 0;                    // biClrUsed
    headers[12] = 0;                    // biClrImportant

    outfile = fopen(filename, "wb");

//
// Headers begin...
// When printing ints and shorts, we write out 1 character at a time to avoid endian issues.
//

    fprintf(outfile, "BM");

    for (n = 0; n <= 5; n++)
    {
        fprintf(outfile, "%c", headers[n] & 0x000000FF);
        fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
        fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
        fprintf(outfile, "%c", (headers[n] & (unsigned int) 0xFF000000) >> 24);
    }

// These next 4 characters are for the biPlanes and biBitCount fields.

    fprintf(outfile, "%c", 1);
    fprintf(outfile, "%c", 0);
    fprintf(outfile, "%c", 24);
    fprintf(outfile, "%c", 0);

    for (n = 7; n <= 12; n++)
    {
        fprintf(outfile, "%c", headers[n] & 0x000000FF);
        fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
        fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
        fprintf(outfile, "%c", (headers[n] & (unsigned int) 0xFF000000) >> 24);
    }

//
// Headers done, now write the data...
//

    for (y = HEIGHT - 1; y >= 0; y--)     // BMP image format is written from bottom to top...
    {
        for (x = 0; x <= WIDTH - 1; x++)
        {

            red = reduce(redcount[x][y] + COLOUR_OFFSET) * red_multiplier;
            green = reduce(greencount[x][y] + COLOUR_OFFSET) * green_multiplier;
            blue = reduce(bluecount[x][y] + COLOUR_OFFSET) * blue_multiplier;

            if (red > 255) red = 255;
            if (red < 0) red = 0;
            if (green > 255) green = 255;
            if (green < 0) green = 0;
            if (blue > 255) blue = 255;
            if (blue < 0) blue = 0;

            // Also, it's written in (b,g,r) format...

            fprintf(outfile, "%c", blue);
            fprintf(outfile, "%c", green);
            fprintf(outfile, "%c", red);
        }
        if (extrabytes)      // See above - BMP lines must be of lengths divisible by 4.
        {
            for (n = 1; n <= extrabytes; n++)
            {
                fprintf(outfile, "%c", 0);
            }
        }
    }

    fclose(outfile);
    return;
}
Esempio n. 9
0
    bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
    {
        std::vector<UMat> inputs;
        std::vector<UMat> outputs;
        std::vector<UMat> internals;

        inputs_.getUMatVector(inputs);
        outputs_.getUMatVector(outputs);
        internals_.getUMatVector(internals);

        CV_Assert(inputs.size() == 1 && outputs.size() == 1);
        CV_Assert(inputs[0].total() == outputs[0].total());

        const UMat& inp0 = inputs[0];
        UMat& buffer = internals[0];
        size_t num = inp0.size[0];
        size_t channels = inp0.size[1];
        size_t channelSize = inp0.total() / (num * channels);
        for (size_t i = 0; i < num; ++i)
        {
            MatShape s = shape(channels, channelSize);
            UMat src = inputs[i].reshape(1, s.size(), &s[0]);
            UMat dst = outputs[i].reshape(1, s.size(), &s[0]);

            UMat abs_mat;
            absdiff(src, cv::Scalar::all(0), abs_mat);
            pow(abs_mat, pnorm, buffer);

            if (acrossSpatial)
            {
                // add eps to avoid overflow
                float absSum = sum(buffer)[0] + epsilon;
                float norm = pow(absSum, 1.0f / pnorm);
                multiply(src, 1.0f / norm, dst);
            }
            else
            {
                Mat norm;
                reduce(buffer, norm, 0, REDUCE_SUM);
                norm += epsilon;

                // compute inverted norm to call multiply instead divide
                cv::pow(norm, -1.0f / pnorm, norm);

                repeat(norm, channels, 1, buffer);
                multiply(src, buffer, dst);
            }

            if (!blobs.empty())
            {
                // scale the output
                Mat scale = blobs[0];
                if (scale.total() == 1)
                {
                    // _scale: 1 x 1
                    multiply(dst, scale.at<float>(0, 0), dst);
                }
                else
                {
                    // _scale: _channels x 1
                    CV_Assert(scale.total() == channels);
                    repeat(scale, 1, dst.cols, buffer);
                    multiply(dst, buffer, dst);
                }
            }
        }
        return true;
    }
void Foam::accordionEngineMesh::checkAndCalculate()
{
    
    label pistonIndex = -1;
    bool foundPiston = false;

    label linerIndex = -1;
    bool foundLiner = false;

    label cylinderHeadIndex = -1;
    bool foundCylinderHead = false;
    
    
    forAll(boundary(), i)
    {
        if (boundary()[i].name() == piston().patchID().name())
        {
            pistonIndex = i;
            foundPiston = true;
        }
        else if (boundary()[i].name() == linerName_)
        {
            linerIndex = i;
            foundLiner = true;
        }
//        else if (boundary()[i].name() == "cylinderHead")
        else if (boundary()[i].name() == cylinderHeadName_)
        {
            cylinderHeadIndex = i;
            foundCylinderHead = true;
        }
    }
    
    reduce(foundPiston, orOp<bool>());
    reduce(foundLiner, orOp<bool>());
    reduce(foundCylinderHead, orOp<bool>());

    if (!foundPiston)
    {
        FatalErrorIn("Foam::accordionEngineMesh::checkAndCalculate()")
            << " : cannot find piston patch"
            << abort(FatalError);
    }

    if (!foundLiner)
    { 
        FatalErrorIn("Foam::accordionEngineMesh::checkAndCalculate()")
            << " : cannot find liner patch"
            << abort(FatalError);
    }

    if (!foundCylinderHead)
    { 
        FatalErrorIn("Foam::accordionEngineMesh::checkAndCalculate()")
            << " : cannot find cylinderHead patch"
            << exit(FatalError);
    }

    {
        if (linerIndex != -1)
        {
            pistonPosition() =
                max(boundary()[pistonIndex].patch().localPoints()).z();
        }
        reduce(pistonPosition(), minOp<scalar>());

        if (cylinderHeadIndex != -1)
        {
            deckHeight() = min
            (
                boundary()[cylinderHeadIndex].patch().localPoints()
            ).z();

 /*        
           deckHeight() = max
            (
                boundary()[linerIndex].patch().localPoints()
            ).z();
*/                        
        }
        reduce(deckHeight(), minOp<scalar>());

        Info<< "deckHeight: " << deckHeight() << nl
            << "piston position: " << pistonPosition() << endl;
    }
        
    
} 
Esempio n. 11
0
TEST(partition, partition_moves_the_state_through)
{
    auto v = std::vector<int> { 1, 2, 3, 4, 5 };
    auto spy = reduce(partition(2u)(first_rf), testing::copy_spy<> {}, v);
    EXPECT_EQ(spy.copied.count(), 0);
}
Esempio n. 12
0
void
mpz_powm (mpz_ptr r, mpz_srcptr b, mpz_srcptr e, mpz_srcptr m)
{
    mp_ptr xp, tp, qp, gp, this_gp;
    mp_srcptr bp, ep, mp;
    mp_size_t bn, es, en, mn, xn;
    mp_limb_t invm, c;
    mpir_ui enb;
    mp_size_t i, K, j, l, k;
    int m_zero_cnt, e_zero_cnt;
    int sh;
    int use_redc;
#if HANDLE_NEGATIVE_EXPONENT
    mpz_t new_b;
#endif
#if REDUCE_EXPONENT
    mpz_t new_e;
#endif
    TMP_DECL;

    mp = PTR(m);
    mn = ABSIZ (m);
    if (mn == 0)
        DIVIDE_BY_ZERO;

    TMP_MARK;

    es = SIZ (e);
    if (es <= 0)
    {
        if (es == 0)
        {
            /* Exponent is zero, result is 1 mod m, i.e., 1 or 0 depending on if
               m equals 1.  */
            SIZ(r) = (mn == 1 && mp[0] == 1) ? 0 : 1;
            PTR(r)[0] = 1;
            TMP_FREE;	/* we haven't really allocated anything here */
            return;
        }
#if HANDLE_NEGATIVE_EXPONENT
        MPZ_TMP_INIT (new_b, mn + 1);

        if (! mpz_invert (new_b, b, m))
            DIVIDE_BY_ZERO;
        b = new_b;
        es = -es;
#else
        DIVIDE_BY_ZERO;
#endif
    }
    en = es;

#if REDUCE_EXPONENT
    /* Reduce exponent by dividing it by phi(m) when m small.  */
    if (mn == 1 && mp[0] < 0x7fffffffL && en * GMP_NUMB_BITS > 150)
    {
        MPZ_TMP_INIT (new_e, 2);
        mpz_mod_ui (new_e, e, phi (mp[0]));
        e = new_e;
    }
#endif

    use_redc = mn < POWM_THRESHOLD && mp[0] % 2 != 0;
    if (use_redc)
    {
        /* invm = -1/m mod 2^BITS_PER_MP_LIMB, must have m odd */
        modlimb_invert (invm, mp[0]);
        invm = -invm;
    }
    else
    {
        /* Normalize m (i.e. make its most significant bit set) as required by
        division functions below.  */
        count_leading_zeros (m_zero_cnt, mp[mn - 1]);
        m_zero_cnt -= GMP_NAIL_BITS;
        if (m_zero_cnt != 0)
        {
            mp_ptr new_mp;
            new_mp = TMP_ALLOC_LIMBS (mn);
            mpn_lshift (new_mp, mp, mn, m_zero_cnt);
            mp = new_mp;
        }
    }

    /* Determine optimal value of k, the number of exponent bits we look at
       at a time.  */
    count_leading_zeros (e_zero_cnt, PTR(e)[en - 1]);
    e_zero_cnt -= GMP_NAIL_BITS;
    enb = en * GMP_NUMB_BITS - e_zero_cnt; /* number of bits of exponent */
    k = 1;
    K = 2;
    while (2 * enb > K * (2 + k * (3 + k)))
    {
        k++;
        K *= 2;
        if (k == 10)			/* cap allocation */
            break;
    }

    tp = TMP_ALLOC_LIMBS (2 * mn);
    qp = TMP_ALLOC_LIMBS (mn + 1);

    gp = __GMP_ALLOCATE_FUNC_LIMBS (K / 2 * mn);

    /* Compute x*R^n where R=2^BITS_PER_MP_LIMB.  */
    bn = ABSIZ (b);
    bp = PTR(b);
    /* Handle |b| >= m by computing b mod m.  FIXME: It is not strictly necessary
       for speed or correctness to do this when b and m have the same number of
       limbs, perhaps remove mpn_cmp call.  */
    if (bn > mn || (bn == mn && mpn_cmp (bp, mp, mn) >= 0))
    {
        /* Reduce possibly huge base while moving it to gp[0].  Use a function
        call to reduce, since we don't want the quotient allocation to
         live until function return.  */
        if (use_redc)
        {
            reduce (tp + mn, bp, bn, mp, mn);	/* b mod m */
            MPN_ZERO (tp, mn);
            mpn_tdiv_qr (qp, gp, 0L, tp, 2 * mn, mp, mn); /* unnormnalized! */
        }
        else
        {
            reduce (gp, bp, bn, mp, mn);
        }
    }
    else
    {
        /* |b| < m.  We pad out operands to become mn limbs,  which simplifies
        the rest of the function, but slows things down when the |b| << m.  */
        if (use_redc)
        {
            MPN_ZERO (tp, mn);
            MPN_COPY (tp + mn, bp, bn);
            MPN_ZERO (tp + mn + bn, mn - bn);
            mpn_tdiv_qr (qp, gp, 0L, tp, 2 * mn, mp, mn);
        }
        else
        {
            MPN_COPY (gp, bp, bn);
            MPN_ZERO (gp + bn, mn - bn);
        }
    }

    /* Compute xx^i for odd g < 2^i.  */

    xp = TMP_ALLOC_LIMBS (mn);
    mpn_sqr (tp, gp, mn);
    if (use_redc)
        mpn_redc_1 (xp, tp, mp, mn, invm);		/* xx = x^2*R^n */
    else
        mpn_tdiv_qr (qp, xp, 0L, tp, 2 * mn, mp, mn);
    this_gp = gp;
    for (i = 1; i < K / 2; i++)
    {
        mpn_mul_n (tp, this_gp, xp, mn);
        this_gp += mn;
        if (use_redc)
            mpn_redc_1 (this_gp,tp, mp, mn, invm);	/* g[i] = x^(2i+1)*R^n */
        else
            mpn_tdiv_qr (qp, this_gp, 0L, tp, 2 * mn, mp, mn);
    }

    /* Start the real stuff.  */
    ep = PTR (e);
    i = en - 1;				/* current index */
    c = ep[i];				/* current limb */
    sh = GMP_NUMB_BITS - e_zero_cnt;	/* significant bits in ep[i] */
    sh -= k;				/* index of lower bit of ep[i] to take into account */
    if (sh < 0)
    {   /* k-sh extra bits are needed */
        if (i > 0)
        {
            i--;
            c <<= (-sh);
            sh += GMP_NUMB_BITS;
            c |= ep[i] >> sh;
        }
    }
Esempio n. 13
0
 /// Assign a numerator and a denominator, then reduce to normal form
 /// @param n numerator
 /// @param d denominator
 /// @pre denominator > 0
 void assign(int n, int d) {
     numerator_ = n;
     denominator_ = d;
     reduce();
 }
Esempio n. 14
0
 rational(double r) : rational{static_cast<int>(r * 10000), 10000} {
     reduce();
 }
Esempio n. 15
0
    node *parse (const rules_char_type *start_,
        const rules_char_type * const end_, const id_type id_,
        const id_type user_id_, const id_type next_dfa_,
        const id_type push_dfa_, const bool pop_dfa_,
        const std::size_t flags_, id_type &eol_id_, const bool seen_bol_,
        const bool macro_)
    {
        node *root_ = 0;
        state re_state_ (start_, end_, flags_, _locale, macro_);
        token *lhs_token_ = 0;
        std::auto_ptr<token> rhs_token_ (new token);
        char action_ = 0;

        _token_stack->push (static_cast<token *>(0));
        _token_stack->top () = rhs_token_.release ();
        rhs_token_.reset (new token);
        tokeniser::next (re_state_, rhs_token_.get ());

        do
        {
            lhs_token_ = _token_stack->top ();
            action_ = lhs_token_->precedence (rhs_token_->_type);

            switch (action_)
            {
            case '<':
            case '=':
                _token_stack->push (static_cast<token *>(0));
                _token_stack->top () = rhs_token_.release ();
                rhs_token_.reset (new token);
                tokeniser::next (re_state_, rhs_token_.get ());
                break;
            case '>':
                reduce (re_state_);
                break;
            default:
                std::ostringstream ss_;

                ss_ << "A syntax error occurred: '" <<
                    lhs_token_->precedence_string () <<
                    "' against '" << rhs_token_->precedence_string () <<
                    "' at index " << re_state_.index () << ".";
                throw runtime_error (ss_.str ().c_str ());
                break;
            }
        } while (!_token_stack->empty ());

        if (_tree_node_stack.empty ())
        {
            throw runtime_error ("Empty rules are not allowed.");
        }

        assert (_tree_node_stack.size () == 1);

        node *lhs_node_ = _tree_node_stack.top ();

        _tree_node_stack.pop ();

        if (macro_)
        {
            // Macros have no end state...
            root_ = lhs_node_;
        }
        else
        {
            _node_ptr_vector->push_back (static_cast<end_node *>(0));

            node *rhs_node_ = new end_node (id_, user_id_, next_dfa_,
                push_dfa_, pop_dfa_);

            _node_ptr_vector->back () = rhs_node_;
            _node_ptr_vector->push_back (static_cast<sequence_node *>(0));
            _node_ptr_vector->back () = new sequence_node
                (lhs_node_, rhs_node_);
            root_ = _node_ptr_vector->back ();
        }

        if (seen_bol_)
        {
            fixup_bol (root_);
        }

        if (re_state_._eol_id != static_cast<id_type>(~0))
        {
            eol_id_ = re_state_._eol_id;
        }

        if ((flags_ & match_zero_len) == 0)
        {
            const typename node::node_vector &firstpos_ = root_->firstpos();
            typename node::node_vector::const_iterator iter_ =
                firstpos_.begin ();
            typename node::node_vector::const_iterator end_ =
                firstpos_.end ();

            for (; iter_ != end_; ++iter_)
            {
                const node *node_ = *iter_;

                if (node_->end_state ())
                {
                    throw runtime_error ("Rules that match zero characters "
                        "are not allowed as this can cause an infinite loop "
                        "in user code. The match_zero_len flag overrides this "
                        "check.");
                }
            }
        }

        return root_;
    }
int Parse(const char *strExpr, double *dblRet)
{
	int ret = 1;	
	ParserData md;
					
	int8_t parseTable[9][9] =
	{
		/*            -------------- input ------------- */
		/*            +   -   *   /   UM  ^   (   )   $  */
		/*            --  --  --  --  --  --  --  --  -- */
		/* stack */
		/* ----- */		
		/*   +   */ { R,  R,  S,  S,  S,  S,  S,  R,  R },
		/*   -   */ { R,  R,  S,  S,  S,  S,  S,  R,  R },
		/*   *   */ { R,  R,  R,  R,  S,  S,  S,  R,  R },
		/*   /   */ { R,  R,  R,  R,  S,  S,  S,  R,  R },
		/*   UM  */ { R,  R,  R,  R,  S,  S,  S,  R,  R },
		/*   ^   */ { R,  R,  R,  R,  R,  S,  S,  R,  R },
		/*   (   */ { S,  S,  S,  S,  S,  S,  S,  R,  E1},
		/*   )   */ { R,  R,  R,  R,  R,  R,  E2, R,  R },
		/*   $   */ { S,  S,  S,  S,  S,  S,  S,  E3, A }
	};		
	
	*dblRet = 0;

	strcpy(md.m_strExpr, strExpr);
	
	md.m_top = -1;
	md.m_value = 0;	
	md.m_topOpr = 0;
	md.m_stackOpr[0] = T_EOL;
	/* printf("SHIFT $\n"); */

	initToken(&(md.m_Token));
	GetNextToken(md.m_strExpr, &(md.m_Token));
	if ( md.m_Token.Type == T_EOL )
	{
		return 1;
	}

	while ( 1 )
	{		
		switch ( md.m_Token.Type )
		{
			case T_UNKNOWN:
				printf("Error 0: invalid token: %s\n", md.m_Token.str);
				return 0;			
			case T_NUMBER:
				md.m_stack[++md.m_top] = md.m_Token.Value;
				/* printf("PUSH %s\n", md.m_Token.str); */
				GetNextToken(md.m_strExpr, &(md.m_Token));
				break;
			case T_UPLUS:
				GetNextToken(md.m_strExpr, &(md.m_Token));			
				break;
			default:
				switch ( parseTable[md.m_stackOpr[md.m_topOpr]][md.m_Token.Type] )
				{
					case S:
						if ( !shift(&md) )
							return 0;
						break;
					case R:
						if ( !reduce(&md) )
							return 0;
						break;
					case A:
						if ( md.m_top != 0 )
						{
							printf("Error 10: missing operator.\n");
							return 0;
						}
						if ( md.m_topOpr != 0 )
						{
							printf("Error 11: missing operand.\n");
							return 0;
						}						
						md.m_value = md.m_stack[(md.m_top)--];
						*dblRet = md.m_value;
						/* printf("ACCEPT: %g\n", *dblRet); */
						return 1;
					case E1:
						printf("Error 1: missing right parenthesis\n");
						return 0;
					case E2:
						printf("Error 2: missing operator\n");
						return 0;					
					case E3:
						printf("Error 3: unbalanced parenthesis\n");
						return 0;						
				}
				break;
		}		
	}

	return ret;
}
Esempio n. 17
0
Foam::functionEntries::codeStream::streamingFunctionType
Foam::functionEntries::codeStream::getFunction
(
    const dictionary& parentDict,
    const dictionary& codeDict
)
{
    // get code, codeInclude, codeOptions
    dynamicCodeContext context(codeDict);

    // codeName: codeStream + _<sha1>
    // codeDir : _<sha1>
    std::string sha1Str(context.sha1().str(true));
    dynamicCode dynCode("codeStream" + sha1Str, sha1Str);

    // Load library if not already loaded
    // Version information is encoded in the libPath (encoded with the SHA1)
    const fileName libPath = dynCode.libPath();

    // see if library is loaded
    void* lib = NULL;
    if (isA<IOdictionary>(topDict(parentDict)))
    {
        lib = libs(parentDict).findLibrary(libPath);
    }

    if (!lib)
    {
        Info<< "Using #codeStream with " << libPath << endl;
    }


    // nothing loaded
    // avoid compilation if possible by loading an existing library
    if (!lib)
    {
        if (isA<IOdictionary>(topDict(parentDict)))
        {
            // Cached access to dl libs. Guarantees clean up upon destruction
            // of Time.
            dlLibraryTable& dlLibs = libs(parentDict);
            if (dlLibs.open(libPath, false))
            {
                lib = dlLibs.findLibrary(libPath);
            }
        }
        else
        {
            // Uncached opening of libPath. Do not complain if cannot be loaded
            lib = dlOpen(libPath, false);
        }
    }


    // create library if required
    if (!lib)
    {
        bool create =
            Pstream::master()
         || (regIOobject::fileModificationSkew <= 0);   // not NFS

        if (create)
        {
            if (!dynCode.upToDate(context))
            {
                // filter with this context
                dynCode.reset(context);

                // compile filtered C template
                dynCode.addCompileFile(codeTemplateC);

                // define Make/options
                dynCode.setMakeOptions
                (
                    "EXE_INC = -g \\\n"
                  + context.options()
                  + "\n\nLIB_LIBS = \\\n"
                  + "    -lOpenFOAM \\\n"
                  + context.libs()
                );

                if (!dynCode.copyOrCreateFiles(true))
                {
                    FatalIOErrorIn
                    (
                        "functionEntries::codeStream::execute(..)",
                        parentDict
                    )   << "Failed writing files for" << nl
                        << dynCode.libRelPath() << nl
                        << exit(FatalIOError);
                }
            }

            if (!dynCode.wmakeLibso())
            {
                FatalIOErrorIn
                (
                    "functionEntries::codeStream::execute(..)",
                    parentDict
                )   << "Failed wmake " << dynCode.libRelPath() << nl
                    << exit(FatalIOError);
            }
        }

        //- Only block if we're not doing master-only reading. (flag set by
        //  regIOobject::read, IOdictionary constructor)
        if
        (
           !regIOobject::masterOnlyReading
         && regIOobject::fileModificationSkew > 0
        )
        {
            //- Since the library has only been compiled on the master the
            //  other nodes need to pick this library up through NFS
            //  We do this by just polling a few times using the
            //  fileModificationSkew.

            off_t mySize = Foam::fileSize(libPath);
            off_t masterSize = mySize;
            Pstream::scatter(masterSize);

            if (debug)
            {
                Pout<< endl<< "on processor " << Pstream::myProcNo()
                    << " have masterSize:" << masterSize
                    << " and localSize:" << mySize
                    << endl;
            }


            if (mySize < masterSize)
            {
                if (debug)
                {
                    Pout<< "Local file " << libPath
                        << " not of same size (" << mySize
                        << ") as master ("
                        << masterSize << "). Waiting for "
                        << regIOobject::fileModificationSkew
                        << " seconds." << endl;
                }
                Foam::sleep(regIOobject::fileModificationSkew);

                // Recheck local size
                mySize = Foam::fileSize(libPath);

                if (mySize < masterSize)
                {
                    FatalIOErrorIn
                    (
                        "functionEntries::codeStream::execute(..)",
                        parentDict
                    )   << "Cannot read (NFS mounted) library " << nl
                        << libPath << nl
                        << "on processor " << Pstream::myProcNo()
                        << " detected size " << mySize
                        << " whereas master size is " << masterSize
                        << " bytes." << nl
                        << "If your case is not NFS mounted"
                        << " (so distributed) set fileModificationSkew"
                        << " to 0"
                        << exit(FatalIOError);
                }
            }

            if (debug)
            {
                Pout<< endl<< "on processor " << Pstream::myProcNo()
                    << " after waiting: have masterSize:" << masterSize
                    << " and localSize:" << mySize
                    << endl;
            }
        }

        if (isA<IOdictionary>(topDict(parentDict)))
        {
            // Cached access to dl libs. Guarantees clean up upon destruction
            // of Time.
            dlLibraryTable& dlLibs = libs(parentDict);

            if (debug)
            {
                Pout<< "Opening cached dictionary:" << libPath << endl;
            }

            if (!dlLibs.open(libPath, false))
            {
                FatalIOErrorIn
                (
                    "functionEntries::codeStream::execute(..)",
                    parentDict
                )   << "Failed loading library " << libPath << nl
                    << "Did you add all libraries to the 'libs' entry"
                    << " in system/controlDict?"
                    << exit(FatalIOError);
            }

            lib = dlLibs.findLibrary(libPath);
        }
        else
        {
            // Uncached opening of libPath
            if (debug)
            {
                Pout<< "Opening uncached dictionary:" << libPath << endl;
            }
            lib = dlOpen(libPath, true);
        }
    }

    bool haveLib = lib;
    reduce(haveLib, andOp<bool>());

    if (!haveLib)
    {
        FatalIOErrorIn
        (
            "functionEntries::codeStream::execute(..)",
            parentDict
        )   << "Failed loading library " << libPath
            << " on some processors."
            << exit(FatalIOError);
    }


    // Find the function handle in the library
    streamingFunctionType function =
        reinterpret_cast<streamingFunctionType>
        (
            dlSym(lib, dynCode.codeName())
        );


    if (!function)
    {
        FatalIOErrorIn
        (
            "functionEntries::codeStream::execute(..)",
            parentDict
        )   << "Failed looking up symbol " << dynCode.codeName()
            << " in library " << lib << exit(FatalIOError);
    }

    return function;
}
Esempio n. 18
0
static VALUE seconds_to_offset(long seconds_offset) {
  do_int64 num = seconds_offset, den = 86400;
  reduce(&num, &den);
  return rb_funcall(rb_cRational, rb_intern("new!"), 2, rb_ll2inum(num), rb_ll2inum(den));
}
Esempio n. 19
0
void
parse(int tk) /* tk: the code for the construct scanned */
{
    int         i;

#ifdef debug
    printf("%2d - %s\n", tk, token);
#endif

    while (ps.p_stack[ps.tos] == ifhead && tk != elselit) {
	/* true if we have an if without an else */
	ps.p_stack[ps.tos] = stmt;	/* apply the if(..) stmt ::= stmt
					 * reduction */
	reduce();		/* see if this allows any reduction */
    }


    switch (tk) {		/* go on and figure out what to do with the
				 * input */

    case decl:			/* scanned a declaration word */
	ps.search_brace = btype_2;
	/* indicate that following brace should be on same line */
	if (ps.p_stack[ps.tos] != decl) {	/* only put one declaration
						 * onto stack */
	    break_comma = true;	/* while in declaration, newline should be
				 * forced after comma */
	    ps.p_stack[++ps.tos] = decl;
	    ps.il[ps.tos] = ps.i_l_follow;

	    if (ps.ljust_decl) {/* only do if we want left justified
				 * declarations */
		ps.ind_level = 0;
		for (i = ps.tos - 1; i > 0; --i)
		    if (ps.p_stack[i] == decl)
			++ps.ind_level;	/* indentation is number of
					 * declaration levels deep we are */
		ps.i_l_follow = ps.ind_level;
	    }
	}
	break;

    case ifstmt:		/* scanned if (...) */
	if (ps.p_stack[ps.tos] == elsehead && ps.else_if)	/* "else if ..." */
	    ps.i_l_follow = ps.il[ps.tos];
    case dolit:		/* 'do' */
    case forstmt:		/* for (...) */
	ps.p_stack[++ps.tos] = tk;
	ps.il[ps.tos] = ps.ind_level = ps.i_l_follow;
	++ps.i_l_follow;	/* subsequent statements should be indented 1 */
	ps.search_brace = btype_2;
	break;

    case lbrace:		/* scanned { */
	break_comma = false;	/* don't break comma in an initial list */
	if (ps.p_stack[ps.tos] == stmt || ps.p_stack[ps.tos] == decl
		|| ps.p_stack[ps.tos] == stmtl)
	    ++ps.i_l_follow;	/* it is a random, isolated stmt group or a
				 * declaration */
	else {
	    if (s_code == e_code) {
		/*
		 * only do this if there is nothing on the line
		 */
		--ps.ind_level;
		/*
		 * it is a group as part of a while, for, etc.
		 */
		if (ps.p_stack[ps.tos] == swstmt && ps.case_indent >= 1)
		    --ps.ind_level;
		/*
		 * for a switch, brace should be two levels out from the code
		 */
	    }
	}

	ps.p_stack[++ps.tos] = lbrace;
	ps.il[ps.tos] = ps.ind_level;
	ps.p_stack[++ps.tos] = stmt;
	/* allow null stmt between braces */
	ps.il[ps.tos] = ps.i_l_follow;
	break;

    case whilestmt:		/* scanned while (...) */
	if (ps.p_stack[ps.tos] == dohead) {
	    /* it is matched with do stmt */
	    ps.ind_level = ps.i_l_follow = ps.il[ps.tos];
	    ps.p_stack[++ps.tos] = whilestmt;
	    ps.il[ps.tos] = ps.ind_level = ps.i_l_follow;
	}
	else {			/* it is a while loop */
	    ps.p_stack[++ps.tos] = whilestmt;
	    ps.il[ps.tos] = ps.i_l_follow;
	    ++ps.i_l_follow;
	    ps.search_brace = btype_2;
	}

	break;

    case elselit:		/* scanned an else */

	if (ps.p_stack[ps.tos] != ifhead)
	    diag2(1, "Unmatched 'else'");
	else {
	    ps.ind_level = ps.il[ps.tos];	/* indentation for else should
						 * be same as for if */
	    ps.i_l_follow = ps.ind_level + 1;	/* everything following should
						 * be in 1 level */
	    ps.p_stack[ps.tos] = elsehead;
	    /* remember if with else */
	    ps.search_brace = btype_2 | ps.else_if;
	}
	break;

    case rbrace:		/* scanned a } */
	/* stack should have <lbrace> <stmt> or <lbrace> <stmtl> */
	if (ps.p_stack[ps.tos - 1] == lbrace) {
	    ps.ind_level = ps.i_l_follow = ps.il[--ps.tos];
	    ps.p_stack[ps.tos] = stmt;
	}
	else
	    diag2(1, "Statement nesting error");
	break;

    case swstmt:		/* had switch (...) */
	ps.p_stack[++ps.tos] = swstmt;
	ps.cstk[ps.tos] = case_ind;
	/* save current case indent level */
	ps.il[ps.tos] = ps.i_l_follow;
	case_ind = ps.i_l_follow + ps.case_indent;	/* cases should be one
							 * level down from
							 * switch */
	ps.i_l_follow += ps.case_indent + 1;	/* statements should be two
						 * levels in */
	ps.search_brace = btype_2;
	break;

    case semicolon:		/* this indicates a simple stmt */
	break_comma = false;	/* turn off flag to break after commas in a
				 * declaration */
	ps.p_stack[++ps.tos] = stmt;
	ps.il[ps.tos] = ps.ind_level;
	break;

    default:			/* this is an error */
	diag2(1, "Unknown code to parser");
	return;


    }				/* end of switch */

    reduce();			/* see if any reduction can be done */

#ifdef debug
    for (i = 1; i <= ps.tos; ++i)
	printf("(%d %d)", ps.p_stack[i], ps.il[i]);
    printf("\n");
#endif

    return;
}
Esempio n. 20
0
static VALUE parse_date_time(const char *date) {
  VALUE ajd, offset;

  int year, month, day, hour, min, sec, usec, hour_offset, minute_offset;
  int jd;
  do_int64 num, den;


  long int gmt_offset;
  int is_dst;

  time_t rawtime;
  struct tm * timeinfo;

  int tokens_read, max_tokens;

  if ( strcmp(date, "") == 0 ) {
    return Qnil;
  }

  if (0 != strchr(date, '.')) {
    // This is a datetime with sub-second precision
    tokens_read = sscanf(date, "%4d-%2d-%2d%*c%2d:%2d:%2d.%d%3d:%2d", &year, &month, &day, &hour, &min, &sec, &usec, &hour_offset, &minute_offset);
    max_tokens = 9;
  } else {
    // This is a datetime second precision
    tokens_read = sscanf(date, "%4d-%2d-%2d%*c%2d:%2d:%2d%3d:%2d", &year, &month, &day, &hour, &min, &sec, &hour_offset, &minute_offset);
    max_tokens = 8;
  }

  if (max_tokens == tokens_read) {
    // We read the Date, Time, and Timezone info
    minute_offset *= hour_offset < 0 ? -1 : 1;
  } else if ((max_tokens - 1) == tokens_read) {
    // We read the Date and Time, but no Minute Offset
    minute_offset = 0;
  } else if (tokens_read == 3) {
    return parse_date(date);
  } else if (tokens_read >= (max_tokens - 3)) {
    // We read the Date and Time, default to the current locale's offset

    // Get localtime
    time(&rawtime);
    timeinfo = localtime(&rawtime);

    is_dst = timeinfo->tm_isdst * 3600;

    // Reset to GM Time
    timeinfo = gmtime(&rawtime);

    gmt_offset = mktime(timeinfo) - rawtime;

    if ( is_dst > 0 )
      gmt_offset -= is_dst;

    hour_offset = -(gmt_offset / 3600);
    minute_offset = -(gmt_offset % 3600 / 60);

  } else {
    // Something went terribly wrong
    rb_raise(eMysqlError, "Couldn't parse date: %s", date);
  }

  jd = jd_from_date(year, month, day);

  // Generate ajd with fractional days for the time
  // Extracted from Date#jd_to_ajd, Date#day_fraction_to_time, and Rational#+ and #-
  num = (hour * 1440) + (min * 24);

  // Modify the numerator so when we apply the timezone everything works out
  num -= (hour_offset * 1440) + (minute_offset * 24);

  den = (24 * 1440);
  reduce(&num, &den);

  num = (num * 86400) + (sec * den);
  den = den * 86400;
  reduce(&num, &den);

  num = (jd * den) + num;

  num = num * 2;
  num = num - den;
  den = den * 2;

  reduce(&num, &den);

  ajd = rb_funcall(rb_cRational, rb_intern("new!"), 2, rb_ull2inum(num), rb_ull2inum(den));
  offset = timezone_to_offset(hour_offset, minute_offset);

  return rb_funcall(rb_cDateTime, ID_NEW_DATE, 3, ajd, offset, INT2NUM(2299161));
}
Esempio n. 21
0
inline
void parallel_reduce( const Kokkos::ParallelWorkRequest  & request ,
                      const FunctorType          & functor )
{
  Impl::ParallelReduce< FunctorType , Kokkos::ParallelWorkRequest > reduce( functor , request );
}
Esempio n. 22
0
Foam::jjc2014Zone::jjc2014Zone
(
    const word& name,
    const fvMesh& mesh,
    const dictionary& dict
)
:
    name_(name),
    mesh_(mesh),
    dict_(dict),
    cellZoneID_(mesh_.cellZones().findZoneID(name)),
#if OFVERSION<230 || EXTBRANCH == 1
    coordSys_(dict, mesh),
#else
    coordSys_(mesh, dict),
#endif
    porosity_( readScalar( dict_.lookup("porosity") ) ),
    addedMassCoeff_( readScalar( dict_.lookup("gammaAddedMass") ) ),
    D_("D", dimensionSet(0, -2, 0, 0, 0), tensor::zero),
    F_("F", dimensionSet(0, -1, 0, 0, 0), tensor::zero)
{
    Info<< "Creating porous zone: " << name_ << endl;

    autoPtr<Foam::porosityCoefficient> pcPtr( Foam::porosityCoefficient::New( dict ) );

    bool foundZone = (cellZoneID_ != -1);
    reduce(foundZone, orOp<bool>());

    if (!foundZone && Pstream::master())
    {
        FatalErrorIn
        (
            "Foam::jjc2014Zone::jjc2014Zone"
            "(const fvMesh&, const word&, const dictionary&)"
        )   << "cannot find porous cellZone " << name_
            << exit(FatalError);
    }

    // porosity
    if (porosity_ <= 0.0 || porosity_ > 1.0)
    {
        FatalIOErrorIn
        (
                "Foam::jjc2014Zone::jjc2014Zone"
                "(const fvMesh&, const word&, const dictionary&)",
                dict_
        )
        << "out-of-range porosity value " << porosity_
        << exit(FatalIOError);
    }

    // local-to-global transformation tensor
#if OFVERSION<230 || EXTBRANCH == 1
    const tensor& E = coordSys_.R();
#else
    const tensor E = coordSys_.R().R();
#endif

    dimensionedVector d( pcPtr->linearCoefficient() );

    if (D_.dimensions() != d.dimensions())
    {
        FatalIOErrorIn
        (
            "Foam::jjc2014Zone::jjc2014Zone"
            "(const fvMesh&, const word&, const dictionary&)",
            dict_
        )   << "incorrect dimensions for d: " << d.dimensions()
        << " should be " << D_.dimensions()
        << exit(FatalIOError);
    }

    checkNegativeResistance(d);

    D_.value().xx() = d.value().x();
    D_.value().yy() = d.value().y();
    D_.value().zz() = d.value().z();
    D_.value() = (E & D_ & E.T()).value();


    dimensionedVector f( pcPtr->quadraticCoefficient() );

    if (F_.dimensions() != f.dimensions())
    {
        FatalIOErrorIn
        (
            "Foam::jjc2014Zone::jjc2014Zone"
            "(const fvMesh&, const word&, const dictionary&)",
            dict_
        )   << "incorrect dimensions for f: " << f.dimensions()
        << " should be " << F_.dimensions()
        << exit(FatalIOError);
    }

    checkNegativeResistance(f);

    F_.value().xx() = 0.5 * f.value().x();
    F_.value().yy() = 0.5 * f.value().y();
    F_.value().zz() = 0.5 * f.value().z();
    F_.value() = (E & F_ & E.T()).value();

    // it is an error not to define anything
    if
    (
        magSqr(D_.value()) <= VSMALL
     && magSqr(F_.value()) <= VSMALL
    )
    {
        FatalIOErrorIn
        (
            "Foam::jjc2014Zone::jjc2014Zone"
            "(const fvMesh&, const word&, const dictionary&)",
            dict_
        )   << "neither powerLaw (C0/C1) "
               "nor Darcy-Forchheimer law (d/f) specified"
            << exit(FatalIOError);
    }
}
Esempio n. 23
0
fraction::fraction(int n, int d ) //constructor with parameters
{
    num = n;
    denom = d;
    reduce();
}
Esempio n. 24
0
static void
calculate_path(void)
{
	char *prog = PI_GetProgramName();	/* use Py_SetProgramName(argv[0]) before Py_Initialize() */
	char argv0_path[MAXPATHLEN+1];
	char *epath;
	char *path = NULL;
	char *ppath = NULL;
#if HAVE_READLINK
	int  numchars;
#endif

	if (strchr(prog, SEP))
		strcpy(progpath, prog);
	else {
#if HAVE_READLINK
            sprintf(argv0_path, "/proc/%d/exe", getpid());
            numchars = readlink(argv0_path, progpath, MAXPATHLEN);
            if (numchars > 0) 
                progpath[numchars] = '\0';
            else {
#endif
		epath = getenv("PATH");
                if (epath) 
                    path = malloc(strlen(epath)+3);
		if (path) {
                    strcpy(path, ".:");
                    strcat(path, epath);
		    ppath = path;
	    	    while (1) {
				char *delim = strchr(ppath, DELIM);

				if (delim) {
					int len = delim - ppath;
					strncpy(progpath, ppath, len);
					*(progpath + len) = '\0';
				}
				else
					strcpy(progpath, ppath);

				joinpath(progpath, prog);
				if (isxfile(progpath))
					break;

				if (!delim) {
					progpath[0] = '\0';
					break;
				}
				ppath = delim + 1;
		    }
                    free(path);
		}
		else
			progpath[0] = '\0';
#if HAVE_READLINK
            }
#endif
	}
	/* at this point progpath includes the executable */
	strcpy(argv0_path, progpath);
	
#if HAVE_READLINK
	{
		char tmpbuffer[MAXPATHLEN+1];
		int linklen = readlink(progpath, tmpbuffer, MAXPATHLEN);
		while (linklen != -1) {
			/* It's not null terminated! */
			tmpbuffer[linklen] = '\0';
			if (tmpbuffer[0] == SEP)
				strcpy(argv0_path, tmpbuffer);
			else {
				/* Interpret relative to progpath */
				reduce(argv0_path);
				joinpath(argv0_path, tmpbuffer);
			}
			linklen = readlink(argv0_path, tmpbuffer, MAXPATHLEN);
		}
                strcpy(progpath, argv0_path);
	}
#endif /* HAVE_READLINK */

	reduce(argv0_path);
	/* now argv0_path is the directory of the executable */

	strcpy(prefix, argv0_path);
	exec_prefix = prefix;
	module_search_path = malloc(strlen(prefix)+1);
	strcpy(module_search_path, prefix);

}
Esempio n. 25
0
    void mStep()
    {
        // Update means_k, covs_k and weights_k from probs_ik
        int dim = trainSamples.cols;

        // Update weights
        // not normalized first
        reduce(trainProbs, weights, 0, CV_REDUCE_SUM);

        // Update means
        means.create(nclusters, dim, CV_64FC1);
        means = Scalar(0);

        const double minPosWeight = trainSamples.rows * DBL_EPSILON;
        double minWeight = DBL_MAX;
        int minWeightClusterIndex = -1;
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            if(weights.at<double>(clusterIndex) <= minPosWeight)
                continue;

            if(weights.at<double>(clusterIndex) < minWeight)
            {
                minWeight = weights.at<double>(clusterIndex);
                minWeightClusterIndex = clusterIndex;
            }

            Mat clusterMean = means.row(clusterIndex);
            for(int sampleIndex = 0; sampleIndex < trainSamples.rows; sampleIndex++)
                clusterMean += trainProbs.at<double>(sampleIndex, clusterIndex) * trainSamples.row(sampleIndex);
            clusterMean /= weights.at<double>(clusterIndex);
        }

        // Update covsEigenValues and invCovsEigenValues
        covs.resize(nclusters);
        covsEigenValues.resize(nclusters);
        if(covMatType == COV_MAT_GENERIC)
            covsRotateMats.resize(nclusters);
        invCovsEigenValues.resize(nclusters);
        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            if(weights.at<double>(clusterIndex) <= minPosWeight)
                continue;

            if(covMatType != COV_MAT_SPHERICAL)
                covsEigenValues[clusterIndex].create(1, dim, CV_64FC1);
            else
                covsEigenValues[clusterIndex].create(1, 1, CV_64FC1);

            if(covMatType == COV_MAT_GENERIC)
                covs[clusterIndex].create(dim, dim, CV_64FC1);

            Mat clusterCov = covMatType != COV_MAT_GENERIC ?
                covsEigenValues[clusterIndex] : covs[clusterIndex];

            clusterCov = Scalar(0);

            Mat centeredSample;
            for(int sampleIndex = 0; sampleIndex < trainSamples.rows; sampleIndex++)
            {
                centeredSample = trainSamples.row(sampleIndex) - means.row(clusterIndex);

                if(covMatType == COV_MAT_GENERIC)
                    clusterCov += trainProbs.at<double>(sampleIndex, clusterIndex) * centeredSample.t() * centeredSample;
                else
                {
                    double p = trainProbs.at<double>(sampleIndex, clusterIndex);
                    for(int di = 0; di < dim; di++ )
                    {
                        double val = centeredSample.at<double>(di);
                        clusterCov.at<double>(covMatType != COV_MAT_SPHERICAL ? di : 0) += p*val*val;
                    }
                }
            }

            if(covMatType == COV_MAT_SPHERICAL)
                clusterCov /= dim;

            clusterCov /= weights.at<double>(clusterIndex);

            // Update covsRotateMats for COV_MAT_GENERIC only
            if(covMatType == COV_MAT_GENERIC)
            {
                SVD svd(covs[clusterIndex], SVD::MODIFY_A + SVD::FULL_UV);
                covsEigenValues[clusterIndex] = svd.w;
                covsRotateMats[clusterIndex] = svd.u;
            }

            max(covsEigenValues[clusterIndex], minEigenValue, covsEigenValues[clusterIndex]);

            // update invCovsEigenValues
            invCovsEigenValues[clusterIndex] = 1./covsEigenValues[clusterIndex];
        }

        for(int clusterIndex = 0; clusterIndex < nclusters; clusterIndex++)
        {
            if(weights.at<double>(clusterIndex) <= minPosWeight)
            {
                Mat clusterMean = means.row(clusterIndex);
                means.row(minWeightClusterIndex).copyTo(clusterMean);
                covs[minWeightClusterIndex].copyTo(covs[clusterIndex]);
                covsEigenValues[minWeightClusterIndex].copyTo(covsEigenValues[clusterIndex]);
                if(covMatType == COV_MAT_GENERIC)
                    covsRotateMats[minWeightClusterIndex].copyTo(covsRotateMats[clusterIndex]);
                invCovsEigenValues[minWeightClusterIndex].copyTo(invCovsEigenValues[clusterIndex]);
            }
        }

        // Normalize weights
        weights /= trainSamples.rows;
    }
Esempio n. 26
0
int test_reduce_xor47(uint47 x)
{
  unsigned result = reduce(xor, x) != 0;
  printf("reduce_xor47(x) = %d\n", result);
  return result;
}  
Foam::engineMesh::engineMesh(const IOobject& io)
:
    fvMesh(io),
    engineDB_(refCast<const engineTime>(time())),
    pistonIndex_(-1),
    linerIndex_(-1),
    cylinderHeadIndex_(-1),
    deckHeight_("deckHeight", dimLength, GREAT),
    pistonPosition_("deckHeight", dimLength, GREAT)
{
    bool foundPiston = false;
    bool foundLiner = false;
    bool foundCylinderHead = false;

    forAll(boundary(), i)
    {
        if (boundary()[i].name() == "piston")
        {
            pistonIndex_ = i;
            foundPiston = true;
        }
        else if (boundary()[i].name() == "liner")
        {
            linerIndex_ = i;
            foundLiner = true;
        }
        else if (boundary()[i].name() == "cylinderHead")
        {
            cylinderHeadIndex_ = i;
            foundCylinderHead = true;
        }
    }

    reduce(foundPiston, orOp<bool>());
    reduce(foundLiner, orOp<bool>());
    reduce(foundCylinderHead, orOp<bool>());

    if (!foundPiston)
    {
        FatalErrorIn("engineMesh::engineMesh(const IOobject& io)")
            << "cannot find piston patch"
            << exit(FatalError);
    }

    if (!foundLiner)
    {
        FatalErrorIn("engineMesh::engineMesh(const IOobject& io)")
            << "cannot find liner patch"
            << exit(FatalError);
    }

    if (!foundCylinderHead)
    {
        FatalErrorIn("engineMesh::engineMesh(const IOobject& io)")
            << "cannot find cylinderHead patch"
            << exit(FatalError);
    }

    {
        if (pistonIndex_ != -1)
        {
            pistonPosition_.value() =
                max(boundary()[pistonIndex_].patch().localPoints()).z();
        }
        reduce(pistonPosition_.value(), minOp<scalar>());

        if (cylinderHeadIndex_ != -1)
        {
            deckHeight_.value() = min
            (
                boundary()[cylinderHeadIndex_].patch().localPoints()
            ).z();
        }
        reduce(deckHeight_.value(), minOp<scalar>());

        Info<< "deckHeight: " << deckHeight_.value() << nl
            << "piston position: " << pistonPosition_.value() << endl;
    }
}
Esempio n. 28
0
static void
calculate_path(void)
{
    extern char *Py_GetProgramName(void);

    static char delimiter[2] = {DELIM, '\0'};
    static char separator[2] = {SEP, '\0'};
    char *pythonpath = PYTHONPATH;
    char *rtpypath = Py_GETENV("PYTHONPATH");
    char *home = Py_GetPythonHome();
    char *path = getenv("PATH");
    char *prog = Py_GetProgramName();
    char argv0_path[MAXPATHLEN+1];
    char zip_path[MAXPATHLEN+1];
    int pfound, efound; /* 1 if found; -1 if found build directory */
    char *buf;
    size_t bufsz;
    size_t prefixsz;
    char *defpath = pythonpath;
#ifdef WITH_NEXT_FRAMEWORK
    NSModule pythonModule;
#endif
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
    uint32_t nsexeclength = MAXPATHLEN;
#else
    unsigned long nsexeclength = MAXPATHLEN;
#endif
#endif

        /* If there is no slash in the argv0 path, then we have to
         * assume python is on the user's $PATH, since there's no
         * other way to find a directory to start the search from.  If
         * $PATH isn't exported, you lose.
         */
        if (strchr(prog, SEP))
                strncpy(progpath, prog, MAXPATHLEN);
#ifdef __APPLE__
     /* On Mac OS X, if a script uses an interpreter of the form
      * "#!/opt/python2.3/bin/python", the kernel only passes "python"
      * as argv[0], which falls through to the $PATH search below.
      * If /opt/python2.3/bin isn't in your path, or is near the end,
      * this algorithm may incorrectly find /usr/bin/python. To work
      * around this, we can use _NSGetExecutablePath to get a better
      * hint of what the intended interpreter was, although this
      * will fail if a relative path was used. but in that case,
      * absolutize() should help us out below
      */
     else if(0 == _NSGetExecutablePath(progpath, &nsexeclength) && progpath[0] == SEP)
       ;
#endif /* __APPLE__ */
        else if (path) {
                while (1) {
                        char *delim = strchr(path, DELIM);

                        if (delim) {
                                size_t len = delim - path;
                                if (len > MAXPATHLEN)
                                        len = MAXPATHLEN;
                                strncpy(progpath, path, len);
                                *(progpath + len) = '\0';
                        }
                        else
                                strncpy(progpath, path, MAXPATHLEN);

                        joinpath(progpath, prog);
                        if (isxfile(progpath))
                                break;

                        if (!delim) {
                                progpath[0] = '\0';
                                break;
                        }
                        path = delim + 1;
                }
        }
        else
                progpath[0] = '\0';
        if (progpath[0] != SEP && progpath[0] != '\0')
                absolutize(progpath);
        strncpy(argv0_path, progpath, MAXPATHLEN);
        argv0_path[MAXPATHLEN] = '\0';

#ifdef WITH_NEXT_FRAMEWORK
        /* On Mac OS X we have a special case if we're running from a framework.
        ** This is because the python home should be set relative to the library,
        ** which is in the framework, not relative to the executable, which may
        ** be outside of the framework. Except when we're in the build directory...
        */
    pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize"));
    /* Use dylib functions to find out where the framework was loaded from */
    buf = (char *)NSLibraryNameForModule(pythonModule);
    if (buf != NULL) {
        /* We're in a framework. */
        /* See if we might be in the build directory. The framework in the
        ** build directory is incomplete, it only has the .dylib and a few
        ** needed symlinks, it doesn't have the Lib directories and such.
        ** If we're running with the framework from the build directory we must
        ** be running the interpreter in the build directory, so we use the
        ** build-directory-specific logic to find Lib and such.
        */
        strncpy(argv0_path, buf, MAXPATHLEN);
        reduce(argv0_path);
        joinpath(argv0_path, lib_python);
        joinpath(argv0_path, LANDMARK);
        if (!ismodule(argv0_path)) {
                /* We are in the build directory so use the name of the
                   executable - we know that the absolute path is passed */
                strncpy(argv0_path, prog, MAXPATHLEN);
        }
        else {
                /* Use the location of the library as the progpath */
                strncpy(argv0_path, buf, MAXPATHLEN);
        }
    }
#endif

#if HAVE_READLINK
    {
        char tmpbuffer[MAXPATHLEN+1];
        int linklen = readlink(progpath, tmpbuffer, MAXPATHLEN);
        while (linklen != -1) {
            /* It's not null terminated! */
            tmpbuffer[linklen] = '\0';
            if (tmpbuffer[0] == SEP)
                /* tmpbuffer should never be longer than MAXPATHLEN,
                   but extra check does not hurt */
                strncpy(argv0_path, tmpbuffer, MAXPATHLEN);
            else {
                /* Interpret relative to progpath */
                reduce(argv0_path);
                joinpath(argv0_path, tmpbuffer);
            }
            linklen = readlink(argv0_path, tmpbuffer, MAXPATHLEN);
        }
    }
#endif /* HAVE_READLINK */

    reduce(argv0_path);
    /* At this point, argv0_path is guaranteed to be less than
       MAXPATHLEN bytes long.
    */

    if (!(pfound = search_for_prefix(argv0_path, home))) {
        if (!Py_FrozenFlag)
            fprintf(stderr,
                "Could not find platform independent libraries <prefix>\n");
        strncpy(prefix, PREFIX, MAXPATHLEN);
        joinpath(prefix, lib_python);
    }
    else
        reduce(prefix);

    strncpy(zip_path, prefix, MAXPATHLEN);
    zip_path[MAXPATHLEN] = '\0';
    if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */
        reduce(zip_path);
        reduce(zip_path);
    }
    else
        strncpy(zip_path, PREFIX, MAXPATHLEN);
    joinpath(zip_path, "lib/python00.zip");
    bufsz = strlen(zip_path);   /* Replace "00" with version */
    zip_path[bufsz - 6] = VERSION[0];
    zip_path[bufsz - 5] = VERSION[2];

    if (!(efound = search_for_exec_prefix(argv0_path, home))) {
        if (!Py_FrozenFlag)
            fprintf(stderr,
                "Could not find platform dependent libraries <exec_prefix>\n");
        strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN);
        joinpath(exec_prefix, "lib/lib-dynload");
    }
    /* If we found EXEC_PREFIX do *not* reduce it!  (Yet.) */

    if ((!pfound || !efound) && !Py_FrozenFlag)
        fprintf(stderr,
                "Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]\n");

    /* Calculate size of return buffer.
     */
    bufsz = 0;

    if (rtpypath)
        bufsz += strlen(rtpypath) + 1;

    prefixsz = strlen(prefix) + 1;

    while (1) {
        char *delim = strchr(defpath, DELIM);

        if (defpath[0] != SEP)
            /* Paths are relative to prefix */
            bufsz += prefixsz;

        if (delim)
            bufsz += delim - defpath + 1;
        else {
            bufsz += strlen(defpath) + 1;
            break;
        }
        defpath = delim + 1;
    }

    bufsz += strlen(zip_path) + 1;
    bufsz += strlen(exec_prefix) + 1;

    /* This is the only malloc call in this file */
    buf = (char *)PyMem_Malloc(bufsz);

    if (buf == NULL) {
        /* We can't exit, so print a warning and limp along */
        fprintf(stderr, "Not enough memory for dynamic PYTHONPATH.\n");
        fprintf(stderr, "Using default static PYTHONPATH.\n");
        module_search_path = PYTHONPATH;
    }
    else {
        /* Run-time value of $PYTHONPATH goes first */
        if (rtpypath) {
            strcpy(buf, rtpypath);
            strcat(buf, delimiter);
        }
        else
            buf[0] = '\0';

        /* Next is the default zip path */
        strcat(buf, zip_path);
        strcat(buf, delimiter);

        /* Next goes merge of compile-time $PYTHONPATH with
         * dynamically located prefix.
         */
        defpath = pythonpath;
        while (1) {
            char *delim = strchr(defpath, DELIM);

            if (defpath[0] != SEP) {
                strcat(buf, prefix);
                strcat(buf, separator);
            }

            if (delim) {
                size_t len = delim - defpath + 1;
                size_t end = strlen(buf) + len;
                strncat(buf, defpath, len);
                *(buf + end) = '\0';
            }
            else {
                strcat(buf, defpath);
                break;
            }
            defpath = delim + 1;
        }
        strcat(buf, delimiter);

        /* Finally, on goes the directory for dynamic-load modules */
        strcat(buf, exec_prefix);

        /* And publish the results */
        module_search_path = buf;
    }

    /* Reduce prefix and exec_prefix to their essence,
     * e.g. /usr/local/lib/python1.5 is reduced to /usr/local.
     * If we're loading relative to the build directory,
     * return the compiled-in defaults instead.
     */
    if (pfound > 0) {
        reduce(prefix);
        reduce(prefix);
        /* The prefix is the root directory, but reduce() chopped
         * off the "/". */
        if (!prefix[0])
                strcpy(prefix, separator);
    }
    else
        strncpy(prefix, PREFIX, MAXPATHLEN);

    if (efound > 0) {
        reduce(exec_prefix);
        reduce(exec_prefix);
        reduce(exec_prefix);
        if (!exec_prefix[0])
                strcpy(exec_prefix, separator);
    }
    else
        strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN);
}
 std::size_t deg(){
     reduce();
     return numerator.deg() - denominator.deg();
 }
Esempio n. 30
0
double OCRHMMDecoder::run( InputArray src,
              InputArray mask,
              string& out_sequence,
	            vector<Rect>* component_rects, 
              vector<string>* component_texts, 
              vector<float>* component_confidences,
              int component_level)
{

  out_sequence.clear();
  component_rects->clear();
  component_texts->clear();
  component_confidences->clear();

  // First we split a line into words (TODO this must be optional)
  vector<Mat> words_mask;
  vector<Mat> words_src;
  vector<Rect> words_rect;

  /// Find contours
  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;
  Mat tmp;
  mask.getMat().copyTo(tmp);
  findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
  if (contours.size() < 6)
  {
    //do not split lines with less than 6 characters
    words_mask.push_back(mask.getMat());
    words_src.push_back(src.getMat());
    words_rect.push_back(Rect(0,0,mask.getMat().cols,mask.getMat().rows));
  }
  else
  {


        Mat_<float> vector_w((int)mask.getMat().cols,1);
        reduce(mask.getMat(), vector_w, 0, CV_REDUCE_SUM, -1);

        vector<int> spaces;
        vector<int> spaces_start;
        vector<int> spaces_end;
        int space_count=0;
        int last_one_idx;
        for (int s=0; s<vector_w.cols; s++)
        {
            if (vector_w.at<float>(0,s) == 0)
            {
                space_count++;
            } else {
                if (space_count!=0)
                {
                    spaces.push_back(space_count);
                    spaces_start.push_back(last_one_idx);
                    spaces_end.push_back(s-1);
                }
                space_count = 0;
                last_one_idx = s;
            }
        }
        Scalar mean_space,std_space;
        meanStdDev(Mat(spaces),mean_space,std_space);
        int num_word_spaces = 0;
        int last_word_space_end = 0;
        for (int s=0; s<spaces.size(); s++)
        {
            if (spaces_end.at(s)-spaces_start.at(s) > mean_space[0]+(mean_space[0]*1.1)) //TODO this 1.1 is a param
            {
                if (num_word_spaces == 0)
                {
                    //cout << " we have a word from  0  to " << spaces_start.at(s) << endl;
                    Mat word_mask, word_src;
                    Rect word_rect = Rect(0,0,spaces_start.at(s),mask.getMat().rows);
                    mask.getMat()(word_rect).copyTo(word_mask);
                    src.getMat()(word_rect).copyTo(word_src);

                    words_mask.push_back(word_mask);
                    words_src.push_back(word_src);
                    words_rect.push_back(word_rect);
                }
                else
                {
                    //cout << " we have a word from " << last_word_space_end << " to " << spaces_start.at(s) << endl;
                    Mat word_mask, word_src;
                    Rect word_rect = Rect(last_word_space_end,0,spaces_start.at(s)-last_word_space_end,mask.getMat().rows);
                    mask.getMat()(word_rect).copyTo(word_mask);
                    src.getMat()(word_rect).copyTo(word_src);

                    words_mask.push_back(word_mask);
                    words_src.push_back(word_src);
                    words_rect.push_back(word_rect);
                }
                num_word_spaces++;
                last_word_space_end = spaces_end.at(s);
            }
        }
        //cout << " we have a word from " << last_word_space_end << " to " << vector_w.cols << endl << endl << endl;
                    Mat word_mask, word_src;
                    Rect word_rect = Rect(last_word_space_end,0,vector_w.cols-last_word_space_end,mask.getMat().rows);
                    mask.getMat()(word_rect).copyTo(word_mask);
                    src.getMat()(word_rect).copyTo(word_src);

                    words_mask.push_back(word_mask);
                    words_src.push_back(word_src);
                    words_rect.push_back(word_rect);

  }

  for (int w=0; w<words_mask.size(); w++)
  {

  vector< vector<int> > observations;
  vector< vector<double> > confidences;
  vector<int> obs;
  // First find contours and sort by x coordinate of bbox
  Mat tmp;
  words_mask[w].copyTo(tmp);
  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;
  /// Find contours
  findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
  vector<Rect> contours_rect;
  for (int i=0; i<contours.size(); i++)
  {
    contours_rect.push_back(boundingRect(contours[i]));
  }

  sort(contours_rect.begin(), contours_rect.end(), sort_rect_horiz);
  
  // Do character recognition foreach contour 
  for (int i=0; i<contours.size(); i++)
  {
    Mat tmp_src;
    Mat tmp_mask;
    words_src[w](contours_rect.at(i)).copyTo(tmp_src);
    words_mask[w](contours_rect.at(i)).copyTo(tmp_mask);

    vector<int> out_class;
    vector<double> out_conf;
    classifier->eval(tmp_src,tmp_mask,out_class,out_conf);
    if (!out_class.empty())
      obs.push_back(out_class[0]);
    observations.push_back(out_class);
    confidences.push_back(out_conf);
  }


  //This must be extracted from dictionary, or just assumed to be equal for all characters
  vector<double> start_p(vocabulary.size());
  for (int i=0; i<vocabulary.size(); i++)
    start_p[i] = 1.0/vocabulary.size();


  Mat V = Mat::zeros(observations.size(),vocabulary.size(),CV_64FC1);
  vector<string> path(vocabulary.size());
    
  // Initialize base cases (t == 0)
  for (int i=0; i<vocabulary.size(); i++)
  {
    for (int j=0; j<observations[0].size(); j++)
    {
      emission_p.at<double>(observations[0][j],obs[0]) = confidences[0][j];
    }
    V.at<double>(0,i) = start_p[i] * emission_p.at<double>(i,obs[0]);
    path[i] = vocabulary.at(i);
  }

    
  // Run Viterbi for t > 0
  for (int t=1; t<obs.size(); t++)
  {

    //Dude this has to be done each time!!
    Mat emission_p = Mat::eye(62,62,CV_64FC1);
    for (int e=0; e<observations[t].size(); e++)
    {
      emission_p.at<double>(observations[t][e],obs[t]) = confidences[t][e];
    }

    vector<string> newpath(vocabulary.size());

    for (int i=0; i<vocabulary.size(); i++)
    {
      double max_prob = 0;
      int best_idx = 0; 
      for (int j=0; j<vocabulary.size(); j++)
      {
        double prob = V.at<double>(t-1,j) * transition_p.at<double>(j,i) * emission_p.at<double>(i,obs[t]);
        if ( prob > max_prob)
        {
          max_prob = prob;
          best_idx = j;
        }
      }

      V.at<double>(t,i) = max_prob;
      newpath[i] = path[best_idx] + vocabulary.at(i);
    }
 
    // Don't need to remember the old paths
    path.swap(newpath);
  }
 
   double max_prob = 0;
   int best_idx = 0; 
   for (int i=0; i<vocabulary.size(); i++)
   {
        double prob = V.at<double>(obs.size()-1,i);
        if ( prob > max_prob)
        {
          max_prob = prob;
          best_idx = i;
        }
   }

   //cout << path[best_idx] << endl;
   out_sequence = out_sequence+" "+path[best_idx];
	 component_rects->push_back(words_rect[w]);
   component_texts->push_back(path[best_idx]);
   component_confidences->push_back(max_prob);

  }
   
  return 0;


}