Example #1
0
int countSingletons(sudoku* s){
  int count = 0;
  int i;
  for (i=0; i<81; ++i){
    if (countBits(s->candidates[i])==1){
      s->fields[i] = getCandidateSingleton(s->candidates[i]);
      count++;
    }
  }
  return count;
}
void CDStarRepeaterRXThread::receiveRadioData(unsigned char* data, unsigned int)
{
    unsigned int errs;
    errs  = countBits(data[VOICE_FRAME_LENGTH_BYTES + 0U] ^ DATA_SYNC_BYTES[0U]);
    errs += countBits(data[VOICE_FRAME_LENGTH_BYTES + 1U] ^ DATA_SYNC_BYTES[1U]);
    errs += countBits(data[VOICE_FRAME_LENGTH_BYTES + 2U] ^ DATA_SYNC_BYTES[2U]);

    // The data sync has been seen, a fuzzy match is used, two bit errors or less
    if (errs <= MAX_DATA_SYNC_BIT_ERRS) {
        // wxLogMessage(wxT("Found data sync at frame %u, errs: %u"), m_radioSeqNo, errs);
        m_radioSeqNo = 0U;
        processRadioFrame(data, FRAME_SYNC);
    } else if (m_radioSeqNo == 20U) {
        // wxLogMessage(wxT("Regenerating data sync"));
        m_radioSeqNo = 0U;
        processRadioFrame(data, FRAME_SYNC);
    } else {
        m_radioSeqNo++;
        processRadioFrame(data, FRAME_NORMAL);
    }
}
Example #3
0
int padBits(int binNum)
{
	int numToPad = 32-countBits(binNum);
	int i;
	for(i = numToPad; i > 0; i--)
	{
		if (i%8 == 0 && i != numToPad)
		{
			printf(" ");
		}
		printf("0");
	}
}
Example #4
0
void printBits(int val)
{
	printf("Value as Int: %d\n", val);
	int number = val;
	int i = 1;
	int remainder;
	int bin = 0;

	while(number != 0)
	{
		//printf("Result: %d ResultMod2: %d\n",result, result%2);
		//printf("Counter: %d\n", counter);
		//counter++;
		//result = result/2;
		remainder = number%2;
		number = number/2;
		bin = bin + (remainder*i);
		i = i*10;
	}

	printf("Binary: %d\n", bin);
	printf("There are %d bits in the above number.\n", countBits(bin));
	printf("We need to pad %d bits.\n", 32-countBits(bin));
	bin = padBits(bin);
	//printBin(bin, countBits(bin));


	/*
	printf("Final Counter Value: %d\n",counter);
	int i;
	for (i = 3; i > 0; i--)
	{
		printf("%d", i);
		//printf(bytes[i]);
	}
	printf("\n");
	*/
}
void CDStarRepeaterRXThread::receiveSlowData(unsigned char* data, unsigned int)
{
    unsigned int errs;
    errs  = countBits(data[VOICE_FRAME_LENGTH_BYTES + 0U] ^ DATA_SYNC_BYTES[0U]);
    errs += countBits(data[VOICE_FRAME_LENGTH_BYTES + 1U] ^ DATA_SYNC_BYTES[1U]);
    errs += countBits(data[VOICE_FRAME_LENGTH_BYTES + 2U] ^ DATA_SYNC_BYTES[2U]);

    // The data sync has been seen, a fuzzy match is used, two bit errors or less
    if (errs <= MAX_DATA_SYNC_BIT_ERRS) {
        // wxLogMessage(wxT("Found data sync at frame %u, errs: %u"), m_radioSeqNo, errs);
        m_radioSeqNo     = 0U;
        m_slowDataDecoder.sync();
    } else if (m_radioSeqNo == 20U) {
        // wxLogMessage(wxT("Assuming data sync"));
        m_radioSeqNo = 0U;
        m_slowDataDecoder.sync();
    } else {
        m_radioSeqNo++;
        m_slowDataDecoder.addData(data + VOICE_FRAME_LENGTH_BYTES);

        CHeaderData* header = m_slowDataDecoder.getHeaderData();
        if (header == NULL)
            return;

        wxLogMessage(wxT("Radio header from slow data - My: %s/%s  Your: %s  Rpt1: %s  Rpt2: %s  Flags: %02X %02X %02X  BER: 0%%"), header->getMyCall1().c_str(), header->getMyCall2().c_str(), header->getYourCall().c_str(), header->getRptCall1().c_str(), header->getRptCall2().c_str(), header->getFlag1(), header->getFlag2(), header->getFlag3());

        if (header != NULL) {
            bool res = processRadioHeader(header);
            if (res) {
                // A valid header and is a DV packet, go to normal data relaying
                setRadioState(DSRXS_PROCESS_DATA);
            } else {
                // This is a DD packet or some other problem
                // wxLogMessage(wxT("Invalid header"));
            }
        }
    }
}
Example #6
0
// Set the pixel format parameters from the visual in "xinfo".
void QEglProperties::setVisualFormat(const QX11Info *xinfo)
{
    if (!xinfo)
        return;
    Visual *visual = (Visual*)xinfo->visual();
    if (!visual)
        return;
    if (visual->c_class != TrueColor && visual->c_class != DirectColor)
        return;
    setValue(EGL_RED_SIZE, countBits(visual->red_mask));
    setValue(EGL_GREEN_SIZE, countBits(visual->green_mask));
    setValue(EGL_BLUE_SIZE, countBits(visual->blue_mask));

    EGLint alphaBits = 0;
#if !defined(QT_NO_XRENDER)
    XRenderPictFormat *format;
    format = XRenderFindVisualFormat(xinfo->display(), visual);
    if (format && (format->type == PictTypeDirect) && format->direct.alphaMask) {
        alphaBits = countBits(format->direct.alphaMask);
        qDebug("QEglProperties::setVisualFormat() - visual's alphaMask is %d", alphaBits);
    }
#endif
    setValue(EGL_ALPHA_SIZE, alphaBits);
}
Example #7
0
int fixPairInCol(sudoku* s, int col, int row1, int row2){
  int i;
  int fixer = (s->candidates2d[row1][col] | s->candidates2d[row2][col]);
  int findings = 0;
  assert(countBits(fixer)==2);
  fixer = ~fixer;
  for (i=0; i<9; ++i){
    if (i!=row1 && i!=row2){
      possible old = s->candidates2d[i][col];
      s->candidates2d[i][col] &= fixer;
      if (old != s->candidates2d[i][col]){
	findings++;
      }
    }
  }
  return findings;
}
Example #8
0
int fixPairInRow(sudoku* s, int row, int col1, int col2){
  int i;
  int fixer = (s->candidates2d[row][col1] | s->candidates2d[row][col2]);
  int findings = 0;
  assert(countBits(fixer)==2);
  fixer = ~fixer;
  for (i=0; i<9; ++i){
    if (i!=col1 && i!=col2){
      possible old = s->candidates2d[row][i];
      s->candidates2d[row][i] &= fixer;
      if (old != s->candidates2d[row][i]){
	findings++;
      }
    }
  }
  return findings;
}
Example #9
0
uint8 rearrange(uint8 v)
{
    int count = countBits(v); /*Number of bits*/
    int numzero = 8-count; 
    int counter1 = 0;
    int counter = 0;
    int zero = 0;
    int ones =1;
    char str1[15];
    char str2[15];
    char str3[8];
    int result;
    
    //UART_1_PutString("Binary Representation: \n\r");
   
    // add code to store rearranged binary value
    
    for(counter1 = 0; counter1<count;counter1 = counter1+1)
    {
        //char str1[15];
        sprintf(str1,"%d",ones);
        UART_1_PutString(str1);
        strcat(str3, str1);
    }
    
    for(counter=0; counter<numzero; counter = counter + 1)
    {   
        //char str2[15];
        sprintf(str2,"%d", zero);
        UART_1_PutString(str2);  
        strcat(str3, str2);
    }   
    
    UART_1_PutString("\n\r");
    
    sscanf(str3, "%d", &result);
    
    return result;
}
Example #10
0
int checkBoard(const board& b){
  int temp_numPieces[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
  int temp_numMinorPieces[2] = {0,0};
  int temp_numMajorPieces[2] = {0,0};
  int temp_numBigPieces[2] = {0,0};
  int temp_materialValue[2] = {0,0};
  U64 temp_pawns[3] = {0ULL, 0ULL, 0ULL};
  temp_pawns[WHITE] = b.pawns[WHITE];
  temp_pawns[BLACK] = b.pawns[BLACK];
  temp_pawns[BOTH] = b.pawns[BOTH];

  int sq120, color, pcount, tempPiece;

  for (int i = wP; i <= bK; ++i){
    for (int j = 0; j < b.numPieces[i]; ++j){
      sq120 = b.pieceList[i][j];
      if (b.pieces[sq120] != i) throw pieceListException();
    }
  }

  for (int i = 0; i < 64; ++i){
    sq120 = SQ64[i];
    tempPiece = b.pieces[sq120];
    temp_numPieces[tempPiece]++;
    color = pieceColor[tempPiece];
    if (isBig[tempPiece]) temp_numBigPieces[color]++;
    if (isMinor[tempPiece]) {
      temp_numMinorPieces[color]++;
    }
    if (isMajor[tempPiece]) temp_numMajorPieces[color]++;
    temp_materialValue[color] += pieceValue[tempPiece];
  }

  for (int i = wP; i<= bK; ++i){
    if (temp_numPieces[i] != b.numPieces[i]){
      throw pieceListException();
    }
  }

  pcount = countBits(temp_pawns[WHITE]);
  if (pcount != b.numPieces[wP]) throw pieceListException();
  pcount = countBits(temp_pawns[BLACK]);
  if (pcount != b.numPieces[bP]) throw pieceListException();
  pcount = countBits(temp_pawns[BOTH]);
  if (pcount != (b.numPieces[wP] + b.numPieces[bP])) {
    std::cout << "Piece count: " << pcount << " White: " << b.numPieces[wP] << " Black: " << b.numPieces[bP] <<
    " Total: " << (b.numPieces[wP] + b.numPieces[bP]) << std::endl;
    throw pieceListException();
  }

  while (temp_pawns[WHITE]){
    int sq = popBit(&temp_pawns[WHITE]);
    if (b.pieces[SQ64[sq]] != wP) throw pieceListException();
  }
  while (temp_pawns[BLACK]){
    int sq = popBit(&temp_pawns[BLACK]);
    if (b.pieces[SQ64[sq]] != bP) throw pieceListException();
  }
  while (temp_pawns[BOTH]){
    int sq = popBit(&temp_pawns[BOTH]);
    if (b.pieces[SQ64[sq]] != bP && b.pieces[SQ64[sq]] != wP){
      throw pieceListException();
    }

  }

  if (temp_materialValue[WHITE] != b.materialValue[WHITE] || temp_materialValue[BLACK] != b.materialValue[BLACK]){
    std::cout << "TmpWhite: " << std::dec <<temp_materialValue[WHITE] << " White: " << std::dec <<b.materialValue[WHITE] << std::endl;
    std::cout << "Tmpblack: " << std::dec << temp_materialValue[BLACK] << " black: " <<std::dec << b.materialValue[BLACK] << std::endl;
    throw pieceListException();
  }
  if (temp_numMajorPieces[WHITE] != b.numMajorPieces[WHITE] || temp_numMajorPieces[BLACK] != b.numMajorPieces[BLACK]){
    throw pieceListException();
  }
  if (temp_numMinorPieces[WHITE] != b.numMinorPieces[WHITE] || temp_numMinorPieces[BLACK] != b.numMinorPieces[BLACK]){
    std::cout << "TmpWhite: " << std::dec << temp_numMinorPieces[WHITE] << " White: " << std::dec <<b.numMinorPieces[WHITE] << std::endl;
    std::cout << "Tmpblack: " << std::dec << temp_numMinorPieces[BLACK] << " black: " <<std::dec << b.numMinorPieces[BLACK] << std::endl;
    throw pieceListException();
  }
  if (temp_numBigPieces[WHITE] != b.numBigPieces[WHITE] && temp_numBigPieces[BLACK] != b.numBigPieces[BLACK]){
    throw pieceListException();
  }
  if (generatePosKey(b) != b.posKey){
    throw pieceListException();
  }
  return 1;
}
Example #11
0
uint16_t solve_442a(std::vector<uint16_t>& cards)
{
    uint16_t accepted_symbols = 0;
    std::vector<uint16_t> unique_cards;
    for (std::vector<uint16_t>::iterator it = cards.begin(); it != cards.end(); it++)
    {
        accepted_symbols = setMask(accepted_symbols, *it);
        std::vector<uint16_t>::iterator val = std::find(unique_cards.begin(), unique_cards.end(), *it);
        if (val == unique_cards.end())
        {
            unique_cards.push_back(*it);
        }
    }
    uint16_t solution = 0;
    uint16_t min = 11;
    if (unique_cards.size() == 1)
    {
        return 0;
    }

    while (++solution < 1024)
    {
        // check if valid
        if ((solution | accepted_symbols) != accepted_symbols)
        {
            continue;
        }
        std::vector<uint16_t> icards = cards;
        std::vector<uint16_t> lucards = unique_cards;
        for (std::vector<uint16_t>::iterator it = icards.begin(); it != icards.end(); it++)
        {
            *it = *it & solution;
        }
        
        // Remove the cards matched directly
        size_t sz = icards.size();
        for (size_t i = 0; i < sz; i++)
        {
            if (icards[i] == cards[i])
            {
                std::vector<uint16_t>::iterator it = find(lucards.begin(), lucards.end(), icards[i]);
                if (it != lucards.end()) lucards.erase(it);
                icards[i] = 0;
            }
        }
        
        // Remove the cards that were matched partially but there is only one type left in the
        // list that contain the same partial part matched
        for (size_t i = 0; i < sz; i++)
        {
            if (icards[i] != 0)
            {
                uint16_t count = 0;
                for (std::vector<uint16_t>::iterator it = lucards.begin(); it != lucards.end(); it++)
                {
                    if ((*it & icards[i]) == icards[i]) count++;
                }
                if (count == 1)
                {
                    std::vector<uint16_t>::iterator it = find(lucards.begin(), lucards.end(), cards[i]);
                    if (it != lucards.end()) lucards.erase(it);
                    icards[i] = 0;
                }
            }
        }
        if (lucards.size() <= 1)
        {
            uint16_t bits = countBits(solution);
            if (bits < min) min = bits;
        }
    }
    return min;
}
Example #12
0
VisualID QEgl::getCompatibleVisualId(EGLConfig config)
{
    VisualID    visualId = 0;
    EGLint      eglValue = 0;

    EGLint configRedSize = 0;
    eglGetConfigAttrib(display(), config, EGL_RED_SIZE, &configRedSize);

    EGLint configGreenSize = 0;
    eglGetConfigAttrib(display(), config, EGL_GREEN_SIZE, &configGreenSize);

    EGLint configBlueSize = 0;
    eglGetConfigAttrib(display(), config, EGL_BLUE_SIZE, &configBlueSize);

    EGLint configAlphaSize = 0;
    eglGetConfigAttrib(display(), config, EGL_ALPHA_SIZE, &configAlphaSize);

    eglGetConfigAttrib(display(), config, EGL_CONFIG_ID, &eglValue);
    int configId = eglValue;

    // See if EGL provided a valid VisualID:
    eglGetConfigAttrib(display(), config, EGL_NATIVE_VISUAL_ID, &eglValue);
    visualId = (VisualID)eglValue;
    if (visualId) {
        // EGL has suggested a visual id, so get the rest of the visual info for that id:
        XVisualInfo visualInfoTemplate;
        memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
        visualInfoTemplate.visualid = visualId;

        XVisualInfo *chosenVisualInfo;
        int matchingCount = 0;
        chosenVisualInfo = XGetVisualInfo(X11->display, VisualIDMask, &visualInfoTemplate, &matchingCount);
        if (chosenVisualInfo) {
            // Skip size checks if implementation supports non-matching visual
            // and config (http://bugreports.qt.nokia.com/browse/QTBUG-9444).
            if (QEgl::hasExtension("EGL_NV_post_convert_rounding")) {
                XFree(chosenVisualInfo);
                return visualId;
            }

            int visualRedSize = countBits(chosenVisualInfo->red_mask);
            int visualGreenSize = countBits(chosenVisualInfo->green_mask);
            int visualBlueSize = countBits(chosenVisualInfo->blue_mask);
            int visualAlphaSize = -1; // Need XRender to tell us the alpha channel size

#if !defined(QT_NO_XRENDER)
            if (X11->use_xrender) {
                // If we have XRender, actually check the visual supplied by EGL is ARGB
                XRenderPictFormat *format;
                format = XRenderFindVisualFormat(X11->display, chosenVisualInfo->visual);
                if (format && (format->type == PictTypeDirect))
                    visualAlphaSize = countBits(format->direct.alphaMask);
            }
#endif

            bool visualMatchesConfig = false;
            if ( visualRedSize == configRedSize &&
                 visualGreenSize == configGreenSize &&
                 visualBlueSize == configBlueSize )
            {
                // We need XRender to check the alpha channel size of the visual. If we don't have
                // the alpha size, we don't check it against the EGL config's alpha size.
                if (visualAlphaSize >= 0)
                    visualMatchesConfig = visualAlphaSize == configAlphaSize;
                else
                    visualMatchesConfig = true;
            }

            if (!visualMatchesConfig) {
                if (visualAlphaSize >= 0) {
                    qWarning("Warning: EGL suggested using X Visual ID %d (ARGB%d%d%d%d) for EGL config %d (ARGB%d%d%d%d), but this is incompatable",
                             (int)visualId, visualAlphaSize, visualRedSize, visualGreenSize, visualBlueSize,
                             configId, configAlphaSize, configRedSize, configGreenSize, configBlueSize);
                } else {
                    qWarning("Warning: EGL suggested using X Visual ID %d (RGB%d%d%d) for EGL config %d (RGB%d%d%d), but this is incompatable",
                             (int)visualId, visualRedSize, visualGreenSize, visualBlueSize,
                             configId, configRedSize, configGreenSize, configBlueSize);
                }
                visualId = 0;
            }
        } else {
            qWarning("Warning: EGL suggested using X Visual ID %d for EGL config %d, but that isn't a valid ID",
                     (int)visualId, configId);
            visualId = 0;
        }
        XFree(chosenVisualInfo);
    }
#ifdef QT_DEBUG_X11_VISUAL_SELECTION
    else
        qDebug("EGL did not suggest a VisualID (EGL_NATIVE_VISUAL_ID was zero) for EGLConfig %d", configId);
#endif

    if (visualId) {
#ifdef QT_DEBUG_X11_VISUAL_SELECTION
        if (configAlphaSize > 0)
            qDebug("Using ARGB Visual ID %d provided by EGL for config %d", (int)visualId, configId);
        else
            qDebug("Using Opaque Visual ID %d provided by EGL for config %d", (int)visualId, configId);
#endif
        return visualId;
    }


    // If EGL didn't give us a valid visual ID, try XRender
#if !defined(QT_NO_XRENDER)
    if (!visualId && X11->use_xrender) {
        XVisualInfo visualInfoTemplate;
        memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));

        visualInfoTemplate.c_class = TrueColor;

        XVisualInfo *matchingVisuals;
        int matchingCount = 0;
        matchingVisuals = XGetVisualInfo(X11->display,
                                         VisualClassMask,
                                         &visualInfoTemplate,
                                         &matchingCount);

        for (int i = 0; i < matchingCount; ++i) {
            XRenderPictFormat *format;
            format = XRenderFindVisualFormat(X11->display, matchingVisuals[i].visual);

            // Check the format for the visual matches the EGL config
            if ( (countBits(format->direct.redMask) == configRedSize) &&
                 (countBits(format->direct.greenMask) == configGreenSize) &&
                 (countBits(format->direct.blueMask) == configBlueSize) &&
                 (countBits(format->direct.alphaMask) == configAlphaSize) )
            {
                visualId = matchingVisuals[i].visualid;
                break;
            }
        }
        if (matchingVisuals)
            XFree(matchingVisuals);

    }
    if (visualId) {
# ifdef QT_DEBUG_X11_VISUAL_SELECTION
        if (configAlphaSize > 0)
            qDebug("Using ARGB Visual ID %d provided by XRender for EGL config %d", (int)visualId, configId);
        else
            qDebug("Using Opaque Visual ID %d provided by XRender for EGL config %d", (int)visualId, configId);
# endif // QT_DEBUG_X11_VISUAL_SELECTION
        return visualId;
    }
