Beispiel #1
0
void Interrupt(){
  unsigned int vcalc;
  unsigned long wts;
  unsigned short encVal = 0;
  unsigned char cs = 50;
  
  if (TMR1IF_bit)  // Timer1 Code
  {
      TMR1IF_bit = 0;
      TMR1H         = Hi(tmrOffset);
      TMR1L         = Lo(tmrOffset);
      if (wavSel == 0)
      {
         wts = (unsigned long)sizeof( envelope_table );
         vcalc = (envelope_table[x1]);
      }
      else if (wavSel == 1)
      {
         wts = (unsigned long)sizeof( envelope_table2 );
         vcalc = (envelope_table2[x1]);
      }
      x1+=xStep;
      if(x1 == wts)
      {
        xStep=1;
        x1 = 0;
        T1CON         = 0x00;
      }
      PWM1_Set_Duty( vcalc );
  }
}
Beispiel #2
0
void save_int_to_eeprom( unsigned char add, unsigned int data )
{
  eeprom_write( add, Hi( data ) );                             //and save msb
  DelayMs( 10 );
  eeprom_write( add + 1, Lo( data ) );                      //and lsb
  DelayMs( 10 );
}
// write data
void Write_Data(unsigned int _data) {
  TFT_RS = 1;
  Lo(LATE) = Hi(_data);
  Lo(LATA) = Lo(_data);
  TFT_WR = 0;
  TFT_WR = 1;
}
Beispiel #4
0
void InitTimer1(){
  T1CON         = 0x00;
  TMR1IF_bit         = 0;
  TMR1H         = Hi(tmrOffset);
  TMR1L         = Lo(tmrOffset);
  TMR1IE_bit         = 1;
  INTCON         = 0xC0;
}
Beispiel #5
0
/*****************************************************************************
 * Function: ADCStoreTemperature()
 *
 * Preconditions: SPIMPolInit and EEPROMInit must be called before.
 *
 * Overview: The function stores the current temperature into EEPROM.
 *
 * Input: None.
 *
 * Output: None.
 *
 *****************************************************************************/
void ADCStoreTemperature(){
unsigned Temp;
    // Get temperature
    Temp = _uADCTemperature>>4;
    // Write MS byte into EEPROM address = 0
    EEPROMWriteByte(Hi(Temp),0);
    // Write LS byte into EEPROM address = 1
    EEPROMWriteByte(Lo(Temp),1);
}
Beispiel #6
0
 // Transfer Address.
 bool SPIFlash::_transferAddress(void) {
   if (address4ByteEnabled) {
     _nextByte(WRITE, Highest(_currentAddress));
   }
   _nextByte(WRITE, Higher(_currentAddress));
   _nextByte(WRITE, Hi(_currentAddress));
   _nextByte(WRITE, Lo(_currentAddress));
   return true;
 }
Beispiel #7
0
char ErrorMessage(char Error){
  unsigned int TempI;
  cmTrBuf1[1]=cmRcBuf1[1]+0x80;
  cmTrBuf1[2]=Error;
  TempI=GetCRC16(cmTrBuf1,3);
  cmTrBuf1[3]=Low(TempI);
  cmTrBuf1[4]=Hi(TempI);  
  return 5;
}//end ErrorMessage()
Beispiel #8
0
void BazaModBus::readarchive(unsigned char* mass, unsigned char shift, unsigned int address){
  if (address<128){
    mass[shift] = Hi(JournalMass[address+1]);
    mass[shift+1] = Lo(JournalMass[address+1]);
  }else{
    mass[shift]=0xFF;
    mass[shift+1]=0xFF;
  }
};
Beispiel #9
0
//формирование ответа об ошибке
char ErrorMessage(char Error) {
    char TempI;
    cmTrBuf0[1]=cmRcBuf0[1]+0x80;;//команда с ошибкой
    cmTrBuf0[2]=Error;
    TempI=GetCRC16(cmTrBuf0,3);//подсчет КС посылки
    cmTrBuf0[3]=Low(TempI);
    cmTrBuf0[4]=Hi(TempI);
    return 5;
}//end ErrorMessage()
Beispiel #10
0
  std::vector<Sparsity>
  LrDpleInternal::getSparsity(const std::map<std::string, std::vector<Sparsity> >& st,
                              const std::vector< std::vector<int> > &Hs_) {
    // Chop-up the arguments
    std::vector<Sparsity> As, Vs, Cs, Hs;
    if (st.count("a")) As = st.at("a");
    if (st.count("v")) Vs = st.at("v");
    if (st.count("c")) Cs = st.at("c");
    if (st.count("h")) Hs = st.at("h");

    bool with_H = !Hs.empty();

    int K = As.size();

    Sparsity A;
    if (K==1) {
      A = As[0];
    } else {
      Sparsity AL = diagcat(vector_slice(As, range(As.size()-1)));

      Sparsity AL2 = horzcat(AL, Sparsity(AL.size1(), As[0].size2()));
      Sparsity AT = horzcat(Sparsity(As[0].size1(), AL.size2()), As.back());
      A = vertcat(AT, AL2);
    }

    Sparsity V = diagcat(Vs.back(), diagcat(vector_slice(Vs, range(Vs.size()-1))));
    Sparsity C;

    if (!Cs.empty()) {
      C = diagcat(Cs.back(), diagcat(vector_slice(Cs, range(Cs.size()-1))));
    }
    Sparsity H;
    std::vector<int> Hs_agg;

    std::vector<int> Hi(1, 0);
    if (Hs_.size()>0 && with_H) {
      H = diagcat(Hs.back(), diagcat(vector_slice(Hs, range(Hs.size()-1))));
      casadi_assert(K==Hs_.size());
      for (int k=0;k<K;++k) {
        Hs_agg.insert(Hs_agg.end(), Hs_[k].begin(), Hs_[k].end());
        int sum=0;
        for (int i=0;i<Hs_[k].size();++i) {
          sum+= Hs_[k][i];
        }
        Hi.push_back(Hi.back()+sum);
      }
    }

    Sparsity res = LrDleInternal::getSparsity(make_map("a", A, "v", V, "c", C, "h", H), Hs_agg);

    if (with_H) {
      return diagsplit(res, Hi);
    } else {
      return diagsplit(res, As[0].size2());
    }
  }
