Ejemplo n.º 1
0
/**
 * <p>Restores the source state indices and the epsilon filter mode from a hash
 * key.</p>
 * <p>The composition algorithm maintains a hash map <i>M</i>:
 * (<code>nSX</code>, <code>nSY</code>, <code>nFlagXY</code>) &rarr;
 * <code>nS</code> which associates a state index <code>nS</code> in the
 * composed transducer with the respective state indices in the left operand
 * (<code>nSX</code>) and in the right operand (<code>nSY</code>) and with an
 * epsilon transition filter mode <code>nFlagXY</code>.</p>
 * @param _this Pointer to composed transducer instance
 * @param lpKey    The hash key to be resolved
 * @param lpSX     Pointer to a buffer to be filled with state index in left operand
 * @param lpSY     Pointer to a buffer to be filled with state index in left operand
 * @param lpFlagXY Pointer to a buffer to be filled epsilon transition filter mode
 * @see Compose CFst_Compose
 */
void CGEN_PRIVATE CFst_Cps_HashResolveKey
(
  CFst*       _this,
  const void* lpKey,
  FST_ITYPE*  lpSX,
  FST_ITYPE*  lpSY,
  BYTE*       lpFlagXY
)
{
  FST_ITYPE nS = (FST_ITYPE)((int)((UINT64)lpKey & 0xffffffff));

  if (nS>=0)
  {
    /* TODO: replace by SD_SX, SD_SY and SD_FLAGYX macros */
    *lpSX     = *(FST_ITYPE*)CData_XAddr(AS(CData,_this->sd),(INT32)nS,_this->m_nIcSdAux  );
    *lpSY     = *(FST_ITYPE*)CData_XAddr(AS(CData,_this->sd),(INT32)nS,_this->m_nIcSdAux+1);
    *lpFlagXY = *(BYTE*     )CData_XAddr(AS(CData,_this->sd),(INT32)nS,_this->m_nIcSdAux+2);
  }
  else
  {
    *lpSX     = _this->m_lpCpsKeybuf[0];
    *lpSY     = _this->m_lpCpsKeybuf[1];
    *lpFlagXY = (BYTE)_this->m_lpCpsKeybuf[2];
  }
}
Ejemplo n.º 2
0
/**
 *  Expand/reduce number of pitch markers to fit new target sum of period length.
 *
 * @param idSrc        source object
 * @param idDst        target object
 * @param n            target length
 * @return O_K if sucessfull, not exec otherwise
 */
INT16 CGEN_PUBLIC CPMproc::ExpandPm(CData *idSrc, CData* idDst, INT32 n)
{
  if(CData_IsEmpty(idSrc) == TRUE) return NOT_EXEC;
  if(n <= 0)                       return NOT_EXEC;

  CREATEVIRTUAL(CData,idSrc,idDst);

  DLPASSERT(CData_GetNComps(idSrc) == 2);

  CData_Reset(idDst, TRUE);
  CData_Scopy(idDst,idSrc);

  INT32    nRecsNew = 0;
  INT32    nRecs    = (INT32)CData_GetNRecs(idSrc);
  INT16* pm_new = NULL;

  if(dlm_pm_expand((INT16*)CData_XAddr(idSrc,0,0), nRecs, &pm_new, &nRecsNew, n) != O_K) {
    return IERROR(this,ERR_NULLARG, "", NULL, NULL);
  }
  CData_Allocate(idDst,nRecsNew);
  dlp_memmove(CData_XAddr(idDst,0,0), pm_new, nRecsNew*2*sizeof(INT16));
  dlp_free(pm_new);
  CData_CopyDescr(idDst,idSrc);

  /* clean up */
  DESTROYVIRTUAL(idSrc,idDst)

  return(O_K);
}
Ejemplo n.º 3
0
/**
 *  Expand/reduce number of pitch markers to new number.
 *
 * @param idSrc        source object
 * @param idDst        target object
 * @param n            target number of pitch markers
 * @return O_K if sucessfull, not exec otherwise
 */
INT16 CGEN_PUBLIC CPMproc::CompressPm(CData *idSrc, CData* idDst, INT32 n)
{
  if(CData_IsEmpty(idSrc) == TRUE) return NOT_EXEC;
  if(n <= 0)                       return NOT_EXEC;

  CREATEVIRTUAL(CData,idSrc,idDst);

  DLPASSERT(CData_GetNComps(idSrc) == 2);
  CData_Reset(idDst, TRUE);
  CData_Scopy(idDst,idSrc);
  CData_Allocate(idDst, n);

  if(dlm_pm_compress((INT16*)CData_XAddr(idSrc,0,0),
                     CData_GetNRecs(idSrc),
                     (INT16*)CData_XAddr(idDst,0,0),
                     CData_GetNRecs(idDst)) != O_K) {
    return IERROR(this,ERR_NULLARG, "", NULL, NULL);
  }
  CData_CopyDescr(idDst,idSrc);

  /* clean up */
  DESTROYVIRTUAL(idSrc,idDst)

  return(O_K);
}
Ejemplo n.º 4
0
/*
 * Manual page at process.def
 */
INT16 CGEN_PUBLIC CProcess::Status()
{
  CData* d;
  char   s[L_INPUTLINE];
  INT32   i;

  printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols());               // Protocol
  printf("\n   Status of instance");                                            // Protocol
  printf("\n   process %s",BASEINST(_this)->m_lpInstanceName);                  // Protocol
  printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols());               // Protocol
  printf("\n   State       : 0x%04X",m_nState);                                 // Protocol
  if (m_nState!=0)                                                              // In any but the maiden state
  {                                                                             // >>
    BOOL b = 0;                                                                 //   Comma flag
    printf(" (");                                                               //   Protocol
    if (m_nState&PRC_DATASENT    ) { if(b) printf(", "); printf("data sent"    ); b=1; }//...
    if (m_nState&PRC_RUNNING     ) { if(b) printf(", "); printf("running"      ); b=1; }//...
    if (m_nState&PRC_COMPLETE    ) { if(b) printf(", "); printf("complete"     ); b=1; }//...
    if (m_nState&PRC_KILLED      ) { if(b) printf(", "); printf("killed"       ); b=1; }//...
    if (m_nState&PRC_DATARECEIVED) { if(b) printf(", "); printf("data received"); b=1; }//...
    printf(")");                                                                //   Protocol
  }                                                                             // <<
  printf("\n   Return value: %ld",(long)m_nRetVal  );                           // Protocol
  if (dlp_strlen(m_psTmpFile)) printf("\n   Temp. files : %s*",m_psTmpFile);    // Protocol
  dlp_strcpy(s,m_psCmdLine); dlp_strreplace(s,m_psTmpFile,"<tmpfile>");         // Abbreviate command line
  if (dlp_strlen(m_psCmdLine)) printf("\n   Command line: %s" ,s);              // Protocol

  // Show transferred data                                                      // ------------------------------------
  if (m_iDto)                                                                   // Have data transfer object
  {                                                                             // >>
    printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols());             //   Protocol
    printf("\n   Transferred data");                                            //   Protocol
    d = (CData*)CDlpObject_FindInstanceWord(m_iDto,PRC_S_IDSIGN,NULL);          //   Get signature table
    printf("\n   - function  : %s",(char*)CData_XAddr(d,0,0));                  //   Protocol (job function name)
    for (i=1; i<CData_GetNRecs(d); i++)                                         //   Loop over function arguemnts
      printf("\n   %13s %s",i==1?"- arguments :":"",(char*)CData_XAddr(d,i,0)); //     Protocol (job function arg.)
    d = (CData*)CDlpObject_FindInstanceWord(m_iDto,PRC_S_IDGLOB,NULL);          //   Get list of global instances
    if (d)                                                                      //   Have one
      for (i=0; i<CData_GetNRecs(d); i++)                                       //     Loop over entries
        printf("\n   %13s %-8s %s",i==0?"- globals   :":"",                     //       Protocol (global instance)
          (char*)CData_XAddr(d,i,0),(char*)CData_XAddr(d,i,1));                 //       |
    printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols());             //   Protocol
    printf("\n   Transferred program");                                         //   Protocol
    for (i=0; dlp_strlen(__sSlaveScript[i]); i++)                               //   Loop over slave script lines
    {                                                                           //   >>
      dlp_strcpy(s,__sSlaveScript[i]);                                          //     Get a line
      if (strstr(s,"##"))*(strstr(s,"##"))='\0';                                //     Truncate at comment
      printf("\n     (%02ld) %s",i,dlp_strtrimright(s));                        //     Protocol (script line)
    }                                                                           //   <<
  }                                                                             // <<

  printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols()); printf("\n"); // Protocol
  return O_K;                                                                   // All done
}
Ejemplo n.º 5
0
/**
 * Returns a pointer to one of the data arrays of a statistics' class
 *
 * @param _this
 *           Pointer to CStatistics instance
 * @param c
 *           Statistics class index
 * @param nData
 *           Data array identifier, one of the <code>STA_DAI_XXX</code>
 *           constants
 * @return The pointer to the first double value of the desired array and class
 *         or <code>NULL</code> in case of errors.
 */
FLOAT64* CGEN_PRIVATE CStatistics_GetPtr(CStatistics* _this, INT32 c, INT16 nData)
{
  INT32 N    = 0;                                                               /* Statistics dimensionality         */
  INT32 nRpb = 0;                                                               /* Records per block                 */
  CHECK_THIS_RV(NULL);                                                          /* Check this pointer                */
  N    = CStatistics_GetDim(_this);                                             /* Get statistics dimensionality     */
  nRpb = CData_GetNRecsPerBlock(_this->m_idDat);                                /* Get records per block             */
  if (nData<STA_DAI_KSUM)                                                       /* Before k-th order sums            */
    return (FLOAT64*)CData_XAddr(_this->m_idDat,c*nRpb + nData,0);              /*   Return pointer to data          */
  else if (nData==STA_DAI_KSUM)                                                 /* k-th order sums                   */
    return (FLOAT64*)CData_XAddr(_this->m_idDat,c*nRpb + N+4,0);                /*   Return pointer to data          */
  else return NULL;                                                             /* Cannot happen                     */
}
Ejemplo n.º 6
0
/**
 * Fills a data table with the sample size (frequency) or the estimated a-priori
 * probability of the classes.
 *
 * @param _this
 *          Pointer to this CStatistics instance
 * @param idDst
 *          Pointer to the destination data instance
 * @param bProb
 *          If <code>TRUE</code> the method estimates class a-priori
 *          probabilities otherwise it stores the classes' sample sizes
 * @return <code>O_K</code> if successsfull, a (negative) error code otherwise
 */
INT16 CGEN_PUBLIC CStatistics_FreqEx
(
  CStatistics* _this,
  CData*       idDst,
  BOOL         bProb
)
{
  INT32    c     = 0;                                                            /* Class loop counter                */
  INT32    C     = 0;                                                            /* Number of statistics classes      */
  INT32    nTsz  = 0;                                                            /* Total sample size                 */
  FLOAT64* lpSsz = NULL;                                                         /* Pointer to class' c sample size   */

  /* Validate */                                                                /* --------------------------------- */
  if (!idDst) return IERROR(_this,ERR_NULLARG,"idDst",0,0);                     /* Check output data instance        */
  CData_Reset(idDst,TRUE);                                                      /* Clear destination instance        */
  CHECK_THIS_RV(NOT_EXEC);                                                      /* Check this pointer                */
  IF_NOK(CStatistics_Check(_this))                                              /* Check instance data               */
    return IERROR(_this,STA_NOTSETUP," ( use -status for details)",0,0);        /* ...                               */

  /* Initialize */                                                              /* --------------------------------- */
  C = CStatistics_GetNClasses(_this);                                           /* Get number of statistics classes  */
  CData_Array(idDst,T_DOUBLE,1,C);                                              /* Allocate output data instance     */
  CData_SetNBlocks(idDst,C);                                                    /* Set block number                  */
  if (!CData_XAddr(idDst,0,0)) return IERROR(_this,ERR_NOMEM,0,0,0);            /* Should have been successfull ...  */

  /* Store sample sizes / estimated a-rpior probabilities */                    /* --------------------------------- */
  nTsz = bProb ? CStatistics_GetNSamples(_this) : 1;                            /* Get frequency divident            */
  for (c=0; c<C; c++)                                                           /* Loop over classes                 */
  {                                                                             /* >>                                */
    DLPASSERT((lpSsz = CStatistics_GetPtr(_this,c,STA_DAI_SSIZE)));             /*   Get ptr. to class' c sample size*/
    CData_Dstore(idDst,lpSsz[0]/(FLOAT64)nTsz,c,0);                              /*   Store sample size of class c    */
  }                                                                             /* <<                                */

  return O_K;
}
Ejemplo n.º 7
0
/**
 * Initialize one record from a token list.
 *
 * @param lpsInit Null ('\0') separated list of tokens. A double null "\0\0"
 *                is expected as list terminator!
 * @param nRec    Record index of first cell to initialize
 * @param nComp   Component index of first cell to initialize
 * @return O_K if successfull, a negative error code otherwise
 */
INT16 CGEN_PUBLIC CData_InitializeRecordEx
(
  CData*      _this,
  const char* lpsInit,
  INT32        nRec,
  INT32        nComp
)
{
  const char* lpsToken = NULL;
  INT32  nXC            = 0;
  INT32  nC             = 0;

  nXC = CData_GetNComps(_this);
  nC  = nComp;

  if (nC<0   || nC>=nXC                    ) return NOT_EXEC;
  if (nRec<0 || nRec>=CData_GetNRecs(_this)) return NOT_EXEC;

  for (lpsToken=lpsInit; *lpsToken && nC<nXC; lpsToken+=dlp_strlen(lpsToken)+1, nC++)
    if (dlp_strcmp(lpsToken,"*")!=0)
      IF_NOK(dlp_sscanx(lpsToken,CData_GetCompType(_this,nC),CData_XAddr(_this,nRec,nC)))
        IERROR(_this,DATA_BADINITIALIZER,lpsToken,(int)nRec,(int)nC);

  if (*lpsToken) return IERROR(_this,DATA_INITIALIZERS,"many",0,0);
  if (nC<nXC   ) IERROR(_this,DATA_INITIALIZERS,"few" ,0,0);
  return O_K;
}
Ejemplo n.º 8
0
/**
 * Initializes the instance from the interpreter command line.
 * <h3>Note</h3>
 * <p>You must setup the method invocation context <code>m_lpMic</code> (see 
 * <a href="dlpinst.html"><code class="link">CDlpInstance</code></a>) before
 * calling this method. Otherwise it will do noting.</p>
 * 
 * @param _this  This instance
 * @param nRec   First record to read
 * @param nComp  First component to read
 * @param nCount Number of items to read
 * @return O_K if successfull, an error code otherwise
 */
INT16 CGEN_PUBLIC CData_InitializeEx(CData* _this, INT32 nRec, INT32 nComp, INT32 nCount)
{
  INT32        nXXR     = 0;
  INT32        nXC      = 0;
  INT32        nR       = 0;
  INT32        nC       = 0;
  INT32        nCtr     = 0;
  BOOL        bRead    = 0;
  const char* lpsToken = NULL;

  if (_this && !CDlpObject_MicGet(BASEINST(_this)))
    return IERROR(_this,ERR_GENERIC,"No method invocation context",0,0);

  if (!_this || CData_IsEmpty(_this))
  {
    /* _this == NULL is ok, just remove the tokens between { and } */
    do
    {
      lpsToken = MIC_NEXTTOKEN_FORCE;
      if (!lpsToken) return IERROR(_this,DATA_HERESCAN,"}",0,0);
    } 
    while (dlp_strcmp(lpsToken,"}")!=0);
    return O_K;
  }

  /* Actual setup */
  nXXR  = CData_GetMaxRecs(_this);
  nXC   = CData_GetNComps(_this);
  nR    = nRec;
  nC    = nComp;
  bRead = TRUE;

  for (;;)
  {
    lpsToken = MIC_NEXTTOKEN_FORCE;
    if (!lpsToken) return IERROR(_this,DATA_HERESCAN,"}",0,0);
    if (dlp_strcmp(lpsToken,"}")==0) break;
    if (!bRead) continue;

    if (nR==nXXR || (nCount>=0 && nCtr>=nCount))
    {
      /* Ignore further initializers */
      bRead = FALSE;
      continue;
    }

    /* Initialize cell value; skip cell on wildcard '*' initializer */
    if (dlp_strcmp(lpsToken,"*")!=0)
      IF_NOK(dlp_sscanx(lpsToken,CData_GetCompType(_this,nC),CData_XAddr(_this,nR,nC)))
        IERROR(_this,DATA_BADINITIALIZER,lpsToken,(int)nR,(int)nC);

    nCtr++;
    nC++;
    if (nC==nXC) { nC=nComp; nR++; }
  } 

  if (nCount>=0&&nCtr<nCount) return IERROR(_this,DATA_INITIALIZERS,"few" ,0,0);
  if (!bRead                ) return IERROR(_this,DATA_INITIALIZERS,"many",0,0);
  return O_K;
}
Ejemplo n.º 9
0
/**
 * Get scaling function coefficients
 *
 * @return O_K if successfull, NOT_EXEC otherwise
 */
INT16 CGEN_PUBLIC CFWTproc::GetCoef(CData *idCoef)
{
  INT16  di=GetDindex();
  const FLOAT64 *h;
  if(!di) return IERROR(this,ERR_INVALARG,"wvltype invalid",0,0);
  if(!(h=dlm_fwt_geth(di))) return NOT_EXEC;
  CData_Array(idCoef,T_DOUBLE,1,di);
  memcpy(CData_XAddr(idCoef,0,0),h,sizeof(FLOAT64)*di);
  return O_K;
}
Ejemplo n.º 10
0
/**
 * Associates the composed state <code>nS</code> with its source states
 * <code>nSX</code> (left operand) and <code>nSY</code> (right operand) and
 * with its epsilon filter mode <code>nFlagXY</code>.
 *
 * @param _this   Pointer to composed (destination) automaton instance
 * @param nS      Unit relative composed (destination) state index
 * @param nSX     Unit relative source state index in left operand (<code>itSrc1</code>)
 * @param nSY     Unit relative source state index in right operand (<code>itSrc2</code>)
 * @param nFlagXY Epsilon filter mode, one of the <code>CPS_EFLT_XXX</code> constants
 * @see Cps_FindState CFst_Cps_FindState
 * @see Cps_AddSdAux CFst_Cps_AddSdAux
 * @see Cps_DelSdAux CFst_Cps_DelSdAux
 */