# ifdef QT_DEBUG_X11_VISUAL_SELECTION
    else
        qDebug("Failed to find an XVisual which matches EGL config %d using XRender", configId);
# endif // QT_DEBUG_X11_VISUAL_SELECTION

#endif //!defined(QT_NO_XRENDER)


    // Finally, if XRender also failed to find a visual (or isn't present), try to
    // use XGetVisualInfo and only use the bit depths to match on:
    if (!visualId) {
        XVisualInfo visualInfoTemplate;
        memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
        XVisualInfo *matchingVisuals;
        int matchingCount = 0;

        visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize + configAlphaSize;
        matchingVisuals = XGetVisualInfo(X11->display,
                                         VisualDepthMask,
                                         &visualInfoTemplate,
                                         &matchingCount);
        if (!matchingVisuals) {
            // Try again without taking the alpha channel into account:
            visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize;
            matchingVisuals = XGetVisualInfo(X11->display,
                                             VisualDepthMask,
                                             &visualInfoTemplate,
                                             &matchingCount);
        }

        if (matchingVisuals) {
            visualId = matchingVisuals[0].visualid;
            XFree(matchingVisuals);
        }
    }

    if (visualId) {
#ifdef QT_DEBUG_X11_VISUAL_SELECTION
        qDebug("Using Visual ID %d provided by XGetVisualInfo for EGL config %d", (int)visualId, configId);
#endif
        return visualId;
    }

    qWarning("Unable to find an X11 visual which matches EGL config %d", configId);
    return (VisualID)0;
}
Example #13
0
int fixPairs(sudoku* s){
  int* indices;
  int pair;
  int i;
  int row, col;
  int findings=0;
  // pairs in rows?
  for(row=0; row<9; ++row){
    for (i=0; i<36; ++i){
      indices=pairIndices[i];
      if ((s->fields2d[row][indices[0]]==0) &&
	  (s->fields2d[row][indices[1]]==0)){ // TODO: why does this segfault?
	pair=(s->candidates2d[row][indices[0]] | s->candidates2d[row][indices[1]]);
	debugprintf("Row %d, cols %d and %d (%u, %u) have %d candidates in sum:\n", 
	       row, indices[0], indices[1],
	       s->candidates2d[row][indices[0]],
	       s->candidates2d[row][indices[1]], countBits(pair));
	int j;
	for (j=1; j<10; ++j){
	  if ((1u<<j)&pair){
	    debugprintf("%d, ", j);
	  }
	}
	debugprintf("\n");
	if (countBits(pair)==2){
	  debugprintf("Fixing pair in row %d (cols %d, %d)\n", row, indices[0], indices[1]);
	  findings += fixPairInRow(s, row, indices[0], indices[1]);
#if DEBUG==1
	  printCandidates(s);
#endif
	}
      }
    }
  }
  // pairs in columns?
  for(col=0; col<9; ++col){
    for (i=0; i<36; ++i){
      indices=pairIndices[i];
      if ((s->fields2d[indices[0]][col]==0) &&
	  (s->fields2d[indices[1]][col]==0)){ // TODO: why does this segfault?
	pair=(s->candidates2d[indices[0]][col] | s->candidates2d[indices[1]][col]);
	debugprintf("Col %d, rows %d and %d (%u, %u) have %d candidates in sum:\n", 
	       col, indices[0], indices[1],
	       s->candidates2d[indices[0]][col],
	       s->candidates2d[indices[1]][col], countBits(pair));
	int j;
	for (j=1; j<10; ++j){
	  if ((1u<<j)&pair){
	    debugprintf("%d, ", j);
	  }
	}
	debugprintf("\n");
	if (countBits(pair)==2){
	  debugprintf("Fixing pair in col %d (rows %d, %d)\n", col, indices[0], indices[1]);
	  findings += fixPairInCol(s, col, indices[0], indices[1]);
#if DEBUG==1
	  printCandidates(s);
#endif
	}
      }
    }
  }
  // do we need additional rounds?
  if (findings){
    fixPairs(s);
    return 1;
  }
  return 0;
}
Example #14
0
uint8_t AnalogInputs::getConnectedBalancePortCellsCount()
{
     return countBits(connectedBalancePortCells);
}
Example #15
0
int validatePosition(Position *pos) {
	int p, n, squares[64], score = 0;
	bitboard occupied = 0, white = 0, black = 0;
	
	for (n = 0; n < 64; n++) {
		squares[n] = EMPTY;
	}
	
	for (p = WP; p <= BK; p++){
		bitboard pbits;
		pbits = pos->bits[p];
		if (occupied & pbits) {
			printf("Multiple pieces at a single square.\n");
			return 0;
		}
		occupied |= pbits;
		if (p < BP) {
			white |= pbits;
		} else {
			black |= pbits;
		}
		score += VAL[p] * countBits(pbits);
		while (pbits) {
			squares[popBit(&pbits)] = p;
		}
		
	}
	//generate the rest of our bitboards:
	
	if (white != pos->bits[WHITE] || black != pos->bits[BLACK] || occupied != pos->bits[OCCUPIED] || ~occupied != pos->bits[EMPTY]) {
		printf("Incorrect derived bitboards.\n");
		printf("white:\n");
		printBitboard(pos->bits[WHITE]);
		printf("\nblack:\n");
		printBitboard(pos->bits[BLACK]);
		printf("\noccupied:\n");
		printBitboard(pos->bits[OCCUPIED]);
		printf("\nempty:\n");
		printBitboard(pos->bits[EMPTY]);
		return 0;
	}
	
	if (score != pos->score) {
		printf("Incorrect score, expected: %d, actual: %d\n", score, pos->score);
		return 0;
	}
	
	for (n = 0; n < 64; n++) {
		if (squares[n] != pos->squares[n]) {
			printf("Incorrect piece buffer.");
			return 0;
		}
	}
	if (pos->ephash != EPHASH(pos)) {
		printf("Incorrect en passant hash code, expected: %llx, actual: %llx.\n", EPHASH(pos), pos->ephash);
		return 0;
	}
	
	if (pos->hash != hashPosition(pos)) {
		printf("Incorrect hash code, expected: %llx, actual: %llx.\n", hashPosition(pos), pos->hash);
		return 0;
	}
	
	return 1;
}
Example #16
0
VisualID QXlibEglIntegration::getCompatibleVisualId(Display *display, EGLDisplay eglDisplay, EGLConfig config)
{
    VisualID    visualId = 0;
    EGLint      eglValue = 0;

    EGLint configRedSize = 0;
    eglGetConfigAttrib(eglDisplay, config, EGL_RED_SIZE, &configRedSize);

    EGLint configGreenSize = 0;
    eglGetConfigAttrib(eglDisplay, config, EGL_GREEN_SIZE, &configGreenSize);

    EGLint configBlueSize = 0;
    eglGetConfigAttrib(eglDisplay, config, EGL_BLUE_SIZE, &configBlueSize);

    EGLint configAlphaSize = 0;
    eglGetConfigAttrib(eglDisplay, config, EGL_ALPHA_SIZE, &configAlphaSize);

    eglGetConfigAttrib(eglDisplay, config, EGL_CONFIG_ID, &eglValue);
    int configId = eglValue;

    // See if EGL provided a valid VisualID:
    eglGetConfigAttrib(eglDisplay, config, EGL_NATIVE_VISUAL_ID, &eglValue);
    visualId = (VisualID)eglValue;
    if (visualId) {
        // EGL has suggested a visual id, so get the rest of the visual info for that id:
        XVisualInfo visualInfoTemplate;
        memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
        visualInfoTemplate.visualid = visualId;

        XVisualInfo *chosenVisualInfo;
        int matchingCount = 0;
        chosenVisualInfo = XGetVisualInfo(display, VisualIDMask, &visualInfoTemplate, &matchingCount);
        if (chosenVisualInfo) {
            // Skip size checks if implementation supports non-matching visual
            // and config (http://bugreports.qt-project.org/browse/QTBUG-9444).
            if (q_hasEglExtension(eglDisplay,"EGL_NV_post_convert_rounding")) {
                XFree(chosenVisualInfo);
                return visualId;
            }

            int visualRedSize = countBits(chosenVisualInfo->red_mask);
            int visualGreenSize = countBits(chosenVisualInfo->green_mask);
            int visualBlueSize = countBits(chosenVisualInfo->blue_mask);
            int visualAlphaSize = -1; // Need XRender to tell us the alpha channel size

            bool visualMatchesConfig = false;
            if ( visualRedSize == configRedSize &&
                 visualGreenSize == configGreenSize &&
                 visualBlueSize == configBlueSize )
            {
                // We need XRender to check the alpha channel size of the visual. If we don't have
                // the alpha size, we don't check it against the EGL config's alpha size.
                if (visualAlphaSize >= 0)
                    visualMatchesConfig = visualAlphaSize == configAlphaSize;
                else
                    visualMatchesConfig = true;
            }

            if (!visualMatchesConfig) {
                if (visualAlphaSize >= 0) {
                    qWarning("Warning: EGL suggested using X Visual ID %d (ARGB%d%d%d%d) for EGL config %d (ARGB%d%d%d%d), but this is incompatable",
                             (int)visualId, visualAlphaSize, visualRedSize, visualGreenSize, visualBlueSize,
                             configId, configAlphaSize, configRedSize, configGreenSize, configBlueSize);
                } else {
                    qWarning("Warning: EGL suggested using X Visual ID %d (RGB%d%d%d) for EGL config %d (RGB%d%d%d), but this is incompatable",
                             (int)visualId, visualRedSize, visualGreenSize, visualBlueSize,
                             configId, configRedSize, configGreenSize, configBlueSize);
                }
                visualId = 0;
            }
        } else {
            qWarning("Warning: EGL suggested using X Visual ID %d for EGL config %d, but that isn't a valid ID",
                     (int)visualId, configId);
            visualId = 0;
        }
        XFree(chosenVisualInfo);
    }
#ifdef QT_DEBUG_X11_VISUAL_SELECTION
    else
        qDebug("EGL did not suggest a VisualID (EGL_NATIVE_VISUAL_ID was zero) for EGLConfig %d", configId);
#endif

    if (visualId) {
#ifdef QT_DEBUG_X11_VISUAL_SELECTION
        if (configAlphaSize > 0)
            qDebug("Using ARGB Visual ID %d provided by EGL for config %d", (int)visualId, configId);
        else
            qDebug("Using Opaque Visual ID %d provided by EGL for config %d", (int)visualId, configId);
#endif
        return visualId;
    }

    // Finally, try to
    // use XGetVisualInfo and only use the bit depths to match on:
    if (!visualId) {
        XVisualInfo visualInfoTemplate;
        memset(&visualInfoTemplate, 0, sizeof(XVisualInfo));
        XVisualInfo *matchingVisuals;
        int matchingCount = 0;

        visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize + configAlphaSize;
        matchingVisuals = XGetVisualInfo(display,
                                         VisualDepthMask,
                                         &visualInfoTemplate,
                                         &matchingCount);
        if (!matchingVisuals) {
            // Try again without taking the alpha channel into account:
            visualInfoTemplate.depth = configRedSize + configGreenSize + configBlueSize;
            matchingVisuals = XGetVisualInfo(display,
                                             VisualDepthMask,
                                             &visualInfoTemplate,
                                             &matchingCount);
        }

        if (matchingVisuals) {
            visualId = matchingVisuals[0].visualid;
            XFree(matchingVisuals);
        }
    }

    if (visualId) {
#ifdef QT_DEBUG_X11_VISUAL_SELECTION
        qDebug("Using Visual ID %d provided by XGetVisualInfo for EGL config %d", (int)visualId, configId);
#endif
        return visualId;
    }

    qWarning("Unable to find an X11 visual which matches EGL config %d", configId);
    return (VisualID)0;
}
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

  // Print settings
  printf("SETTINGS\nAnalyze output from new Analyzer\n");
  printf("Input file = %s\n",fileIn);
  printf("School distance = %f m, angle = %f deg\n",distance,angle);
  printf("School orientation: tel1=%f deg, tel2=%f deg\n",phi1Corr,phi2Corr);
  printf("Max Chi2 = %f\n",maxchisquare);
  printf("Theta Rel Range = %f - %f deg\n",minthetarel,maxthetarel);
  printf("Range for N sattellite in each run = (tel1) %f - %f, (tel2) %f - %f \n",minAvSat[0],maxAvSat[0],minAvSat[1],maxAvSat[1]);
  printf("Min N satellite in a single event = %i\n",satEventThr);

  Int_t adayMin = (yearRange[0]-2014) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2014) * 1000 + monthRange[1]*50 + dayRange[1];

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

  // define some histos
  TH1F *hDeltaTheta = new TH1F("hDeltaTheta","#Delta#theta below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi = new TH1F("hDeltaPhi","#Delta#phi below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack = new TH1F("hDeltaThetaBack","#Delta#theta out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack = new TH1F("hDeltaPhiBack","#Delta#phi out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel = new TH1F("hThetaRel","#theta_{rel} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack = new TH1F("hThetaRelBack","#theta_{rel} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH2F *hAngle = new TH2F("hAngle",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);
  TH2F *hAngleBack = new TH2F("hAngleBack",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);

  TProfile *hModulation = new  TProfile("hModulation","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulation2 = new  TProfile("hModulation2","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAv = new  TProfile("hModulationAv","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAvCorr = new  TProfile("hModulationAvCorr","#theta^{rel} < 10#circ;#phi - #alpha;diff (ns)",50,0,360);

  TH1F *hnsigpeak = new TH1F("hnsigpeak","",50,0,360);
  TH1F *hnbackpeak = new TH1F("hnbackpeak","",50,0,360);

  TProfile *hSinTheta = new  TProfile("hSinTheta",";#phi - #alpha;sin(#theta)",50,0,360);
  TProfile *hSinTheta2 = new  TProfile("hSinTheta2",";#phi - #alpha;sin(#theta)",50,0,360);

  TH1F *hRunCut[2];
  hRunCut[0] = new TH1F("hRunCut1","Reason for Run Rejection Tel-1;Reason;runs rejected",11,0,11);
  hRunCut[1] = new TH1F("hRunCut2","Reason for Run Rejection Tel-2;Reason;runs rejected",11,0,11);

  for(Int_t i=0;i<2;i++){
    hRunCut[i]->Fill("DateRange",0);
    hRunCut[i]->Fill("LowFractionGT",0);
    hRunCut[i]->Fill("TimeDuration",0);
    hRunCut[i]->Fill("rateGT",0);
    hRunCut[i]->Fill("RunNumber",0);
    hRunCut[i]->Fill("MissingHitFrac",0);
    hRunCut[i]->Fill("DeadStripBot",0);
    hRunCut[i]->Fill("DeadStripMid",0);
    hRunCut[i]->Fill("DeadStripTop",0);
    hRunCut[i]->Fill("NSatellites",0);
    hRunCut[i]->Fill("NoGoodWeather",0);  
  }

  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[2];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");

  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  const Int_t nyearmax = 5;
  Bool_t runstatus[2][nyearmax][12][31][500]; //#telescope, year-2014, month, day, run
  Float_t effTel[2][nyearmax][12][31][500];
  Int_t nStripDeadBot[2][nyearmax][12][31][500];
  Int_t nStripDeadMid[2][nyearmax][12][31][500];
  Int_t nStripDeadTop[2][nyearmax][12][31][500];

  Float_t nstripDeadB[2]={0,0},nstripDeadM[2]={0,0},nstripDeadT[2]={0,0};

  // sat info
  Float_t NsatAv[2][nyearmax][12][31][500];

  // weather info
  Float_t pressureTel[2][nyearmax][12][31][500];
  Float_t TempInTel[2][nyearmax][12][31][500];
  Float_t TempOutTel[2][nyearmax][12][31][500];
  Float_t timeWeath[2][nyearmax][12][31][500];

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

  if(tel[0] && tel[1]){
    for(Int_t i=0;i < 2;i++){ // loop on telescopes
      printf("Tel-%i\n",i+1);
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	rateGT = tel[i]->GetLeaf("FractionGoodTrack")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue();

	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2014) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

        if(i==1) printf("%f %f\n",rateGT , rateMin[i]);

	if(aday < adayMin || aday > adayMax){
	  hRunCut[i]->Fill("DateRange",1); continue;}
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]){
	  hRunCut[i]->Fill("LowFractionGT",1); continue;} // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]){
	  hRunCut[i]->Fill("TimeDuration",1); continue;} // cut on the number of event
	if(rateGT < rateMin[i] || rateGT > rateMax[i]){
	  hRunCut[i]->Fill("rateGT",1); continue;} // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499){
	  hRunCut[i]->Fill("RunNumber",1); continue;} // run < 500

        if(i==1) printf("GR\n");

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]){
	  hRunCut[i]->Fill("MissingHitFrac",1); continue;}
		
	// active strip maps
	if(tel[i]->GetLeaf("maskB")) nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskB")->GetValue()));
	if(tel[i]->GetLeaf("maskM")) nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskM")->GetValue()));
	if(tel[i]->GetLeaf("maskT")) nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskT")->GetValue()));

	if(nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadBotMax[i] || nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadBotMin[i]) {
	  hRunCut[i]->Fill("DeadStripBot",1); continue;}
	if(nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadMidMax[i] || nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadMidMin[i]){
	  hRunCut[i]->Fill("DeadStripMid",1); continue;}
	if(nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadTopMax[i] || nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadTopMin[i]){
	  hRunCut[i]->Fill("DeadStripTop",1); continue;}
     
	// nsat averaged  per run
	if(tel[i]->GetLeaf("nSat")) NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("nSat")->GetValue();


	if(NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minAvSat[i] || NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxAvSat[i]){
	 hRunCut[i]->Fill("NSatellites",1); continue;}

	// weather info
	if(tel[i]->GetLeaf("Pressure")) pressureTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("Pressure")->GetValue();
	if(tel[i]->GetLeaf("IndoorTemperature")) TempInTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("IndoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("OutdoorTemperature")) TempOutTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("OutdoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("TimeWeatherUpdate")) timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("TimeWeatherUpdate")->GetValue();

	if(timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minWeathTimeDelay[i] ||  timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxWeathTimeDelay[i]){ hRunCut[i]->Fill("NoGoodWeather",1); continue;	}

	// Set good runs
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	effTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = 1;//rateGT/refRate[i];

      }
    }
  }
  else{
    telC = NULL;
  }

  printf("Start to process correlations\n");
  Int_t n = t->GetEntries();
  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
      nstripDeadB[0] += countBits(nStripDeadBot[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[0] += countBits(nStripDeadMid[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[0] += countBits(nStripDeadTop[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();

      nstripDeadB[1] += countBits(nStripDeadBot[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[1] += countBits(nStripDeadMid[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[1] += countBits(nStripDeadTop[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
    }
    nstripDeadB[0] /= nsecGR;
    nstripDeadM[0] /= nsecGR;
    nstripDeadT[0] /= nsecGR;

    nstripDeadB[1] /= nsecGR;
    nstripDeadM[1] /= nsecGR;
    nstripDeadT[1] /= nsecGR;

    printf("Dead channel tel1 = %f - %f - %f\n",nstripDeadB[0],nstripDeadM[0],nstripDeadT[0]);
    printf("Dead channel tel2 = %f - %f - %f\n",nstripDeadB[1],nstripDeadM[1],nstripDeadT[1]);
  }
  
  char title[300];
  TH1F *h;
  
  sprintf(title,"correction assuming #Delta#phi = %4.2f, #DeltaL = %.1f m;#Deltat (ns);entries",angle,distance);
  
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  
  Float_t DeltaT;
  Float_t phiAv,thetaAv,corr;
  
  Float_t Theta1,Theta2;
  Float_t Phi1,Phi2;
  Int_t nsatel1cur,nsatel2cur,ntrack1,ntrack2;

  Float_t v1[3],v2[3],vSP; // variable to recompute ThetaRel on the fly
  Float_t eff = 1; 
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499)) continue;
  
    if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;


    eff = effTel[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())];
    eff *= effTel[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())];
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
    }
    }

    Float_t thetarel = t->GetLeaf("ThetaRel")->GetValue();
    Theta1 = (t->GetLeaf("Theta1")->GetValue())*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    
    nsatel1cur = t->GetLeaf("Nsatellite1")->GetValue();
    nsatel2cur = t->GetLeaf("Nsatellite2")->GetValue();
    ntrack1 = t->GetLeaf("Ntracks1")->GetValue();
    ntrack2 = t->GetLeaf("Ntracks2")->GetValue();

    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 += phi1Corr*TMath::DegToRad();
      Phi2 += phi2Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      
      v1[0] *= v2[0];
      v1[1] *= v2[1];
      v1[2] *= v2[2];
      
      vSP = v1[0] + v1[1] + v1[2];
      
      thetarel = TMath::ACos(vSP)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel < minthetarel) continue;
    if(thetarel > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    

    neventsGR++;

    // reject events with not enough satellites
    if(nsatel1cur < satEventThr || nsatel1cur < satEventThr) continue;

    neventsGRandSat++;
    
    DeltaT = t->GetLeaf("DiffTime")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();

    thetaAv = (Theta1+Theta2)*0.5;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    Float_t resFactor = 1;
    if(thetarel > 10 ) resFactor *= 0.5;
    if(thetarel > 20 ) resFactor *= 0.5;
    if(thetarel > 30 ) resFactor *= 0.5;

    corr = distance * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle)/2.99792458000000039e-01 + deltatCorr;

    phirelative = (Phi1-angle)*TMath::RadToDeg();
    if(phirelative < 0) phirelative += 360;
    if(phirelative < 0) phirelative += 360;
    if(phirelative > 360) phirelative -= 360;
    if(phirelative > 360) phirelative -= 360;

    phirelative2 = (Phi2-angle)*TMath::RadToDeg();
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 > 360) phirelative2 -= 360;
    if(phirelative2 > 360) phirelative2 -= 360;

    phirelativeAv = (phiAv-angle)*TMath::RadToDeg();
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;


    // if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
      
    // }

    if(thetarel < 10){//cos(thetarel*TMath::DegToRad())>0.98 && sin(thetaAv)>0.1){
      if(TMath::Abs(DeltaT- corr) < windowAlignment)
	hModulationAvCorr->Fill(phirelativeAv,DeltaT-corr);
      if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
	hModulation->Fill(phirelative,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulation2->Fill(phirelative2,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulationAv->Fill(phirelativeAv,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hSinTheta->Fill(phirelative,sin(thetaAv));
	hSinTheta2->Fill(phirelative2,sin(thetaAv));
	nsigPeak++;
	hnsigpeak->Fill(phirelativeAv);
      }
      else if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment*10){
	nbackPeak++;
	hnbackpeak->Fill(phirelativeAv);
      }
    }

    h->Fill(DeltaT-corr,1./eff);
    if(TMath::Abs(DeltaT-corr) < windowAlignment){
      hDeltaTheta->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel->Fill(thetarel);
      hAngle->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
    else if(TMath::Abs(DeltaT-corr) > windowAlignment*2 && TMath::Abs(DeltaT-corr) < windowAlignment*12){
      hDeltaThetaBack->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack->Fill(thetarel);
      hAngleBack->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
  }
  
  // compute (S+B)/S
  for(Int_t i=1;i<=50;i++){
    Float_t corrfactorPeak = 1;
    if(nsigPeak-nbackPeak*0.1 > 0)
      corrfactorPeak = hnsigpeak->GetBinContent(i)/(hnsigpeak->GetBinContent(i)-hnbackpeak->GetBinContent(i)*0.1);
    else
      printf("bin %i) not enough statistics\n",i);
    hnsigpeak->SetBinContent(i,corrfactorPeak);
  }

  TF1 *fpol0 = new TF1("fpol0","pol0");
  hnsigpeak->Fit(fpol0);

  hModulation->Scale(fpol0->GetParameter(0));
  hModulation2->Scale(fpol0->GetParameter(0));
  hModulationAv->Scale(fpol0->GetParameter(0));
  hModulationAvCorr->Scale(fpol0->GetParameter(0));
  
  TF1 *fmod = new TF1("fmod","[0] + [1]*cos((x-[2])*TMath::DegToRad())"); 
  hModulationAv->Fit(fmod); 

  printf("Estimates from time delay: Distance = %f +/- %f m -- Angle = %f +/- %f deg\n",fmod->GetParameter(1),fmod->GetParError(1),fmod->GetParameter(2),fmod->GetParError(2));

  h->SetStats(0);

  hDeltaThetaBack->Sumw2();
  hDeltaPhiBack->Sumw2();
  hThetaRelBack->Sumw2();
  hDeltaThetaBack->Scale(0.1);
  hDeltaPhiBack->Scale(0.1);
  hThetaRelBack->Scale(0.1);
  hAngleBack->Scale(0.1);
  hAngle->Add(hAngleBack,-1);

  printf("bin counting: SIGNAL = %f +/- %f\n",hDeltaPhi->Integral()-hDeltaPhiBack->Integral(),sqrt(hDeltaPhi->Integral()));
  rate = (hDeltaPhi->Integral()-hDeltaPhiBack->Integral())/nsecGR*86400;
  rateErr = sqrt(hDeltaPhi->Integral())/nsecGR*86400;


  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,maxwidth);
  ff->SetParameter(2,350); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,(tmax-tmin)/nbint); // bin width

  ff->SetNpx(1000);
  
  if(cout) cout->cd();
  h->Fit(ff,"EI","",-10000,10000);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  new TCanvas;

  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  // correct nsecGR for the event rejected because of the number of satellites (event by event cut)
  nsecGR *= neventsGRandSat/neventsGR;

  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("outputCERN-01-02.root","RECREATE");
  h->Write();
  hDeltaTheta->Write();
  hDeltaPhi->Write();
  hThetaRel->Write();
  hDeltaThetaBack->Write();
  hDeltaPhiBack->Write();
  hThetaRelBack->Write();
  hAngle->Write();
  hModulation->Write();
  hModulation2->Write();
  hModulationAv->Write();
  hModulationAvCorr->Write();
  hSinTheta->Write();
  hSinTheta2->Write();
  hnsigpeak->Write();
  hRunCut[0]->Write();
  hRunCut[1]->Write();
  fo->Close();

  return nsecGR*1./86400;
  
}
Example #18
0
File: eval.cpp Project: mkd/chess0x
/*!
 * Evaluate the current board taking in account only the position.
 *
 * @return a float with a positive number for white leading, negative number for
 *         black leading and 0.0 for an equal situation.
 */
int evalPosition()
{
    int est = 0;
    ColorType myColor = COLOR_TYPE_NONE;


    // Add mobility bonus to each piece, according to their number of moves.
    est += countBits(getAllAttacks(COLOR_TYPE_WHITE)) / 2;
    est -= countBits(getAllAttacks(COLOR_TYPE_BLACK)) / 2;


    /*!
     * Loop through the whole board and check every piece, their position and
     * their influence in the game.
     *
     * Note: is there a faster way to do this?
     */
    for (unsigned short i = 0; i < 64; i++)
    {
        // skip empty squares
        if (board[i] == 0)
            continue;

        // store color of the piece we are looking at
        if ((board[i] / Abs(board[i])) == 1)
            myColor = COLOR_TYPE_WHITE;
        else
            myColor = COLOR_TYPE_BLACK;


        // positional values to each piece (depending on the square)
        switch (board[i])
        {
            case PIECE_PAWN:    est += quanta_WP[i];
                                break;

            case -PIECE_PAWN:   est += quanta_BP[i];
                                break;

            case PIECE_KNIGHT:  est += quanta_WN[i];
                                break;

            case -PIECE_KNIGHT: est += quanta_BN[i];
                                break;

            case PIECE_BISHOP:  est += quanta_WB[i];
                                break;

            case -PIECE_BISHOP: est += quanta_BB[i];
                                break;

            case PIECE_ROOK:    est += quanta_WR[i];
                                break;

            case -PIECE_ROOK:   est += quanta_BR[i];
                                break;

            case PIECE_QUEEN:   est += quanta_WQ[i];
                                break;

            case -PIECE_QUEEN:  est += quanta_BQ[i];
                                break;

            case PIECE_KING:    if (phase == PHASE_TYPE_END)
                                    est += quanta_WZ[i];
                                else
                                    est += quanta_WK[i];
                                break;

            case -PIECE_KING:   if (phase == PHASE_TYPE_END)
                                    est += quanta_BZ[i];
                                else
                                    est += quanta_BK[i];
                                break;

            default: est += 0;
        }


        /*!
         * Evaluate Kings:
         * 1) King safety
         * 2) XXX
         */
        if (Abs(board[i]) == PIECE_KING)
        {
            /*!
             * See if any king is castled and where. Save it for the code below
             * to use it.
             */
            int tCastle;
            if (board[i] == PIECE_KING)
                tCastle = wCastle;
            else
                tCastle = bCastle;


            /*!
             * 1) King safety
             *
             * Verify the king safety, meaning castling and castle pawn
             * structure.
             */
            if (tCastle && (phase != PHASE_TYPE_END))
            {
                Bitboard kSide;
                Bitboard tPawns;
                unordered_map<string, Bitboard> tKingSafeMask;

                // king shield, -0.10 for 1-square pawn move, -0.40 farther
                if (board[i] == PIECE_KING)
                {
                    kSide = wKing;
                    tPawns = wPawn;
                    tKingSafeMask = wKingSafeMask;
                }
                else
                {
                    kSide = bKing;
                    tPawns = bPawn;
                    tKingSafeMask = bKingSafeMask;
                }

                unsigned short s1Pawns = 0;
                unsigned short sxPawns = 0;
                unsigned short l1Pawns = 0;
                unsigned short lxPawns = 0;

                // short castle
                if (kSide & shortCastleMask)
                {
                    if (tPawns & tKingSafeMask["s1"])
                    {
                        s1Pawns = countBits(tPawns & tKingSafeMask["s1"]);
                        est -= 10 * s1Pawns * myColor;
                    }

                    sxPawns = countBits(tPawns & tKingSafeMask["sx"]);
                    if (sxPawns < 3)
                    {
                        est -= 40 * (3 - sxPawns - s1Pawns) * myColor;
                    }
                }
                    
                // long castle
                else
                {
                    if (tPawns & tKingSafeMask["l1"])
                    {
                        l1Pawns = countBits(tPawns & tKingSafeMask["l1"]);
                        est -= 10 * l1Pawns * myColor;
                    }

                    lxPawns = countBits(tPawns & tKingSafeMask["lx"]);
                    if (lxPawns < 3)
                    {
                        est -= 40 * (3- lxPawns - l1Pawns) * myColor;
                    }
                }
            }

          
            // penalty for king on open file: -0.20
            if (!(fileMask[File(i) + 'a'] & (wPawn | bPawn)))
                est += 20 * myColor;


            // king with very low mobility: -0.10
            if (getKingAttacks(i, myColor) == 0)
                est -= 10 * myColor;


            // castled kings: +0.40
            if (tCastle)
                est += 40 * myColor;


            // king has moved without castling: -0.40
            else if ((myColor == COLOR_TYPE_WHITE) && !(wCK | wCQ))
                est -= 40;
            else if ((myColor == COLOR_TYPE_BLACK) && !(bCK | bCQ))
                est += 40;


            // king at opening prefers first rank, penalty for other ranks: -0.15 per higher rank
            if (phase == PHASE_TYPE_OPENING)
                est -= (Rank(i) - 1) * 0.15 * myColor;


            // king under check (midgame / endgame): -0.75 / -0.10
            if (phase == PHASE_TYPE_END)
                est -= 10 * check;
            else
                est -= 50 * check;
        }


        // QUEENS
        else if ((Abs(board[i]) == PIECE_QUEEN) && (phase == PHASE_TYPE_OPENING))
        {
            // moved queen in opening: -0.10 * times moved
            est -= 10 * wQueenMoves;
            est += 10 * bQueenMoves;
        }


        // ROOKS
        else if (Abs(board[i]) == PIECE_ROOK)
        {
            // reward for rooks on open file: +0.20
            if (!(fileMask[File(i) + 'a'] & (wPawn | bPawn)))
            {
                //cout << "Rook at " << i << " is on open file!" << endl;
                est += 20 * myColor;
            }
        }

    
        /*!
         * Bisohps at the end are more worthy: +0.10
         */
        else if ((Abs(board[i]) == PIECE_BISHOP) && (phase == PHASE_TYPE_END))
        {
            if (board[i] == PIECE_BISHOP)
                est += 10;
            else
                est -= 10;
        }
        
        
        /*!
         * Knights at the end are less worthy: -0.10
         */
        else if ((Abs(board[i]) == PIECE_KNIGHT) && (phase == PHASE_TYPE_END))
        {
            if (board[i] == PIECE_KNIGHT)
                est -= 10;
            else
                est += 10;
        }
    }


    /*!
     * White's pawn structures
     */
    // doubled pawns: -0.16
    for (char i = 'a'; i < 'i'; i++)
        if (countBits(wPawn & fileMask[i + 'a']) > 1)
            est -= 16;

    /*!
     * isolated pawns: -0.20
     * passed pawns: +0.50
     * rook pawns: -0.15
     */
    unsigned short aPawns = countBits(fileMask['a'] & wPawn);
    unsigned short hPawns = countBits(fileMask['h'] & wPawn);

    // rook pawns
    if (aPawns)
    {
        est -= 15 * aPawns;

        // isolated pawn
        if ((fileMask['b'] & wPawn) == 0)
            est -= 20 * aPawns;

        // passed pawn
        if (((fileMask['a'] & bPawn) == 0) &&
            ((fileMask['b'] & bPawn) == 0))
            est += 50 * aPawns;
    }

    if (hPawns)
    {
        est -= 15 * hPawns;

        // isolated pawn
        if ((fileMask['g'] & wPawn) == 0)
            est -= 20 * hPawns;

        // passed pawn
        if (((fileMask['h'] & bPawn) == 0) &&
            ((fileMask['g'] & bPawn) == 0))
            est += 50 * hPawns;
    }


    // rest of files
    for (unsigned short file = 'b'; file < 'h'; file++)
    {
        unsigned short fPawns = countBits(file & wPawn);

        // isolated pawn
        if (((fileMask[file - 1] & wPawn) == 0) &&
            ((fileMask[file + 1] & wPawn) == 0))
            est -= 20 * fPawns;

        // passed pawn
        if (((fileMask[file] & bPawn) == 0) &&
            ((fileMask[file - 1] & bPawn) == 0) &&
            ((fileMask[file + 1] & bPawn) == 0))
            est += 50 * fPawns;
    }


    /*!
     * Blacks's pawn structures
     */
    // doubled pawns: -0.16
    for (char i = 'a'; i < 'i'; i++)
        if (countBits(bPawn & fileMask[i + 'a']) > 1)
            est += 16;

    /*!
     * isolated pawns: -0.20
     * passed pawns: +0.50
     * rook pawns: -0.15
     */
    unsigned short baPawns = countBits(fileMask['a'] & bPawn);
    unsigned short bhPawns = countBits(fileMask['h'] & bPawn);

    // rook pawns
    if (baPawns)
    {
        est += 15 * baPawns;

        // isolated pawn
        if ((fileMask['b'] & bPawn) == 0)
            est += 20 * baPawns;

        // passed pawn
        if (((fileMask['a'] & wPawn) == 0) &&
            ((fileMask['b'] & wPawn) == 0))
            est -= 50 * baPawns;
    }

    if (bhPawns)
    {
        est += 15 * bhPawns;

        // isolated pawn
        if ((fileMask['g'] & bPawn) == 0)
            est += 20 * bhPawns;

        // passed pawn
        if (((fileMask['h'] & wPawn) == 0) &&
            ((fileMask['g'] & wPawn) == 0))
            est -= 50 * bhPawns;
    }


    // rest of files
    for (unsigned short file = 'b'; file < 'h'; file++)
    {
        unsigned short bfPawns = countBits(file & bPawn);

        // isolated pawn
        if (((fileMask[file - 1] & bPawn) == 0) &&
            ((fileMask[file + 1] & bPawn) == 0))
            est += 20 * bfPawns;

        // passed pawn
        if (((fileMask[file] & wPawn) == 0) &&
            ((fileMask[file - 1] & wPawn) == 0) &&
            ((fileMask[file + 1] & wPawn) == 0))
            est -= 50 * bfPawns;
    }


    /*!
     * Bonus for tempo: add bonus to moving player: +0.10
     */
    est += 10 * sideToMove;


    /*!
     * Pair of bishops is more worthy: +0.10
     */
    if (countBits(wBishop) > 1)
        est += 10;
    if (countBits(bBishop) > 1)
        est -= 10;


    // default: position doesn't count
    return est;
    
}
Example #19
0
void printRTC(uint8_t digits)
{
	// 8 chars, X decimal points, and \0 at the end
	static char str[BUF_SIZE];
	uint8_t cnt = 0;

	uint8_t bits = countBits(digits);

	uint8_t i;

menu_loop:

	switch (bits)
	{
	case 8:
		switch (rtcMenu.state)
		{
		case ddd_hhmm:
			sprintf(str, "%s %02d.%02d", dow[date.dow], date.hour, date.minute);
			break;
		case DD_MM_YY:
			sprintf(str, "%02d-%02d-%02d", date.day, date.month, date.year % 100);
			break;
		case hhmmss:
			sprintf(str, "  %02d.%02d.%02d", date.hour, date.minute, date.second);
			break;
			/*case dd_hhmm:
				sprintf(str, " %c%c %02d.%02d", DOW(date.dow)[0], DOW(date.dow)[1], date.hour, date.minute);
				break;*/
			/*case DDMMYY:
				sprintf(str, "  %02d.%02d.%02d", date.day, date.month, date.year % 100);
				break;*/
			/*case hhmm:
				sprintf(str, "    %02d.%02d", date.hour, date.minute);
				break;
			case DDMM:
				sprintf(str, "    %02d.%02d", date.day, date.month);
				break;*/
		default:
			i = BUF_SIZE;
			while (--i)
				str[i-1] = '\0';
			break;
		}
		break;
	case 6 ... 7:
		switch (rtcMenu.state)
		{
		case hhmmss:
			sprintf(str, "%02d.%02d.%02d", date.hour, date.minute, date.second);
			break;
		case dd_hhmm:
			sprintf(str, "%c%c %02d.%02d", DOW(date.dow)[0], DOW(date.dow)[1], date.minute, date.second);
			break;
		case DDMMYY:
			sprintf(str, "%02d.%02d.%02d", date.day, date.month, date.year % 100);
			break;
			/*case hhmm:
				sprintf(str, "  %02d.%02d", date.hour, date.minute);
				break;
			case DDMM:
				sprintf(str, "  %02d.%02d", date.day, date.month);
				break;*/
		default:
			i = BUF_SIZE;
			while (--i)
				str[i - 1] = '\0';
			break;
		}
		break;
	case 4 ... 5:
		switch (rtcMenu.state)
		{
		case hhmm:
			sprintf(str, "%02d.%02d", date.hour, date.minute);
			break;
		case DDMM:
			sprintf(str, "%02d.%02d", date.day, date.month);
			break;
		default:
			i = BUF_SIZE;
			while (--i)
				str[i - 1] = '\0';
			break;
		}
		break;
	case 3:
		switch (rtcMenu.state)
		{
		case ddd:
			sprintf(str, "%02d.%02d", date.hour, date.minute);
			break;
		}
		break;
	case 2:
		switch (rtcMenu.state)
		{
		case dd:
			sprintf(str, "%c%c", date.hour, date.minute);
			break;
		default:
			i = BUF_SIZE;
			while (--i)
				str[i - 1] = '\0';
			break;
		}
		break;
	case 0 ... 1:
		sprintf(str, "    ");
		break;
	}
	if (*str == 0)
	{
		cnt++;
		advState();
		if (cnt < DATEVIEWS)
		{
			goto menu_loop;
		}
		else
		{
			sprintf(str, "ERR");
		}
	}

	writeString(digits, str);
	screen.changed |= digits;
}
Example #20
0
uint8_t AnalogInputs::getConnectedBalancePortsCount()
{
     return countBits(getConnectedBalancePorts());
}