Beispiel #11
0
char ModBus(char NumByte) {
    int TempI;
    //вывод посылки на экран
    cmRcBuf0[NumByte]=0x00;

    //обработка посылки
    if (cmRcBuf0[0]!=0x20) return 0x00; //адрес устройства  //ответ не нужен
    CRC16=GetCRC16(cmRcBuf0,NumByte-2);//подсчет CRC в принятой посылке
    TempI=(int) (cmRcBuf0[NumByte-1]<<8) + cmRcBuf0[NumByte-2];
    if (CRC16!=TempI) return 0x00;  //контрольная сумма //ответ не нужен
    cmTrBuf0[0]=0x20;//адрес устройства
    //код команды
    switch(cmRcBuf0[1]) {
    case 0x03: { //чтение регистров
        TempI=(int) (cmRcBuf0[2]<<8) + cmRcBuf0[3];
        if (TempI!=1) { //првоерка номера регистра, есть только 1 регистр
            return ErrorMessage(0x02); //данный адрес не может быть обработан
        }
        TempI=(int) (cmRcBuf0[4]<<8) + cmRcBuf0[5];
        if (TempI!=1) { //проверка кол-ва запрашиваемых регистров, есть только 1 регистр
            return ErrorMessage(0x02); //данный адрес не может быть обработан
        }
        cmTrBuf0[1]=0x03;//команда
        cmTrBuf0[2]=0x02;//кол-во байт данных
        cmTrBuf0[3]=0x00;//старший байт
        TempI=PINB;
        cmTrBuf0[4]=Low(TempI);//уровни порта F
        TempI=GetCRC16(cmTrBuf0,5);//подсчет КС посылки
        cmTrBuf0[5]=Low(TempI);
        cmTrBuf0[6]=Hi(TempI);
        return 7;
    }
    case 0x06: { //запись в единичный регистр
        TempI=(int) (cmRcBuf0[2]<<8) + cmRcBuf0[3];
        if (TempI!=1) { //првоерка номера регистра, есть только 1 регистр
            return ErrorMessage(0x02); //данный адрес не может быть обработан
        }
        TempI=(int) (cmRcBuf0[4]<<8) + cmRcBuf0[5];
        if (TempI>0xFF) { //проверка числа, которое надо записать в порт
            return ErrorMessage(0x03); //недопустимые данные в запросе
        }
        PORTB=Low(TempI);
        cmTrBuf0[1]=cmRcBuf0[1];//команда
        cmTrBuf0[2]=cmRcBuf0[2];//адрес
        cmTrBuf0[3]=cmRcBuf0[3];//
        cmTrBuf0[4]=cmRcBuf0[4];//данные
        cmTrBuf0[5]=cmRcBuf0[5];//
        cmTrBuf0[6]=cmRcBuf0[6];//КС
        cmTrBuf0[7]=cmRcBuf0[7];//
        return 8;
    }
    default: {
        return ErrorMessage(0x01); //недопустимая команда
    }
    }
}//end ModBus()
Beispiel #12
0
  /** Execute the algorithm.
   */
  void CalculateUMatrix::exec()
  {
    double a=this->getProperty("a");
    double b=this->getProperty("b");
    double c=this->getProperty("c");
    double alpha=this->getProperty("alpha");
    double beta=this->getProperty("beta");
    double gamma=this->getProperty("gamma");
    OrientedLattice o(a,b,c,alpha,beta,gamma);
    Matrix<double> B=o.getB();

    double H,K,L;

    PeaksWorkspace_sptr ws;
    ws = boost::dynamic_pointer_cast<PeaksWorkspace>(AnalysisDataService::Instance().retrieve(this->getProperty("PeaksWorkspace")) );
    if (!ws) throw std::runtime_error("Problems reading the peaks workspace");

    Matrix<double> Hi(4,4),Si(4,4),HS(4,4),zero(4,4);
    for (int i=0;i<ws->getNumberPeaks();i++)
    {
      Peak p=ws->getPeaks()[i];
      H=p.getH();
      K=p.getK();
      L=p.getL();
      if(H*H+K*K+L*L>0)
      {
        V3D Qhkl=B*V3D(H,K,L);
        Hi[0][0]=0.;        Hi[0][1]=-Qhkl.X(); Hi[0][2]=-Qhkl.Y(); Hi[0][3]=-Qhkl.Z();
        Hi[1][0]=Qhkl.X();  Hi[1][1]=0.;        Hi[1][2]=Qhkl.Z();  Hi[1][3]=-Qhkl.Y();
        Hi[2][0]=Qhkl.Y();  Hi[2][1]=-Qhkl.Z(); Hi[2][2]=0.;        Hi[2][3]=Qhkl.X();
        Hi[3][0]=Qhkl.Z();  Hi[3][1]=Qhkl.Y();  Hi[3][2]=-Qhkl.X(); Hi[3][3]=0.;

        V3D Qgon=p.getQSampleFrame();
        Si[0][0]=0.;        Si[0][1]=-Qgon.X(); Si[0][2]=-Qgon.Y(); Si[0][3]=-Qgon.Z();
        Si[1][0]=Qgon.X();  Si[1][1]=0.;        Si[1][2]=-Qgon.Z(); Si[1][3]=Qgon.Y();
        Si[2][0]=Qgon.Y();  Si[2][1]=Qgon.Z();  Si[2][2]=0.;        Si[2][3]=-Qgon.X();
        Si[3][0]=Qgon.Z();  Si[3][1]=-Qgon.Y(); Si[3][2]=Qgon.X(); Si[3][3]=0.;

        HS+=(Hi*Si);
      }
    }
    //check if HS is 0
    if (HS==zero) throw std::invalid_argument("The peaks workspace is not indexed or something really bad happened");

    Matrix<double> Eval;
    Matrix<double> Diag;
    HS.Diagonalise(Eval,Diag);
    Eval.sortEigen(Diag);
    Mantid::Kernel::Quat qR(Eval[0][0],Eval[1][0],Eval[2][0],Eval[3][0]);//the first column corresponds to the highest eigenvalue
    DblMatrix U(qR.getRotation());
    o.setU(U);

    ws->mutableSample().setOrientedLattice(new OrientedLattice(o));

  }