void CGEN_PRIVATE CFst_Cps_SetSdAux
(
  CFst*     _this,
  FST_ITYPE nS,
  FST_ITYPE nSX,
  FST_ITYPE nSY,
  BYTE      nFlagXY
)
{
  IFCHECKEX(2)
    printf("\n       nS=%ld: Set [X=%ld, Y=%ld, Flg=%d]",(long)nS,(long)nSX,(long)nSY,(int)nFlagXY);

  /* Store state's auxiliary info */
  /* TODO: replace by SD_SX, SD_SY and SD_FLAGYX macros */
  *(FST_ITYPE*)(CData_XAddr(AS(CData,_this->sd),nS,_this->m_nIcSdAux  )) = nSX;
  *(FST_ITYPE*)(CData_XAddr(AS(CData,_this->sd),nS,_this->m_nIcSdAux+1)) = nSY;
  *(BYTE*     )(CData_XAddr(AS(CData,_this->sd),nS,_this->m_nIcSdAux+2)) = nFlagXY;

  /* Insert state into state hashmap for reverse lookup */
  hash_alloc_insert((hash_t*)_this->m_lpCpsHash,(void*)(long)nS,(void*)(long)nS);
}
Ejemplo n.º 11
0
/**
 * Prints the instance in text mode (exactly one component of type 1).
 */
INT16 CGEN_PRIVATE CData_PrintText(CData* _this)
{
  INT32  nR   = 0;                                                               /* Current record                    */
  INT32  nXR  = 0;                                                               /* Number of records                 */
  char* tx   = NULL;                                                            /* Auxilary char pointer #1          */
  char* tx0  = NULL;                                                            /* Pointer to string                 */
  char* ty   = NULL;                                                            /* Auxilary char pointer #2          */
  char* ty0  = NULL;                                                            /* Pointer to last white space       */
  INT32  nCtr = 0;                                                               /* Line counter                      */
  char  sBuf[255];                                                              /* Printing buffer                   */

  /* Initialize */                                                              /* --------------------------------- */
  nXR = CData_GetNRecs(_this);                                                  /* Get number of records             */

  /* Print data contents as text */                                             /* --------------------------------- */
  DLPASSERT(FMSG("ALPHA: String mode not tested yet"));                         /* TODO: Remove after debugging      */
  printf("\n  String Mode"); dlp_inc_printlines(1);                             /* Protocol                          */
  tx0=tx=(char*)CData_XAddr(_this,0,0);                                         /* Initialize char pointers          */
  if (!*tx)                                                                     /* Empty string                      */
  {                                                                             /* >>                                */
    printf("\n  [empty]");                                                      /*   Protocol                        */
    dlp_inc_printlines(1);                                                      /*   Adjust no. of printed lines     */
  }                                                                             /* <<                                */
  else while (*tx)                                                              /* Loop over characters              */
  {                                                                             /* >>                                */
    /* Make line breaks */                                                      /*   - - - - - - - - - - - - - - - - */
    for (ty=tx,ty0=NULL; *ty && ty<tx0+nXR; )                                   /*   Do until end of string          */
    {                                                                           /*   >>                              */
      while (*ty && ty<tx0+nXR && !iswspace(*ty)) ty++;                         /*     Seek next white space         */
      while (*ty && ty<tx0+nXR &&  iswspace(*ty)) ty++;                         /*     Skip following white spaces   */
      ty0=ty;                                                                   /*     Remember previous white spc.  */
      if (ty>tx+dlp_maxprintcols()-16) break;                                   /*     Line full                     */
    }                                                                           /*   <<                              */
    if (ty0) ty=ty0;                                                            /*   Go back to last white space     */

    /* Print one line */                                                        /*   - - - - - - - - - - - - - - - - */
    dlp_memset(sBuf,0,255);                                                     /*   Clear printing buffer           */
    dlp_memmove(sBuf,tx,ty-tx);                                                 /*   Copy characters in              */
    printf("\n  %4d(%06d): %s",(int)nCtr,(int)(tx-tx0),sBuf);                   /*   Print 'em                       */
    dlp_inc_printlines(1);                                                      /*   Adjust no. of printed lines     */
    if (dlp_if_printstop()) break;                                              /*   Break listing                   */

    /* End-of-line actions */                                                   /*   - - - - - - - - - - - - - - - - */
    DLPASSERT(ty>tx);                                                           /*   Should have made some progress  */
    tx=ty;                                                                      /*   Move to end of printed line     */
    nCtr++;                                                                     /*   Increment line counter          */
  }                                                                             /* <<                                */
  if (nR>=nXR) printf("\n  No more data - Stop.");                              /* Protocol                          */
  else         printf("\n  Cancelled - Stop.");                                 /* Protocol                          */
  return O_K;                                                                   /* Ok                                */
}
Ejemplo n.º 12
0
/**
 * <p>INTERNAL USE ONLY. This method is called by {@link -pool} to pool the
 * statistics blocks contained in <code>idSrc</code> and store the result in
 * <code>idPool</code>. The operation is controlled through the pooling mode
 * flag <code>nMode</code> as follows:</p>
 *
 * <ul>
 *   <li>nMode=0: Pool sum data, <code>idPool</code> will be overwritten</li>
 *   <li>nMode=1: Pool min data</li>
 *   <li>nMode=2: Pool max data</li>
 * </ul>
 *
 * <h3>Remarks</h3>
 * <ul>
 *   <li>In order to pool raw statistics data, there are three calls
 *     (<code>nMode</code>=0,1 and 2) necessary. The first call of these
 *     <em>must</em> be the one with <code>nMode</code>=0!</li>
 *   <li>There are NO checks performed</li>
 * </ul>
 *
 * @param idPool
 *          Pooled raw statistics data block
 * @param idSrc
 *          Raw statistics data blocks to be pooled
 * @param nMode
 *          Pooling mode, see above
 */
void CGEN_SPRIVATE CStatistics_PoolInt(CData* idPool, CData* idSrc, INT32 nMode)
{
  CData* idAux      = NULL;                                                     /* Auxilary data instance #1         */

  if (nMode==0)                                                                 /* Sum aggregation mode              */
  {                                                                             /* >>                                */
    ISETOPTION(idPool,"/block");                                                /*   Switch target to block mode     */
    CData_Aggregate(idPool,idSrc,NULL,CMPLX(0),"sum");                          /*   Aggregate (sum up)              */
    IRESETOPTIONS(idPool);                                                      /*   Switch target to normal mode    */
  }                                                                             /* <<                                */
  else if (nMode==1 || nMode==2)                                                /* Extrama aggregation modes         */
  {                                                                             /* >>                                */
    ICREATEEX(CData,idAux,"CStatistics_Pool_int.~idAux",NULL);                  /*   Create auxilary data instance #1*/
    ISETOPTION(idAux,"/block");                                                 /*   Switch target to block mode     */
    CData_Aggregate(idAux,idSrc,NULL,CMPLX(0),nMode==1?"min":"max");            /*   Aggregate (minimum or maximum)  */
    dlp_memmove(CData_XAddr(idPool,nMode,0),CData_XAddr(idAux,nMode,0),         /*   Copy aggregated min. or max. ...*/
      CData_GetRecLen(idAux));                                                  /*   | ... to target                 */
    IRESETOPTIONS(idAux);                                                       /*   Switch target to normal mode    */
    IDESTROY(idAux);                                                            /*   Destroy auxilary data inst. #1  */
  }                                                                             /* <<                                */
  else                                                                          /* Unknown mode                      */
    DLPASSERT(FMSG("Invalid internal pooling mode"));                           /*   Not so good ...                 */
}
Ejemplo n.º 13
0
/**
 * Converts the automaton weights to weights to another semiring.
 *
 * @param nSrType Semiring type (<code>FST_WSR_PROB</code>,
 *                <code>FST_WSR_LOG</code> or <code>FST_WSR_TROP</code>)
 * @return <code>O_K</code> if successfull, a (negative) error code otherwise
 */
INT16 CGEN_PUBLIC CFst_Wsr_Convert(CFst* _this, INT16 nSrType)
{
  INT16 nWsrt = FST_WSR_NONE;
  INT32  nIcW  = -1;
  INT32  nT    = 0;
  INT32  nXXT  = 0;
  INT32  nRlt  = 0;
  BYTE* lpW   = NULL;
  BYTE* lpW0  = NULL;

  /* Validation */                                                              /* --------------------------------- */
  CHECK_THIS_RV(NOT_EXEC);                                                      /* Check this pointer                */
  CFst_Check(_this);                                                            /* Check FST(s)                      */

  /* Initialize */                                                              /* --------------------------------- */
  nWsrt = CFst_Wsr_GetType(_this,&nIcW);                                        /* Get current weight semiring type  */
  if (nWsrt==FST_WSR_NONE) return IERROR(_this,FST_UNWEIGHTED,0,0,0);           /* No weights, no service            */
  if (nWsrt==nSrType     ) return O_K;                                          /* Nothing to be done                */
  lpW0 = CData_XAddr(AS(CData,_this->td),0,nIcW);                               /* Get pointer to weight component   */
  nRlt = CData_GetRecLen(AS(CData,_this->td));                                  /* Get record length of trans. list  */
  nXXT = UD_XXT(_this);                                                         /* Get total number of transitions   */

  /* Convert weights */                                                         /* --------------------------------- */
  switch (nSrType)                                                              /* Branch for target weight sr. type */
  {                                                                             /* >>                                */
  case FST_WSR_PROB:                                                            /* Probability semiring              */
    /* TODO: Push log/tropical weights to the left!!! */                        /* X X X X X X X X X X X X X X X X X */
    IERROR(_this,FST_INTERNALW,"Probabilities may be >1",__FILE__,__LINE__);    /* Warn user!                        */
    for (nT=0,lpW=lpW0; nT<nXXT; nT++,lpW+=nRlt)                                /* Loop over all transitions         */
      *(FST_WTYPE*)lpW = exp(*(FST_WTYPE*)lpW*-1);                              /*   P = exp(-w)                     */
    CData_SetCname(AS(CData,_this->td),nIcW,NC_TD_PSR);                         /*   Rename weight component         */
    break;                                                                      /* ==                                */
  case FST_WSR_LOG:                                                             /* Log semiring                      */
    if (nWsrt==FST_WSR_PROB)                                                    /* Converting from probabilities     */
      for (nT=0,lpW=lpW0; nT<nXXT; nT++,lpW+=nRlt)                              /*   Loop over all transitions       */
        *(FST_WTYPE*)lpW = -1*log(*(FST_WTYPE*)lpW);                            /*     w = -log(P)                   */
    CData_SetCname(AS(CData,_this->td),nIcW,NC_TD_LSR);                         /*   Rename weight component         */
    break;                                                                      /* ==                                */
  case FST_WSR_TROP:                                                            /* Topical semiring                  */
    if (nWsrt==FST_WSR_PROB)                                                    /* Converting from probabilities     */
      for (nT=0,lpW=lpW0; nT<nXXT; nT++,lpW+=nRlt)                              /*   Loop over all transitions       */
        *(FST_WTYPE*)lpW = -1*log(*(FST_WTYPE*)lpW);                            /*     w = -log(P)                   */
    CData_SetCname(AS(CData,_this->td),nIcW,NC_TD_TSR);                         /*   Rename weight component         */
    break;                                                                      /* ==                                */
  default:                                                                      /* nSrType unknown                   */
    return IERROR(_this,FST_INVALID,"weight semiring type",0,0);                /*   Error                           */
  }                                                                             /* <<                                */
  return O_K;                                                                   /* All right                         */
}
Ejemplo n.º 14
0
/**
 * Prints the instance in list mode (old style, with option /list).
 */
INT16 CGEN_PUBLIC CData_PrintList(CData* _this)
{
  INT32 nR   = 0;                                                                /* Current record                    */
  INT32 nXR  = 0;                                                                /* Number of records                 */
  INT32 nXC  = 0;                                                                /* Number of components              */
  INT32 nRpb = 0;                                                                /* Number of records per block       */

  /* Initialize */                                                              /* --------------------------------- */
  nXR  = CData_GetNRecs(_this);                                                 /* Get number of records             */
  nXC  = CData_GetNComps(_this);                                                /* Get number of components          */
  nRpb = CData_GetNRecsPerBlock(_this);                                         /* Get number of records per block   */

  /* Print headings */                                                          /* --------------------------------- */
  printf("\n   Rec.(offset):");                                                 /* Protocol                          */
  dlp_inc_printlines(CData_PrintRec(_this,-1,0,nXC,16)-1);                      /* Protocol                          */

  /* Print values */                                                            /* --------------------------------- */
  for (nR=0; nR<nXR; )                                                          /* Loop over records                 */
  {                                                                             /* >>                                */
    printf("\n%c %4ld (%06ld):",CData_RecIsMarked(_this,nR)?'*':' ',(long)nR,   /*   Print line header               */
      (long)((char*)CData_XAddr(_this,nR,0)-(char*)CData_XAddr(_this,0,0)));    /*   |                               */
    dlp_inc_printlines(CData_PrintRec(_this,nR,0,nXC,16));                      /*   Print values                    */
    if (nRpb>0 && (nR+1)%nRpb==0)                                               /*   Block boundary                  */
    {                                                                           /*   >>                              */
      printf("\n - %c End of block %ld - - - - -",                              /*     Print block delimiter         */
        CData_BlockIsMarked(_this,nR/nRpb)?'*':' ',(long)nR/nRpb);              /*     |                             */
      dlp_inc_printlines(1);                                                    /*     Adjust no. of printed lines   */
    }                                                                           /*   <<                              */
    if ((nR=dlp_printstop_nix(nR,"record",NULL))==-1) break;                    /*   Break listing                   */
    if (nR< -2 ) nR=0;                                                          /*   Bad user reply -> start over    */
    if (nR>=nXR) break;                                                         /*   No more records -> break        */
  }                                                                             /* <<                                */
  if (nR>=nXR) printf("\n  No more data - Stop.");                              /* Protocol                          */
  else         printf("\n  Cancelled - Stop.");                                 /* Protocol                          */
  return O_K;                                                                   /* Ok                                */
}
Ejemplo n.º 15
0
/**
 * Implementation of the class function. Leaves the value of the variable on
 * the stack.
 */
void CGEN_PROTECTED CVar_Exec(CVar *_this)
{
  switch (_this->m_nType)
  {
    case T_BOOL:
      CDlpObject_MicPutB(BASEINST(_this),_this->m_bBVal);
      break;
    case T_DOUBLE:
    case T_COMPLEX:
      CDlpObject_MicPutN(BASEINST(_this),_this->m_nNVal);
      break;
    case T_STRING:
      CDlpObject_MicPutS(BASEINST(_this),_this->m_lpsSVal);
      break;
    case T_INSTANCE:
      CDlpObject_MicPutI(BASEINST(_this),BASEINST(_this)->m_iAliasInst);
      break;
    case T_RDOUBLE: {
      _this->m_nInd  = (INT32)(rand()/_this->m_nNorm);
      _this->m_nNVal = CMPLX(_this->m_nLow+_this->m_nInd*_this->m_nDelta);
      CDlpObject_MicPutN(BASEINST(_this),_this->m_nNVal);
      break; }
    case T_RDDATA:
      _this->m_nInd  = (INT32)(rand()/_this->m_nNorm);
      _this->m_nNVal = CData_Cfetch(AS(CData,_this->m_idRndSet),_this->m_nInd, _this->m_nIcomp);
      CDlpObject_MicPutN(BASEINST(_this),_this->m_nNVal);
      break;
    case T_RSDATA:
      _this->m_nInd = (INT32)(rand()/_this->m_nNorm);
      CVar_Sset(_this,(char*)CData_XAddr(AS(CData,_this->m_idRndSet),_this->m_nInd,_this->m_nIcomp));
      _this->m_nType = T_RSDATA;
      CDlpObject_MicPutS(BASEINST(_this),_this->m_lpsSVal);
      break;
    default: DLPASSERT(FMSG("Unknown variable type"));
  }
}
Ejemplo n.º 16
0
/*
 * Manual page at fst_man.def
 */
