int CMRF2::GetFactors( int numberOfNodes, const int *nodes,
                      pFactorVector *params ) const
{
    /* bad-args check */
    PNL_CHECK_RANGES( numberOfNodes, 1, 2 );
    PNL_CHECK_IS_NULL_POINTER(nodes);
    PNL_CHECK_IS_NULL_POINTER(params);
    /* bad-args check end */
    
    params->clear();
    
    int       numOfClqsFrstNode;
    const int *clqsFrstNode;
    
    GetClqsNumsForNode( *nodes, &numOfClqsFrstNode, &clqsFrstNode );
    
    if( numberOfNodes == 1 )
    {
        const int *clqsIt = clqsFrstNode,
            *clqs_end = clqsFrstNode + numOfClqsFrstNode;
        
        for( ; clqs_end - clqsIt; ++clqsIt )
        {
            params->push_back(GetFactor(*clqsIt));
        }
    }
    else
    {
        int       numOfClqsScndNode;
        const int *clqsScndNode;
        
        GetClqsNumsForNode( *(nodes + 1), &numOfClqsScndNode, &clqsScndNode );
        
        const int *pClqNum = std::find_first_of( clqsFrstNode,
            clqsFrstNode + numOfClqsFrstNode, clqsScndNode,
            clqsScndNode + numOfClqsScndNode );
        
        if( pClqNum == clqsFrstNode + numOfClqsFrstNode )
        {
            return 0;
        }
        
        params->push_back(GetFactor(*pClqNum));
    }
    
    assert( params->size() != 0 );
    
    return 1;
}
Beispiel #2
0
// =============================================================================
void WrapSpaceN(double *X, const mwSize Step, const mwSize nX, const mwSize nDX,
                double *Space, double *Y)
{
  // Call different methods depending of the dimensions ofthe input.
  // X has more than 1 vector. Therefore precalculating the spacing factors is
  // cheaper.
  
  double *Factor;
  
  // Precalculate spacing factors:
  if ((Factor = (double *) mxMalloc(nDX * sizeof(double))) == NULL) {
     mexErrMsgIdAndTxt(ERR_ID   "NoMemory",
                       ERR_HEAD "No memory for Factor vector.");
  }
  GetFactor(Space, nDX, Factor);
  
  if (Step == 1) {   // Operate on 1st dimension:
     CoreDim1FactorN(X, nX, nDX, Factor, Y);
  } else {           // Operate on any dimension:
     CoreDimNFactorN(X, Step, nX, nDX, Factor, Y);
  }
  
  mxFree(Factor);
     
  return;
}
float CMNet::ComputeLogLik( const CEvidence *pEv ) const
{

    if( GetModelDomain() != pEv->GetModelDomain() )
    {
        PNL_THROW(CBadArg, "different model domain")
    }
    int nnodes = GetGraph()->GetNumberOfNodes();
    int nObsNodes = pEv->GetNumberObsNodes();
    if( nObsNodes != nnodes )
    {
        PNL_THROW(CNotImplemented, "all nodes must be observed")
    }

    const int* flags = pEv->GetObsNodesFlags();
    if( std::find( flags, flags + nnodes, 0 ) != flags + nnodes )
    {
        PNL_THROW( CNotImplemented, "all nodes must be observed" )
    }

    float ll = 0.0f;
    int i;
    for( i = 0; i < GetNumberOfCliques(); i++ )
    {
        ll += GetFactor( i )->GetLogLik( pEv );
    }
    return ll;
}
Beispiel #4
0
bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
                      , const vector<FactorType> &inputFactor) const
{
  const size_t subSize = subPhraseVector.size()
                         ,thisSize= GetSize();
  if (subSize > thisSize)
    return false;

  // try to match word-for-word
  for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
    bool match = true;

    for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
      FactorType factorType = inputFactor[currFactorIndex];
      for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
        size_t currThisPos = currSubPos + currStartPos;
        const string &subStr	= subPhraseVector[currSubPos][currFactorIndex];
        StringPiece thisStr	= GetFactor(currThisPos, factorType)->GetString();
        if (subStr != thisStr) {
          match = false;
          break;
        }
      }
      if (!match)
        break;
    }

    if (match)
      return true;
  }
  return false;
}
int CMNet::GetFactors( int numberOfNodes, const int *nodes,
		               pFactorVector *params ) const
{
    // the function is to find all the factors which are set on
	// the domains	which contain "nodes" as a subset

	// bad-args check
    PNL_CHECK_LEFT_BORDER( numberOfNodes, 1 );
    PNL_CHECK_IS_NULL_POINTER(nodes);
    PNL_CHECK_IS_NULL_POINTER(params);
	// bad-args check end

    params->clear();


    int       numOfClqs;
    const int *clqsNums;

    GetClqsNumsForNode( *nodes, &numOfClqs, &clqsNums );

    assert( numOfClqs > 0 );

    intVector factsNums( clqsNums, clqsNums + numOfClqs );

    const int *ndsIt   = nodes + 1,
              *nds_end = nodes + numberOfNodes;

    for( ; ndsIt != nds_end; ++ndsIt )
    {
        GetClqsNumsForNode( *ndsIt, &numOfClqs, &clqsNums );

        intVector::iterator       factsNumsIt = factsNums.end() - 1;
        intVector::const_iterator factsNums_before_begin
            = factsNums.begin() - 1;

        for( ; factsNumsIt != factsNums_before_begin; --factsNumsIt )
        {
            if( std::find( clqsNums, clqsNums + numOfClqs, *factsNumsIt )
                == clqsNums + numOfClqs )
            {
                factsNums.erase(factsNumsIt);
            }

            if( factsNums.empty() )
            {
                return 0;
            }
        }
    }

    intVector::const_iterator factsNumsIt   = factsNums.begin(),
	factsNums_end = factsNums.end();

    for( ; factsNumsIt != factsNums_end; ++factsNumsIt )
    {
	params->push_back(GetFactor(*factsNumsIt));
    }

    return 1;
}
Beispiel #6
0
bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
	if (inputPhrase.GetSize() != GetSize())	{ return false;	}
	for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
	{
		if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
			return false;
	}
	return true;
}
bool CMNet::IsValid(std::string* description)const
{
    int i;
    int numFactors = GetNumberOfFactors();
    
    bool ret = 1;
    for( i = 0; i < numFactors; ++i )
    {
        const CFactor* pFact = GetFactor(i);
        
        if( !pFact )
        {
            if( description )
            {
                std::stringstream st;
                st<<"The Markov Network haven't factor for group of nodes "<<i<<"."<<std::endl;
                std::string s = st.str();
                description->insert( description->begin(), s.begin(), s.end() );
            }
            ret = 0;
        }
        else
        {
            if( !pFact->IsValid(description) )
            {
                if( description )
                {
                    std::stringstream st;
                    st<<"The Markov Network have invalid potential for nodes:";
                    int domSize;
                    const int* dom;
                    pFact->GetDomain(&domSize, &dom);
                    int j;
                    for( j = 0; j < domSize; j++ )
                    {
                        st<< dom[j];
                    }
                    st<<std::endl;
                    std::string s = st.str();
                    description->insert( description->begin(),
                        s.begin(), s.end() );
                }
                ret = 0;
            }
        }
    }
    
    if(GetNumberOfCliques() != numFactors )
    {
        description->insert( 0,
                "The Markov Network haven't factors for every clique.\n", 55 );
        ret = 0;
    }
    return ret;
}
Beispiel #8
0
void Unit::SetBonus(int i, int value, bool first)
{
	int diff = 0;
	switch(i)
	{
	case 0:
		bonushealth = value;
		if (first == false)
			SetFactor(0,GetFactor(0));
		break;
	case 1:
		bonusmana = value;
		if (first == false)
			SetFactor(1,GetFactor(1));
		break;
	case 2:
		bonusstrength = value;
		//diff = value - bonusstrength;
		//SetDamage(GetDamage() + diff);
		if (first == false)
			SetFactor(2,GetFactor(2));
		break;
	case 3:
		bonusmagic = value;
		//int diff = value - bonusstrength;
		//SetDamage(GetDamage() + diff);
		break;
	case 4:
		bonusagility = value;
		//diff = value - bonusagility;
		//(GetSpeed() + diff);
		if (first == false)
			SetFactor(4,GetFactor(4));
		break;
	case 5:
		bonusdefense = value;
		SetDefence(bonusdefense);
		break;
	default:
		break;
	}
}
Beispiel #9
0
Phrase Phrase::GetSubString(const WordsRange &wordsRange, FactorType factorType) const
{
  Phrase retPhrase(wordsRange.GetNumWordsCovered());

  for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
    const Factor* f = GetFactor(currPos, factorType);
    Word &word = retPhrase.AddWord();
    word.SetFactor(factorType, f);
  }

  return retPhrase;
}
Beispiel #10
0
void CFindEnemyFunc::Execute(edict_t *pEntity)
{
	if (m_pBot->IsEnemy(pEntity))
	{
		float fFactor = GetFactor(pEntity);

		if (!m_pBest || (fFactor < m_fBestFactor))
		{
			m_pBest = pEntity;
			m_fBestFactor = fFactor;
		}
	}
}
Beispiel #11
0
bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
  if (inputPhrase.GetSize() != GetSize())	{
    return false;
  }
  for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
    for (std::vector<FactorType>::const_iterator i = factorVec.begin();
         i != factorVec.end(); ++i) {
      if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
        return false;
    }
  }
  return true;
}
Beispiel #12
0
bool ListReaderH5::GetStressData (T *a_) const
{
  // set up the indices to read the portion of the boundary conditions that
  // we are going to read
  int nVals = m_nFields - m_nAuxFields - 3 - m_ial;
  std::pair<int, int> myPair(0, nVals);
  VEC_INT_PAIR indices(3, myPair);
  indices.at(1).second = m_nRows;
  indices.at(2).first = m_stress - 1;
  indices.at(2).second = 1;

  CStr str(m_path), parType;

  str += "/";
  str += PROPERTY;
  H5DataSetReader r(m_file, str, indices);
  r.AllowTypeConversions(true);
  std::vector<Real> d, fact;
  r.GetData(d);
  GetFactor(fact, 0);

  Parameters::ParTypeFromH5Path(m_path, parType);
  if (Parameters::CheckListSubstituteOk())
  {
    Parameters::SubstituteList(d, fact, parType);
  }
  else if (parType == "STR")
  {
    mfLibExp_StrCondFact(&fact[0], (int)fact.size());
  }
  try
  {
    for (int i=0; i<m_nRows; i++)
    {
      for (int j=0; j<nVals; j++)
      {
        a_[i*m_nFields+3+j] = (T)(d.at(j*m_nRows+i));
      }
      //ASSERT(_CrtCheckMemory());
    }
  }
  catch (std::out_of_range)
  {
    return false;
  }
  return true;
} // ListReaderH5::GetStressData
Beispiel #13
0
bool ListReaderH5::FillInDataT (T *a_)
{
  listReader_GetMapId().clear();
  // we only have to do this the first time
  GetVersion();
  // need to read this in case they have 0 in the first stress period
  //if (m_stress == 1)
  //{
    for (int i=0; i<m_nRows*m_nFields; i++)
      a_[i] = 0.0;
    // fill in cell k i j
    if (!GetCellKIJ(a_))
      return false;
    // fill in the auxilary values like IFACE and 
    // cellgrp (for post processing CCF)
    if (m_nAuxFields > 0)
    {
      if (GetAuxIdx("IFACE") > -1)
      {
        if (!GetIface(a_))
          return false;
      }
      char* factStr[4] = { "CONDFACT", "QFACT", "SHEADFACT", "EHEADFACT"};
      int   factFlg[4] = {          0,       0,           1,           2};
      for (int i = 0; i < 4; ++i)
      {
        int index = GetAuxIdx(factStr[i]);
        if (index > -1)
        {
          if (!GetFactor(a_, index, factFlg[i]))
            return false;
        }
      }
      if (GetAuxIdx("CELLGRP") > -1)
      {
        if (!GetCellGroup(a_))
          return false;
      }
      GetSeawatAux(a_);
      GetUsgTransportAux(a_);
    }
    ASSERT(_CrtCheckMemory());
  //}

  // fill in the boundary condition values like head, conductance, elevation
  return (GetStressData(a_));
} // ListReaderH5::FillInData
Beispiel #14
0
bool ListReaderH5::GetFactor (T *a_,
                              const int a_auxIdx,
                              const int a_sheadFact) const
{
  std::vector<Real> fact;
  if (GetFactor(fact, a_sheadFact))
  {
    int index;
    index = m_nFields - m_nAuxFields + a_auxIdx - m_nCbcFields;
    for (size_t i=0; i<fact.size(); i++)
    {
      a_[i*m_nFields+index] = (T)fact.at(i);
    }
  }
  else
    return false;
  return true;
} // ListReaderH5::GetFactor
Beispiel #15
0
bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
  if (inputPhrase.GetSize() != GetSize()) {
    return false;
  }

  const size_t size = GetSize();

  const size_t maxNumFactors = MAX_NUM_FACTORS;
  for (size_t currPos = 0 ; currPos < size ; currPos++) {
    for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
      FactorType factorType = static_cast<FactorType>(currFactor);
      const Factor *thisFactor 		= GetFactor(currPos, factorType)
                                    ,*inputFactor	= inputPhrase.GetFactor(currPos, factorType);
      if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
        return false;
    }
  }
  return true;

}
T FindPrimeFactor(T number)
{
  return CheckPrime(number) ? number : FindPrimeFactor(GetFactor(number));
}
Beispiel #17
0
uint8_t SmallCap(Capacitor_Type *Cap)
{
  uint8_t           Flag = 3;      /* return value */
  uint8_t           TempByte;      /* temp. value */
  int8_t            Scale;         /* capacitance scale */
  uint16_t          Ticks;         /* timer counter */
  uint16_t          Ticks2;        /* timer overflow counter */
  uint16_t          U_c;           /* voltage of capacitor */
  uint32_t          Raw;           /* raw capacitance value */
  uint32_t          Value;         /* corrected capacitance value */


  /*
   *  Measurement method used for small caps < 50uF:
   *  We need a much better resolution for the time measurement. Therefore we
   *  use the MCUs internal 16-bit counter and analog comparator. The counter
   *  inceases until the comparator detects that the voltage of the DUT is as
   *  high as the internal bandgap reference. To support the higher time
   *  resolution we use the Rh probe resistor for charging.
   *
   *  Remark:
   *  The analog comparator has an Input Leakage Current of -50nA up to 50nA 
   *  at Vcc/2. The Input Offset is <10mV at Vcc/2.
   */

  Ticks2 = 0;                           /* reset timer overflow counter */

  /*
   *  init hardware
   */

  /* prepare probes */
  DischargeProbes();                    /* try to discharge probes */
  if (Check.Found == COMP_ERROR) return 0;     /* skip on error */

  /* set probes: Gnd -- all probes / Gnd -- Rh -- probe-1 */
  R_PORT = 0;                           /* set resistor port to low */
  /* set ADC probe pins to output mode */
  ADC_DDR = (1 << TP1) | (1 << TP2) | (1 << TP3);
  ADC_PORT = 0;                         /* set ADC port to low */
  R_DDR = Probes.Rh_1;                  /* pull-down probe-1 via Rh */

  /* setup analog comparator */
  ADCSRB = (1 << ACME);                 /* use ADC multiplexer as negative input */
  ACSR =  (1 << ACBG) | (1 << ACIC);    /* use bandgap as positive input, trigger timer1 */
  ADMUX = (1 << REFS0) | Probes.Pin_1;  /* switch ADC multiplexer to probe 1 */
                                        /* and set AREF to Vcc */
  ADCSRA = ADC_CLOCK_DIV;               /* disable ADC, but keep clock dividers */
  wait200us();

  /* setup timer */
  TCCR1A = 0;                           /* set default mode */
  TCCR1B = 0;                           /* set more timer modes */
  /* timer stopped, falling edge detection, noise canceler disabled */
  TCNT1 = 0;                            /* set Counter1 to 0 */
  /* clear all flags (input capture, compare A & B, overflow */
  TIFR1 = (1 << ICF1) | (1 << OCF1B) | (1 << OCF1A) | (1 << TOV1);
  R_PORT = Probes.Rh_1;                 /* pull-up probe-1 via Rh */  
                                        
  /* enable timer */
  if (Check.Found == COMP_FET)
  {
    /* keep all probe pins pulled down but probe-1 */
    TempByte = (((1 << TP1) | (1 << TP2) | (1 << TP3)) & ~(1 << Probes.Pin_1));    
  }
  else
  {
    TempByte = Probes.ADC_2;            /* keep just probe-1 pulled down */
  }

  /* start timer by setting clock prescaler (1/1 clock divider) */
  TCCR1B = (1 << CS10);
  ADC_DDR = TempByte;                   /* start charging DUT */


  /*
   *  timer loop
   *  - run until voltage is reached
   *  - detect timer overflows
   */

   while (1)
   {
     TempByte = TIFR1;                  /* get timer1 flags */

     /* end loop if input capture flag is set (= same voltage) */
     if (TempByte & (1 << ICF1)) break;

     /* detect timer overflow by checking the overflow flag */
     if (TempByte & (1 << TOV1))
     {
       /* happens at 65.536ms for 1MHz or 8.192ms for 8MHz */
       TIFR1 = (1 << TOV1);             /* reset flag */
       wdt_reset();                     /* reset watchdog */
       Ticks2++;                        /* increase overflow counter */

       /* end loop if charging takes too long (13.1s) */
       if (Ticks2 == (CPU_FREQ / 5000)) break;
     }
   }

  /* stop counter */
  TCCR1B = 0;                           /* stop timer */
  TIFR1 = (1 << ICF1);                  /* reset Input Capture flag */

  Ticks = ICR1;                         /* get counter value */

  /* disable charging */
  R_DDR = 0;                  /* set resistor port to HiZ mode */

  /* catch missed timer overflow */
  if ((TCNT1 > Ticks) && (TempByte & (1 << TOV1)))
  {
    TIFR1 = (1 << TOV1);                /* reset overflow flag */
    Ticks2++;                           /* increase overflow counter */
  }

  /* enable ADC again */
  ADCSRA = (1 << ADEN) | (1 << ADIF) | ADC_CLOCK_DIV;

  /* get voltage of DUT */
  U_c = ReadU(Probes.Pin_1);       /* get voltage of cap */

  /* start discharging DUT */
  R_PORT = 0;                      /* pull down probe-2 via Rh */
  R_DDR = Probes.Rh_1;             /* enable Rh for probe-1 again */

  /* skip measurement if charging took too long */
  if (Ticks2 >= (CPU_FREQ / 5000)) Flag = 1;


  /*
   *  calculate capacitance (<50uF)
   *  - use factor from pre-calculated SmallCap_table
   */

  if (Flag == 3)
  {
    /*  combine both counter values */
    Raw = (uint32_t)Ticks;                /* set lower 16 bits */
    Raw |= (uint32_t)Ticks2 << 16;        /* set upper 16 bits */
    if (Raw > 2) Raw -= 2;                /* subtract processing time overhead */

    Scale = -12;                          /* default factor is for pF scale */
    if (Raw > (UINT32_MAX / 1000))        /* prevent overflow (4.3*10^6) */
    {
      Raw /= 1000;                        /* scale down by 10^3 */
      Scale += 3;                         /* add 3 to the exponent (nF) */
    }

    /* multiply with factor from table */
    Raw *= GetFactor(Config.Bandgap + NV.CompOffset, TABLE_SMALL_CAP);

    /* divide by CPU frequency to get the time and multiply with table scale */
    Raw /= (CPU_FREQ / 10000);
    Value = Raw;                          /* take raw value */

    /* take care about zero offset if feasable */
    if (Scale == -12)                     /* pF scale */
    {
      if (Value >= NV.CapZero)            /* if value is larger than offset */
      {
        Value -= NV.CapZero;              /* substract offset */
      }
      else                                /* if value is smaller than offset */
      {
        /* we have to prevent a negative value */
        Value = 0;                        /* set value to 0 */
      }
    }

    /* copy data */
    Cap->A = Probes.Pin_2;    /* pull-down probe pin */
    Cap->B = Probes.Pin_1;    /* pull-up probe pin */
    Cap->Scale = Scale;       /* -12 or -9 */
    Cap->Raw = Raw;
    Cap->Value = Value;       /* max. 5.1*10^6pF or 125*10^3nF */


    /*
     *  Self-adjust the voltage offset of the analog comparator and internal
     *  bandgap reference if C is 100nF up to 20µF. The minimum of 100nF
     *  should keep the voltage stable long enough for the measurements. 
     *  Changed offsets will be used in next test run.
     */

    if (((Scale == -12) && (Value >= 100000)) ||
        ((Scale == -9) && (Value <= 20000)))
    {
      int16_t         Offset;
      int32_t         TempLong;

      /*
       *  We can self-adjust the offset of the internal bandgap reference
       *  by measuring a voltage lower than the bandgap reference, one time
       *  with the bandgap as reference and a second time with Vcc as
       *  reference. The common voltage source is the cap we just measured.
       */

       while (ReadU(Probes.Pin_1) > 980)
       {
         /* keep discharging */
       }

       R_DDR = 0;                       /* stop discharging */

       Config.AutoScale = 0;            /* disable auto scaling */
       Ticks = ReadU(Probes.Pin_1);     /* U_c with Vcc reference */
       Config.AutoScale = 1;            /* enable auto scaling again */
       Ticks2 = ReadU(Probes.Pin_1);    /* U_c with bandgap reference */

       R_DDR = Probes.Rh_1;             /* resume discharging */

       Offset = Ticks - Ticks2;
       /* allow some offset caused by the different voltage resolutions
          (4.88 vs. 1.07) */
       if ((Offset < -4) || (Offset > 4))    /* offset too large */
       {
         /*
          *  Calculate total offset:
          *  - first get offset per mV: Offset / U_c
          *  - total offset for U_ref: (Offset / U_c) * U_ref
          */

         TempLong = Offset;
         TempLong *= Config.Bandgap;         /* * U_ref */
         TempLong /= Ticks2;                 /* / U_c */

         NV.RefOffset = (int8_t)TempLong;
       }


      /*
       *  In the cap measurement above the analog comparator compared
       *  the voltages of the cap and the bandgap reference. Since the MCU
       *  has an internal voltage drop for the bandgap reference the
       *  MCU used actually U_bandgap - U_offset. We get that offset by
       *  comparing the bandgap reference with the voltage of the cap:
       *  U_c = U_bandgap - U_offset -> U_offset = U_c - U_bandgap
       */

      Offset = U_c - Config.Bandgap;

      /* limit offset to a valid range of -50mV - 50mV */
      if ((Offset > -50) && (Offset < 50)) NV.CompOffset = Offset;
    }
  }

  return Flag;
}
Beispiel #18
0
void KVSpIdGUI::SpiderIdentification()
{
   if ((!fHisto) || (!fGrid)) return;

   TVirtualPad* pad = fGrid->GetPad();
   fGrid->UnDraw();

   fZp = fZpEntry->GetIntNumber();
   if (!fUserParameter) fSpFactor = GetFactor();
   else fSpFactor = fSpiderFactorEntry->GetNumber();

   fAnglesUp   = fAngleUpEntry->GetIntNumber();
   fAnglesDown = fAngleDownEntry->GetIntNumber();
   fAlpha      = fApertureUpEntry->GetNumber();
   fPiedType   = fPiedChoice->GetSelected();
   fMatrixType = fTypeChoice->GetSelected();
   Int_t type  = fMatrixType;

   TH2*   tmpHisto = fHisto;
   TList* tmpCut   = 0;
   if (fUseCut) {
      tmpHisto = (TH2*)fHisto->Clone(Form("%s_cut", fHisto->GetName()));
      tmpHisto->Reset();
      for (int i = 1; i <= fHisto->GetNbinsX(); i++) {
         for (int j = 1; j <= fHisto->GetNbinsY(); j++) {
            Stat_t ww = fHisto->GetBinContent(i, j);
            Axis_t x0 = fHisto->GetXaxis()->GetBinCenter(i);
            Axis_t y0 = fHisto->GetYaxis()->GetBinCenter(j);
            if (fGrid->IsIdentifiable(x0, y0)) tmpHisto->Fill(x0, y0, ww);
         }
      }
      tmpCut = (TList*)fGrid->GetCuts()->Clone("tmpCuts");
   }

   fGrid->Clear();

   if (fScaledHisto) delete fScaledHisto;
   KVHistoManipulator hm;

   TF1 RtLt("RtLt", Form("x*%lf", fSfx), 0, tmpHisto->GetXaxis()->GetXmax());
   TF1 RtLty("RtLty", Form("x*%lf", fSfy), 0, tmpHisto->GetXaxis()->GetXmax());
   fScaledHisto = (TH2F*)hm.ScaleHisto(tmpHisto, &RtLt, &RtLty);

   if (fIdentificator) delete fIdentificator;
   fIdentificator = new KVSpiderIdentificator(fScaledHisto, fXm * fSfx, fYm * fSfy);

   switch (fPiedType) {
      case kUser:
         fIdentificator->SetX0(fPdx * fSfx);
         fIdentificator->SetY0(fPdy * fSfy);
         break;
      case kAuto:
         break;
      case kNone:
         fIdentificator->SetX0(0.);
         fIdentificator->SetY0(0.);
   }

   fIdentificator->SetParameters(fSpFactor);
   fIdentificator->SetNangles(fAnglesUp, fAnglesDown);
   fIdentificator->SetAlpha(fAlpha);

   fProgressBar->SetRange(0, fAnglesUp + fAnglesDown + 1);
   fProgressBar->Reset();
   fIdentificator->Connect("Increment(Float_t)", "TGHProgressBar", fProgressBar, "SetPosition(Float_t)");

   fTestButton->SetEnabled(kFALSE);
   fCloseButton->SetEnabled(kFALSE);
   fIdentificator->ProcessIdentification();
   fTestButton->SetEnabled(kTRUE);
   fCloseButton->SetEnabled(kTRUE);

   fIdentificator->Disconnect("Increment(Float_t)", fProgressBar, "SetPosition(Float_t)");
   fProgressBar->Reset();

   if (fDebug) fIdentificator->Draw(fOption.Data());

   TList* ll = (TList*)fIdentificator->GetListOfLines();

   KVIDZALine* TheLine = 0;
   int zmax = 0;

   KVSpiderLine* spline = 0;
   TIter next_line(ll);
   while ((spline = (KVSpiderLine*)next_line())) {
      if ((spline->GetN() > 10)) { //&&(spline->GetX(0)<=fIdentificator->GetX0()+200.))
         TF1* ff1 = 0;
         if (type == kSiCsI) ff1 = spline->GetFunction(fPdx * fSfx, TMath::Max(fScaledHisto->GetXaxis()->GetXmax() * 0.9, spline->GetX(spline->GetN() - 1)));
         else if (type == kSiSi)  ff1 = spline->GetFunction(fPdx * fSfx, TMath::Min(fScaledHisto->GetXaxis()->GetXmax() * 0.9, spline->GetX(spline->GetN() - 1) * 1.5));
         else if (type == kChIoSi)  ff1 = spline->GetFunction(fPdx * fSfx, TMath::Min(fScaledHisto->GetXaxis()->GetXmax() * 0.9, spline->GetX(spline->GetN() - 1) * 1.5));
         else ff1 = spline->GetFunction();
         if ((type == kSiCsI) && (ff1->GetParameter(1) >= 3000. || (ff1->GetParameter(2) <= 0.35) || (ff1->GetParameter(2) >= 1.))) {
            Info("SpiderIdentification", "Z = %d has been rejected (fit parameters)", spline->GetZ());
            continue;
         }
         TheLine = (KVIDZALine*)((KVIDZAGrid*)fGrid)->NewLine("ID");
         TheLine->SetZ(spline->GetZ());
         double min, max;
         ff1->GetRange(min, max);
         double step = TMath::Min((max - min) * 0.05, 20.); //20.;
         double stepmax = (max - min) * 0.2; //800.;
         double x = 0.;
         for (x = min + 1; x < max + step; x += step) {
            if (step <= stepmax) step *= 1.3;
            if (ff1->Eval(x) < 4000) TheLine->SetPoint(TheLine->GetN(), x, ff1->Eval(x));
         }
         if (max > x) TheLine->SetPoint(TheLine->GetN(), max, ff1->Eval(max));

         fGrid->Add("ID", TheLine);
         if (spline->GetZ() >= zmax) zmax = spline->GetZ();
      } else {
         Info("SpiderIdentification", "Z = %d has been rejected (too few points)", spline->GetZ());
      }
   }

   TF1 fx("fx12", Form("x/%lf", fSfx), 0., fScaledHisto->GetNbinsX() * 1.);
   TF1 fy("fy12", Form("x/%lf", fSfy), 0., fScaledHisto->GetNbinsY() * 1.);
   fGrid->Scale(&fx, &fy);

   if (fUseCut) delete tmpHisto;

   if (tmpCut) fGrid->GetCuts()->AddAll(tmpCut);
   pad->cd();
   fGrid->Draw();
   pad->Modified();
   pad->Update();

   DoClose();
}
void SparseHieroReorderingFeature::EvaluateChart(
  const ChartHypothesis&  cur_hypo ,
  ScoreComponentCollection* accumulator) const
{
  // get index map for underlying hypotheses
  //const AlignmentInfo::NonTermIndexMap &nonTermIndexMap =
  //  cur_hypo.GetCurrTargetPhrase().GetAlignNonTerm().GetNonTermIndexMap();
  
  //The Huck features. For a rule with source side:
  //   abXcdXef
  //We first have to split into blocks:
  // ab X cd X ef
  //Then we extract features based in the boundary words of the neighbouring blocks
  //For the block pair, we use the right word of the left block, and the left 
  //word of the right block.

  //Need to get blocks, and their alignment. Each block has a word range (on the 
  // on the source), a non-terminal flag, and  a set of alignment points in the target phrase

  //We need to be able to map source word position to target word position, as
  //much as possible (don't need interior of non-terminals). The alignment info
  //objects just give us the mappings between *rule* positions. So if we can 
  //map source word position to source rule position, and target rule position
  //to target word position, then we can map right through.

  size_t sourceStart = cur_hypo.GetCurrSourceRange().GetStartPos();
  size_t sourceSize = cur_hypo.GetCurrSourceRange().GetNumWordsCovered();

  vector<WordsRange> sourceNTSpans;
  for (size_t prevHypoId = 0; prevHypoId < cur_hypo.GetPrevHypos().size(); ++prevHypoId) {
    sourceNTSpans.push_back(cur_hypo.GetPrevHypo(prevHypoId)->GetCurrSourceRange());
  }
  //put in source order. Is this necessary?
  sort(sourceNTSpans.begin(), sourceNTSpans.end()); 
  //cerr << "Source NTs: ";
  //for (size_t i = 0; i < sourceNTSpans.size(); ++i) cerr << sourceNTSpans[i] << " ";
  //cerr << endl;

  typedef pair<WordsRange,bool> Block;//flag indicates NT
  vector<Block> sourceBlocks; 
  sourceBlocks.push_back(Block(cur_hypo.GetCurrSourceRange(),false));
  for (vector<WordsRange>::const_iterator i = sourceNTSpans.begin(); 
      i != sourceNTSpans.end(); ++i) {
    const WordsRange& prevHypoRange = *i;
    Block lastBlock = sourceBlocks.back();
    sourceBlocks.pop_back();
    //split this range into before NT, NT and after NT
    if (prevHypoRange.GetStartPos() > lastBlock.first.GetStartPos()) {
      sourceBlocks.push_back(Block(WordsRange(lastBlock.first.GetStartPos(),prevHypoRange.GetStartPos()-1),false));
    }
    sourceBlocks.push_back(Block(prevHypoRange,true));
    if (prevHypoRange.GetEndPos() < lastBlock.first.GetEndPos()) {
      sourceBlocks.push_back(Block(WordsRange(prevHypoRange.GetEndPos()+1,lastBlock.first.GetEndPos()), false));
    }
  }
  /*
  cerr << "Source Blocks: ";
  for (size_t i = 0; i < sourceBlocks.size(); ++i) cerr << sourceBlocks[i].first << " "
      << (sourceBlocks[i].second ? "NT" : "T") << " ";
  cerr << endl;
  */

  //Mapping from source word to target rule position
  vector<size_t> sourceWordToTargetRulePos(sourceSize);
  map<size_t,size_t> alignMap;
  alignMap.insert(
    cur_hypo.GetCurrTargetPhrase().GetAlignTerm().begin(),
    cur_hypo.GetCurrTargetPhrase().GetAlignTerm().end());
  alignMap.insert(
    cur_hypo.GetCurrTargetPhrase().GetAlignNonTerm().begin(),
    cur_hypo.GetCurrTargetPhrase().GetAlignNonTerm().end());
  //vector<size_t> alignMapTerm = cur_hypo.GetCurrTargetPhrase().GetAlignNonTerm()
  size_t sourceRulePos = 0;
  //cerr << "SW->RP ";
  for (vector<Block>::const_iterator sourceBlockIt = sourceBlocks.begin(); 
    sourceBlockIt != sourceBlocks.end(); ++sourceBlockIt) {
    for (size_t sourceWordPos = sourceBlockIt->first.GetStartPos();
      sourceWordPos <= sourceBlockIt->first.GetEndPos(); ++sourceWordPos) {
      sourceWordToTargetRulePos[sourceWordPos - sourceStart] = alignMap[sourceRulePos];
   //   cerr << sourceWordPos - sourceStart << "-" << alignMap[sourceRulePos] << " ";
      if (! sourceBlockIt->second) {
        //T
        ++sourceRulePos;
      }
    }
    if ( sourceBlockIt->second) {
      //NT
      ++sourceRulePos;
    }
  }
  //cerr << endl;

  //Iterate through block pairs
  const Sentence& sentence = 
    dynamic_cast<const Sentence&>(cur_hypo.GetManager().GetSource());
  //const TargetPhrase& targetPhrase = cur_hypo.GetCurrTargetPhrase();
  for (size_t i = 0; i < sourceBlocks.size()-1; ++i) {
    Block& leftSourceBlock = sourceBlocks[i];
    Block& rightSourceBlock = sourceBlocks[i+1];
    size_t sourceLeftBoundaryPos = leftSourceBlock.first.GetEndPos();
    size_t sourceRightBoundaryPos = rightSourceBlock.first.GetStartPos();
    const Word& sourceLeftBoundaryWord = sentence.GetWord(sourceLeftBoundaryPos);
    const Word& sourceRightBoundaryWord = sentence.GetWord(sourceRightBoundaryPos);
    sourceLeftBoundaryPos -= sourceStart;
    sourceRightBoundaryPos -= sourceStart;
    
    // Need to figure out where these map to on the target.
    size_t targetLeftRulePos = 
      sourceWordToTargetRulePos[sourceLeftBoundaryPos];
    size_t targetRightRulePos = 
      sourceWordToTargetRulePos[sourceRightBoundaryPos];

    bool isMonotone = true;
    if ((sourceLeftBoundaryPos < sourceRightBoundaryPos  &&
          targetLeftRulePos > targetRightRulePos) ||
      ((sourceLeftBoundaryPos > sourceRightBoundaryPos  &&
          targetLeftRulePos < targetRightRulePos)))
    {
      isMonotone = false;
    }
    stringstream buf;
    buf << "h_"; //sparse reordering, Huck
    if (m_type == SourceLeft || m_type == SourceCombined) {
      buf << GetFactor(sourceLeftBoundaryWord,m_sourceVocab,m_sourceFactor)->GetString();
      buf << "_";
    }
    if (m_type == SourceRight || m_type == SourceCombined) {
    buf << GetFactor(sourceRightBoundaryWord,m_sourceVocab,m_sourceFactor)->GetString();
      buf << "_";
    }
    buf << (isMonotone ? "M" : "S");
    accumulator->PlusEquals(this,buf.str(), 1);
  }
//  cerr << endl;
}
Beispiel #20
0
uint8_t LargeCap(Capacitor_Type *Cap)
{
  uint8_t           Flag = 3;      /* return value */
  uint8_t           TempByte;      /* temp. value */
  uint8_t           Mode;          /* measurement mode */
  int8_t            Scale;         /* capacitance scale */
  uint16_t          TempInt;       /* temp. value */
  uint16_t          Pulses;        /* number of charging pulses */
  uint16_t          U_Zero;        /* voltage before charging */
  uint16_t          U_Cap;         /* voltage of DUT */
  uint16_t          U_Drop = 0;    /* voltage drop */
  uint32_t          Raw;           /* raw capacitance value */
  uint32_t          Value;         /* corrected capacitance value */

  /* setup mode */
  Mode = FLAG_10MS | FLAG_PULLUP;       /* start with large caps */


  /*
   *  We charge the DUT with up to 500 pulses each 10ms long until the
   *  DUT reaches 300mV. The charging is done via Rl. This method is
   *  suitable for large capacitances from 47uF up to 100mF. If we find a 
   *  lower capacitance we'll switch to 1ms charging pulses and try again
   *  (4.7µF up to 47µF).
   *
   *  Problem:
   *  ReadADC() needs about 5ms (44 runs). We charge the DUT for 10ms and
   *  measure for 5ms. During that time the voltage will drop due to
   *  resistive losses of the DUT and the measurement itself. So the DUT
   *  seems to need more time to reach 300mV causing a higher capacitance
   *  be calculated.
   *
   *  Remark:
   *  The Analog Input Resistance of the ADC is 100MOhm typically.
   */

large_cap:

  /* prepare probes */
  DischargeProbes();                    /* try to discharge probes */
  if (Check.Found == COMP_ERROR) return 0;     /* skip on error */

  /* setup probes: Gnd -- probe 1 / probe 2 -- Rl -- Vcc */
  ADC_PORT = 0;                    /* set ADC port to low */
  ADC_DDR = Probes.ADC_2;          /* pull-down probe 2 directly */
  R_PORT = 0;                      /* set resistor port to low */
  R_DDR = 0;                       /* set resistor port to HiZ */
  U_Zero = ReadU(Probes.Pin_1);    /* get zero voltage (noise) */

  /* charge DUT with up to 500 pulses until it reaches 300mV */
  Pulses = 0;
  TempByte = 1;
  while (TempByte)
  {
    Pulses++;
    PullProbe(Probes.Rl_1, Mode);       /* charging pulse */
    U_Cap = ReadU(Probes.Pin_1);        /* get voltage */

    /* zero offset */
    if (U_Cap > U_Zero)            /* voltage higher than zero offset */
      U_Cap -= U_Zero;                  /* subtract zero offset */
    else                           /* shouldn't happen but you never know */
      U_Cap = 0;                        /* assume 0V */

    /* end loop if charging is too slow */
    if ((Pulses == 126) && (U_Cap < 75)) TempByte = 0;
    
    /* end loop if 300mV are reached */
    if (U_Cap >= 300) TempByte = 0;

    /* end loop if maximum pulses are reached */
    if (Pulses == 500) TempByte = 0;

    wdt_reset();                        /* reset watchdog */
  }

  /* if 300mV are not reached DUT isn't a cap or much too large (>100mF) */
  /* we can ignore that for mid-sized caps */
  if (U_Cap < 300)
  {
    Flag = 1;
  }

  /* if 1300mV are reached with one pulse we got a small cap */
  if ((Pulses == 1) && (U_Cap > 1300))
  {
    if (Mode & FLAG_10MS)                    /* 10ms pulses (>47µF) */
    {
      Mode = FLAG_1MS | FLAG_PULLUP;         /* set mode to 1ms charging pulses (<47µF) */
      goto large_cap;                        /* and re-run */
    }
    else                                     /* 1ms pulses (<47µF) */
    {
      Flag = 2;                              /* signal low capacitance (<4.7µF) */
    }
  }


  /*
   *  check if DUT sustains the charge and get the voltage drop
   *  - run the same time as before minus the 10ms charging time
   *  - this gives us the approximation of the self-discharging
   */

  if (Flag == 3)
  {
    /* check self-discharging */
    TempInt = Pulses;
    while (TempInt > 0)
    {
      TempInt--;                        /* descrease timeout */
      U_Drop = ReadU(Probes.Pin_1);     /* get voltage */
      U_Drop -= U_Zero;                 /* zero offset */
      wdt_reset();                      /* reset watchdog */
    }

    /* calculate voltage drop */
    if (U_Cap > U_Drop) U_Drop = U_Cap - U_Drop;
    else U_Drop = 0;

    /* if voltage drop is too large consider DUT not to be a cap */
    if (U_Drop > 100) Flag = 0;
  }


  /*
   *  calculate capacitance
   *  - use factor from pre-calculated LargeCap_table
   *  - ignore NV.CapZero since it's in the pF range
   */

  if (Flag == 3)
  {
    Scale = -9;                           /* factor is scaled to nF */
    /* get interpolated factor from table */
    Raw = GetFactor(U_Cap + U_Drop, TABLE_LARGE_CAP);
    Raw *= Pulses;                        /* C = pulses * factor */
    if (Mode & FLAG_10MS) Raw *= 10;      /* *10 for 10ms charging pulses */

    if (Raw > (UINT32_MAX / 1000))        /* scale down if C >4.3mF */
    {
      Raw /= 1000;                        /* scale down by 10^3 */
      Scale += 3;                         /* add 3 to the exponent */
    }

    Value = Raw;                          /* copy raw value */

    /* it seems that we got a systematic error */
    Value *= 100;
    if (Mode & FLAG_10MS) Value /= 109;   /* -9% for large cap */
    else Value /= 104;                    /* -4% for mid cap */

    /* copy data */
    Cap->A = Probes.Pin_2;    /* pull-down probe pin */
    Cap->B = Probes.Pin_1;    /* pull-up probe pin */
    Cap->Scale = Scale;       /* -9 or -6 */
    Cap->Raw = Raw;
    Cap->Value = Value;       /* max. 4.3*10^6nF or 100*10^3µF */ 
  }

  return Flag;
}
Beispiel #21
0
void CFindEnemyFunc::SetOldEnemy(edict_t *pEntity)
{
	m_pBest = pEntity;
	m_fBestFactor = GetFactor(pEntity);
}