Beispiel #13
0
void BazaModBus::readregister(unsigned char* mass, unsigned char shift, unsigned int address){
  //если считываем пароль пользователя
  if (address==0x0016) NewPass(ePassword);
  if (address<256){
    mass[shift] = Hi(DataMass[address]);
    mass[shift+1] = Lo(DataMass[address]);
  }else{
    mass[shift]=0xFF;
    mass[shift+1]=0xFF;
  }
};
/**************************************************************************************************
* Function MP3_SCI_Write()
* -------------------------------------------------------------------------------------------------
* Overview: Function writes one byte to MP3 SCI
* Input: register address in codec, data
* Output: Nothing
**************************************************************************************************/
void MP3_SCI_Write(char address, unsigned int data_in) {
  XDCS = 1;

  MP3_CS = 0;                    // select MP3 SCI
  SPI0_Write(WRITE_CODE);
  SPI0_Write(address);
  SPI0_Write(Hi(data_in));       // high byte
  SPI0_Write(Lo(data_in));       // low byte
  MP3_CS = 1;                    // deselect MP3 SCI
  while (DREQ == 0);             // wait until DREQ becomes 1, see MP3 codec datasheet, Serial Protocol for SCI
}
Beispiel #15
0
void BazaModBus::readregisters(unsigned char* mass, unsigned char shift, unsigned int address, unsigned char number) {
  for (i_mod=0; i_mod<number; i_mod++){
    if ((address+i_mod)<256){
      mass[shift+i_mod*2] = Hi(DataMass[address+i_mod]);
      mass[shift+1+i_mod*2] = Lo(DataMass[address+i_mod]);
    }
    else{
      mass[shift+i_mod*2]=0xFF;
      mass[shift+1+i_mod*2]=0xFF;
    }
  }
};
Beispiel #16
0
//настройка UART
void StartUART0(void) {
    UBRRH=Hi(((dXTAL/16)/19200)-1);
    UBRRL=Low(((dXTAL/16)/19200)-1);

    UCSRA=0x00;
    UCSRB=0xD8;
    UCSRC=0x86;

    UBRRH=0x00;
    UBRRL=0x33;

    EnableReceive0;
    InitTimer0;
    StartTimer0;
}//end void StartUART0()
Beispiel #17
0
double gcta::lgL_reduce_mdl(double y_Ssq, bool no_constrain)
{
    if(_r_indx.size()==0) return 0;
    bool multi_comp=(_r_indx.size()-_r_indx_drop.size()>1);
    cout<<"\nCalculating the logLikelihood for the reduced model ...\n(variance component"<<(multi_comp?"s ":" ");
    for(int i=0; i<_r_indx.size(); i++){
        if(find(_r_indx_drop.begin(), _r_indx_drop.end(), _r_indx[i])==_r_indx_drop.end()) cout<<_r_indx[i]+1<<" ";
    }
    cout<<(multi_comp?"are":"is")<<" dropped from the model)"<<endl;
    vector<int> vi_buf(_r_indx);
    _r_indx=_r_indx_drop;
	eigenMatrix Vi_X(_n, _X_c), Xt_Vi_X_i(_X_c, _X_c), Hi(_r_indx.size()+1, _r_indx.size()+1);
    eigenVector Py(_n);
    eigenVector varcmp(_r_indx.size()+1);
    varcmp.setConstant(y_Ssq/(_r_indx.size()+1));
    double lgL=reml_iteration(y_Ssq, Vi_X, Xt_Vi_X_i, Hi, Py, varcmp, false, no_constrain);
    _r_indx=vi_buf;
	return(lgL);
}
Beispiel #18
0
S16 CalcRamp1(S16 ref,S16 max,S16 min, S16 incr)
{
	S32 tmpl;

	/* new reference limitation */
	if (ref > max) ref = max;
	else if (ref < min) ref = min;
	
	/* process reference ramp */
	if (incr)
	   {
		   min = Hi(ramp1);
		   if (ref > min)      /* reference must be increased */
		      {
		      tmpl = ramp1 + incr;
		      if (Hi(tmpl) > ref)
		         {
		         Hi(ramp1) = ref;
		         Lo(ramp1) = 0;
		         }
		      else ramp1 = tmpl;
		      }
		   else if (ref < min) /* reference must be decreased */
		      {
		      tmpl = ramp1 - incr;
		      if (Hi(tmpl) < ref)
		         {
		         Hi(ramp1) = ref;
		         Lo(ramp1) = 0;
		         }
		      else ramp1 = tmpl;
	      }
	   }
	else /* no ramp */
	   {
	   Hi(ramp1) = ref;
	   Lo(ramp1) = 0;
	   }
	min = Hi(ramp1);
	
	return (min);
}
Beispiel #19
0
void hello() {
  
  
  std::thread t1(hi);
  std::thread t2(Hi(3)); // pass copy of local object
  hi();

  t1.join();
  t2.join();

  Hi::start=3;	
  Hi oneHi; // create local object
  std::thread t3(std::ref(oneHi)); // pass reference to oneHi
  std::thread t4(std::ref(oneHi));
  std::cout << "start is " << Hi::start << std::endl;
  oneHi();
  std::cout << "start is " << Hi::start << std::endl;
  
  t3.join();
  t4.join();
  std::cout << "j is " << oneHi.j << std::endl;

}
Beispiel #20
0
// Write int to EEPROM.
void EEPROM_Write_int(unsigned int address, unsigned int num) {
   EEPROM_Write(address  , Lo(num));
   EEPROM_Write(address+1, Hi(num));
  // Note that the EEPROM delay is only needed between write and read functions.
}
Beispiel #21
0
/**
 * FUNCTION NAME: fbfAnalysis
 *
 * DESCRIPTION: This function performs the FBF analysis
 */