INT16 CGEN_PUBLIC CFst_Rcs(CFst* _this, INT32 nUnit, FLOAT64 nSeed)
{
#ifdef __UNENTANGLE_FST

  return IERROR(_this,FST_INTERNAL,__FILE__,__LINE__,0);
  /* NOTE: __UNENTANGLE_FST was defined (probably in dlp_config.h or fst.def).
   *       Undefine it to use this feature!
   */

#else /* #ifdef __UNENTANGLE_FST */

  INT32      nU     = 0;                                                        /* Current unit                       */
  FST_ITYPE nS     = 0;                                                        /* Current state                      */
  FST_ITYPE nS2    = 0;                                                        /* Current state                      */
  FST_ITYPE nFS    = 0;                                                        /* First state of current unit        */
  FST_ITYPE nXS    = 0;                                                        /* Number of states of current unit   */
  FST_ITYPE nT     = 0;                                                        /* Current transition                 */
  FST_ITYPE nFT    = 0;                                                        /* First transition of current unit   */
  FST_ITYPE nXT    = 0;                                                        /* Number of tran. of current unit    */
  CData*    idP    = NULL;                                                     /* Incidence matrix                   */
  CData*    idB    = NULL;                                                     /* Constanct vector of (idP-E)idX=idB */
  CData*    idI    = NULL;                                                     /* idI = (idP-E)^-1                   */
  CData*    idX    = NULL;                                                     /* Solution of (idP-E)idX=idB         */
  FST_WTYPE nPSum  = 0.;                                                       /* Probability sum/state              */
  INT32      nIcW   = -1;                                                       /* Index of probability comp. in td   */
  INT32      nIcRcs = -1;                                                       /* Index of ref. counter comp. in sd  */
  INT32      nIcRct = -1;                                                       /* Index of ref. counter comp. in td  */

  /* Validation */
  CHECK_THIS_RV(NOT_EXEC);
  CFst_Check(_this);

  if (CFst_Wsr_GetType(_this,&nIcW)!=FST_WSR_PROB)
    return IERROR(_this,FST_MISS,"transition probability component",NC_TD_PSR,"transition table");

  /* Initialize - Find or add reference counters */
  nIcRcs = CData_FindComp(AS(CData,_this->sd),NC_SD_RC);
  nIcRct = CData_FindComp(AS(CData,_this->td),NC_TD_RC);
  if (nIcRcs<0)
  {
    CData_AddComp(AS(CData,_this->sd),NC_SD_RC,DLP_TYPE(FST_WTYPE));
    nIcRcs = CData_GetNComps(AS(CData,_this->sd))-1;
  }
  if (nIcRct<0)
  {
    CData_AddComp(AS(CData,_this->td),NC_TD_RC,DLP_TYPE(FST_WTYPE));
    nIcRct = CData_GetNComps(AS(CData,_this->td))-1;
  }

  /* Initialize - Create auxilary instances */
  ICREATEEX(CData,idP,"~CFst_Reverse.idP",NULL);
  ICREATEEX(CData,idB,"~CFst_Reverse.idB",NULL);
  ICREATEEX(CData,idI,"~CFst_Reverse.idI",NULL);
  ICREATEEX(CData,idX,"~CFst_Reverse.idX",NULL);

  /* Loop over units */
  for (nU=nUnit<0?0:nUnit; nU<UD_XXU(_this); nU++)
  {
    CData_Reset(BASEINST(idP),TRUE);
    CData_Reset(BASEINST(idB),TRUE);
    CData_Reset(BASEINST(idI),TRUE);
    CData_Reset(BASEINST(idX),TRUE);
    nFS = UD_FS(_this,nU);
    nXS = UD_XS(_this,nU);
    nFT = UD_FT(_this,nU);
    nXT = UD_XT(_this,nU);

    /* Export transposed ergodic incidence matrix */
    IF_NOK(CData_AddNcomps(idP,DLP_TYPE(FST_WTYPE),UD_XS(_this,nU)+1)) break;
    IF_NOK(CData_Allocate (idP,UD_XS(_this,nU)+1)                    ) break;
    IF_NOK(CData_AddNcomps(idB,DLP_TYPE(FST_WTYPE),1                )) break;
    IF_NOK(CData_Allocate (idB,UD_XS(_this,nU)+1)                    ) break;

    /* Fill transposed incidence matrix
       (summing up probabilities of parallel transitions) */
    for (nT=nFT; nT<nFT+nXT; nT++)
      *(FST_WTYPE*)CData_XAddr(idP,TD_TER(_this,nT),TD_INI(_this,nT)) +=
        *(FST_WTYPE*)CData_XAddr(AS(CData,_this->td),nT,nIcW);

    for (nS=0; nS<nXS; nS++)
    {
      if ((SD_FLG(_this,nS+nFS)&0x01)==0x01)     /* Connect final states with start state */
      {
        for (nS2=1, nPSum=0.; nS2<nXS; nS2++)
          nPSum += *(FST_WTYPE*)CData_XAddr(idP,nS2,nS);

        *(FST_WTYPE*)CData_XAddr(idP,0,nS) = 1.-nPSum;
      }

      *(FST_WTYPE*)CData_XAddr(idP,nS,nS)-=1.;   /* Subtract eigenvalue 1 from main diagonal */
      *(FST_WTYPE*)CData_XAddr(idP,nXS,nS)=1.;   /* Additional equation implementing constraint sum(P_state)=1 */
      *(FST_WTYPE*)CData_XAddr(idP,nS,nXS)=1.;   /* Additional variable making incidence matrix quadratic */
    }

    /* Fill constant vector */
    CData_Fill(idB,CMPLX(1.),CMPLX(0.));

    /* Calculate eigenvector of length 1 and eigenvalue 1
       --> stationary state probabilities */
    CMatrix_Op(idI,idP,T_INSTANCE,NULL,T_IGNORE,OP_INVT);
    CMatrix_Op(idX,idB,T_INSTANCE,idI,T_INSTANCE,OP_MULT);

    /* Fill in state reference counters */
    if (nSeed>0.) nSeed /= CData_Dfetch(idX,0,0); else nSeed = 1.;
    for (nS=0; nS<nXS; nS++)
      CData_Dstore(AS(CData,_this->sd),nSeed*CData_Dfetch(idX,nS,0),nS+nFS,nIcRcs);

    /* Calculate stationary transition probabilities */
    for (nT=nFT; nT<nFT+nXT; nT++)
      CData_Dstore
      (
        AS(CData,_this->td),
        CData_Dfetch(AS(CData,_this->sd),TD_INI(_this,nT)+nFS,nIcRcs) *
          CData_Dfetch(AS(CData,_this->td),nT,nIcW),
        nT,nIcRct
      );

    /* Clean up */
    IDESTROY(idP);
    IDESTROY(idB);
    IDESTROY(idI);
    IDESTROY(idX);

    /* Stop in single unit mode */
    if (nUnit>=0) break;
  }

  return O_K;

#endif /* #ifdef __UNENTANGLE_FST */
}
Ejemplo n.º 17
0
/**
 * Prints the content of one record formatted as columns. If printing requires
 * more than <a href="dlp_base.html#cfn_dlp_maxprintcols">dlp_maxprintcols</a>
 * characters the listing will be continued on the next line(s).</p>
 *
 * @param _this
 *          Pointer to data instance
 * @param nRec
 *          Index of record to print
 * @param nIcFirst
 *          Index of first component to print
 * @param nComps
 *          Number of components to print
 * @param nIndent
 *          Indentation (spaces) at beginning of lines (<b>Note</b>: the first
 *          line will <em>not</em> be indented!)
 * @return The number of lines printed
 */
INT16 CGEN_PUBLIC CData_PrintRec
(
  CData* _this,
  INT32    nRec,
  INT32    nIcFirst,
  INT32    nComps,
  INT16   nIndent
)
{
  INT16 nLines = 1;
  INT16 nCol   = nIndent;
  INT32  nXC    = 0;
  INT32  nC     = 0;
  INT16 i      = 0;
  INT16 I      = 0;
  char  sBuf[L_SSTR+1];

  nXC = CData_GetNComps(_this);

  if (nIcFirst<0 || nIcFirst>=nXC) return 1; /* NOTE: This is still one line! */
  if (nIcFirst+nComps>nXC) nComps=nXC-nIcFirst;
  if (nRec>=CData_GetNRecs(_this)) return 0;

  for (nC=nIcFirst,nCol=nIndent; nC<nIcFirst+nComps; nC++)
  {
    if (nRec<0)
    {
      /* Heading */
      I=dlp_printlen(CData_GetCompType(_this,nC));
      strcpy(sBuf," ");
      for (i=I-(INT16)dlp_strlen(CData_GetCname(_this,nC))-1; i>0; i--) strcat(sBuf," ");
      if(CData_CompIsMarked(_this,nC)) sBuf[dlp_strlen(sBuf)-2]='*';
      strcat(sBuf,CData_GetCname(_this,nC));
      nCol+=dlp_printlen(CData_GetCompType(_this,nC)); /* Count standard width (!) */
      printf(sBuf);
    }
    else
    {
      /* Print values */
      dlp_sprintx(sBuf,(char*)CData_XAddr(_this,nRec,nC),CData_GetCompType(_this,nC),_this->m_bExact);
      nCol+=dlp_printlen(CData_GetCompType(_this,nC)); /* Count standard width (!) */
      dlp_strconvert(SC_PRC_ESCAPE,sBuf,sBuf);
      dlp_strreplace(sBuf,"\n","\\n");
      dlp_strreplace(sBuf,"\r","\\r");
      dlp_strreplace(sBuf,"\t","\\t");
      printf(sBuf);
    }

    if ((nC<nIcFirst+nComps-1)                                               &&
        (nCol+dlp_printlen(CData_GetCompType(_this,nC+1))>dlp_maxprintcols()) )
    {
      /* Line break */
      strcpy(sBuf,"\n");
      for (i=nIndent-(nIndent>7?7:0); i>0;i--) strcat(sBuf," ");
      printf(sBuf);
      if (nIndent>7) printf("%5ld  ",(long)(nC+1));
      nCol=nIndent;
      nLines++;
    }
  }

  return nLines;
}
Ejemplo n.º 18
0
/**
 * Computes the print widths of the head column and one data vector.
 */
INT16 CGEN_PRIVATE CData_PrintVectors_GetColWidth
(
  CData* _this,                                                                 /* Pointer to data instance          */
  INT32   nR0,                                                                   /* First record to be printed        */
  INT32   nC0,                                                                   /* First component to be printed     */
  INT32*  lpnWI,                                                                 /* Print width of comp.idx.col.(ret) */
  INT32*  lpnW0,                                                                 /* Print width of head column (ret)  */
  INT32*  lpnW                                                                   /* Print width of data column (ret)  */
)                                                                               /* Returns O_K or (neg.) error code  */
{
  INT32   nR   = 0;                                                              /* Current record                    */
  INT32   nXR  = 0;                                                              /* Number of records                 */
  INT32   nC   = 0;                                                              /* Current component                 */
  INT32   nXC  = 0;                                                              /* Number of components              */
  INT32   nWn  = 0;                                                              /* Widest number in cols. of screen  */
  INT32   nWs  = 0;                                                              /* Widest string in cols. of screen  */
  FLOAT64 nBuf = 0.;                                                             /* Double buffer                     */
  char   sBuf[L_SSTR+1];                                                        /* String buffer                     */
  UINT64 nTime = 0;

  /* Initialize */                                                              /* --------------------------------- */
  *lpnW  = 0;                                                                   /* Data column width                 */
  *lpnWI = 0;                                                                   /* Component index column width      */
  *lpnW0 = 0;                                                                   /* Head column width                 */
  nXR    = CData_GetNRecs(_this);                                               /* Get number of records             */
  nXC    = CData_GetNComps(_this);                                              /* Get number of components          */

  /* Compute head column print width */                                         /* --------------------------------- */
  for (*lpnW0=0,nC=nC0; nC<nXC; nC++)                                           /* Loop over remaining components    */
  {                                                                             /* >>                                */
    if                                                                          /*   Displaying physical units?      */
    (                                                                           /*   |                               */
      dlp_is_numeric_type_code(CData_GetCompType(_this,nC)) &&                  /*   | Numeric component             */
      dlp_strlen(_this->m_lpCunit) && _this->m_nCinc!=0.                        /*   | Physical units specified      */
    )                                                                           /*   |                               */
    {                                                                           /*   >>                              */
      nBuf = _this->m_nCofs + nC*_this->m_nCinc;                                /*     The physical coordinate       */
      __sprintx(sBuf,&nBuf,T_DOUBLE,_this->m_bExact);                           /*     Print to a string             */
    }                                                                           /*   <<                              */
    else                                                                        /*   String comp. or no phys. units  */
      __sprintx(sBuf,CData_GetCname(_this,nC),10,_this->m_bExact);              /*     Print component name to str.  */
    *lpnW0 = MAX(*lpnW0,(INT32)dlp_strlen(sBuf));                               /*   Get length of phys. unit / name */
  }                                                                             /* <<                                */

  /* Compute component index column print width */                              /* --------------------------------- */
  nC--;                                                                         /* Last component to be printed      */
  __sprintx(sBuf,&nC,T_INT,_this->m_bExact);                                    /* Print greatest comp. index to str.*/
  *lpnWI = (INT32)dlp_strlen(sBuf);                                             /* Get length of component index col.*/

  /* Compute data vector print width */                                         /* --------------------------------- */
  nTime = dlp_time();
  for (*lpnW=0,nR=nR0; nR<nXR; nR++)                                            /* Loop over remaining records       */
  {                                                                             /* >>                                */
    /* Determine width of physical unit */                                      /*   - - - - - - - - - - - - - - - - */
    if (dlp_strlen(_this->m_lpRunit) && _this->m_lpTable->m_fsr!=0.)            /*   Displaying physical units?      */
    {                                                                           /*   >>                              */
      nBuf = _this->m_lpTable->m_ofs + nR*_this->m_lpTable->m_fsr;              /*     The physical coordinate       */
      __sprintx(sBuf,&nBuf,T_DOUBLE,_this->m_bExact);                           /*     Print to a string             */
      *lpnW = MAX((INT32)dlp_strlen(sBuf),*lpnW);                               /*     Aggregate actual print width  */
    }                                                                           /*   <<                              */

    /* Determine width of record index */                                       /*   - - - - - - - - - - - - - - - - */
    __sprintx(sBuf,&nR,T_INT,_this->m_bExact);                                  /*   Print record index to a string  */
    *lpnW = MAX((INT32)dlp_strlen(sBuf),*lpnW);                                 /*     Aggregate actual print width  */

    /* Determine greatest component width */                                    /*   - - - - - - - - - - - - - - - - */
    for (nC=nC0; nC<nXC; nC++)                                                  /*   Loop over remaining components  */
    {                                                                           /*   >>                              */
      __sprintx(sBuf,CData_XAddr(_this,nR,nC),                                  /*     Print cell value to a string  */
          CData_GetCompType(_this,nC),_this->m_bExact);                         /*       |                           */
      if (dlp_is_numeric_type_code(CData_GetCompType(_this,nC)))                /*     It is a number                */
        nWn = MAX((INT32)dlp_strlen(sBuf),nWn);                                 /*       Aggr. number print width    */
      else if (dlp_is_symbolic_type_code(CData_GetCompType(_this,nC)))          /*     It is a string                */
        nWs = MAX((INT32)dlp_strlen(sBuf),nWs);                                  /*       Aggr. string print width    */
      if (dlp_time()-nTime>__TIMEOUT) break;                                    /*      Takes too long -> forget it! */
    }                                                                           /*   <<                              */

    if (dlp_time()-nTime>__TIMEOUT) break;                                      /*    Takes too long -> forget it!   */
    if ((nR-nR0+2)*((*lpnW)+1)>dlp_maxprintcols()-*lpnWI-*lpnW0-3) break;       /*    Next vec. would not fit anymore*/
  }                                                                             /*  <<                               */

  /* If computing data vector print width timed out ... */                      /* --------------------------------- */
  if (dlp_time()-nTime>__TIMEOUT)                                               /* There was a time out              */
    for (nC=nC0; nC<nXC; nC++)                                                  /*   Loop over remaining components  */
      if (dlp_is_numeric_type_code(CData_GetCompType(_this,nC)))                /*     It is a number                */
        nWn = MAX(dlp_printlen(CData_GetCompType(_this,nC)),nWn);               /*       Use standard print width    */
      else if (dlp_is_symbolic_type_code(CData_GetCompType(_this,nC)))          /*     It is a string                */
        nWs = MAX(dlp_printlen(CData_GetCompType(_this,nC)),nWs);               /*       Also use std. print width   */

  /* Aftermath */                                                               /* --------------------------------- */
  if (nWs>dlp_maxprintcols()-(*lpnW0)-(*lpnWI)-3)                               /* Limit string width to line length */
    nWs=dlp_maxprintcols()-(*lpnW0)-(*lpnWI)-3;                                 /* ...                               */
  if (nWn<=0) *lpnW = MAX(nWs,*lpnW);                                           /* No numbers -> complete strings    */
  else *lpnW = MAX(nWn,*lpnW);                                                  /* Minimal space req. for numbers    */
  /*if (nWn>0 && *lpnW+3<nWs) (*lpnW) += 3;*/                                       /* Print a little more of the strs.  */
  if (nWn>0 && *lpnW<nWs) *lpnW = MIN(16,nWs);                                  /* Print max. 16 chars. of strings   */
  return O_K;                                                                   /* Ok                                */
}
Ejemplo n.º 19
0
/*
 * Manual page at statistics.def
 */