double FBF::fbfAnalysis() {
	trace.funcEntry("FBF::fbfAnalysis");
	vector<int> n;
	for ( int i = 0 ; i < fbf.size(); i++ ) {
		n.emplace_back(populateNi(i));
		cout<<"Elements in : "<<i<<" filter: "<<n[i]<<endl;
	}

	double fbfFPR = 0.0;

	fbfFPR = ( 1 - fbf[future].effective_n_given_fpp(n[future], fbf[future].getSaltSize()));
	fbfFPR *= 1 - fbf[present].effective_n_given_fpp(n[present], (int)(fbf[present].getSaltSize()));
	fbfFPR *= (1 - fbf[present].effective_n_given_fpp(n[present], (int)(fbf[present].getSaltSize())))*(1 - fbf[present].effective_n_given_fpp(n[present], (int)(fbf[present].getSaltSize() - Hi(future))) * fbf[pastStart].effective_n_given_fpp(n[pastStart], (int)Hi(future)));
	fbfFPR *= 1 - fbf[pastStart].effective_n_given_fpp(n[pastStart], (int)(fbf[pastStart].getSaltSize() - Hi(present)));
	double finalFP = 1 - fbfFPR;
	cout<<"  INFO :: fbf Analysis FPR: " <<finalFP<<endl;
	trace.funcExit("FBF::fbfAnalysis", (int)finalFP);
	return finalFP;
}
Beispiel #22
0
  /** Execute the algorithm.
   */
  void CalculateUMatrix::exec()
  {
    double a=this->getProperty("a");
    double b=this->getProperty("b");
    double c=this->getProperty("c");
    double alpha=this->getProperty("alpha");
    double beta=this->getProperty("beta");
    double gamma=this->getProperty("gamma");
    OrientedLattice o(a,b,c,alpha,beta,gamma);
    Matrix<double> B=o.getB();

    double H,K,L;

    PeaksWorkspace_sptr ws;
    ws = AnalysisDataService::Instance().retrieveWS<PeaksWorkspace>(this->getProperty("PeaksWorkspace") );
    if (!ws) throw std::runtime_error("Problems reading the peaks workspace");

    size_t nIndexedpeaks=0;
    bool found2nc=false;
    V3D old(0,0,0);
    Matrix<double> Hi(4,4),Si(4,4),HS(4,4),zero(4,4);
    for (int i=0;i<ws->getNumberPeaks();i++)
    {
      Peak p=ws->getPeaks()[i];
      H=p.getH();
      K=p.getK();
      L=p.getL();
      if(H*H+K*K+L*L>0)
      {
        nIndexedpeaks++;
        if (!found2nc)
        {
          if (nIndexedpeaks==1)
          {
            old=V3D(H,K,L);
          }
          else
          {
            if (!old.coLinear(V3D(0,0,0),V3D(H,K,L))) found2nc=true;
          }
        }
        V3D Qhkl=B*V3D(H,K,L);
        Hi[0][0]=0.;        Hi[0][1]=-Qhkl.X(); Hi[0][2]=-Qhkl.Y(); Hi[0][3]=-Qhkl.Z();
        Hi[1][0]=Qhkl.X();  Hi[1][1]=0.;        Hi[1][2]=Qhkl.Z();  Hi[1][3]=-Qhkl.Y();
        Hi[2][0]=Qhkl.Y();  Hi[2][1]=-Qhkl.Z(); Hi[2][2]=0.;        Hi[2][3]=Qhkl.X();
        Hi[3][0]=Qhkl.Z();  Hi[3][1]=Qhkl.Y();  Hi[3][2]=-Qhkl.X(); Hi[3][3]=0.;

        V3D Qgon=p.getQSampleFrame();
        Si[0][0]=0.;        Si[0][1]=-Qgon.X(); Si[0][2]=-Qgon.Y(); Si[0][3]=-Qgon.Z();
        Si[1][0]=Qgon.X();  Si[1][1]=0.;        Si[1][2]=-Qgon.Z(); Si[1][3]=Qgon.Y();
        Si[2][0]=Qgon.Y();  Si[2][1]=Qgon.Z();  Si[2][2]=0.;        Si[2][3]=-Qgon.X();
        Si[3][0]=Qgon.Z();  Si[3][1]=-Qgon.Y(); Si[3][2]=Qgon.X(); Si[3][3]=0.;

        HS+=(Hi*Si);
      }
    }
    //check if enough peaks are indexed or if HS is 0
    if ((nIndexedpeaks<2) || (found2nc==false)) throw std::invalid_argument("Less then two non-colinear peaks indexed");
    if (HS==zero) throw std::invalid_argument("Something really bad happened");

    Matrix<double> Eval;
    Matrix<double> Diag;
    HS.Diagonalise(Eval,Diag);
    Eval.sortEigen(Diag);
    Mantid::Kernel::Quat qR(Eval[0][0],Eval[1][0],Eval[2][0],Eval[3][0]);//the first column corresponds to the highest eigenvalue
    DblMatrix U(qR.getRotation());
    o.setU(U);

    ws->mutableSample().setOrientedLattice(new OrientedLattice(o));

  }