INT16 CGEN_PUBLIC CStatistics_Pool
(
  CStatistics* _this,
  CStatistics* iSrc,
  CData*       idMap
)
{
  INT32   i          = 0;                                                        /* Current component index           */
  INT32   nC         = 0;                                                        /* Current pooled statistics class   */
  INT32   nCs        = 0;                                                        /* Current source class index        */
  INT32   nXC        = 0;                                                        /* Number of pooled classes          */
  INT32   nRpb       = 0;                                                        /* Statistics raw data block size    */
  INT16  nCheckSave = 0;                                                        /* Saved check level                 */
  CData* idAux      = NULL;                                                     /* Auxilary data instance #1         */
  CData* idPmp      = NULL;                                                     /* Pooling map                       */
  CData* idPcd      = NULL;                                                     /* Pooled class raw data buffer      */

  /* Initialize */                                                              /* --------------------------------- */
  CHECK_THIS_RV(0);                                                             /* Check this instance               */
  IF_NOK(CStatistics_Check(iSrc))                                               /* Check source statistics           */
    return IERROR(_this,ERR_INVALARG,"iSrc",0,0);                               /* ...                               */
  nCheckSave = _this->m_nCheck;                                                 /* Save check level                  */
  CStatistics_Reset(BASEINST(_this),TRUE);                                      /* Reset destination                 */
  _this->m_nCheck = nCheckSave;                                                 /* Restore check level               */
  IFIELD_RESET(CData,"dat");                                                    /* Create pool raw stats. data inst. */

  /* Protocol */                                                                /* --------------------------------- */
  IFCHECK                                                                       /* On verbose level 1                */
  {                                                                             /* >>                                */
    printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols());             /*   Print protocol header           */
    printf("\n   statistics -pool");                                            /*   ...                             */
    printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols());printf("\n");/*   ...                             */
  }                                                                             /* <<                                */

  /* No map --> pool all classes */                                             /* --------------------------------- */
  if (CData_IsEmpty(idMap))                                                     /* NULL or empty map instance        */
  {                                                                             /* >>                                */
    IFCHECK printf("\n   Empty pooling map --> pool all classes");              /*   Protocol (verbose level 1)      */
    CStatistics_PoolInt(_this->m_idDat,iSrc->m_idDat,0);                        /*   Pool sum data                   */
    CStatistics_PoolInt(_this->m_idDat,iSrc->m_idDat,1);                        /*   Pool min data                   */
    CStatistics_PoolInt(_this->m_idDat,iSrc->m_idDat,2);                        /*   Pool max data                   */
    STA_PROTOCOL_FOOTER(1,"done");                                              /*   Print protocol footer           */
    return O_K;                                                                 /*   That's it                       */
  }

  IFCHECK printf("\n   Pooling by map");                                        /* Protocol (verbose level 1)        */
  ICREATEEX(CData,idAux,"CStatistics_Pool.~idAux",NULL);                        /* Create auxilary data instance #1  */
  ICREATEEX(CData,idPmp,"CStatistics_Pool.~idPmp",NULL);                        /* Create pooling map                */
  ICREATEEX(CData,idPcd,"CStatistics_Pool.~idPcs",NULL);                        /* Create pooled raw stats.data inst.*/

  /* Find and copy map component (pooled class) */                              /* --------------------------------- */
  for (i=0; i<CData_GetNComps(idMap); i++)                                      /* Loop over components of idMap     */
    if (dlp_is_numeric_type_code(CData_GetCompType(idMap,i)))                   /*   Is current component numeric?   */
    {                                                                           /*   >> (Yes)                        */
      CData_SelectComps(idPmp,idMap,i,1);                                       /*     Copy component                */
      break;                                                                    /*     Have ready :)                 */
    }                                                                           /*   <<                              */
  if (CData_IsEmpty(idPmp))                                                     /* Have not got map component        */
  {                                                                             /* >>                                */
    IERROR(_this,STA_BADCOMP,"map",BASEINST(idMap)->m_lpInstanceName,"numeric");/*   Error message                   */
    DLPTHROW(STA_BADCOMP);                                                      /*   Throw exception                 */
  }                                                                             /* <<                                */

  /* Create source class component */                                           /* --------------------------------- */
  CData_AddComp(idPmp,"srcc",T_LONG);                                           /* Add source class index component  */
  for (i=0; i<CData_GetNRecs(idPmp); i++) CData_Dstore(idPmp,i,i,1);            /* Fill it                           */

  /* Finish pooling map and initialize pooling */                               /* --------------------------------- */
  CData_Sortup(idPmp,idPmp,0);                                                  /* Sort map by pooled class index    */
  nXC = (INT32)CData_Dfetch(idPmp,CData_GetNRecs(idPmp)-1,0)+1;                 /* Get greatest pooled class index   */
  IFCHECK printf("\n   Pooling %ld statistics classes",(long)nXC);              /* Protocol (verbose level 1)        */
  IFCHECKEX(3) CData_Print(idPmp);                                              /* Print pooling map (verbose lvl.3) */
  nRpb = CData_GetNRecsPerBlock(iSrc->m_idDat);                                 /* Get block size                    */

  /* Prepare pooled statistics */                                               /* --------------------------------- */
  CData_Scopy(_this->m_idDat,iSrc->m_idDat);                                    /* Create target raw data components */
  CData_Allocate(_this->m_idDat,nRpb*nXC);                                      /* Allocate target raw data          */
  CData_SetNBlocks(_this->m_idDat,nXC);                                         /* Set target statistics block number*/

  /* Pooling loop */                                                            /* --------------------------------- */
  for (i=0; i<CData_GetNRecs(idPmp); )                                          /* Loop over pooling map             */
  {                                                                             /* >>                                */
    /* - Copy raw statistics data of one pooled class */                        /*   - - - - - - - - - - - - - - - - */
    nC = (INT32)CData_Dfetch(idPmp,0,0);                                         /*   Get pooled class index          */
    IFCHECK printf("\n     Pooled class %3ld");                                 /*   Protocol (verbose level 1)      */
    for (i=0; i<CData_GetNRecs(idPmp); i++)                                     /*   Loop over partition of pool.map */
    {                                                                           /*   >>                              */
      if (nC != (INT32)CData_Dfetch(idPmp,0,0)) break;                           /*     Not the current class anymore */
      nCs = (INT32)CData_Dfetch(idPmp,i,1);                                      /*     Get source class index        */
      IFCHECK printf("\n     - Source class %3ld",nCs);                         /*     Protocol (verbose level 1)    */
      CData_SelectBlocks(idAux,iSrc->m_idDat,nCs,1);                            /*     Copy raw stats. data block    */
      CData_Cat(idPcd,idAux);                                                   /*     Append to buffer              */
    }                                                                           /*   <<                              */

    /* - Pool data */                                                           /*   - - - - - - - - - - - - - - - - */
    CData_SetNBlocks(idPcd,CData_GetNRecs(idPcd)/nRpb);                         /*   Set block count of aggr. buffer */
    IFCHECK                                                                     /*   Protocol (verbose level 1)      */
      printf("\n     - Aggregating %ld statistics classes",                     /*   |                               */
      (long)CData_GetNBlocks(idPcd));                                           /*   |                               */
    CStatistics_PoolInt(idAux,idPcd,0);                                         /*   Pool sum data                   */
    CStatistics_PoolInt(idAux,idPcd,1);                                         /*   Pool min data                   */
    CStatistics_PoolInt(idAux,idPcd,2);                                         /*   Pool max data                   */

    /* - Store pooled raw statistics data block */                              /*   - - - - - - - - - - - - - - - - */
    dlp_memmove                                                                 /*   Copy pooled raw stats. data     */
    (                                                                           /*   |                               */
      CData_XAddr(_this->m_idDat,nC*nRpb,0),                                    /*   | To target statistics block    */
      CData_XAddr(idAux,0,0),                                                   /*   | From aggregation buffer       */
      CData_GetNRecs(idAux)*CData_GetRecLen(idAux)                              /*   | Length of aggregation buffer  */
    );                                                                          /*   |                               */

    /* - Clean up auxilary instances */                                         /*   - - - - - - - - - - - - - - - - */
    CData_Reset(idPcd,TRUE);                                                    /*   Clear aggregation buffer        */
  }

  /* Clean up */                                                                /* --------------------------------- */
  IDESTROY(idAux);                                                              /* Destroy auxilary data instance #1 */
  IDESTROY(idPmp);                                                              /* Destroy pooling map               */
  IDESTROY(idPcd);                                                              /* Destroy pooled cls. raw data inst.*/
  STA_PROTOCOL_FOOTER(1,"done");                                                /* Print protocol footer             */
  return O_K;                                                                   /* Ok                                */

DLPCATCH(STA_BADCOMP)                                                           /* == Catch STA_BADCOMP exception    */
  IDESTROY(idAux);                                                              /* Destroy auxilary data instance #1 */
  IDESTROY(idPmp);                                                              /* Destroy pooling map               */
  IDESTROY(idPcd);                                                              /* Destroy pooled cls. raw data inst.*/
  STA_PROTOCOL_FOOTER(1,"FAILED");                                              /* Print protocol footer             */
  return NOT_EXEC;                                                              /* Not ok                            */
}
Ejemplo n.º 20
0
/**
 * Prints one block of the instance in vector mode (standard).
 */
INT32 CGEN_PRIVATE CData_PrintVectors_Block
(
  CData* _this,                                                                 /* Pointer to data instance          */
  INT32   nBlock                                                                 /* Block index (<0: ignore blocks)   */
)                                                                               /* Returns number of lines printed   */
{
  INT32 i      = 0;                                                              /* Universal loop counter            */
  INT32 nR     = 0;                                                              /* Current record                    */
  INT32 nR_    = 0;                                                              /* First record to be printed        */
  INT32 nR0    = 0;                                                              /* First record of current page      */
  INT32 nSR    = 0;                                                              /* Number of records of currenr page */
  INT32 nXR    = 0;                                                              /* Last record to print plus one     */
  INT32 nC     = 0;                                                              /* Current component                 */
  INT32 nXC    = 0;                                                              /* Number of components              */
  INT32 nWI    = 0;                                                              /* Component index column width      */
  INT32 nW0    = 0;                                                              /* Head column width                 */
  INT32 nW     = 0;                                                              /* Column width                      */
  INT32 nP     = 0;                                                              /* Current page                      */
  INT32 nPps   = 0;                                                              /* Pages per screen                  */
  INT32 nL     = 0;                                                              /* Line counter                      */
  BOOL bPur   = FALSE;                                                          /* Print physical record unit flag   */
  BOOL bPuc   = FALSE;                                                          /* Print physical component unit flg.*/
  FLOAT64 nBuf = 0.;                                                             /* Double buffer                     */
  char   sBuf[L_SSTR+1];                                                        /* String buffer                     */

  /* Validate */                                                                /* --------------------------------- */
  if (nBlock>=CData_GetNBlocks(_this)) return 0;                                /* Requested block does not exist    */

  /* Initialize */                                                              /* --------------------------------- */
  nR_ = nBlock>=0 ? CData_GetNRecsPerBlock(_this)*nBlock : 0;                   /* Get first record to print         */
  nXR = nBlock>=0 ? nR_+CData_GetNRecsPerBlock(_this) : CData_GetNRecs(_this);  /* Get number of records             */
  nXC = CData_GetNComps(_this);                                                 /* Get number of components          */
  bPur = _this->m_lpTable->m_fsr!=1. && _this->m_lpTable->m_fsr!=0.;            /* Displaying physical record units? */
  bPuc = _this->m_nCinc!=1. && _this->m_nCinc!=0.;                              /* Displaying physical comp. units?  */
  nPps = dlp_maxprintlines()/(nXC+4);                                           /* Compute no. of pages per sceeen   */

  /* Print vectors */                                                           /* --------------------------------- */
  if (nBlock>=0)                                                                /* Printing blockwise?               */
  {                                                                             /* >>                                */
    printf("\n   Block %ld (offset %ld)",(long)nBlock,(long)nR_);               /*   Show current block index        */
    dlp_inc_printlines(1);  nL++;                                               /*   Adjust number of printed lines  */
  }                                                                             /* <<                                */
  for (nR0=nR_; nR0<nXR; )                                                      /* Loop over records                 */
  {                                                                             /* >>                                */
    CData_PrintVectors_GetColWidth(_this,nR0,0,&nWI,&nW0,&nW);                  /*   Comp. head and data col. widths */
    nSR = (dlp_maxprintcols()-nWI-nW0-4)/(nW+1);                                /*   Number of columns to print      */
    if (nR0+nSR>nXR) nSR = nXR-nR0;                                             /*   No more than there are records! */

    /* Print record header */                                                   /*   - - - - - - - - - - - - - - - - */
    if (bPur)                                                                   /*   Display physical record units?  */
    {                                                                           /*   >>                              */
      printf("\n %s ->",__pad(strcpy(sBuf,_this->m_lpRunit),nW0+nWI,'r'));      /*     Print name of physical unit   */
      for (nR=nR0; nR<nR0+nSR; nR++)                                            /*     Loop over remaining records   */
      {                                                                         /*     >>                            */
        nBuf = _this->m_lpTable->m_ofs + (nR-nR_)*_this->m_lpTable->m_fsr;      /*       Compute abscissa value      */
        __sprintx(sBuf,&nBuf,T_DOUBLE,_this->m_bExact);                         /*       Print to a string           */
        printf("%s ",__pad(sBuf,nW,'r'));                                       /*       Format and print to screen  */
      }                                                                         /*     <<                            */
      dlp_inc_printlines(1); nL++;                                              /*     Adjust number of printed lines*/
    }                                                                           /*   <<                              */
    sBuf[0]='\0';                                                               /*   Clear string buffer             */
    if (bPuc) sprintf(sBuf,"%s| ",_this->m_lpCunit);                            /*   Print phys. comp. unit name...  */
    printf("\n %s",__pad(sBuf,nW0+nWI+3,'r'));                                  /*   ... or empty string             */
    for (nR=nR0; nR<nR0+nSR; nR++)                                              /*   Loop over remaining records     */
    {                                                                           /*   >>                              */
      i=nR-nR_; __sprintx(sBuf,&i,T_INT,_this->m_bExact);                       /*     Print record index to a str.  */
      printf("%s%c",__pad(sBuf,nW,'r'),CData_RecIsMarked(_this,nR)?'*':' ');    /*     Format and print to screen    */
    }                                                                           /*   <<                              */
    sBuf[0]='\0';                                                               /*   Clear string buffer             */
    if (bPuc) sprintf(sBuf,"%c ",bPuc?'v':' ');                                 /*   Print down arrow ...            */
    printf("\n %s",__pad(sBuf,nW0+nWI+3,'r'));                                  /*   ... or empty string             */
    sBuf[0]='\0'; for (i=0; i<nW; i++) sBuf[i]='.'; sBuf[i]='\0';               /*   Make horizonal delimiter        */
    for (nR=nR0; nR<nR0+nSR; nR++) printf("%s ",sBuf);                          /*   Print one per vector            */
    dlp_inc_printlines(2);  nL+=2;                                              /*   Adjust number of printed lines  */

    /* Print data */                                                            /*   - - - - - - - - - - - - - - - - */
    for (nC=0; nC<nXC; )                                                        /*   Loop over components            */
    {                                                                           /*   >>                              */
      __sprintx(sBuf,&nC,T_INT,_this->m_bExact);                                /*     Print comp. index to a string */
      printf("\n%c%s ",                                                         /*     Format and print to screen    */
        CData_CompIsMarked(_this,nC)?'*':' ',__pad(sBuf,nWI,'r'));              /*     | (incl. "*" for "marked")    */
      if (bPuc && dlp_is_numeric_type_code(CData_GetCompType(_this,nC)))        /*     Display ordinate value?       */
      {                                                                         /*     >>                            */
        nBuf = _this->m_nCofs + nC*_this->m_nCinc;                              /*       Compute it                  */
        __sprintx(sBuf,&nBuf,T_DOUBLE,_this->m_bExact);                         /*       Print it to a string        */
      }                                                                         /*     <<                            */
      else strcpy(sBuf,CData_GetCname(_this,nC));                               /*     else display component name   */
      printf("%s: ",__pad(dlp_strtrimleft(dlp_strtrimright(sBuf)),nW0,'r'));    /*     Format and print to screen    */
      for (nR=nR0; nR<nR0+nSR; nR++)                                            /*     Loop over remaining records   */
      {                                                                         /*     >>                            */
        __sprintx(sBuf,CData_XAddr(_this,nR,nC),                                /*       Print cell value to a str.  */
            CData_GetCompType(_this,nC),_this->m_bExact);                       /*         |                         */
        if (dlp_is_symbolic_type_code(CData_GetCompType(_this,nC)))             /*       Is string value             */
          if ((INT32)dlp_strlen(sBuf)>nW)                                        /*         Will not fit in column    */
            dlp_strabbrv(sBuf,sBuf,nW);                                         /*           Abbreviate it           */
        if (dlp_is_numeric_type_code(CData_GetCompType(_this,nC)))              /*       Is numeric value            */
          if (_this->m_bNz && CMPLX_EQUAL(CData_Cfetch(_this,nR,nC),CMPLX(0.)))
            dlp_strcpy(sBuf,"-");
        printf("%s%c",__pad(sBuf,nW,'r'),                                       /*       Format and print to screen  */
          CData_CellIsMarked(_this,nR*CData_GetNComps(_this)+nC)?'*':' ');      /*       | (incl. "*" for "marked")  */
      }                                                                         /*     <<                            */
      dlp_inc_printlines(1); nL++;                                              /*     Adjust number of printed lines*/

      /* Break component listing */                                             /*     - - - - - - - - - - - - - - - */
      if (nPps==0)                                                              /*     Not all comps. fit on screen  */
      {                                                                         /*     >>                            */
        sprintf(sBuf,"component (0..%ld), cancel -3",(long)nXC-1);              /*       Make user hint              */
        if ((nC=dlp_printstop_nix(nC,sBuf,NULL))==-1) break;                    /*       Break listing               */
        if (nC< -2 ) return -1;                                                 /*       Cancelled by user           */
        if (nC>=nXC) break;                                                     /*       No more components -> break */
      }                                                                         /*     <<                            */
      else nC++;                                                                /*     No breaking -> count comps.   */
    }                                                                           /*   <<                              */
    nR0+=nSR;                                                                   /*   First record on next page       */
    nP++;                                                                       /*   Count pages                     */
    if (nR0<nXR)                                                                /*   There are more records          */
    {                                                                           /*   >>                              */
      printf("\n"); dlp_fprint_x_line(stdout,'-',dlp_maxprintcols());           /*     Print a separator             */
      dlp_inc_printlines(1); nL++;                                              /*     Adjust number of printed lines*/
    }                                                                           /*   <<                              */

    /* Break record listing */                                                  /*   - - - - - - - - - - - - - - - - */
    if (((nPps>0 && nP>=nPps) || nPps==0) && nR0<nXR)                           /*   Complicated break condition :)  */
    {                                                                           /*   >>                              */
      dlp_inc_printlines(dlp_maxprintlines());                                  /*     Do stop right here            */
        sprintf(sBuf,"record (%ld..%ld)%s",(long)nR_,(long)nXR-1,               /*     Make user hint                */
          nBlock>=0?", cancel -3":"");                                          /*     |                             */
      if ((nR0=dlp_printstop_nix(--nR0,sBuf,NULL))==-1) break;                  /*     Break listing                 */
      if (nR0< -2 ) return -1;                                                  /*     Cancelled by user             */
      if (nR0< nR_) nR0=nR_;                                                    /*     No previous blocks, please!   */
      if (nR0>=nXR) break;                                                      /*     No more records -> break      */
      nP=0;                                                                     /*     Reset page counter            */
    }                                                                           /*   <<                              */
  }                                                                             /* <<                                */

  return nL;                                                                    /* Return number of printed lines    */
}
Ejemplo n.º 21
0
INT16 CGmm_PrecalcD(CGmm* _this, BOOL bCleanup)
#endif
{
  INT32      i       = 0;                                                        /* Triangular inv. cov. matrix cntr. */
  INT32      c       = 0;                                                        /* Index of inv. covariance matrix   */
  INT32      k       = 0;                                                        /* Gaussian loop counter             */
  INT32      n       = 0;                                                        /* Dimension loop counter            */
  INT32      m       = 0;                                                        /* Dimension loop counter            */
  INT32      K       = 0;                                                        /* Number of single Gaussians        */
  INT32      N       = 0;                                                        /* Feature space dimensionality      */
  GMM_FTYPE nDelta1 = 0.;                                                       /* Class indep. term of delta const. */
#ifdef __TMS
  GMM_FTYPE *mean = (GMM_FTYPE*)CData_XAddr(AS(CData,_this->m_idMean),0,0);
#endif


  /* Clean up precalculated data */                                             /* --------------------------------- */
  dlp_free(_this->m_lpAlpha);                                                   /* Clear alpha vector                */
  dlp_free(_this->m_lpBeta );                                                   /* Clear beta vectors                */
  dlp_free(_this->m_lpGamma);                                                   /* Clear gamma vector                */
  dlp_free(_this->m_lpDelta);                                                   /* Clear delta vector                */
  dlp_free(_this->m_lpI    );                                                   /* Clear inv. cov. pointer array     */
  dlp_free(_this->m_lpV    );                                                   /* Clear inverse variance array      */
  if(_this->m_idSse2Icov){
    CData *idSse2Icov=AS(CData,_this->m_idSse2Icov);
    IDESTROY(idSse2Icov);                                                     /* Destroy inv.covs. for SSE2 opt.   */
    _this->m_idSse2Icov=NULL;
  }
  dlp_free(_this->m_lpSse2Buf);                                                 /* Clear aux. buffer for SSE2 opt.   */
  dlp_free(_this->m_lpLdlL);                                                    /* Clear L-matrix buffer for LDL     */
  dlp_free(_this->m_lpLdlD);                                                    /* Clear D-vector buffer for LDL     */
  _this->m_nN = 0;                                                              /* Clear feature space dimensionality*/
  _this->m_nK = 0;                                                              /* Clear number of single Gaussians  */
  if (bCleanup) return O_K;                                                     /* When cleaning up that's it        */

  /* Initialize */                                                              /* --------------------------------- */
  K       = CGmm_GetNGauss(_this);                                              /* Get nuumber of single Gaussians   */
  N       = CGmm_GetDim(_this);                                                 /* Get feature space dimensionality  */
  nDelta1 = -N/2*log(2*F_PI);                                                   /* Compute part of delta term        */

  /* Basic validation */                                                        /* --------------------------------- */
  IF_NOK(CGmm_CheckMean(_this)) DLPTHROW(GMM_NOTSETUP);                         /* Check mean vectors                */
  IF_NOK(CGmm_CheckIvar(_this)) DLPTHROW(GMM_NOTSETUP);                         /* Check inverse variance vectors    */
  IF_NOK(CGmm_CheckCdet(_this)) DLPTHROW(GMM_NOTSETUP);                         /* Check (co-)variance determinants  */

  /* Basic dimensions */                                                        /* --------------------------------- */
  _this->m_nN = N;                                                              /* Feature space dimensionality      */
  _this->m_nK = K;                                                              /* Number of single Gaussians        */

  /* Create inverse covariance matrix map */                                    /* --------------------------------- */
  if (_this->m_idIcov)                                                          /* If using covariances              */
  {                                                                             /* >>                                */
    IF_NOK(CGmm_CheckIcov(_this)) DLPTHROW(GMM_NOTSETUP);                       /*   Inverse covariance data corrupt */
    _this->m_lpI = dlp_calloc(K,sizeof(GMM_FTYPE*));                            /*   Allocate map                    */
    if (!_this->m_lpI) DLPTHROW(ERR_NOMEM);                                     /*   Out of memory                   */
    for (k=0; k<K; k++)                                                         /*   Loop over Gaussians             */
    {                                                                           /*   >>                              */
      c=_this->m_idCmap ? (INT32)CData_Dfetch(AS(CData,_this->m_idCmap),k,0) : k;/*     Cov. mat. idx. for Gaussian k */
      I[k] = (GMM_FTYPE*)CData_XAddr(AS(CData,_this->m_idIcov),c,0);            /*     Store ptr. to inv. cov. matrix*/
    }                                                                           /*   <<                              */
  }                                                                             /* <<                                */

  /* Create inverse variance vector map */                                      /* --------------------------------- */
  IF_NOK(CGmm_CheckIvar(_this)) DLPTHROW(GMM_NOTSETUP);                         /*   Inverse covariance data corrupt */
  _this->m_lpV = dlp_calloc(K,sizeof(GMM_FTYPE*));                              /*   Allocate map                    */
  if (!_this->m_lpV) DLPTHROW(ERR_NOMEM);                                       /*   Out of memory                   */
  for (k=0; k<K; k++)                                                           /*   Loop over Gaussians             */
    V[k] = (GMM_FTYPE*)CData_XAddr(AS(CData,_this->m_idIvar),k,0);              /*     Store ptr. to inv. cov. matrix*/

  /* LDL-factorization */                                                       /* --------------------------------- */
  if(_this->m_nLDL)                                                             /* LDL factorization used            */
  {                                                                             /* >>                                */
    /* TODO: GMM_TYPE is float => dlm_factldl in float */                       /*   ------------------------------- */
    _this->m_lpLdlL = dlp_malloc(K*N*(N-1)/2*sizeof(GMM_FTYPE));                /*   Alloc L matrix                  */
    _this->m_lpLdlD = dlp_malloc(K*N*sizeof(GMM_FTYPE));                        /*   Alloc D vector                  */
    if (!_this->m_lpLdlL || !_this->m_lpLdlD) DLPTHROW(ERR_NOMEM);              /*   Out of memory                   */
    {
    FLOAT64 *lpAux1 = (FLOAT64 *)dlp_malloc(N*N*sizeof(FLOAT64));                  /*   Alloc auxilary matrix #1        */
    FLOAT64 *lpAux2 = (FLOAT64 *)dlp_malloc(N*N*sizeof(FLOAT64));                  /*   Alloc auxilary matrix #2        */
    if (!lpAux1 || !lpAux2) DLPTHROW(ERR_NOMEM);                                /*   Out of memory                   */
    for(k=0;k<K;k++)                                                            /*   Loop over all Gaussians         */
    {                                                                           /*   >>                              */
      for(n=0;n<N;n++)                                                          /*     Loop over Gaussian dimension  */
      {                                                                         /*     >>                            */
        lpAux1[n*N+n] = V[k][n];                                                /*       Copy inverse variance values*/
        for(m=0;m<n;m++) lpAux1[n*N+m] = lpAux1[m*N+n] =                        /*       Copy inverse covariance val.*/
          I?I[k][m*N-2*m-m*(m-1)/2+n-1]:0.;                                     /*       |                           */
      }                                                                         /*     <<                            */
      dlm_factldl(lpAux1,lpAux2,N);                                             /*     Factorize matrix              */
      for(n=0;n<N;n++)                                                          /*     Loop over Gaussian dimension  */
      {                                                                         /*     >>                            */
        for(m=n+1;m<N;m++) Li(N,k,n,m) = lpAux1[n*N+m];                         /*       Store L matrix values       */
        D(N,k,n) = lpAux2[n*N+n];                                               /*       Store D vector values       */
      }                                                                         /*     <<                            */
      if(_this->m_nLdlCoef>=0 && _this->m_nLdlCoef<N*(N-1)/2)
      {
        FLOAT64 nMinAbs;
        memcpy(lpAux1,&L(N,k,0),N*(N-1)/2);
#if GMM_FTYPE_CODE == T_FLOAT
        qsort(lpAux1,N*(N-1)/2,sizeof(FLOAT64),cf_absfloat_down);
#else
        qsort(lpAux1,N*(N-1)/2,sizeof(FLOAT64),cf_absdouble_down);
#endif
        nMinAbs=fabs(lpAux1[_this->m_nLdlCoef]);
        for(n=0;n<N*(N-1)/2;n++) if(fabs(L(N,k,n))<=nMinAbs) L(N,k,n)=0.;
      }
    }                                                                           /*   <<                              */
    dlp_free(lpAux1);                                                           /*   Free auxilary matrix #1         */
    dlp_free(lpAux2);                                                           /*   Free auxilary matrix #2         */
    }
  }                                                                             /* <<                                */

  /* Precalculate alpha and beta vectors */                                     /* --------------------------------- */
  if(!_this->m_nLDL)                                                            /* No LDL factorization used         */
  {                                                                             /* >>                                */
    _this->m_lpAlpha = dlp_calloc(K,sizeof(GMM_FTYPE));                         /*   Allocate buffer                 */
    _this->m_lpBeta  = dlp_calloc(K*N,sizeof(GMM_FTYPE));                       /*   Allocate buffer                 */
    if (!_this->m_lpAlpha || !_this->m_lpBeta) DLPTHROW(ERR_NOMEM);             /*   Out of memory                   */
    for (k=0; k<K; k++)                                                         /*   Loop over Gaussians             */
      for (n=0; n<N; n++)                                                       /*     Loop over dimensions          */
        for (m=0; m<N; m++)                                                     /*       Loop over dimensions        */
          if (m==n)                                                             /*         Main diagonal (variances)?*/
          {                                                                     /*         >>                        */
            alpha[k]     += V[k][n]*mu(k,m)*mu(k,n);                            /*           Sum up alpha val. (n==m)*/
            beta [k*N+n] += V[k][n]*mu(k,m);                                    /*           Sum up beta value (n==m)*/
          }                                                                     /*         <<                        */
          else if (_this->m_lpI)                                                /*         Otherwise cov.(if present)*/
          {                                                                     /*         >>                        */
            if (m>n) i = n*N - 2*n - n*(n-1)/2 + m - 1;                         /*           Calc index if I[n,m] in */
            else     i = m*N - 2*m - m*(m-1)/2 + n - 1;                         /*           | triangular icov. mat. */
            alpha[k]     += I[k][i]*mu(k,m)*mu(k,n);                            /*           Sum up alpha val. (n!=m)*/
            beta [k*N+n] += I[k][i]*mu(k,m);                                    /*           Sum up beta value (n!=m)*/
          }                                                                     /*         <<                        */
  }                                                                             /* <<                                */
  else                                                                          /* LDL factorization used            */
  {                                                                             /* >>                                */
    _this->m_lpAlpha = NULL;                                                    /*   No alpha needed here            */
    _this->m_lpBeta  = dlp_calloc(K*N,sizeof(GMM_FTYPE));                       /*   Allocate buffer                 */
    if (!_this->m_lpBeta) DLPTHROW(ERR_NOMEM);                                  /*   Out of memory                   */
    for(k=0;k<K;k++) for(n=0;n<N;n++)                                           /*   Loop over Gaussians & dimensions*/
    {                                                                           /*   >>                              */
      beta[k*N+n] = mu(k,n);                                                    /*     Init beta with mean value     */
      for(m=n+1;m<N;m++) beta[k*N+n] += mu(k,m)*Li(N,k,n,m);                    /*     Calculate beta from L*mu      */
    }                                                                           /*   <<                              */
  }                                                                             /* <<                                */

  /* Allocate gamma vector */                                                   /* --------------------------------- */
  /* NOTE: If this fails there will just be no lazy computation -> no big deal*//*                                   */
  if (_this->m_idCmap && _this->m_idIcov && _this->m_lpI)                       /* Wanna do lazy computation?        */
    if (CData_GetDescr(AS(CData,_this->m_idIvar),0)==0.)                        /*   Only if variances are tied too  */
      _this->m_lpGamma = dlp_calloc(K,sizeof(GMM_FTYPE));                       /*     Allocate buffer               */

  /* Precalculate delta vector */                                               /* --------------------------------- */
  _this->m_lpDelta = dlp_calloc(K,sizeof(GMM_FTYPE));                           /* Allocate buffer                   */
  if (!_this->m_lpDelta) DLPTHROW(ERR_NOMEM);                                   /* Out of memory                     */
  for (k=0; k<K; k++)                                                           /* Loop over Gaussians               */
    delta[k] = nDelta1-(GMM_FTYPE)(0.5*log(                                     /*   Calculate delta[k]              */
      CData_Dfetch(AS(CData,_this->m_idCdet),k,0)));                            /*   |                               */

  /* SSE2 precalculated objects */                                              /* --------------------------------- */
#ifdef GMM_SSE2                                                                 /* Use SSE2?                         */
  IFIELD_RESET(CData,"sse2_icov");                                              /* Create/reset SSE2 inv.cov. matrs. */
  CGmm_Extract(_this,NULL,_this->m_idSse2Icov);                                 /* ... and go get 'em                */
  _this->m_lpSse2Buf = dlp_calloc(2*N,sizeof(GMM_FTYPE));                       /* Allocate auxilary buffer          */
  if (!_this->m_lpSse2Buf) DLPTHROW(ERR_NOMEM);                                 /* Out of memory                     */
#endif                                                                          /* #ifdef GMM_SSE2                   */

  /* Final checkup */                                                           /* --------------------------------- */
#ifndef __NOXALLOC
  IF_NOK(CGmm_CheckPrecalc(_this)) DLPTHROW(GMM_NOTSETUP);                      /* Check precalculated data          */
#endif
  return O_K;                                                                   /* That's it folks ...               */

DLPCATCH(GMM_NOTSETUP)                                                          /* On NOT_EXEC exception             */
DLPCATCH(ERR_NOMEM)                                                             /* On ERR_NOMEM exception            */
#if GMM_FTYPE_CODE == T_FLOAT
  CGmm_PrecalcF(_this,TRUE);                                                    /* - Free memory of precalc'd. data  */
#else
  CGmm_PrecalcD(_this,TRUE);                                                    /* - Free memory of precalc'd. data  */
#endif
  return NOT_EXEC;                                                              /* - Indicate failure                */
}
Ejemplo n.º 22
0
/*
 * Manual page at fst_man.def
 */