Beispiel #23
0
static lbfgsfloatval_t PLMNegLogPosteriorBlock(void *instance,
    const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
    const lbfgsfloatval_t step) {
    /* Compute the the negative log posterior, which is the negative 
       penalized log-(pseudo)likelihood and the objective for MAP inference
    */
    void **d = (void **)instance;
    alignment_t *ali = (alignment_t *) d[0];
    options_t *options = (options_t *) d[1];
    numeric_t *lambdas = (numeric_t *) d[2];

    /* Initialize log-likelihood and gradient */
    lbfgsfloatval_t fx = 0.0;
    for (int i = 0; i < ali->nParams; i++) g[i] = 0;

    /* Block fields hi */
    numeric_t *hi = (numeric_t *)
        malloc(ali->nSites * ali->nCodes * sizeof(numeric_t));
    numeric_t *gHi = (numeric_t *)
        malloc(ali->nSites * ali->nCodes * sizeof(numeric_t));
    for (int i = 0; i < ali->nSites; i++)
        for (int ai = 0; ai < ali->nCodes; ai++) Hi(i, ai) = xHi(i, ai);
    for (int i = 0; i < ali->nSites * ali->nCodes; i++) gHi[i] = 0;

    /* Block couplings eij */
    numeric_t *eij = (numeric_t *) malloc(ali->nSites * ali->nSites
        * ali->nCodes * ali->nCodes * sizeof(numeric_t));
    numeric_t *gEij = (numeric_t *) malloc(ali->nSites * ali->nSites
        * ali->nCodes * ali->nCodes * sizeof(numeric_t));
    for (int i = 0; i < ali->nSites * ali->nSites * ali->nCodes * ali->nCodes;
        i++) eij[i] = 0.0;
    for (int i = 0; i < ali->nSites * ali->nSites * ali->nCodes * ali->nCodes;
        i++) gEij[i] = 0.0;
    for (int i = 0; i < ali->nSites - 1; i++)
        for (int j = i + 1; j < ali->nSites; j++)
            for (int ai = 0; ai < ali->nCodes; ai++)
                for (int aj = 0; aj < ali->nCodes; aj++)
                    Eij(j, aj, i, ai) = Eij(i, ai, j, aj) = xEij(i, j, ai, aj);


    /* Negative log-pseudolikelihood */
    for (int s = 0; s < ali->nSeqs; s++) {
        /* Form potential for conditional log likelihoods at every site */
        numeric_t *H = (numeric_t *)
            malloc(ali->nCodes * ali->nSites * sizeof(numeric_t));
        numeric_t *Z = (numeric_t *) malloc(ali->nSites * sizeof(numeric_t));

        /* Initialize potentials with fields */
        // memcpy(H, hi, ali->nSites * ali->nCodes * sizeof(numeric_t));
        for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++) H[jx] = hi[jx];

        /* Contribute coupling block due to i, ai */
        for (int i = 0; i < ali->nSites; i++) {
            const letter_t ai = seq(s, i);
            const numeric_t *jB = &(Eij(i, ai, 0, 0));
            for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++)
                H[jx] += jB[jx];
        }

        /* Conditional log likelihoods */
        for (int i = 0; i < ali->nSites * ali->nCodes; i++) H[i] = exp(H[i]);
        for (int i = 0; i < ali->nSites; i++) Z[i] = 0;
        for (int i = 0; i < ali->nSites; i++)
            for (int ai = 0; ai < ali->nSites; ai++) Z[i] += Hp(i, ai);
        for (int i = 0; i < ali->nSites; i++)
            for (int ai = 0; ai < ali->nSites; ai++) Hp(i, ai) /= Z[i];

        numeric_t seqFx = 0;
        for (int i = 0; i < ali->nSites; i++)
            seqFx -= ali->weights[s] * log(Hp(i, seq(s, i)));

        for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++)
            H[jx] *= -ali->weights[s];

        for (int i = 0; i < ali->nSites; i++)
            gHi(i, seq(s, i)) -= ali->weights[s];
        for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++) gHi[jx] -= H[jx];

        for (int i = 0; i < ali->nSites - 1; i++)
            for (int j = i; j < ali->nSites; j++)
                gEij(i, seq(s, i), j, seq(s, j)) -= ali->weights[s];

        for (int i = 0; i < ali->nSites; i++) {
            const letter_t ai = seq(s, i);
            numeric_t *jgBlock = &(gEij(i, ai, 0, 0));
            for (int jx = 0; jx < ali->nSites * ali->nCodes; jx++)
                jgBlock[jx] -= H[jx];
        }

        free(H);
        free(Z);
        fx += seqFx;
    }

    for (int i = 0; i < ali->nSites; i++)
        for (int ai = 0; ai < ali->nCodes; ai++)
            dHi(i, ai) += gHi(i, ai);

    for (int i = 0; i < ali->nSites - 1; i++)
        for (int j = i + 1; j < ali->nSites; j++)
            for (int ai = 0; ai < ali->nCodes; ai++)
                for (int aj = 0; aj < ali->nCodes; aj++)
                    dEij(i, j, ai, aj) += gEij(j, aj, i, ai) + gEij(i, ai, j, aj);
    free(hi);
    free(gHi);
    free(eij);
    free(gEij);

    ali->negLogLk = fx;

    /* Gaussian priors */
    for (int i = 0; i < ali->nSites; i++)
        for (int ai = 0; ai < ali->nCodes; ai++) {
            dHi(i, ai) += lambdaHi(i) * 2.0 * xHi(i, ai);
            fx += lambdaHi(i) * xHi(i, ai) * xHi(i, ai);
        }

    for (int i = 0; i < ali->nSites-1; i++)
        for (int j = i + 1; j < ali->nSites; j++)
            for (int ai = 0; ai < ali->nCodes; ai++)
                for (int aj = 0; aj < ali->nCodes; aj++) {
                    dEij(i, j, ai, aj) += lambdaEij(i, j)
                        * 2.0 * xEij(i, j, ai, aj);
                    fx += lambdaEij(i, j)
                        * xEij(i, j, ai, aj) * xEij(i, j, ai, aj);
                }

    fx = PostCondition(x, g, fx, ali, options);
    return fx;
}
Beispiel #24
0
SparseMatrix BSplineBasis::evalBasisHessian(DenseVector &x) const
{
    // Hessian basis matrix
    /* Hij = B1 x ... x DBi x ... x DBj x ... x Bn
     * (Hii = B1 x ... x DDBi x ... x Bn)
     * Where B are basis functions evaluated at x,
     * DB are the derivative of the basis functions,
     * and x is the kronecker product.
     * Hij is in R^(numBasisFunctions x 1)
     * so that basis hessian H is in R^(numBasisFunctions*numInputs x numInputs)
     * The real B-spline Hessian is calculated as (c^T x 1^(numInputs x 1))*H
     */
    SparseMatrix H(getNumBasisFunctions()*numVariables, numVariables);
    //H.setZero(numBasisFunctions()*numInputs, numInputs);

    // Calculate partial derivatives
    // Utilizing that Hessian is symmetric
    // Filling out lower left triangular
    for (unsigned int i = 0; i < numVariables; i++) // row
    {
        for (unsigned int j = 0; j <= i; j++) // col
        {
            // One column in basis jacobian
            SparseMatrix Hi(1,1);
            Hi.insert(0,0) = 1;

            for (unsigned int k = 0; k < numVariables; k++)
            {
                SparseMatrix temp = Hi;
                SparseMatrix Bk;
                if (i == j && k == i)
                {
                    // Diagonal element
                    Bk = bases.at(k).evaluateDerivative(x(k),2);
                }
                else if (k == i || k == j)
                {
                    Bk = bases.at(k).evaluateDerivative(x(k),1);
                }
                else
                {
                    Bk = bases.at(k).evaluate(x(k));
                }
                Hi = kroneckerProduct(temp, Bk);
            }

            // Fill out column
            for (int k = 0; k < Hi.outerSize(); ++k)
            for (SparseMatrix::InnerIterator it(Hi,k); it; ++it)
            {
                if (it.value() != 0)
                {
                    int row = i*getNumBasisFunctions()+it.row();
                    int col = j;
                    H.insert(row,col) = it.value();
                }
            }
        }
    }

    H.makeCompressed();

    return H;
}
int main(void) {
	/* Init system */
	TM_RCC_InitSystem();
	
	/* Init HAL layer */
	HAL_Init();
	
	/* Timer Init for SysTick */
	timer_start();

	/* Init leds */
	TM_DISCO_LedInit();
	
	/* Init delay */
	TM_DELAY_Init();
	
	/* Init USB peripheral */
	TM_USB_Init();
	
	/* Init VCP on FS port.. */
	TM_USBD_CDC_Init(TM_USB_FS);
	
	/* Start USB device mode on FS port.. */
	TM_USBD_Start(TM_USB_FS);
	
	while (1) {
		/* Process USB CDC device, send remaining data if needed */
		/* It is better if you call this in periodic timer, like each ms in SYSTICK handler */
		TM_USBD_CDC_Process(TM_USB_FS);
		
		/* Check if device is ready, if drivers are installed if needed on FS port */
		if (TM_USBD_IsDeviceReady(TM_USB_FS) == TM_USBD_Result_Ok) {
			TM_DISCO_LedOn(LED_GREEN);
		} else {
			TM_DISCO_LedOff(LED_GREEN);
		}
		
		/* Check if user has changed parameter for COM port */
		TM_USBD_CDC_GetSettings(TM_USB_FS, &USB_FS_Settings);
		
		/* Check if updated */
		if (USB_FS_Settings.Updated) {
			/* Update settings for UART here if needed */
			TM_USBD_CDC_Puts(TM_USB_FS, "USB FS settings changed!\n");
		}
		
		/* Check if anything received on FS port */
		if (TM_USBD_CDC_Getc(TM_USB_FS, &ch)) {
			/* One character received */
			
			/* Send it back */
			/* TM_USBD_CDC_Putc(TM_USB_FS, ch); */

			/* Control LEDs based on input (debug) */
			switch(ch){
			case '1':
				TM_DISCO_LedToggle(LED_BLUE);
				break;
			case '2':
				TM_DISCO_LedToggle(LED_ORANGE);
				TM_USBD_CDC_Puts(TM_USB_FS, "Toggling Orange LED\n");
				break;
			case '3':
				TM_DISCO_LedToggle(LED_RED);
				TM_USBD_CDC_Puts(TM_USB_FS, "Toggling Red LED\n");
				break;
			case '4':
				TM_DISCO_LedToggle(LED_GREEN);
				break;
			case '5':
				/* Transfer Sample Audio */
				  trace_puts("Sending Audio Sample");

				/* For now, send entire sample audio data */
				/* TODO get size of sample to be transfered from serial port */

				/* at 115k BAUD 800 bytes is sub 10 msec total transfer time */
				for(int i = 0; i < SAMPLEAUDIO_SIZE;i++)
				{
					/* Need to split 16 bit samples into upper and lower bytes */
					/* Note that these will need to be reconstructed in the
					 * processing script. Updated Buffer size to 1024 from 256 in
					 * USBD_CDC library file for this operation.
					 */
					/* Send MSB first */
					TM_USBD_CDC_Putc(TM_USB_FS, Hi(SampleAudio[i]));
					trace_putchar((int)Hi(SampleAudio[i]));
					/* Then Send LSB */
					TM_USBD_CDC_Putc(TM_USB_FS, Lo(SampleAudio[i]));
					trace_putchar((int)Lo(SampleAudio[i]));
				}
				break;
			default:
				break;
			}
		}
		//Wait for next system tick
		while (g_SysTick_Flag == 0){};
		g_SysTick_Flag = 0;
		TM_DISCO_LedToggle(LED_BLUE);
	}
}
Beispiel #26
0
void init_ramp1(S16 init_val)
{
	Hi(ramp1) = init_val;
	Lo(ramp1) = 0;
}
Beispiel #27
0
void init_ramp2(S16 init_val)
{
	Hi(ramp2) = init_val;
	Lo(ramp2) = 0;
}
Beispiel #28
0
void BazaModBus::writeregister(unsigned char* mass){
  switch(AddressRegister){
    case 0x0010:
    case 0x0011:
    case 0x0012:
    case 0x0013:
    case 0x0014:
    case 0x0015:{//изменение даты/времени
      for(i_mod=0; i_mod<6; i_mod++) mass[4+i_mod]=((DataMass[i_mod+0x10]/10)<<4)+(DataMass[i_mod+0x10]%10);
      mass[4+AddressRegister-0x10]=(char) (((DataRegister/10)<<4) + (DataRegister%10));
      NumCom=0xB2; NumByte=6;
    }break;
    case 0x0016:{ //запись пароля в EEPROM
      ePassword[0]=((DataRegister>>12)&0x0F)+0x30;
      ePassword[1]=((DataRegister>>8)&0x0F)+0x30;
      ePassword[2]=((DataRegister>>4)&0x0F)+0x30;
      ePassword[3]=(DataRegister&0x0F)+0x30;
      eWrite=1;eAddressWrite=0;eMassiveWrite=ePassword;
    }break;
    case 0x0030:
    case 0x0033:
    case 0x0036:{
      if (DataRegister==2) {NumCom=0x71; NumByte=0;}  //ввод утройств
      if (DataRegister==0) {NumCom=0x70; NumByte=0;}  //вывод устройств
    }break;
    case 0x0050:
    case 0x0051:
    case 0x0052:
    case 0x0053:
    case 0x0054:
    case 0x0055:
    case 0x0056:{
      NumCom=AddressRegister+0x31; NumByte=1;
      mass[4]=DataRegister;
    }break;
    case 0x0060:
    case 0x0061:{
      NumCom=AddressRegister+0x31; NumByte=1;
      mass[4]=DataRegister;
    }break;
    case 0x0062:
    case 0x0063:
    case 0x0064:
    case 0x0065:{
      NumCom=0x94; NumByte=2;
      mass[4]=AddressRegister-0x0061;
      mass[5]=DataRegister;
    }break;
    case 0x0066:
    case 0x0067:
    case 0x0068:
    case 0x0069:{
      NumCom=0x95; NumByte=2;
      mass[4]=AddressRegister-0x0065;
      mass[5]=DataRegister;
    }break;
 /*
    case 0x0062:
    case 0x0063:
    case 0x0064:
    case 0x0065{
      NumCom=0x94; NumByte=2;
      mass[4]=AddressRegister-0x0062+1;
      mass[5]=DataRegister;
    }break;
    case 0x0066:
    case 0x0067:
    case 0x0068:
    case 0x0069:{
      NumCom=0x95; NumByte=2;
      mass[4]=AddressREgister-0x0066+1;
      mass[5]=DataRegister;
    }break;
*/
    case 0x006A:
    case 0x006B:
    case 0x006C:
    case 0x006D:
    case 0x006E:
    case 0x006F:
    case 0x0070:
    case 0x0071:
    case 0x0072:
    case 0x0073:
    case 0x0074:
    case 0x0075:
    case 0x0076:
    case 0x0077:
    case 0x0078:
    case 0x0079:
    case 0x007A:
    case 0x007B:
    case 0x007C:
    case 0x007D:
    case 0x007E:
    case 0x007F:
    case 0x0080:
    case 0x0081:
    case 0x0082:
    case 0x0083:
    case 0x0084:
    case 0x0085:
    case 0x0086:
    case 0x0087:
    case 0x0088:
    case 0x0089:{
      NumCom=0x93; NumByte=2;
      mass[4]=AddressRegister-0x6A+1;
      mass[5]=DataRegister;
    }break;
    case 0x0090:
    case 0x0091:
    case 0x0092:{
      NumCom=AddressRegister+0x11; NumByte=1;
      mass[4]=DataRegister;
    }break;
    case 0x0093:
    case 0x0094:
    case 0x0095:
    case 0x0096:{
      NumCom=0xA4; NumByte=2;
      mass[4]=AddressRegister-0x0092;
      mass[5]=DataRegister;
    }break;
    case 0x0097:
    case 0x0098:
    case 0x0099:
    case 0x009A:{
      NumCom=0xA5; NumByte=2;
      mass[4]=AddressRegister-0x0096;
      mass[5]=DataRegister;
    }break;
/*
    case 0x0093:
    case 0x0094:
    case 0x0095:
    case 0x0096:{
      NumCom=0xA4; NumByte=2;
      mass[4]=AddressRegister-0x93+1;
      mass[5]=DataRegister;
    }break;
    case 0x0097:
    case 0x0098:
    case 0x0099:
    case 0x009A:{
      NumCom=0xA5; NumByte=2;
      mass[4]=AddressRegister-0x97+1;
      mass[5]=DataRegister;
    }break;
*/
    case 0x00A0:
    case 0x00A1:
    case 0x00A2:
    case 0x00A3:
    case 0x00A4:{
      NumCom=AddressRegister+0x15; NumByte=1;
      mass[4]=DataRegister;
    }break;
    case 0x00A5:{
      NumCom=AddressRegister+0x15; NumByte=2;
      mass[4]=Hi(DataRegister);
      mass[5]=Lo(DataRegister);
    }break;
    case 0x00A6:{
      NumCom=AddressRegister+0x15; NumByte=1;
      mass[4]=DataRegister;
    }break;
    case 0x00A7:{
      NumCom=0xBD; NumByte=1;
      mass[4]=DataRegister;
    }break;
    case 0x00B4:{
      NumCom=0xFA; NumByte=0;
      for (i_mod=0; i_mod<129; i_mod++) JournalMass[i_mod]=0xEEEE;
    }break; //стереть архив событий, для этого пишется любое значение в ячейку с количеством записей архива
    case 0x00B5:{
      NumCom=0xCA; NumByte=0;
      for (i_mod=0; i_mod<129; i_mod++) JournalMass[i_mod]=0xEEEE;
    }break; //стереть архив Поста, для этого пишется любое значение в ячейку с количеством записей архива
    case 0x00B6:{
      NumCom=0xDA; NumByte=0;
      for (i_mod=0; i_mod<129; i_mod++) JournalMass[i_mod]=0xEEEE;
    }break; //стереть архив Приемника, для этого пишется любое значение в ячейку с количеством записей архива
    case 0x00B7:{
      NumCom=0xEA; NumByte=0;
      for (i_mod=0; i_mod<129; i_mod++) JournalMass[i_mod]=0xEEEE;
    }break; //стереть архив Передатчика, для этого пишется любое значение в ячейку с количеством записей архива
  }
};
Beispiel #29
0
char* TScramAuth::getChallenge(const TCHAR *challenge)
{
	unsigned chlLen, saltLen = 0;
	ptrA snonce, salt;
	int ind = -1;

	ptrA chl((char*)mir_base64_decode(_T2A(challenge), &chlLen));

	for (char *p = strtok(NEWSTR_ALLOCA(chl), ","); p != NULL; p = strtok(NULL, ",")) {
		if (*p == 'r' && p[1] == '=') { // snonce
			if (strncmp(cnonce, p + 2, mir_strlen(cnonce)))
				return NULL;
			snonce = mir_strdup(p + 2);
		}
		else if (*p == 's' && p[1] == '=') // salt
			salt = (char*)mir_base64_decode(p + 2, &saltLen);
		else if (*p == 'i' && p[1] == '=')
			ind = atoi(p + 2);
	}

	if (snonce == NULL || salt == NULL || ind == -1)
		return NULL;

	ptrA passw(mir_utf8encodeT(info->conn.password));
	size_t passwLen = mir_strlen(passw);

	BYTE saltedPassw[MIR_SHA1_HASH_SIZE];
	Hi(saltedPassw, passw, passwLen, salt, saltLen, ind);

	BYTE clientKey[MIR_SHA1_HASH_SIZE];
	mir_hmac_sha1(clientKey, saltedPassw, sizeof(saltedPassw), (BYTE*)"Client Key", 10);

	BYTE storedKey[MIR_SHA1_HASH_SIZE];

	mir_sha1_ctx ctx;
	mir_sha1_init(&ctx);
	mir_sha1_append(&ctx, clientKey, MIR_SHA1_HASH_SIZE);
	mir_sha1_finish(&ctx, storedKey);

	char authmsg[4096];
	int authmsgLen = mir_snprintf(authmsg, _countof(authmsg), "%s,%s,c=biws,r=%s", msg1, chl, snonce);

	BYTE clientSig[MIR_SHA1_HASH_SIZE];
	mir_hmac_sha1(clientSig, storedKey, sizeof(storedKey), (BYTE*)authmsg, authmsgLen);

	BYTE clientProof[MIR_SHA1_HASH_SIZE];
	for (unsigned j = 0; j < sizeof(clientKey); j++)
		clientProof[j] = clientKey[j] ^ clientSig[j];

	/* Calculate the server signature */
	BYTE serverKey[MIR_SHA1_HASH_SIZE];
	mir_hmac_sha1(serverKey, saltedPassw, sizeof(saltedPassw), (BYTE*)"Server Key", 10);

	BYTE srvSig[MIR_SHA1_HASH_SIZE];
	mir_hmac_sha1(srvSig, serverKey, sizeof(serverKey), (BYTE*)authmsg, authmsgLen);
	serverSignature = mir_base64_encode((PBYTE)srvSig, sizeof(srvSig));

	char buf[4096];
	ptrA encproof(mir_base64_encode((PBYTE)clientProof, sizeof(clientProof)));
	int cbLen = mir_snprintf(buf, "c=biws,r=%s,p=%s", snonce, encproof);
	return mir_base64_encode((PBYTE)buf, cbLen);
}
Beispiel #30
0
// Read int from EEPROM.
unsigned int EEPROM_Read_int (unsigned int address) {
   unsigned int num = 0;
   Lo(num) = EEPROM_Read(address);
   Hi(num) = EEPROM_Read(address+1);
   return num;
}