INT16 CGEN_PUBLIC CFst_Product
(
  CFst* _this,
  CFst* itSrc1,
  CFst* itSrc2,
  INT32  nUnit1,
  INT32  nUnit2
)
{
  INT32      nC           = 0;                                                   /* Current component                  */
  INT32      nFCS2        = 0;                                                   /* 1st data comp. of state tab.itSrc2 */
  INT32      nXCS1        = 0;                                                   /* No. of comps. of state tab. itSrc1 */
  INT32      nXCS2        = 0;                                                   /* No. of comps. of state tab. itSrc2 */
  INT32      nFCT2        = 0;                                                   /* 1st data comp. of trans.tab.itSrc2 */
  INT32      nXCT1        = 0;                                                   /* No. of comps. of trans.tab. itSrc1 */
  INT32      nXCT2        = 0;                                                   /* No. of comps. of trans.tab. itSrc2 */
  INT32      nRls1        = 0;                                                   /* Rec. len. of state table of itSrc1 */
  INT32      nRls2        = 0;                                                   /* Rec. len. of state table of itSrc2 */
  INT32      nRlt1        = 0;                                                   /* Rec. len. of trans.table of itSrc1 */
  INT32      nRlt2        = 0;                                                   /* Rec. len. of trans.table of itSrc2 */
  FST_ITYPE nS1          = 0;
  FST_ITYPE nS2          = 0;
  FST_ITYPE nFS1         = 0;
  FST_ITYPE nFS2         = 0;
  FST_ITYPE nXS1         = 0;
  FST_ITYPE nXS2         = 0;
  FST_ITYPE nT           = 0;
  FST_ITYPE nIni         = 0;
  FST_ITYPE nTer         = 0;
  FST_ITYPE nT1          = 0;
  FST_ITYPE nT2          = 0;
  FST_ITYPE nFT1         = 0;
  FST_ITYPE nFT2         = 0;
  FST_ITYPE nXT1         = 0;
  FST_ITYPE nXT2         = 0;
  char*     lpsBuf       = NULL;                                                /* String buffer                      */
  INT16     nVirt        = 0;                                                   /* Auxiliary: patching ovrl.args. bug */
  BOOL      bNoloopsSave = FALSE;                                               /* Save buffer for /noloops option    */

  /* Validate */
  CHECK_THIS_RV(NOT_EXEC);
  if (itSrc1==NULL || itSrc2==NULL)
  {
    CFst_Reset(BASEINST(_this),TRUE);
    return O_K;
  }
  if (nUnit1<0 || nUnit1>=UD_XXU(itSrc1)) return IERROR(_this,FST_BADID,"unit",nUnit1,0);
  if (nUnit2<0 || nUnit2>=UD_XXU(itSrc2)) return IERROR(_this,FST_BADID,"unit",nUnit2,0);

  /* Initialize */
  /* HACK: Multiple overlapping arguments on _this not handled correctly by
           CREATEVIRTUAL --> */
  if (_this==itSrc1 && _this==itSrc2) return IERROR(_this,ERR_GENERIC,"Invalid arguments",0,0);
  if      (itSrc1==_this) { CREATEVIRTUAL(CFst,itSrc1,_this); nVirt=1; }
  else if (itSrc2==_this) { CREATEVIRTUAL(CFst,itSrc2,_this); nVirt=2; }
  /* <-- */
  bNoloopsSave = _this->m_bNoloops;
  CFst_Reset(BASEINST(_this),TRUE);
  _this->m_bNoloops = bNoloopsSave;

  /* Initialize destination state table */
  nFS1  = UD_FS(itSrc1,nUnit1);
  nXS1  = UD_XS(itSrc1,nUnit1);
  nFS2  = UD_FS(itSrc2,nUnit2);
  nXS2  = UD_XS(itSrc2,nUnit2);
  nRls1 = CData_GetRecLen(AS(CData,itSrc1->sd)) - CData_GetCompOffset(AS(CData,itSrc1->sd),IC_SD_DATA);
  nRls2 = CData_GetRecLen(AS(CData,itSrc2->sd)) - CData_GetCompOffset(AS(CData,itSrc2->sd),IC_SD_DATA);
  nXCS1 = CData_GetNComps(AS(CData,itSrc1->sd)) - IC_SD_DATA;
  nXCS2 = CData_GetNComps(AS(CData,itSrc2->sd)) - IC_SD_DATA;
  nFCS2 = IC_SD_DATA + nXCS1;
  for (nC=IC_SD_DATA; nC<IC_SD_DATA+nXCS1; nC++)
    CData_AddComp
    (
      AS(CData,_this->sd),
      CData_GetCname(AS(CData,itSrc1->sd),nC),
      CData_GetCompType(AS(CData,itSrc1->sd),nC)
    );
  for (nC=IC_SD_DATA; nC<IC_SD_DATA+nXCS2; nC++)
    CData_AddComp
    (
      AS(CData,_this->sd),
      CData_GetCname(AS(CData,itSrc2->sd),nC),
      CData_GetCompType(AS(CData,itSrc2->sd),nC)
    );

  /* Initialize destination transition table */
  nFT1  = UD_FT(itSrc1,nUnit1);
  nXT1  = UD_XT(itSrc1,nUnit1);
  nFT2  = UD_FT(itSrc2,nUnit2);
  nXT2  = UD_XT(itSrc2,nUnit2);
  nRlt1 = CData_GetRecLen(AS(CData,itSrc1->td)) - CData_GetCompOffset(AS(CData,itSrc1->td),IC_TD_DATA);
  nRlt2 = CData_GetRecLen(AS(CData,itSrc2->td)) - CData_GetCompOffset(AS(CData,itSrc2->td),IC_TD_DATA);
  nXCT1 = CData_GetNComps(AS(CData,itSrc1->td)) - IC_TD_DATA;
  nXCT2 = CData_GetNComps(AS(CData,itSrc2->td)) - IC_TD_DATA;
  nFCT2 = IC_TD_DATA + nXCT1;
  for (nC=IC_TD_DATA; nC<IC_TD_DATA+nXCT1; nC++)
    CData_AddComp
    (
      AS(CData,_this->td),
      CData_GetCname(AS(CData,itSrc1->td),nC),
      CData_GetCompType(AS(CData,itSrc1->td),nC)
    );
  for (nC=IC_TD_DATA; nC<IC_TD_DATA+nXCT2; nC++)
    CData_AddComp
    (
      AS(CData,_this->td),
      CData_GetCname(AS(CData,itSrc2->td),nC),
      CData_GetCompType(AS(CData,itSrc2->td),nC)
    );

  /* Copy input and output symbol tables */
  CData_Copy(_this->is,itSrc1->is);
  CData_Copy(_this->os,itSrc2->os);

  /* Initialize destination unit */
  lpsBuf = (char*)dlp_calloc
  (
    CData_GetCompType(AS(CData,itSrc1->ud),IC_UD_NAME) +
    CData_GetCompType(AS(CData,itSrc2->ud),IC_UD_NAME) + 2,
    sizeof(char)
  );
  sprintf
  (
    lpsBuf,"%s.%s",
    (const char*)CData_XAddr(AS(CData,itSrc1->ud),nUnit1,IC_UD_NAME),
    (const char*)CData_XAddr(AS(CData,itSrc2->ud),nUnit2,IC_UD_NAME)
  );
  CFst_Addunit(_this,lpsBuf);
  dlp_free(lpsBuf);

  /* Add product states */
  CFst_Addstates(_this,0,nXS1*nXS2,FALSE);

  /* Copy state qualification (including final state flag) */
  for (nS1=0; nS1<nXS1; nS1++)
    for (nS2=0; nS2<nXS2; nS2++)
    {
      if ((SD_FLG(itSrc1,nS1+nFS1)&0x01)==0x01 && (SD_FLG(itSrc2,nS2+nFS2)&0x01)==0x01)
        SD_FLG(_this,nS1*nXS2+nS2) |= 0x01;
      if (nRls1>0)
        dlp_memmove
        (
          CData_XAddr(AS(CData,_this ->sd),nS1*nXS2+nS2,IC_SD_DATA),
          CData_XAddr(AS(CData,itSrc1->sd),nS1+nFS1    ,IC_SD_DATA),
          nRls1
        );
      if (nRls2>0)
        dlp_memmove
        (
          CData_XAddr(AS(CData,_this ->sd),nS1*nXS2+nS2,nFCS2     ),
          CData_XAddr(AS(CData,itSrc2->sd),nS2+nFS2    ,IC_SD_DATA),
          nRls2
        );
    }

  CData_AddRecs(AS(CData,_this->td),nXT1*nXT2,_this->m_nGrany);
  /* Loop over all transitions of both factors */
  for (nT=0, nT1=nFT1; nT1<nFT1+nXT1; nT1++)
    for (nT2=nFT2; nT2<nFT2+nXT2; nT2++, nT++)
    {
      /* Get product of initial and terminal state */
      nIni = TD_INI(itSrc1,nT1)*nXS2 + TD_INI(itSrc2,nT2);
      nTer = TD_TER(itSrc1,nT1)*nXS2 + TD_TER(itSrc2,nT2);
      if (_this->m_bNoloops && nIni==nTer) continue;

      /* Add product transition */
      *(FST_ITYPE*)CData_XAddr(AS(CData,_this->td),nT,IC_TD_INI) = nIni;
      *(FST_ITYPE*)CData_XAddr(AS(CData,_this->td),nT,IC_TD_TER) = nTer;

      /* Copy transition qualification */
      dlp_memmove
      (
        CData_XAddr(AS(CData,_this ->td),nT ,IC_TD_DATA),
        CData_XAddr(AS(CData,itSrc1->td),nT1,IC_TD_DATA),
        nRlt1
      );
      dlp_memmove
      (
        CData_XAddr(AS(CData,_this ->td),nT ,nFCT2     ),
        CData_XAddr(AS(CData,itSrc2->td),nT2,IC_TD_DATA),
        nRlt2
      );
    }

  /* Finish destination instance */
  CData_SelectRecs(AS(CData,_this->td),AS(CData,_this->td),0,nT);
  UD_XT(_this,0) = nT;
  /* TODO: Trim result !? */

  /* Clean up */
  if (nVirt==1) { DESTROYVIRTUAL(itSrc1,_this); }
  if (nVirt==2) { DESTROYVIRTUAL(itSrc2,_this); }
  return O_K;
}
Ejemplo n.º 23
0
/* NO JAVADOC
 * Calculates the Mahalanobis distance or the (logarithmic) probability density
 * of a feature vector given a single Gaussian distribution. There are NO CHECKS
 * performed.
 * 
 * Complexity: 2N + N*N where N=m_nDim
 * 
 * @author Rainer Schaffer
 * @param _this
 *          Pointer to GMM instance
 * @param x
 *          Feature vector (expected to have N=m_nDim values
 * @param k
 *          Index of single Gaussian
 * @param nMode
 *          Operation mode, one of the GMMG_XXX constants
 * @return  The (logarithmic) probability density or Mahalanobis distance of x
 *          in single Gaussian k.
 */
double CGmm_GaussD_SSE2(CGmm* _this, double* x, INT32 k, INT16 nMode)
{
  INT32            dim;                                                          /* Feature space dimensionality      */
  double*         icov;                                                         /* Ptr. to inverse covariance matrix */
  double*         h;                                                            /* Ptr. to aux.buffer (2*dim doubles)*/
  double*         m;                                                            /* Ptr. to mean vector               */
  short            i = 0, j = 0;                                                 /* (Rainer's variables)              */
  volatile double tsum[2];                                                      /* (Rainer's variables)              */
  register double *covd, *covd2;                                                /* (Rainer's variables)              */

  dim  = _this->m_nN;                                                           /* Initialize Rainer's varibles      */
  m    = &((double*)CData_XAddr(_this->m_idMean,0,0))[k*dim];                   /* Initialize Rainer's varibles      */
  icov = &((double*)CData_XAddr(_this->m_idSse2Icov,0,0))[k*dim*dim];           /* Initialize Rainer's varibles      */
  h    = (double*)_this->m_lpSse2Buf;                                           /* Initialize Rainer's varibles      */
  if (*(double*)CData_XAddr(_this->m_idCdet,k,0)==0.)                           /* Covariance matrix invalid         */
    return CGmm_GetLimit(_this,nMode);                                          /*   Return limit                    */

  /* ---- Rainer's code ----> */
  if( m == NULL ) 
    return(.0);

  /* Bestimmung der ersten Werte der Matrix-Vektor-Multiplikation (i = 0) */
  covd = &icov[0];
  covd2 = &icov[dim];
  xorpd_r2r( xmm3, xmm3 );  /* Ergebnisvektor xmm3 (Vekt-Vekt-Mult) l�schen */
  movapd_r2r( xmm3, xmm6 ); /* Ergebnisvektor xmm6 (Matr-Vekt-Mult) l�schen */
  movapd_r2r( xmm3, xmm7 ); /* Ergebnisvektor xmm7 (Matr-Vekt-Mult) l�schen */
  for( j = 0; j < dim-1; j += 2 ){ 
    /* Differenz zweier Vektoren (m-x) */
    movupd_m2r( *(m+j), xmm0 );
    movupd_m2r( *(x+j), xmm1 );
    subpd_r2r( xmm1, xmm0 );
    movupd_r2m( xmm0, *(h+j) );
    /* Bestimmung der Elemente */
    movupd_m2r( *(covd+j), xmm1 );
    movupd_m2r( *(covd2+j), xmm2 );
    mulpd_r2r( xmm0, xmm1 );
    mulpd_r2r( xmm0, xmm2 );
    addpd_r2r( xmm1, xmm6 );
    addpd_r2r( xmm2, xmm7 );
  }
  movapd_r2r( xmm6, xmm0 );
  movlhps_r2r( xmm7, xmm6 );
  movhlps_r2r( xmm0, xmm7 );
  addpd_r2r( xmm6, xmm7 );
  for( ; j < dim; ++j ){ /* Durchf�hrung nichtparalleler Befehle */
    h[j] = m[j] - x[j]; 
    tsum[0] = covd[j]*h[j];
    tsum[1] = covd2[j]*h[j];
    movupd_m2r( *tsum, xmm0 );
    addpd_r2r( xmm0, xmm7 );
  } 
  /* Vektor-Vektor-Multiplikation (1. Teil) */
  movupd_m2r( *(h), xmm0 );
  mulpd_r2r( xmm7, xmm0 );
  addpd_r2r( xmm0, xmm3 );
  

  /* Bestimmung der weiteren Werte der Matrix-Vektor-Multiplikation (i > 0) */
  for( i = 2; i < dim-1; i += 2 ){
    covd = &icov[i*dim];
    covd2 = &icov[i*dim+dim];
    xorpd_r2r( xmm6, xmm6 ); /* Ergebnisvektoren xmm6 und xmm7 l�schen */
    movapd_r2r( xmm6, xmm7 );
    for( j = 0; j < dim-1; j += 2 ){ 
      /* Lesen der Differenz zweier Vektoren (m-x) */
      movupd_m2r( *(h+j), xmm0 );
      /* Bestimmung der Elemente */
      movupd_m2r( *(covd+j), xmm1 );
      movupd_m2r( *(covd2+j), xmm2 );
      mulpd_r2r( xmm0, xmm1 );
      mulpd_r2r( xmm0, xmm2 );
      addpd_r2r( xmm1, xmm6 );
      addpd_r2r( xmm2, xmm7 );
    }
    movapd_r2r( xmm6, xmm0 );
    movlhps_r2r( xmm7, xmm6 );
    movhlps_r2r( xmm0, xmm7 );
    addpd_r2r( xmm6, xmm7 );
    for( ; j < dim; ++j ){ /* Durchf�hrung nichtparalleler Befehle */
      tsum[0] = covd[j]*h[j];
      tsum[1] = covd2[j]*h[j];
      movupd_m2r( *tsum, xmm0 );
      addpd_r2r( xmm0, xmm7 );
    } 
    /* Vektor-Vektor-Multiplikation */
    movupd_m2r( *(h+i), xmm0 );
    mulpd_r2r( xmm7, xmm0 );
    addpd_r2r( xmm0, xmm3 );
  }
  /* Durchf�hrung nichtparalleler Befehle */
  tsum[0] = 0.0;
  for( ; i < dim; ++i ){
    tsum[1] = 0.0;
    covd = &icov[i*dim];
    for( j = 0; j < dim; ++j ){
      tsum[1] += covd[j]*h[j];      
    }
    tsum[0] += h[i]*tsum[1];
  }
  /* Quersumme vom Ergebnisvektor mm3 */
  movhlps_r2r( xmm3, xmm0 );
  addpd_r2r( xmm0, xmm3 );
  if( dim%2 != 0 ){ /* Durchf�hrung nichtparalleler Befehle */
    movupd_m2r( *tsum, xmm0 );
    addpd_r2r( xmm0, xmm3 );
  }
  movupd_r2m( xmm3, *tsum );
  /* <---- Rainer's code ---- */

  if (tsum[0]<0.0) tsum[0]=0.0;                                                 /* Distance must be non-negative     */
  switch (nMode)                                                                /* Branch by operation mode          */
  {                                                                             /* >>                                */
    case GMMG_MDIST : return tsum[0];                                           /*   Mahalanobis distance            */
    case GMMG_LDENS : return delta[k] - 0.5*tsum[0];                            /*   Logarithmic probability density */
    case GMMG_NLDENS: return -(delta[k] - 0.5*tsum[0]);                         /*   Negative log. prob. density     */
    case GMMG_DENS  : return exp(delta[k] - 0.5*tsum[0]);                       /*   Probability density             */
  }                                                                             /* <<                                */
  DLPASSERT(FMSG("Unknown Gauss mode"));                                        /* Invalid value of nMode!           */
  return 0.;                                                                    /* Emergency exit                    */
}
Ejemplo n.º 24
0
/* NO JAVADOC
 * Calculates the Mahalanobis distance or the (logarithmic) probability density
 * of a feature vector given a single Gaussian distribution. There are NO CHECKS
 * performed.
 * 
 * Complexity: 2N + N*N where N=m_nDim
 * 
 * @author Rainer Schaffer
 * @param _this
 *          Pointer to GMM instance
 * @param x
 *          Feature vector (expected to have N=m_nDim values
 * @param k
 *          Index of single Gaussian
 * @param nMode
 *          Operation mode, one of the GMMG_XXX constants
 * @return  The (logarithmic) probability density or Mahalanobis distance of x
 *          in single Gaussian k.
 */
float CGmm_GaussF_SSE2(CGmm* _this, float* x, INT32 k, INT16 nMode)
{
  INT32           dim;                                                           /* Feature space dimensionality      */
  float*         icov;                                                          /* Ptr. to inverse covariance matrix */
  float*         h;                                                             /* Ptr. to aux. buffer (2*dim floats)*/
  float*         m;                                                             /* Ptr. to mean vector               */
  short           i = 0, j = 0;                                                  /* (Rainer's variables)              */
  volatile float tsum[4];                                                       /* (Rainer's variables)              */
  register float *covd0, *covd1, *covd2, *covd3;                                /* (Rainer's variables)              */

  dim  = _this->m_nN;                                                           /* Initialize Rainer's varibles      */
  m    = &((float*)CData_XAddr(_this->m_idMean,0,0))[k*dim];                    /* Initialize Rainer's varibles      */
  icov = &((float*)CData_XAddr(_this->m_idSse2Icov,0,0))[k*dim*dim];            /* Initialize Rainer's varibles      */
  h    = (float*)_this->m_lpSse2Buf;                                            /* Initialize Rainer's varibles      */
  if (*(float*)CData_XAddr(_this->m_idCdet,k,0)==0.)                            /* Covariance matrix invalid         */
    return (float)CGmm_GetLimit(_this,nMode);                                   /*   Return limit                    */

  /* ---- Rainer's code ----> */
  if( m == NULL ) 
    return(.0);

  /* Bestimmung der ersten Werte der Matrix-Vektor-Multiplikation (i = 0) */
  covd0 = &icov[0];
  covd1 = &icov[dim];
  covd2 = &icov[2*dim];
  covd3 = &icov[3*dim];
  xorps_r2r( xmm3, xmm3 );  /* Ergebnisvektor xmm3 (Vekt-Vekt-Mult) l�schen */
  movaps_r2r( xmm3, xmm4 ); /* Ergebnisvektor xmm6 (Matr-Vekt-Mult) l�schen */
  movaps_r2r( xmm3, xmm5 ); /* Ergebnisvektor xmm6 (Matr-Vekt-Mult) l�schen */
  movaps_r2r( xmm3, xmm6 ); /* Ergebnisvektor xmm6 (Matr-Vekt-Mult) l�schen */
  movaps_r2r( xmm3, xmm7 ); /* Ergebnisvektor xmm7 (Matr-Vekt-Mult) l�schen */
  for( j = 0; j < dim-3; j += 4 ){ 
    /* Differenz zweier Vektoren (m-x) */
    movups_m2r( *(m+j), xmm0 );
    movups_m2r( *(x+j), xmm1 );
    subps_r2r( xmm1, xmm0 );
    movups_r2m( xmm0, *(h+j) );
    /* Bestimmung der Elemente */
    movups_m2r( *(covd0+j), xmm1 );
    mulps_r2r( xmm0, xmm1 );
    addps_r2r( xmm1, xmm4 ); /* xmm4 = a3, a2, a1, a0 */
    movups_m2r( *(covd1+j), xmm2 );
    mulps_r2r( xmm0, xmm2 );
    addps_r2r( xmm2, xmm5 ); /* xmm5 = b3, b2, b1, b0 */
    movups_m2r( *(covd2+j), xmm1 );
    mulps_r2r( xmm0, xmm1 );
    addps_r2r( xmm1, xmm6 ); /* xmm6 = c3, c2, c1, c0 */
    movups_m2r( *(covd3+j), xmm2 );
    mulps_r2r( xmm0, xmm2 );
    addps_r2r( xmm2, xmm7 ); /* xmm7 = d3, d2, d1, d0 */
  }
  movaps_r2r( xmm4, xmm0 );   /* xmm0 = a3 , a2 , a1 , a0  */
  movlhps_r2r( xmm6, xmm4 );  /* xmm4 = c1 , c0 , a1 , a0  */
  movhlps_r2r( xmm0, xmm6 );  /* xmm6 = c3 , c2 , a3 , a2  */
  addps_r2r( xmm4, xmm6 );    /* xmm6 = c1', c0', a1', a0' */
  movaps_r2r( xmm5, xmm0 );   /* xmm0 = b3 , b2 , b1 , b0  */
  movlhps_r2r( xmm7, xmm5 );  /* xmm5 = d1 , d0 , b1 , b0  */
  movhlps_r2r( xmm0, xmm7 );  /* xmm7 = d3 , d2 , b3 , b2  */
  addps_r2r( xmm5, xmm7 );    /* xmm7 = d1', d0', b1', b0' */
  movaps_r2r( xmm6, xmm1 );   /* xmm1 = c1', c0', a1', a0' */
  unpckhps_r2r( xmm7, xmm6 ); /* xmm6 = d1', c1', d0', c0' */
  unpcklps_r2r( xmm7, xmm1 ); /* xmm1 = b1', a1', b0', a0' */
  movaps_r2r( xmm1, xmm0 );   /* xmm0 = b1', a1', b0', a0' */
  movlhps_r2r( xmm6, xmm1 );  /* xmm1 = d0', c0', b0', a0' */
  movhlps_r2r( xmm0, xmm6 );  /* xmm6 = d1', c1', b1', a1' */
  addps_r2r( xmm1, xmm6 );    /* xmm6 = d* , c* , b* , a*  */
  for( ; j < dim; ++j ){ /* Durchf�hrung nichtparalleler Befehle  */
    h[j] = m[j] - x[j]; 
    tsum[0] = covd0[j]*h[j];
    tsum[1] = covd1[j]*h[j];
    tsum[2] = covd2[j]*h[j];
    tsum[3] = covd3[j]*h[j];
    movups_m2r( *tsum, xmm0 );
    addps_r2r( xmm0, xmm6 );
  } 
  /* Vektor-Vektor-Multiplikation (1. Teil) */
  movups_m2r( *(h), xmm0 );
  mulps_r2r( xmm6, xmm0 );
  addps_r2r( xmm0, xmm3 );

  /* Bestimmung der weiteren Werte der Matrix-Vektor-Multiplikation (i > 0) */
  for( i = 4; i < dim-3; i += 4 ){
    covd0 = &icov[i*dim];
    covd1 = &icov[(i+1)*dim];
    covd2 = &icov[(i+2)*dim];
    covd3 = &icov[(i+3)*dim];
    xorps_r2r( xmm4, xmm4 ); /* Ergebnisvektoren xmm4 bis xmm7 l�schen */
    movaps_r2r( xmm4, xmm5 );
    movaps_r2r( xmm4, xmm6 );
    movaps_r2r( xmm4, xmm7 );
    for( j = 0; j < dim-3; j += 4 ){ 
      /* sum += covd[j] * h[j]; */
      /* Lesen der Differenz zweier Vektoren (m-x) */
      movups_m2r( *(h+j), xmm0 );
      /* Bestimmung der Elemente */
      movups_m2r( *(covd0+j), xmm1 );
      mulps_r2r( xmm0, xmm1 );
      addps_r2r( xmm1, xmm4 ); /* xmm4 = a3, a2, a1, a0 */
      movups_m2r( *(covd1+j), xmm2 );
      mulps_r2r( xmm0, xmm2 );
      addps_r2r( xmm2, xmm5 ); /* xmm5 = b3, b2, b1, b0 */
      movups_m2r( *(covd2+j), xmm1 );
      mulps_r2r( xmm0, xmm1 );
      addps_r2r( xmm1, xmm6 ); /* xmm6 = c3, c2, c1, c0 */
      movups_m2r( *(covd3+j), xmm2 );
      mulps_r2r( xmm0, xmm2 );
      addps_r2r( xmm2, xmm7 ); /* xmm7 = d3, d2, d1, d0 */
    }
    movaps_r2r( xmm4, xmm0 );   /* xmm0 = a3 , a2 , a1 , a0  */
    movlhps_r2r( xmm6, xmm4 );  /* xmm4 = c1 , c0 , a1 , a0  */
    movhlps_r2r( xmm0, xmm6 );  /* xmm6 = c3 , c2 , a3 , a2  */
    addps_r2r( xmm4, xmm6 );    /* xmm6 = c1', c0', a1', a0' */
    movaps_r2r( xmm5, xmm0 );   /* xmm0 = b3 , b2 , b1 , b0  */
    movlhps_r2r( xmm7, xmm5 );  /* xmm5 = d1 , d0 , b1 , b0  */
    movhlps_r2r( xmm0, xmm7 );  /* xmm7 = d3 , d2 , b3 , b2  */
    addps_r2r( xmm5, xmm7 );    /* xmm7 = d1', d0', b1', b0' */
    movaps_r2r( xmm6, xmm1 );   /* xmm1 = c1', c0', a1', a0' */
    unpckhps_r2r( xmm7, xmm6 ); /* xmm6 = d1', c1', d0', c0' */
    unpcklps_r2r( xmm7, xmm1 ); /* xmm1 = b1', a1', b0', a0' */
    movaps_r2r( xmm1, xmm0 );   /* xmm0 = b1', a1', b0', a0' */
    movlhps_r2r( xmm6, xmm1 );  /* xmm1 = d0', c0', b0', a0' */
    movhlps_r2r( xmm0, xmm6 );  /* xmm6 = d1', c1', b1', a1' */
    addps_r2r( xmm1, xmm6 );    /* xmm6 = d* , c* , b* , a*  */
    for( ; j < dim; ++j ){ /* Durchf�hrung nichtparalleler Befehle  */
      h[j] = m[j] - x[j]; 
      tsum[0] = covd0[j]*h[j];
      tsum[1] = covd1[j]*h[j];
      tsum[2] = covd2[j]*h[j];
      tsum[3] = covd3[j]*h[j];
      movups_m2r( *tsum, xmm0 );
      addps_r2r( xmm0, xmm6 );
    } 
    /* Vektor-Vektor-Multiplikation */
    movups_m2r( *(h+i), xmm0 );
    mulps_r2r( xmm6, xmm0 );
    addps_r2r( xmm0, xmm3 );
  }

  /* Durchf�hrung nichtparalleler Befehle */
  tsum[0] = 0.0;
  for( ; i < dim; ++i ){
    tsum[1] = 0.0;
    covd0 = &icov[i*dim];
    for( j = 0; j < dim; ++j ){
      tsum[1] += covd0[j]*h[j];      
    }
    tsum[0] += h[i]*tsum[1];
  }

  /* Quersumme vom Ergebnisvektor mm3 */
  movhlps_r2r( xmm3, xmm0 );
  addps_r2r( xmm0, xmm3 );
  unpcklps_r2r( xmm3, xmm3 );
  movhlps_r2r( xmm3, xmm0 );
  addps_r2r( xmm0, xmm3 );  
  if( dim%4 != 0 ){ /* Durchf�hrung nichtparalleler Befehle */
    movups_m2r( *tsum, xmm0 );
    addps_r2r( xmm0, xmm3 );
  }
  movups_r2m( xmm3, *tsum );
  /* <---- Rainer's code ---- */

  if (tsum[0]<0.0) tsum[0]=0.0;                                                 /* Distance must be non-negative     */
  switch (nMode)                                                                /* Branch by operation mode          */
  {                                                                             /* >>                                */
    case GMMG_MDIST : return tsum[0];                                           /*   Mahalanobis distance            */
    case GMMG_LDENS : return delta[k] - 0.5*tsum[0];                            /*   Logarithmic probability density */
    case GMMG_NLDENS: return -(delta[k] - 0.5*tsum[0]);                         /*   Negative log. prob. density     */
    case GMMG_DENS  : return exp(delta[k] - 0.5*tsum[0]);                       /*   Probability density             */
  }                                                                             /* <<                                */
  DLPASSERT(FMSG("Unknown Gauss mode"));                                        /* Invalid value of nMode!           */
  return 0.;                                                                    /* Emergency exit                    */
}
Ejemplo n.º 25
0
void CGEN_PUBLIC CVmap_MapVectorF
#else
void CGEN_PUBLIC CVmap_MapVectorD
#endif
(
  CVmap*  _this,
  VMAP_FTYPE* lpX,
  VMAP_FTYPE* lpY,
  INT32    nXdim,
  INT32    nYdim
)
{
  BOOL    f  = 1;                                                               /* First non-zero summand flag       */
  INT32    n  = 0;                                                               /* Input dimension loop counter      */
  INT32    m  = 0;                                                               /* Output dimension loop counter     */
  INT32    N  = 0;                                                               /* Input dimensionality of mapping   */
  INT32    M  = 0;                                                               /* Output dimensionality of mapping  */
  VMAP_FTYPE* W  = NULL;                                                        /* Pointer to transformation matrix  */
  VMAP_FTYPE* Wm = NULL;                                                        /* Pointer to column m of trafo.mtx. */

  /* Initialize */                                                              /* --------------------------------- */
  CHECK_THIS();                                                                 /* Check this pointer                */
  if (!lpY) return;                                                             /* No output buffer, no service      */
  DLPASSERT(lpX!=lpY);                                                          /* Check in-/output ptrs. not equal  */
  for (m=0; m<nYdim; m++) lpY[m]=_this->m_nZero;                                /* Initialize output vector          */
  if (!lpX) return;                                                             /* If no input vector -> all done    */
  N = CData_GetNComps(AS(CData,_this->m_idTmx));                                /* Get mapping input dimensionality  */
  M = CData_GetNRecs(AS(CData,_this->m_idTmx));                                 /* Get mapping output dimensionality */
  if (nXdim>N) nXdim = N;                                                       /* Clip input dim. to mapping dim.   */
  if (nYdim>M) nYdim = M;                                                       /* Clip output dim. to mapping dim.  */
  if(CData_IsEmpty(AS(CData,_this->m_idWeakTmx)))                               /* Do not use weak tmx               */
  {                                                                             /* >>                                */
    W = (VMAP_FTYPE*)CData_XAddr(AS(CData,_this->m_idTmx),0,0);                 /*   Get pointer to trafo. matrix    */
     if (!W) return;                                                             /*   No trafo. mat., also no service */

    /* Compute generalized scalar product for each y[m] */                      /*   ------------------------------- */
    for (m=0; m<nYdim; m++)                                                     /*   Loop over output dimensions     */
      for (n=0,f=1,Wm=&W[m*N]; n<nXdim; n++)                                    /*     Loop over input dimensions    */
        if (Wm[n]!=_this->m_nZero)                                              /*       Weight of comp. n non-zero  */
        {                                                                       /*       >>                          */
          if (f)                                                                /*         First summand             */
          {                                                                     /*         >>                        */
            lpY[m] = DLP_SCALOP(Wm[n],lpX[n],_this->m_nWop);                    /*           Skip aggregation op     */
            f      = 0;                                                         /*           This WAS the first one..*/
          }                                                                     /*         <<                        */
          else                                                                  /*         Second and further summd's*/
            lpY[m] = DLP_SCALOP(lpY[m],DLP_SCALOP(Wm[n],lpX[n],_this->m_nWop),  /*           Weight & aggregate      */
              _this->m_nAop);                                                   /*           |                       */
        }                                                                       /*       <<                          */
  }else{                                                                        /* << Use weak tmx >>                */
    BYTE*   Id = NULL;                                                          /*   Pointer to index vector         */
    INT32 nRecLen = CData_GetRecLen(AS(CData,_this->m_idWeakTmx));               /*   Get size of one record          */
    INT16 nIType = CData_GetCompType(AS(CData,_this->m_idWeakTmx),0);
    nXdim = CData_GetNRecs(AS(CData,_this->m_idWeakTmx));                       /*   Get max. numb. of out's per in  */
    for (m=0;m<nYdim;m++)                                                       /*   Loop over output dimensions     */
    {                                                                           /*   >>                              */
      Id=CData_XAddr(AS(CData,_this->m_idWeakTmx),0,m*2);                       /*     Get start adress of component */
      switch(nIType){
      case T_LONG:
        for (n=0;n<nXdim && *((INT64*)Id)>=0;n++,Id+=nRecLen)                    /*       Loop over in's for this out */
          if(!n) lpY[m]=DLP_SCALOP(*((VMAP_FTYPE *)(Id+sizeof(INT64))),          /*         First input =>            */
            lpX[*((INT64*)Id)],_this->m_nWop);                                   /*         | Calc out from in        */
          else lpY[m]=DLP_SCALOP(lpY[m],                                        /*         Else => Calc out from     */
            DLP_SCALOP(*((VMAP_FTYPE *)(Id+sizeof(INT64))),                      /*         |                         */
            lpX[*((INT64*)Id)],_this->m_nWop),_this->m_nAop);                    /*         | prev. out and in        */
      break;
      case T_INT:
        for (n=0;n<nXdim && *((INT32*)Id)>=0;n++,Id+=nRecLen)                     /*       Loop over in's for this out */
          if(!n) lpY[m]=DLP_SCALOP(*((VMAP_FTYPE *)(Id+sizeof(INT32))),           /*         First input =>            */
            lpX[*((INT32*)Id)],_this->m_nWop);                                    /*         | Calc out from in        */
          else lpY[m]=DLP_SCALOP(lpY[m],                                        /*         Else => Calc out from     */
            DLP_SCALOP(*((VMAP_FTYPE *)(Id+sizeof(INT32))),                       /*         |                         */
            lpX[*((INT32*)Id)],_this->m_nWop),_this->m_nAop);                     /*         | prev. out and in        */
      break;
      default:
        IERROR(_this,ERR_INVALARG,"weaktmx int type is wheter int nor long",0,0);
      }
    }                                                                           /*   <<                              */
  }                                                                             /* <<                                */
}
Ejemplo n.º 26
0
/*
 * Manual page at statistics.def
 */
INT16 CGEN_PUBLIC CStatistics_Update
(
  CStatistics* _this,
  CData*       idVec,
  INT32         nIcLab,
  CData*       idW
)
{
  INT32        i           = 0;                                                  /* Update vector loop counter        */
  INT32        I           = 0;                                                  /* Number of update vectors          */
  INT32        c           = 0;                                                  /* Class of current update vector    */
  INT32        C           = 0;                                                  /* Number of classes                 */
  INT32        n           = 0;                                                  /* Dimension loop counter            */
  INT32        N           = 0;                                                  /* Statistics' dimensionality        */
  FLOAT64      w           = 0.;                                                 /* Weight of current update vector   */
  char*          lpsLab      = NULL;                                               /* Symbolic label of curr. upd. vec. */
  FLOAT64*     lpX         = NULL;                                               /* Vector copy buffer                */
  INT32        nVecIgnored = 0;                                                  /* Number of ignored vectors         */

  /* Validate */                                                                /* --------------------------------- */
  CHECK_THIS_RV(NOT_EXEC);                                                      /* Check this pointer                */
  IF_NOK(CStatistics_Check(_this))                                              /* Check instance data               */
    return IERROR(_this,STA_NOTSETUP," ( use -status for details)",0,0);        /* ...                               */
  if (CData_IsEmpty(idVec)) return O_K;                                         /* No input vector(s), no service!   */
  I = CData_GetNRecs(idVec);                                                    /* Get number of update vectors      */
  C = CStatistics_GetNClasses(_this);                                           /* Get number of statitistics classes*/
  N = CStatistics_GetDim(_this);                                                /* Get statistics vector dimension   */
  if (C>1)                                                                      /* Multiclass statistics needs labels*/
  {                                                                             /* >>                                */
    if (_this->m_idLtb)                                                         /*   Need symbolic labels            */
    {                                                                           /*   >>                              */
      if ((nIcLab<0 || nIcLab>=CData_GetNComps(idVec)))                         /*     Symbolic label comp. not spec.*/
        for (nIcLab=0; nIcLab<CData_GetNComps(idVec); nIcLab++)                 /*       Seek label component        */
          if (dlp_is_symbolic_type_code(CData_GetCompType(idVec,nIcLab)))       /*       ...                         */
            break;                                                              /*       ...                         */
      if (!dlp_is_symbolic_type_code(CData_GetCompType(idVec,nIcLab)))          /*     Symbolic label comp. not found*/
        return                                                                  /*       -> Error                    */
          IERROR(_this,STA_BADCOMP,"Label",idVec->m_lpInstanceName,"symbolic"); /*       |                           */
    }                                                                           /*   <<                              */
    else                                                                        /*   Need numeric labels             */
    {                                                                           /*   >>                              */
      if (!dlp_is_numeric_type_code(CData_GetCompType(idVec,nIcLab)) &&         /*     Numeric label comp. not found */
          (nIcLab>=0 || CData_GetNComps(idW)!=C))                               /*     |                             */
        return                                                                  /*       -> Error                    */
          IERROR(_this,STA_BADCOMP,"Label",idVec->m_lpInstanceName,"numeric");  /*       |                           */
    }                                                                           /*   <<                              */
  }                                                                             /* <<                                */
  /*else if (nIcLab>=0) IERROR(_this,STA_IGNORE,"label component",0,0);        / * Only one class  -> ignore labels  */
  if (dlp_is_numeric_type_code(CData_GetCompType(idVec,nIcLab)))                /* Check no. of comps. in idVec ...  */
  {                                                                             /* >>                                */
    if (CData_GetNNumericComps(idVec)!=N+1)                                     /*   Wrong number of numeric comps.  */
      IERROR(_this,STA_DIM,idVec->m_lpInstanceName,"numeric components",N+1);   /*     -> Warning                    */
  }                                                                             /* <<                                */
  else if (CData_GetNNumericComps(idVec)!=N)                                    /* Wrong number of numeric comps.    */
    IERROR(_this,STA_DIM,idVec->m_lpInstanceName,"numeric components",N);       /*   -> Warning                      */

  if (idW)                                                                      /* Weigths passed -> check 'em       */
  {                                                                             /* >>                                */
    if (!dlp_is_numeric_type_code(CData_GetCompType(idW,0)))                    /*   Component 0 not numeric         */
      return                                                                    /*   -> Error                        */
        IERROR(_this,STA_BADCOMP,"Weight",idW->m_lpInstanceName,"numeric");     /*   |                               */
    if (CData_GetNComps(idW)!=1 && CData_GetNComps(idW)!=C)                     /*   More than one component         */
      IERROR(_this,STA_IGNORE,"components in weight sequence",0,0);             /*   -> Warning                      */
    if (CData_GetNRecs(idW)!=I)                                                 /*   Not exactly one weight per vec. */
      IERROR(_this,STA_DIM,idW->m_lpInstanceName,"records",I);                  /*   -> Warning                      */
  }                                                                             /* <<                                */

  /* Initialize - NO RETURNS BEYOND THIS POINT! - */                            /* --------------------------------- */
  lpX = (FLOAT64*)dlp_calloc(N,sizeof(FLOAT64));                                  /* Allocate vector copy buffer       */

  /* Update statistics */                                                       /* --------------------------------- */
  for (i=0; i<I; i++)                                                           /* Loop over update vectors          */
  {                                                                             /* >>                                */
    /* Get vector label */                                                      /*   - - - - - - - - - - - - - - - - */
    if (C>1)                                                                    /*   Multiclass stats. needs labels  */
    {                                                                           /*   >>                              */
      if (_this->m_idLtb)                                                       /*     idVec contains symbolic labs. */
      {                                                                         /*     >>                            */
        INT32 nLIdx = 0;
        DLPASSERT(dlp_is_symbolic_type_code(CData_GetCompType(idVec,nIcLab)));  /*       Must be checked before!     */
        lpsLab = (char*)CData_XAddr(idVec,i,nIcLab);                            /*       Get string ptr. to label    */
        if(_this->m_bLabel){
          nLIdx=strlen(lpsLab)-1;
          if(nLIdx && lpsLab[nLIdx]==']') nLIdx--; else nLIdx=0;
          if(nLIdx && lpsLab[nLIdx]>='0' && lpsLab[nLIdx]<='9') nLIdx--; else nLIdx=0;
          while(nLIdx && lpsLab[nLIdx]>='0' && lpsLab[nLIdx]<='9') nLIdx--;
          if(nLIdx && lpsLab[nLIdx]=='[') lpsLab[nLIdx]='\0'; else nLIdx=0;
        }
        c      = CData_Find(_this->m_idLtb,0,C,1,0,lpsLab);                     /*       Look up label -> class idx. */
        if(nLIdx) lpsLab[nLIdx]='[';
        if (c<0)                                                                /*       Label invalid               */
        {                                                                       /*       >>                          */
          IERROR(_this,STA_SLAB,i,lpsLab?lpsLab:"(null)",0);                    /*         Warning                   */
          continue;                                                             /*         Ignore record             */
        }                                                                       /*       <<                          */
      }                                                                         /*     <<                            */
      else if(nIcLab>=0)                                                        /*     idVec contains numeric labs.  */
      {                                                                         /*     >>                            */
        c = (INT32)CData_Dfetch(idVec,i,nIcLab);                                 /*       Fetch label                 */
        if (c<0 || c>=C)                                                        /*       Label invalid               */
        {                                                                       /*       >>                          */
          IERROR(_this,STA_NLAB,i,c,0);                                         /*         Warning                   */
          continue;                                                             /*         Ignore record             */
        }                                                                       /*       <<                          */
      }                                                                         /*     <<                            */
      else c = 0;                                                               /*     Default class is 0            */
    }                                                                           /*   <<                              */
    else c = 0;                                                                 /*   Default class is 0              */

    do                                                                          /*   Loop over classes               */
    {                                                                           /*   >>                              */

    /* Get (weighted) update vector and update statistics */                    /*   - - - - - - - - - - - - - - - - */
    if (idW)                                                                    /*   Using weights                   */
    {                                                                           /*   >>                              */
      w = CData_Dfetch(idW,i,_this->m_idLtb || nIcLab>=0 ? 0 : c);              /*     Fetch weight for this vector  */
      if(w==0.) continue;                                                       /*     Nothing to do if no weight    */
      _this->m_bWeighted=TRUE;
    } else w=1.;                                                                /*   <<                              */
    CData_DrecFetch(idVec,lpX,i,N,nIcLab);                                      /*   Fetch update vector             */
    fpclassify(0.);
    for (n=0; n<N; n++)                                                         /*   Loop over vector components     */
      if (fabs(lpX[n])>1E100)                                                   /*     Check value                   */
        break;                                                                  /*       There's something wrong ... */
    if (n<N) { nVecIgnored++; continue; }                                       /*   Ignore this vector              */
    CStatistics_UpdateVector(_this,lpX,c,w);                                    /*   Update statistics with vector   */

    }                                                                           /*   <<                              */
    while(!_this->m_idLtb && nIcLab<0 && ++c<C);                                /*   Next class if there is one      */
  }                                                                             /* <<                                */

  /* Clean up */                                                                /* --------------------------------- */
  if (nVecIgnored>0) IERROR(_this,STA_VECIGNORED,nVecIgnored,0,0);              /* Error: some vectors ignored       */
  dlp_free(lpX);                                                                /* Free vector copy buffer           */
  return O_K;                                                                   /* Done                              */
}
Ejemplo n.º 27
0
/**
 * Creates a tree with the best <code>nPaths</code> paths (minimum cost) taken from <code>itSrc</code>. There are no
 * checks performed.
 *
 * @param _this  Pointer to this (destination) automaton instance
 * @param itSrc  Pointer to source automaton instance
 * @param nUnit  Index of unit to process
 * @param nPaths Number of paths to be extracted
 * @param nPathlength Length of paths to be extracted
 * @return O_K if successfull, a (negative) error code otherwise
 * @see BestN CFst_BestN
 */
INT16 CGEN_PROTECTED CFst_BestNUnit(CFst* _this, CFst* itSrc, INT32 nUnit, INT32 nPaths, INT32 nPathlength)
{
  FST_PQU_TYPE* lpPQ      = NULL;                                              /* Priority queue data struct         */
  FST_TID_TYPE* lpTIX     = NULL;                                              /* Source graph iterator data struct  */
  BYTE*         lpTX      = NULL;                                              /* Ptr. to current source transition  */
  FST_ITYPE     nFS       = 0;                                                 /* First state of source unit         */
  INT32          nArrivals = 0;                                                 /* Paths having reached a final state */
  FST_WTYPE     nNeAdd    = 0.;                                                /* Neutral element of addition        */
  FST_WTYPE     nNeMult   = 0.;                                                /* Neutral element of multiplication  */
  FST_ITYPE     nPQsize   = 0;                                                 /* Priority queue size                */
  FST_ITYPE     nT        = 0;                                                 /* Index of current source transition */
  FST_ITYPE     nNewT     = 0;                                                 /* Index of newly inserted dst. trans.*/
  FST_ITYPE     nSini     = 0;                                                 /* Ini. state of curr. dest. trans.   */
  FST_ITYPE     nXini     = 0;                                                 /* Ini. state of curr. source trans.  */
  FST_ITYPE     nYini     = 0;                                                 /* Ini. state of curr. aux. trans.    */
  FST_ITYPE     nSter     = 0;                                                 /* Ter. state of curr. dest. trans.   */
  FST_ITYPE     nXter     = 0;                                                 /* Ter. state of curr. source trans.  */
  FST_ITYPE     nYter     = 0;                                                 /* Ter. state of curr. aux. trans.    */
  FST_ITYPE     nPlen     = 0;                                                 /* length of the path up to here      */
  FST_WTYPE     nWX       = 0.0;                                               /* Weight of current src. transition  */
  FST_WTYPE     nPot      = 0.0;                                               /* Potential of current src. state    */
  FST_WTYPE     nCacc     = 0.0;                                               /* Accumulated cost from start state  */
  FST_WTYPE     nCtot     = 0.0;                                               /* Total cost to final state          */
  FST_WTYPE     nCmax     = 0.0;                                               /* Maximal cost in priority queue     */
  INT32          nNewY     = 0;                                                 /* New auxiliary state                */
  INT32          nIcP      = 0;                                                 /* Comp. index of src. state potential*/
  INT16         nCheck    = 0;                                                 /* Copy buffer for verbose level      */
  BOOL          bPush     = FALSE;                                             /* Copy of m_bPush option             */
  INT32          k         = 0;                                                 /* Auxilary loop counter              */

  /* Validate */
  DLPASSERT(_this!=itSrc);
  DLPASSERT(nUnit>=0 && nUnit<UD_XXU(itSrc));

  /* Initialize destination */
  nCheck = BASEINST(_this)->m_nCheck;
  bPush  = _this->m_bPush;
  CFst_Reset(BASEINST(_this),TRUE);
  BASEINST(_this)->m_nCheck=nCheck;
  CData_Scopy(AS(CData,_this->sd),AS(CData,itSrc->sd));
  CData_Scopy(AS(CData,_this->td),AS(CData,itSrc->td));
  CData_SelectRecs(AS(CData,_this->ud),AS(CData,itSrc->ud),nUnit,1);
  UD_FS(_this,0)  = 0;
  UD_FT(_this,0)  = 0;
  UD_XS(_this,0)  = 0;
  UD_XT(_this,0)  = 0;
  _this->m_nGrany = itSrc->m_nGrany;
  _this->m_nWsr   = CFst_Wsr_GetType(itSrc,&_this->m_nIcW);
  BASEINST(_this)->m_nCheck = BASEINST(_this)->m_nCheck>BASEINST(itSrc)->m_nCheck?BASEINST(_this)->m_nCheck:BASEINST(itSrc)->m_nCheck;

  CFst_Cps_AddSdAux(_this);
  nNeMult = CFst_Wsr_NeMult(_this->m_nWsr);
  nNeAdd  = CFst_Wsr_NeAdd (_this->m_nWsr);

  /* Add in itSrc the component Extracted that stores how many times this node has been visited */
  nIcP = CData_FindComp(AS(CData,itSrc->sd),NC_SD_POT);
  DLPASSERT(nIcP         >=0);
  DLPASSERT(_this->m_nIcW>=0);

  /* Initialize - Create priority queue */
  lpPQ = (FST_PQU_TYPE*)dlp_calloc(nPaths+1,sizeof(FST_PQU_TYPE));
  for (k=0; k<nPaths+1; k++) lpPQ[k].nCtot = nNeAdd;

  /* Initialize - Graph iterator */
  lpTIX = CFst_STI_Init(itSrc,nUnit,FSTI_SORTINI);
  nFS   = UD_FS(itSrc,nUnit);

  /* Create initial state in _this */
  nXter = CFst_Addstates(_this,0,1,SD_FLG(itSrc,nFS)&0x01);
  CFst_Cps_SetSdAux(_this,nXter,0,0,0);

  /* Initialize local variables */
  nXter = 0;
  nYter = 0;
  nCacc = nNeMult;

  /* Best-N computation */
  for(;;)
  {
    /* For all transitions leaving nXter */
    lpTX = NULL;
    while ((lpTX=CFst_STI_TfromS(lpTIX,nXter,lpTX))!=NULL)
    {
      /* Compute nCtot following the current transition */
      nT    = CFst_STI_GetTransId(lpTIX,lpTX);
      nWX   = *CFst_STI_TW(lpTIX,lpTX);
      nPot  = *(FST_WTYPE*)(CData_XAddr(AS(CData,itSrc->sd),TD_TER(itSrc,nT)+lpTIX->nFS,nIcP));
      nCtot = CFst_Wsr_Op(_this,nCacc,CFst_Wsr_Op(_this,nPot,nWX,OP_MULT),OP_MULT); /* nCacc + nWX + nPot; */
      IFCHECKEX(1)
        printf("\n state: %d \t Cacc: %f\t W: %f \t Pot: %f \t Ctot: %f\t\n",
          (int)nXter,(float)nCacc,(float)nWX,(float)nPot,(float)nCtot);

      /* Insert into priority queue? */
      if
      (
        nPQsize < (nPaths - nArrivals)              ||
        (
          nPQsize==(nPaths - nArrivals)             &&
          CFst_Wsr_Op(_this,nCtot,nCmax,OP_GREATER)
        )
      )
      {
        nNewY++;

        /* Push into priority queue */
        lpPQ[nPQsize].nXini = nXter;
        lpPQ[nPQsize].nYini = nYter;
        lpPQ[nPQsize].nXter = *CFst_STI_TTer(lpTIX,lpTX);
        lpPQ[nPQsize].nYter = nNewY;
        lpPQ[nPQsize].nTran = nT;
        lpPQ[nPQsize].nPlen = nPlen+1;
        lpPQ[nPQsize].nCacc = CFst_Wsr_Op(_this,nCacc,nWX,OP_MULT); /* nWX + nCacc; */
        lpPQ[nPQsize].nCtot = nCtot;
        nPQsize++;

        IFCHECKEX(1)
          printf("\n PriQsize:%d PUSH: [X:%d Y:%d] --- Cacc:%f Tran:%d Plen:%d Ctot:%f ----> [X:%d Y:%d]\n",
            (int)nPQsize,(int)nXter,(int)nYter,(float)nCacc,(int)nT,(int)nPlen,
            (float)nCtot,(int)*CFst_STI_TTer(lpTIX,lpTX),(int)nNewY);

        /* Sort priority queue */
        if (_this->m_nWsr == FST_WSR_PROB)
          qsort(lpPQ,nPaths+1,sizeof(FST_PQU_TYPE),CFst_Bsn_CompDown);
        else
          qsort(lpPQ,nPaths+1,sizeof(FST_PQU_TYPE),CFst_Bsn_CompUp);

        /* Delete last element from queue (if neccesary) to keep its size smaller than nPaths+1 */
        if (nPQsize == nPaths+1-nArrivals)
        {
          lpPQ[nPQsize-1].nCtot = nNeAdd;
          nPQsize--;
        }
        nCmax = lpPQ[nPQsize-1].nCtot;

        IFCHECKEX(2)
          for (k=0; k<nPQsize; k++)
            printf("Q %d : [X:%d Y:%d] ---  Tran:%d  ----> [X:%d Y:%d] Plen:%d Cacc:%f ",
              (int)k,(int)lpPQ[k].nXini,(int)lpPQ[k].nYini,(int)lpPQ[k].nTran,
              (int)lpPQ[k].nXter,(int)lpPQ[k].nYter,(int)lpPQ[k].nPlen,(float)lpPQ[k].nCacc),
          printf("Ctot:%f \n",lpPQ[k].nCtot);
      }
    }

    /* Write transition and state in _this */
    DLPASSERT(nPQsize>=0);
    if (nPQsize>0)
    {
      /* Pop first record data from priority queue */
      nXini = lpPQ[0].nXini;
      nYini = lpPQ[0].nYini;
      nXter = lpPQ[0].nXter;
      nYter = lpPQ[0].nYter;
      nT    = lpPQ[0].nTran;
      nPlen = lpPQ[0].nPlen;
      nCacc = lpPQ[0].nCacc;
      nCtot = lpPQ[0].nCtot;

      dlp_memmove(lpPQ,&lpPQ[1],nPaths*sizeof(FST_PQU_TYPE));
      lpPQ[nPQsize-1].nCtot = nNeAdd;
      nPQsize--;
      IFCHECKEX(1) printf(" Pop priority queue\n");
      IFCHECKEX(2)
        for (k=0; k<nPQsize; k++)
          printf("Q %d : [X:%d Y:%d] ---  Tran:%d  ----> [X:%d Y:%d] Plen:%d Cacc:%f ",
            (int)k,(int)lpPQ[k].nXini,(int)lpPQ[k].nYini,(int)lpPQ[k].nTran,
            (int)lpPQ[k].nXter,(int)lpPQ[k].nYter,(int)lpPQ[k].nPlen,(float)lpPQ[k].nCacc),
          printf("Ctot:%f \n",(float)lpPQ[k].nCtot);

      /* Add state and trans in _this */
      nSini = CFst_Cps_FindState(_this,nXini,nYini,0);
      nSter = CFst_Addstates(_this,0,1,(nPathlength<=0||nPlen>=nPathlength)?(SD_FLG(itSrc,nXter+nFS)&0x01):0); /* FS-Flag ist only used if Path is long enough */
      CFst_Cps_SetSdAux(_this,nSter,nXter,nYter,0);

      /* If the path in itSrc is finished and path length exceeded increment nArrivals */
      if ((SD_FLG(itSrc,nXter+nFS)&0x01) && (nPathlength<=0 || nPlen>=nPathlength))
      {
        nArrivals++;
        nWX = nCtot;
      }
      else nWX = nNeMult;

      nNewT = CFst_AddtransCopy(_this,0,nSini,nSter,itSrc,nT);
      if (bPush) *(FST_WTYPE*)CData_XAddr(AS(CData,_this->td),nNewT,_this->m_nIcW) = nWX;

      IFCHECKEX(1)
        printf("\n AddTrans: [X:%d Y:%d] --- Cacc:%f Tran:%d Plen:%d Ctot:%f ----> [X:%d Y:%d]\n",
          (int)nXini,(int)nYini,(float)nCacc,(int)nT,(int)nPlen,(float)nCtot,(int)nXter,(int)nYter);
    }