Exemple #1
0
/**
 * <p id=dlm_fft_C>Computes the complex (inverse) fast Fourier transform.</p>
 *
 * @param C
 *          Pointer to an array containing the input, will be
 *          overwritten with the result.
 * @param nXL
 *          Length of signals. If length not power of 2 {@link dlm_dftC} will be
 *          executed.
 * @param bInv
 *          If non-zero the function computes the inverse complex Fourier
 *          transform
 * @return <code>O_K</code> if successfull, a (begative) error code otherwise
 *
 * <h4>Remarks</h4>
 * <ul>
 *   <li>The function creates the tables by its own, stores them in static arrays and
 *   reuses them for all subsequent calls with the same value of
 *   <code>nXL</code>.</li>
 * </ul>
 */
INT16 dlm_fftC
(
  COMPLEX64*     C,
  INT32          nXL,
  INT16          bInv
)
{
  register INT32 i;
  INT16 ret = O_K;
  FLOAT64* RE = (FLOAT64*)dlp_calloc(nXL, sizeof(FLOAT64));
  FLOAT64* IM = (FLOAT64*)dlp_calloc(nXL, sizeof(FLOAT64));

  for(i = nXL-1; i >= 0; i--) {
    RE[i] = C[i].x;
    IM[i] = C[i].y;
  }
  if((ret = dlm_fft(RE,IM,nXL,bInv)) == O_K) {
    for(i = nXL-1; i >= 0; i--) {
      C[i].x = RE[i];
      C[i].y = IM[i];
    }
  }

  dlp_free(RE);
  dlp_free(IM);

  return ret;                                                                   /* All done                          */
}
Exemple #2
0
/**
 * <p>Stabilises a polynomial. I.e. mirroring all roots located outside the unit circle into the unit circle.</p>
 *
 * @param poly
 *          Pointer to polynomial coefficients.
 * @param n_poly
 *          Number of polynomial coefficients stored in  <CODE>poly</CODE>.
 * @return  Number of mirrored roots.
 */
INT32 dlm_stabilise(FLOAT64* poly, INT32 n_poly) {
  COMPLEX64* roots = NULL;
  FLOAT64* a1 = NULL;
  FLOAT64* a2 = NULL;
  FLOAT64 a0;
  FLOAT64 r;
  FLOAT64 rr;
  INT16 is_stable;
  INT32 i_poly1;
  INT32 i_poly2;
  INT32 i_poly3;
  INT32 n_roots_stabilised = 0;

  roots = (COMPLEX64*) dlp_calloc(n_poly-1, sizeof(COMPLEX64));
  a1 = (FLOAT64*) dlp_calloc(2*n_poly, sizeof(FLOAT64));
  a2 = a1 + n_poly;

  a0 = poly[0];

  dlm_roots(poly, roots, n_poly);
  is_stable = 1;
  rr = 1.0;
  for (i_poly1 = 0; i_poly1 < (n_poly - 1); i_poly1++) {
    r = roots[i_poly1].x * roots[i_poly1].x + roots[i_poly1].y * roots[i_poly1].y;
    if (r > 1.0) {
      n_roots_stabilised++;
      is_stable = 0;
      roots[i_poly1].x /= r;
      roots[i_poly1].y /= r;
      rr = rr * sqrt(r);
    }
  }
  if (is_stable == 0) {
    a1[0] = 1.0;
    memset(a1 + 1, 0L, (n_poly - 1) * sizeof(FLOAT64));
    memset(a2, 0L, n_poly * sizeof(FLOAT64));
    for (i_poly2 = 0; i_poly2 < (n_poly - 1); i_poly2++) {
      for (i_poly3 = i_poly2 + 1; i_poly3 > 0; i_poly3--) {
        a1[i_poly3] -= roots[i_poly2].x * a1[i_poly3 - 1] - roots[i_poly2].y * a2[i_poly3 - 1];
        a2[i_poly3] -= roots[i_poly2].x * a2[i_poly3 - 1] + roots[i_poly2].y * a1[i_poly3 - 1];
      }
    }
    for (i_poly2 = 1; i_poly2 < n_poly; i_poly2++) {
      poly[i_poly2] = a1[i_poly2];
    }
    *poly = a0 * rr;
  }

  dlp_free(roots);
  dlp_free(a1);

  return n_roots_stabilised;
}
Exemple #3
0
/**
 * <p>Calculates polynomial from roots.</p>
 *
 * @param rtr
 *          Real roots.
 * @param rti
 *          Imaginary roots.
 * @param m
 *          Number of roots stored in  <CODE>rtr</CODE> and <CODE>rti</CODE>.
 * @param ar
 *          Pointer to resulting real polynomial coefficients.
 * @param ai
 *          Pointer to resulting imaginary polynomial coefficients (or <code>NULL</code>).
 * @return <code>O_K</code> if successful, a (negative) error code otherwise
 */
INT16 dlm_poly(FLOAT64 rtr[], FLOAT64 rti[], INT16 m, FLOAT64 ar[], FLOAT64 ai[]) {
  INT16 i = 0;
  INT16 j = 0;
  FLOAT64* arp = NULL;
  FLOAT64* aip = NULL;

  if ((!ar) || (!rtr) || (!rti)) return NOT_EXEC;

  if (ai == NULL) {
    aip = (FLOAT64*) dlp_calloc(m+1, sizeof(FLOAT64));
    if (!aip) return ERR_MEM;
    arp = ar;
  } else {
    aip = ai;
    arp = ar;
  }

  dlp_memset(arp, 0L, (m + 1) * sizeof(FLOAT64));
  dlp_memset(aip, 0L, (m + 1) * sizeof(FLOAT64));
  arp[0] = 1.0;

  for (i = 0; i < m; i++) {
    for (j = i; j >= 0; j--) {
      arp[j + 1] = arp[j + 1] - rtr[i] * arp[j] + rti[i] * aip[j];
      aip[j + 1] = aip[j + 1] - rti[i] * arp[j] - rtr[i] * aip[j];
    }
  }

  if (ai == NULL) dlp_free(aip);

  return O_K;
}
Exemple #4
0
/**
 * Composed state hash map node allocation function. Hash nodes are taken from
 * a pool: {@link grany m_nGrany} nodes are allocated at a time to save memory
 * allocations.
 */
hnode_t* CFst_Cps_HashAllocNode(void* lpContext)
{
  CFst*    _this = NULL;
  INT32    nPool = 0;
  INT32    nItem = 0;
  hnode_t* lpRet = NULL;

  /* Get this pointer and locate next hash node */
  _this = (CFst*)lpContext;
  nPool = _this->m_nCpsHnpoolSize / _this->m_nGrany;
  nItem = _this->m_nCpsHnpoolSize - nPool*_this->m_nGrany;

  /* Grow size of hash node pool table if necessary */
  if (nPool>=(INT32)(dlp_size(_this->m_lpCpsHnpool)/sizeof(hnode_t*)))
    _this->m_lpCpsHnpool =
      (void**)dlp_realloc(_this->m_lpCpsHnpool,nPool+100,sizeof(hnode_t*));

  /* Allocate a new hash node pool if necessary */
  if (_this->m_lpCpsHnpool[nPool]==NULL)
    ((hnode_t**)_this->m_lpCpsHnpool)[nPool] =
    	(hnode_t*)dlp_calloc(_this->m_nGrany,sizeof(hnode_t));

  /* Increment pool size and return pointer to new hash node */
  _this->m_nCpsHnpoolSize++;
  lpRet = &((hnode_t**)_this->m_lpCpsHnpool)[nPool][nItem];
  return lpRet;
}
Exemple #5
0
INT16 CGEN_IGNORE dlm_pam(FLOAT64* X, INT32 nC, INT32 nRX, FLOAT64* Q, INT32 nRQ) {
  INT32* clusters = (INT32*) dlp_calloc(nRQ,sizeof(INT32));
  INT32* classify = (INT32*) dlp_calloc(nRX,sizeof(INT32));
  INT32 iRX1 = 0;
  INT32 iRX2 = 0;
  INT32 iRQ = 0;
  FLOAT64 min = T_DOUBLE_MAX;
  FLOAT64 distance = 0.0;
  FLOAT64 error = T_DOUBLE_MAX;
  FLOAT64 error_old = T_DOUBLE_MAX;
  FLOAT64* pX = X;


  for(iRQ = 0; iRQ < nRQ; iRQ++) {
    clusters[iRQ] = iRQ * nRX / nRQ;
  }
  while(1) {
    error_old = error;
    error = dlm_pam_assign(X,nC,classify,nRX,clusters,nRQ);
    if(error_old <= error) break;
    for(iRQ = 0; iRQ < nRQ; iRQ++) {
      min = T_DOUBLE_MAX;
      for(iRX1 = 0; iRX1 < nRX; iRX1++) {
        if(classify[iRX1] != iRQ) continue;
        pX = X+iRX1*nC;
        distance = 0.0;
        for(iRX2 = 0; iRX2 < nRX; iRX2++) {
          if(classify[iRX2] != iRQ) continue;
          distance += dlm_pam_norm2(pX,X+iRX2*nC,nC);
        }
        if(min > distance) {
          min = distance;
          clusters[iRQ] = iRX1;
        }
      }
    }
  }
  for(iRQ = 0; iRQ < nRQ; iRQ++) {
    dlp_memmove(Q+iRQ*nC,X+clusters[iRQ]*nC,nC*sizeof(FLOAT64));
  }
  dlp_free(clusters);
  dlp_free(classify);

  return O_K;
}
Exemple #6
0
INT16 CHFAproc::Init(BOOL bCallVirtual)
{
	DEBUGMSG(-1,"CHFAproc::Init, (bCallVirtual=%d)",(int)bCallVirtual,0,0);
	//{{CGEN_INITCODE
  INIT;
  m_lpStrHFA=(tHFA *)dlp_calloc(1,sizeof(tHFA));
	//}}CGEN_INITCODE

	// If last derivation call reset (do not reset members; already done by Init())
	if (bCallVirtual) return Reset(FALSE);
	else              return O_K;
}
Exemple #7
0
/**
 * <p>Converts a coefficient vector of a polynomial in z: a(1)z^0+a(2)z^1+...
 * to a coefficient vector of a polynomial in s: b(1)s^0+b(2)s^1+...
 * by a bilinear map z:= (s+1)/(s-1)
 * which converts zeros of z inside the unit circle
 * into zeros of s in the left halfplane,
 * i.e. prepares a polynomial for the Routh/Hurwitz-test.</p>
 *
 * @param poly
 *          Pointer to polynomial coefficients.
 * @param n_order
 *          Number of polynomial coefficients stored in  <CODE>poly</CODE>.
 * @return <code>O_K</code> if successful, a (negative) error code otherwise
 */
INT16 dlm_z2s(FLOAT64* poly, INT16 n_order) {
  INT16 i_order1;
  INT16 i_order2;
  INT32 n_order2 = n_order * n_order;
  FLOAT64* pp = NULL;
  FLOAT64* pm = NULL;
  FLOAT64* ppd = NULL;
  FLOAT64* pmd = NULL;
  FLOAT64* poly_z = NULL;
  FLOAT64* poly_s = NULL;

  pp = (FLOAT64*) dlp_calloc(2*n_order2+4*n_order, sizeof(FLOAT64));
  pm = pp + n_order2;
  ppd = pm + n_order2;
  pmd = ppd + n_order;
  poly_z = pmd + n_order;
  poly_s = poly_z + n_order;

  if (dlm_pascal(pp, n_order) != O_K) return NOT_EXEC;

  dlp_memmove(pm, pp, n_order2 * sizeof(FLOAT64));

  for (i_order1 = 1; i_order1 < n_order; i_order1 += 2) {
    for (i_order2 = 0; i_order2 < n_order; i_order2++) {
      pm[i_order2 * n_order + i_order1] = -pp[i_order2 * n_order + i_order1];
    }
  }

  for (i_order1 = 0; i_order1 < n_order; i_order1++) {
    for (i_order2 = 0; i_order2 < (n_order - i_order1); i_order2++) {
      pmd[i_order2] = pm[i_order2 * n_order + n_order - i_order1 - 1 - i_order2];
    }
    for (i_order2 = n_order - i_order1; i_order2 < n_order; i_order2++) {
      pmd[i_order2] = 0.0;
    }
    for (i_order2 = 0; i_order2 <= i_order1; i_order2++) {
      ppd[i_order2] = pp[i_order2 * n_order + i_order1 - i_order2];
    }
    for (i_order2 = i_order1 + 1; i_order2 < n_order; i_order2++) {
      ppd[i_order2] = 0.0;
    }
    dlm_filter_fir(ppd, n_order, pmd, poly_z, n_order, NULL, 0);
    for (i_order2 = 0; i_order2 < n_order; i_order2++) {
      poly_s[i_order2] += poly_z[i_order2] * poly[n_order - 1 - i_order1];
    }
  }
  dlp_memmove(poly, poly_s, n_order * sizeof(FLOAT64));
  dlp_free(pp);
  return O_K;
}
Exemple #8
0
INT16 CGEN_VPROTECTED CLPCproc::SynthesizeFrameImpl(FLOAT64* lpcCoef, INT16 n_lpcCoeff, FLOAT64* exc, INT32 n_exc, FLOAT64 nPfaLambda, FLOAT64 nSynLambda, FLOAT64* syn) {
  INT32    i    = 0;
  FLOAT64  gain = 0.0;
  FLOAT64* lpc  = NULL;

  if(n_lpcCoeff != m_nCoeff) {
    if(m_lpMemLpc != NULL) {
      dlp_free(m_lpMemLpc);
    }
  }
  if(m_lpMemLpc == NULL) {
    m_lpMemLpc = (FLOAT64*)dlp_calloc(n_lpcCoeff - 1, sizeof(FLOAT64));        //  allocate memory
    if(!m_lpMemLpc) return ERR_MEM;
    m_nCoeff = n_lpcCoeff;
  }

  lpc = (FLOAT64*)dlp_calloc(n_lpcCoeff, sizeof(FLOAT64));
  if(!lpc) return IERROR(this, ERR_MEM, "lpc", 0, 0);

  gain = *lpcCoef;
  *lpcCoef = 1.0;
  if(nPfaLambda != nSynLambda) {
    dlm_mlpc2lpc(lpcCoef, n_lpcCoeff, lpc, n_lpcCoeff, (nPfaLambda-nSynLambda)/(1-nPfaLambda*nSynLambda));
  } else {
    dlp_memmove(lpc, lpcCoef, n_lpcCoeff*sizeof(FLOAT64));
  }

  gain = gain/ *lpc;
  *lpc = 1.0;
  dlm_filter_iir(lpc, n_lpcCoeff, exc, syn, n_exc, m_lpMemLpc, n_lpcCoeff - 1);
  for(i = 0; i < n_exc; i++) {
    syn[i] *= gain;
  }

  dlp_free(lpc);
  return O_K;
}
Exemple #9
0
/**
 * <p id="dlm_invert_gel">Inverts a matrix and computes its determinant through Gaussian
 * elimination.</p>
 *
 * @param A
 *          Pointer to input matrix, replaced in computation by resultant
 *          inverse
 * @param nXA
 *          Order of matrix (number of rows and columns)
 * @param lpnDet
 *          Pointer to be filled with resultant determinant (may be
 *          <code>NULL</code>)
 * @return <code>O_K</code> if successfull, a (negative) error code otherwise
 */
INT16 dlm_invert_gel(FLOAT64* A, INT32 nXA, FLOAT64* lpnDet) {
  integer n = (integer) nXA;
  integer c__1 = 1;
  integer c_n1 = -1;
  integer info = 0;
  integer* ipiv = dlp_calloc(n, sizeof(integer));
  void* work = NULL;
  char opts[1] = { ' ' };
  extern integer ilaenv_(integer*,char*,char*,integer*,integer*,integer*,integer*,ftnlen,ftnlen);

#ifdef __MAX_TYPE_32BIT
  extern int sgetrf_(integer*,integer*,real*,integer*,integer*,integer*);
  extern int sgetri_(integer*,real*,integer*,integer*,real*,integer*,integer*);
  char name[8] = { 'S', 'G', 'E', 'T', 'R', 'I' };
  integer lwork = n * ilaenv_(&c__1, name, opts, &n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1);
  work = dlp_calloc(lwork, sizeof(real));
  if(!ipiv || !work) return ERR_MEM;
  sgetrf_(&n,&n,A,&n,ipiv,&info);
  if(lpnDet != NULL) *lpnDet = (info > 0) ? 0.0 : dlm_get_det_trf(A, nXA, ipiv);
  sgetri_(&n,A,&n,ipiv,work,&lwork,&info);
#else
  extern int dgetrf_(integer*,integer*,doublereal*,integer*,integer*,integer*);
  extern int dgetri_(integer*,doublereal*,integer*,integer*,doublereal*,integer*,integer*);
  char name[8] = { 'D', 'G', 'E', 'T', 'R', 'I' };
  integer lwork = n * ilaenv_(&c__1, name, opts, &n, &c_n1, &c_n1, &c_n1, (ftnlen) 6, (ftnlen) 1);
  work = dlp_calloc(lwork, sizeof(doublereal));
  if (!ipiv || !work) return ERR_MEM;
  dgetrf_(&n, &n, A, &n, ipiv, &info);
  if (lpnDet != NULL) *lpnDet = (info > 0) ? 0.0 : dlm_get_det_trf(A, nXA, ipiv);
  dgetri_(&n, A, &n, ipiv, work, &lwork, &info);
#endif

  dlp_free(work);
  dlp_free(ipiv);
  return (info == 0) ? O_K : NOT_EXEC;
}
Exemple #10
0
/**
 * <p>Same as {@link dlm_invert_gel} but for complex input</p>
 *
 */
INT16 dlm_invert_gelC(COMPLEX64* A, INT32 nXA, COMPLEX64* lpnDet) {
  integer n = (integer) nXA;
  integer c__1 = 1;
  integer c_n1 = -1;
  integer info = 0;
  integer* ipiv = dlp_calloc(n, sizeof(integer));
  void* work = NULL;
  char opts[1] = { ' ' };
  extern integer ilaenv_(integer*,char*,char*,integer*,integer*,integer*,integer*,ftnlen,ftnlen);

#ifdef __MAX_TYPE_32BIT
  extern int cgetrf_(integer*,integer*,complex*,integer*,integer*,integer*);
  extern int cgetri_(integer*,complex*,integer*,integer*,complex*,integer*,integer*);
  char name[8] = { 'C', 'G', 'E', 'T', 'R', 'I' };
  integer lwork = n * ilaenv_(&c__1, name, opts, &n, &c_n1, &c_n1, &c_n1, (ftnlen)6, (ftnlen)1);
  work = dlp_calloc(lwork, sizeof(complex));
  if(!ipiv || !work) return ERR_MEM;
  cgetrf_(&n,&n,(complex*)A,&n,ipiv,&info);
  if(lpnDet != NULL) *lpnDet = (info > 0) ? CMPLX(0.0) : dlm_get_det_trfC(A, nXA, ipiv);
  cgetri_(&n,(complex*)A,&n,ipiv,work,&lwork,&info);
#else
  extern int zgetrf_(integer*,integer*,doublecomplex*,integer*,integer*,integer*);
  extern int zgetri_(integer*,doublecomplex*,integer*,integer*,doublecomplex*,integer*,integer*);
  char name[8] = { 'Z', 'G', 'E', 'T', 'R', 'I' };
  integer lwork = n * ilaenv_(&c__1, name, opts, &n, &c_n1, &c_n1, &c_n1, (ftnlen) 6, (ftnlen) 1);
  work = dlp_calloc(lwork, sizeof(doublecomplex));
  if (!ipiv || !work) return ERR_MEM;
  zgetrf_(&n, &n, (doublecomplex*) A, &n, ipiv, &info);
  if (lpnDet != NULL) *lpnDet = (info > 0) ? CMPLX(0.0) : dlm_get_det_trfC(A, nXA, ipiv);
  zgetri_(&n, (doublecomplex*) A, &n, ipiv, work, &lwork, &info);
#endif

  dlp_free(work);
  dlp_free(ipiv);
  return (info == 0) ? O_K : NOT_EXEC;
}
Exemple #11
0
/**
 * <p id=dlm_unwrap>Unwraps radian phases given in imaginary part of <code>C</code> to their 2&pi; complement if the
 * phase jumps greater than &pi;.</p>
 *
 * @param S
 *          Pointer to an array containing radian complex numbers, overwritten with the result.
 * @param nSL
 *          Length of input <code>S</code>.
 * @return <code>O_K</code> if successfull, a (negative) error code otherwise
 */
INT16 dlm_unwrapC(COMPLEX64* S, INT32 nSL) {
  INT32 iSL = 0;
  INT16* nCorr = (INT16*) dlp_calloc(nSL, sizeof(INT16));
  if (nCorr == NULL) return ERR_MEM;

  for (iSL = 1; iSL < nSL; iSL++) {
    if (((S + iSL)->y - (S + iSL - 1)->y) > F_PI) *(nCorr + iSL) = *(nCorr + iSL - 1) - 1;
    else if (((S + iSL)->y - (S + iSL - 1)->y) < -F_PI) *(nCorr + iSL) = *(nCorr + iSL - 1) + 1;
    else *(nCorr + iSL) = *(nCorr + iSL - 1);
  }
  for (iSL = 1; iSL < nSL; iSL++) {
    (S + iSL)->y += *(nCorr + iSL) * 2 * F_PI;
  }
  dlp_free(nCorr);
  return O_K;
}
Exemple #12
0
/**
 * Inverse Scalar Vector Quantization
 *
 * <p>This is the inverse of {@link dlm_svq}. The according to the coded input indices stream <code>I</code> and the
 * code book <code>Q</code> the output vector sequence <code>Y</code> is restored.
 *
 * @param Q Code book
 * @param nCQ Number of compnents of <code>Q</code>
 * @param nRQ Number of records of <code>Q</code>
 * @param I Input byte stream containing the indices to the code book
 * @param nRI Number of records of <code>I</code>
 * @param nCI Number of components of <code>I</code>
 * @param B Bit table containing the number of bits of the indices of each component
 * @param nRB Number of records of <code>B</code>
 * @param Y restored <code>nCQ&times;nRI</code> vector sequence
 */
INT16 CGEN_PUBLIC dlm_isvq(FLOAT64* Q, INT32 nCQ, INT32 nRQ, BYTE* I, INT32 nRI, INT32 nCI, INT32* B, INT32 nRB, FLOAT64* Y) {
  INT16 ret = O_K;
  INT32 iRI = 0;
  INT32 iCQ = 0;
  INT32 iCI = 0;
  INT32 iBB = 0;
  INT32 iBI = 0;
  INT32* pI = (INT32*) dlp_calloc(nCQ*nRI, sizeof(INT32));

  if ((Q == NULL) || (B == NULL) || (Y == NULL)) return NOT_EXEC;

  for (iRI = 0; iRI < nRI; iRI++) {
    iCQ = 0;
    iCI = 0;
    iBI = 0;
    iBB = B[0] - 1;
    pI[iRI * nCQ] = 0;
    while (iCI < nCI) {
      pI[iRI * nCQ + iCQ] |= ((I[iRI * nCI + iCI] >> iBI) & 0x1) << iBB;
      iBB--;
      iBI++;
      if (iBB < 0) {
        iCQ++;
        if (iCQ >= nCQ) break;
        iBB = B[iCQ] - 1;
      }
      if (iBI >= 8) {
        iCI++;
        iBI = 0;
      }
    }
  }

  for (iRI = 0; iRI < nRI; iRI++) {
    for (iCQ = 0; iCQ < nCQ; iCQ++) {
      if (pI[iRI * nCQ + iCQ] < nRQ) {
        Y[iRI * nCQ + iCQ] = Q[pI[iRI * nCQ + iCQ] * nCQ + iCQ];
      } else {
        ret = NOT_EXEC;
      }
    }
  }

  dlp_free(pI);

  return ret;
}
Exemple #13
0
INT16 CGEN_IGNORE __dlm_getNewCentroids(FLOAT64* X, INT32* pI, INT32 nRX, INT32 nCX, FLOAT64* Q, INT32 nRQ) {
  INT32 iRX = 0;
  INT32 iRQ = 0;
  INT32* C = (INT32*) dlp_calloc(nRQ, sizeof(INT32));

  for (iRQ = 0; iRQ < nRQ; iRQ++) {
    Q[iRQ * nCX] = 0;
  }
  for (iRX = 0; iRX < nRX; iRX++) {
    Q[pI[iRX * nCX] * nCX] += X[iRX * nCX];
    C[pI[iRX * nCX]]++;
  }
  for (iRQ = 0; iRQ < nRQ; iRQ++) {
    Q[iRQ * nCX] /= (FLOAT64) C[iRQ];
  }
  dlp_free(C);
  return O_K;
}
Exemple #14
0
INT16 dlm_routh(FLOAT64* poly, INT16 order) {
  INT16 i;
  INT16 j;
  INT16 n = (order + 1) / 2 * 2 + 2;
  FLOAT64* b1 = NULL;
  FLOAT64* b2 = NULL;
  FLOAT64* a = NULL;

  a = (FLOAT64*) dlp_calloc(order+n+n, sizeof(FLOAT64));
  b1 = a + order;
  b2 = b1 + n;

  for (i = order - 1; i >= 0; i--)
    a[i] = poly[i] / poly[0];

  dlm_z2s(a, order);

  for (i = order - 1; i >= 0; i--) {
    b1[n - order + i] = a[order - i - 1];
    b2[i] = 0.0;
  }
  for (; n - order + i >= 0; i--) {
    b1[n - order + i] = 0.0;
    b2[i] = 0.0;
  }

  for (j = n - 3; j > 2; j -= 2) {
    for (i = 0; i < n - 3; i += 2)
      b2[n - 1 - i] = b1[n - 3 - i] - b1[n - 1] * b1[n - 4 - i] / b1[n - 2];
    for (i = 1; i < n - 3; i += 2)
      b2[n - 1 - i] = b1[n - 3 - i] - b1[n - 2] * b2[n - 2 - i] / b2[n - 1];
    if ((b2[n - 1] < 0.0) || (b2[n - 2] < 0.0)) {
      dlp_free(a);
      return DLM_ROOTS_UNSTABLE;
    }
    memcpy(b1, b2, n * sizeof(FLOAT64));
  }

  dlp_free(a);

  return DLM_ROOTS_STABLE;
}
Exemple #15
0
INT16 CGEN_IGNORE dlm_lbg(FLOAT64* X, INT32 nC, INT32 nRX, FLOAT64* Q, INT32 nRQ) {
  FLOAT64* icb = (FLOAT64*) dlp_calloc(nC,sizeof(FLOAT64));
  INT32 iC = 0;
  INT32 iRX = 0;
  extern void lbg(FLOAT64*, const INT32, const INT32, FLOAT64*, INT32, FLOAT64*, const INT32, const INT32, const INT32, const INT32, const INT32, const FLOAT64, const FLOAT64);

  for (iRX = 0; iRX < nRX; iRX++) {
    for (iC = 0; iC < nC; iC++) {
      icb[iC] += X[iRX * nC + iC];
    }
  }
  for (iC = 0; iC < nC; iC++) {
    icb[iC] /= (FLOAT64) nRX;
  }

  lbg(X, nC, nRX, icb, 1, Q, nRQ, 1000, 1, 1, 1, 0.0001, 0.0001);

  dlp_free(icb);
  return O_K;
}
Exemple #16
0
 /*   Inverse Daubechies D4 transform
 *
 *    FLOAT64* trans       transformed signal
 *    FLOAT64* sig         signal array 
 *    INT32    size        transformed signal array size
 *    INT16   level       detail level (max. level = -1) that was used to transform signal  
 */
INT16 CGEN_IGNORE dlm_fwt_d4_inv(FLOAT64* trans, FLOAT64* sig, INT32 size, INT16 level)
{
  register INT32 i;
  register INT32 n;
  register INT32 size2;
  FLOAT64*  transTemp;

  if(size < 4)
  {
    return NOT_EXEC;
  } 

  transTemp = (FLOAT64*)dlp_calloc(size, sizeof(FLOAT64));
  dlp_memmove(transTemp, trans, size * sizeof(FLOAT64));

  if(level > 0)
  {
    n = size >> (level-1);
    if(n<4) n=4;
  }
Exemple #17
0
INT16 CGEN_VPROTECTED CLSFproc::SynthesizeFrameImpl(FLOAT64* lsf, INT16 n_lsf, FLOAT64* exc, INT32 n_exc, FLOAT64 nPfaLambda, FLOAT64 nSynLambda, FLOAT64* syn) {
  INT16   ret   = O_K;
  INT16   n_lpc = n_lsf;
  FLOAT64* lpc   = NULL;

  if(m_bSynLsf) {
    if(nPfaLambda == nSynLambda) {
      return dlm_lsf_synthesize(lsf, n_lsf, exc, n_exc, syn, &m_lpMemLsf);
    } else {
      return dlm_mlsf_synthesize(lsf, n_lsf, exc, n_exc, (nPfaLambda-nSynLambda)/(1.0-nSynLambda*nPfaLambda), syn, &m_lpMemLsf);
    }
  }

  if(nPfaLambda != nSynLambda) n_lpc = 4*n_lsf;

  lpc = (FLOAT64*)dlp_calloc(n_lpc, sizeof(FLOAT64));
  if(!lpc) return IERROR(this, ERR_MEM, "lpc", 0, 0);

  if(nPfaLambda == nSynLambda) {
    if(m_bSynLpcFilt) {
      if(dlm_lsf2poly_filt(lsf, n_lsf, lpc, n_lpc, &m_lpMemLsf) != O_K) { dlp_free(lpc); return NOT_EXEC; }
    } else {
      if(dlm_lsf2poly(lsf, lpc, n_lsf) != O_K) { dlp_free(lpc); return NOT_EXEC; }
    }
  } else {
    if(m_bSynLpcFilt) {
      if(dlm_mlsf2poly_filt(lsf, n_lsf, lpc, n_lpc, (nPfaLambda-nSynLambda)/(1.0-nSynLambda*nPfaLambda), &m_lpMemLsf) != O_K) { dlp_free(lpc); return NOT_EXEC; }
    } else {
      if(dlm_lsf2poly(lsf, lpc, n_lsf) != O_K) { dlp_free(lpc); return NOT_EXEC; }
      if(dlm_mlpc2lpc(lpc,n_lsf,lpc,n_lpc,(nPfaLambda-nSynLambda)/(1.0-nSynLambda*nPfaLambda)) != O_K) { dlp_free(lpc); return NOT_EXEC; }
    }
    nPfaLambda = nSynLambda = 0.0;
  }

  if(dlm_gmult(lpc, lpc, n_lpc, -1.0) != O_K) return NOT_EXEC;

  ret = CLPCproc::SynthesizeFrameImpl(lpc, n_lpc, exc, n_exc, nPfaLambda, nSynLambda, syn);

  dlp_free(lpc);
  return ret;
}
Exemple #18
0
/**
 * Adds three auxiliary components to the state table of this instance. These
 * components are used by {@link -compose CFst_Compose} and
 * {@link -best_n CFst_BestN} to associate a composed state with its source
 * states and an epsilon filter mode. The method sets the field
 * {@link ic_sd_aux m_nIcSdAux} to the first component added.
 *
 * @param _this Pointer to automaton instance
 * @see Cps_DelSdAux CFst_Cps_DelSdAux
 * @see Cps_SetSdAux CFst_Cps_SetSdAux
 * @see Cps_FindState CFst_Cps_FindState
 */
void CGEN_PRIVATE CFst_Cps_AddSdAux(CFst* _this)
{
  /* Add auxiliary components to state table */
  CData_AddComp(AS(CData,_this->sd),"X"  ,DLP_TYPE(FST_ITYPE));
  CData_AddComp(AS(CData,_this->sd),"Y"  ,DLP_TYPE(FST_ITYPE));
  CData_AddComp(AS(CData,_this->sd),"Flg",T_BYTE             );

  DLPASSERT((_this->m_nIcSdAux = CData_FindComp(AS(CData,_this->sd),"X"  ))>=0);
  DLPASSERT(                     CData_FindComp(AS(CData,_this->sd),"Y"  ) >=0);
  DLPASSERT(                     CData_FindComp(AS(CData,_this->sd),"Flg") >=0);

  /* Initialize hash node pool */
  DLPASSERT(_this->m_lpCpsHnpool   ==NULL);
  DLPASSERT(_this->m_nCpsHnpoolSize==0   );
  _this->m_lpCpsHnpool    = (void**)dlp_calloc(100,sizeof(hnode_t*));
  _this->m_nCpsHnpoolSize = 0;
  dlp_memset(_this->m_lpCpsKeybuf,0,3*sizeof(FST_ITYPE));

  /* Initialize composed state hash map */
  DLPASSERT(_this->m_lpCpsHash==NULL);
  _this->m_lpCpsHash = hash_create(HASHCOUNT_T_MAX,CFst_Cps_HashCmp,CFst_Cps_HashFn,_this);
  hash_set_allocator((hash_t*)_this->m_lpCpsHash,CFst_Cps_HashAllocNode,CFst_Cps_HashFreeNode,_this);
}
Exemple #19
0
 /*   Daubechies D4 transform
 *
 *    FLOAT64* sig         signal array
 *    FLOAT64* trans       transformed signal
 *    INT32    size        signal size
 *    INT16   level       detail level (max. level = -1)  
  */
INT16 CGEN_IGNORE dlm_fwt_d4(FLOAT64* sig, FLOAT64* trans, INT32 size, INT16 level)
{
  register INT32 i;
  register INT32 n;
  register INT32 size2;
  FLOAT64* sigTemp;
  

  if(size < 4)
  {
    return NOT_EXEC;
  } 
  
  sigTemp = (FLOAT64*)dlp_calloc(size, sizeof(FLOAT64));
  dlp_memmove(sigTemp, sig, size * sizeof(FLOAT64));
  
  for (n = size; n >= 4; n >>= 1)
  {
    size2 = n >> 1;
    for (i = 0; i <= size2-2; i++)
    {
      trans[i]       = sigTemp[i*2]*h0 + sigTemp[i*2+1]*h1 + sigTemp[i*2+2]*h2 + sigTemp[i*2+3]*h3; /* scaling function coefficients */
      trans[i+size2] = sigTemp[i*2]*h3 - sigTemp[i*2+1]*h2 + sigTemp[i*2+2]*h1 - sigTemp[i*2+3]*h0; /* wavelet function coefficents */
    }

    trans[i]       = sigTemp[n-2]*h0 + sigTemp[n-1]*h1 + sigTemp[0]*h2 + sigTemp[1]*h3;
    trans[i+size2] = sigTemp[n-2]*h3 - sigTemp[n-1]*h2 + sigTemp[0]*h1 - sigTemp[1]*h0;

    dlp_memmove(sigTemp, trans, n * sizeof(FLOAT64));
    level--;
    if(level == 0) break; /* reduce detail level and exit if reaching 0; if detail level is max. (-1) nothing happens */
  }
  
  dlp_free(sigTemp);
  
  return O_K;
}
Exemple #20
0
INT16 CGEN_IGNORE dlm_pascal(FLOAT64* p, INT16 n_order) {
  INT16 i_order1;
  INT16 i_order2;
  INT16 i_order3;
  FLOAT64* pp = NULL;

  if ((!p) || (n_order < 1)) return NOT_EXEC;

  pp = (FLOAT64*) dlp_calloc(n_order*n_order, sizeof(FLOAT64));

  for (i_order1 = 0; i_order1 < n_order; i_order1++) {
    pp[i_order1 * n_order] = 1.0;
    pp[i_order1 * n_order + i_order1] = (i_order1 % 2) ? -1 : 1;
  }

  for (i_order1 = 1; i_order1 < n_order - 1; i_order1++) {
    for (i_order2 = i_order1 + 1; i_order2 < n_order; i_order2++) {
      pp[i_order2 * n_order + i_order1] =
          pp[(i_order2 - 1) * n_order + i_order1] - pp[(i_order2 - 1) * n_order + i_order1 - 1];
    }
  }
  for (i_order1 = 0; i_order1 < n_order; i_order1++) {
    for (i_order2 = i_order1; i_order2 < n_order; i_order2++) {
      p[i_order1 * n_order + i_order2] = 0.0;
      for (i_order3 = 0; i_order3 < n_order; i_order3++) {
        p[i_order1 * n_order + i_order2] += pp[i_order1 * n_order + i_order3] * pp[i_order2 * n_order + i_order3];
      }
    }
  }
  for (i_order1 = 0; i_order1 < n_order; i_order1++) {
    for (i_order2 = 0; i_order2 < i_order1; i_order2++) {
      p[i_order1 * n_order + i_order2] = p[i_order2 * n_order + i_order1];
    }
  }
  dlp_free(pp);
  return O_K;
}
Exemple #21
0
/**
 * Import and export of non-native file formats.
 *
 * @param _this       This instance.
 * @param sFilename   Name of file to import.
 * @param sFilter     Filter to use for import.
 * @param iInst       Instance where to save imported data.
 * @param nMode       Import or export mode.
 * @return <code>O_K</code> if successful, a (negative) error code otherwise
 */
INT16 CGEN_PROTECTED CDlpFile_ImportExport
(
  CDlpFile*   _this,
  const char* sFilename,
  const char* sFilter,
  CDlpObject* iInst,
  INT16 nMode
)
{
  INT16    retVal     = O_K;
  lnode_t* lpNode     = NULL;
  CFILE_FTYPE* lpType = NULL;
  FILE* lpFile        = NULL;
  char lpsFilenameLoc[L_PATH];
  char lpsCmd[L_PATH*2];

  CHECK_THIS_RV(FALSE);

  if(!dlp_strlen(sFilename)) return IERROR(_this,FIL_FILENAME,0     ,0,0);
  if(!iInst                ) return IERROR(_this,ERR_NULLARG,"iInst",0,0);

  dlp_strcpy(lpsFilenameLoc,sFilename);

  /* create target directory if necessary */
  if(nMode==EXPORT_FILE)
  {
    char lpNewDir[L_PATH] = "";
    char lpCurDir[L_PATH] = "";

#ifndef __TMS
    if(!_this->m_bExecute)
    {
      if(getcwd(lpCurDir,L_PATH) == NULL) return IERROR(_this,ERR_GETCWD,0,0,0);
      dlp_splitpath(lpsFilenameLoc,lpNewDir,NULL);
      if(0<dlp_strlen(lpNewDir))
      {
        if(dlp_chdir(lpNewDir,TRUE))
        {
          dlp_chdir(lpCurDir,FALSE);
          return
          IERROR(_this,ERR_FILEOPEN,lpsFilenameLoc,
              "writing (failed to create directory)",0);
        }
        dlp_chdir(lpCurDir,FALSE);
      }
    }
#endif
  }

#ifndef __TMS
  /* Execute lpsFilenameLoc (initialization & execute if import) */
  if(_this->m_bExecute)
  {
    char lpsBase[L_PATH];
    char *lpsTmp;
    dlp_splitpath(lpsFilenameLoc,NULL,lpsBase);
    if(strchr(lpsBase,' ')) *strchr(lpsBase,' ')='\0';
    lpsTmp=dlp_tempnam(NULL,lpsBase);
    snprintf(lpsCmd, L_PATH*2-1, "%s %c %s", lpsFilenameLoc, nMode==EXPORT_FILE?'<':'>', lpsTmp);
    dlp_strcpy(lpsFilenameLoc,lpsTmp);
    if(nMode==IMPORT_FILE) if(dlp_system(lpsCmd)!=0) return IERROR(_this,ERR_FILEOPEN,lpsCmd,"executing",0);
  }
#endif

  /* test if file is readable/writable */
  if(nMode==IMPORT_FILE)
    lpFile = fopen(lpsFilenameLoc,"r");
  else if(nMode==EXPORT_FILE)
    lpFile = fopen(lpsFilenameLoc,"a");
  else DLPASSERT(FMSG("Unknown operation mode."));

  if(!lpFile)
  {
    if (nMode==IMPORT_FILE)
      return IERROR(_this,ERR_FILEOPEN,sFilename,"reading",0);
    else if (nMode==EXPORT_FILE)
      return IERROR(_this,ERR_FILEOPEN,sFilename,"writing",0);
  }
  fclose(lpFile);

  /* lookup filter function from list */
  lpType = (CFILE_FTYPE*)dlp_calloc(1,sizeof(CFILE_FTYPE));
  if(!lpType) return IERROR(_this,ERR_NOMEM,0,0,0);

  dlp_strncpy(lpType->lpName,sFilter,L_NAMES);
  dlp_strncpy(lpType->lpClassName,iInst->m_lpClassName,L_NAMES);
  lpType->nMode = nMode;

  lpNode = list_find(_this->m_lpFtypes,lpType,CDlpFile_CompareFTypeList);
  if(!lpNode)
  {
    dlp_free(lpType);
    return
      IERROR(_this,FIL_NOIMEX,nMode==IMPORT_FILE?"import":"export",sFilter,
        iInst->m_lpClassName);
  }
  dlp_free(lpType);
  lpType = NULL;

  /* Invoke import function */
  lpType = (CFILE_FTYPE*)lnode_get(lpNode);
  retVal = lpType->FilterFunc(_this,lpsFilenameLoc,iInst,lpType->lpName);

#ifndef __TMS
  /* Execute lpsFilenameLoc (execute if export & finalization) */
  if(_this->m_bExecute)
  {
    if(nMode==EXPORT_FILE) dlp_system(lpsCmd);
    unlink(lpsFilenameLoc);
  }else
#endif
  if(nMode==EXPORT_FILE && _this->m_bZip) dlp_fzip(lpsFilenameLoc,"wb6");

  if(retVal != O_K)
  {
    if(nMode==IMPORT_FILE) return IERROR(_this,FIL_IMPORT,lpsFilenameLoc,sFilter,0);
    else                   return IERROR(_this,FIL_EXPORT,lpsFilenameLoc,sFilter,0);
  }

  return O_K;
}
Exemple #22
0
/**
 *  Scalar Vector Quantization.
 *
 *  <p>This function calculates a code-book from the input vectors for each component independently. The number
 *  of columns of <code>X</code>, <code>B</code> and <code>Q</code> are equal. The bit-table determines the number of
 *  code-book entries for each component. The number of rows of <code>B</code> is <code>1</code> and of <code>Q</code>
 *  <code>max(2<sup>B</sup>)</code>. For each component <code>n</code> of <code>B</code> where
 *  <code>B[n]&lt;max(B)</code> there will be <code>NaN</code>'s for fill-up.</p>
 *
 * @param X   input containing the vectors to quantize
 * @param nRX number of input vectors
 * @param nCX dimension/components of input vectors
 * @param B   bit-table
 * @param I   output byte stream containing indices of code book
 * @param nCI Number of components of <code>I</code>
 * @param Q   output code-book
 * @param nRQ maximum number of code book entries of each single component (could be changed by shrinked codebook)
 *
 * @return <code>O_K</code> if ok, <code>NOT_EXEC</code> otherwise.
 */
INT16 CGEN_PUBLIC dlm_svq(FLOAT64* X, INT32 nRX, INT32 nCX, INT32* B, INT32 nRB, BYTE* I, INT32* nCI, FLOAT64* Q, INT32* nRQ) {
  INT16 ret = O_K;
  INT32 iCX = 0;
  INT32 iCI = 0;
  INT32 iRX = 0;
  INT32 iBB = 0;
  INT32 iBI = 0;
  INT32 iRQ = 0;
  INT32 nRQNew = 0;
  INT32 nCINew = 0;
  BOOL bChanged = TRUE;
  INT32* pI = (INT32*) dlp_calloc(nCX*nRX, sizeof(INT32));
  INT32* pNC = (INT32*) dlp_calloc(nCX, sizeof(INT32));

  if ((X == NULL) || (B == NULL) || (I == NULL) || (Q == NULL)) return NOT_EXEC;

  __dlm_getNCentroids(pNC, B, nCX);

  for (iCX = 0; iCX < nCX; iCX++) {
    iRQ = 1;
    Q[iCX] = 0;

    for (iRX = 0; iRX < nRX; iRX++) {
      Q[iCX] += X[iRX * nCX + iCX];
    }
    Q[iCX] /= (FLOAT64) nRX;

    while (iRQ < dlm_pow2(B[iCX])) {
      __dlm_splitCentroids(Q + iCX, nCX, &iRQ);
      bChanged = TRUE;
      do {
        bChanged = __dlm_assignIndices(X + iCX, Q + iCX, iRQ, nRX, nCX, *nRQ, pI + iCX);
        __dlm_getNewCentroids(X + iCX, pI + iCX, nRX, nCX, Q + iCX, iRQ);
      } while (bChanged);
    }
    while (iRQ < *nRQ) {
      Q[iRQ * nCX + iCX] = 0.0 / 0.0;
      iRQ++;
    }

    __dlm_sortCentroids(Q + iCX, nCX, iRQ);
    __dlm_shrinkCentroids(Q + iCX, B + iCX, nCX, &iRQ);
    __dlm_assignIndices(X + iCX, Q + iCX, iRQ, nRX, nCX, *nRQ, pI + iCX);
    nRQNew = MAX(nRQNew, iRQ);
  }

  *nRQ = nRQNew;

  for (iRX = 0; iRX < nRX; iRX++) {
    iCX = 0;
    iCI = 0;
    iBI = 0;
    iBB = B[0] - 1;
    I[iRX * *nCI] = 0;
    while (iCI < *nCI) {
      I[iRX * *nCI + iCI] |= ((pI[iRX * nCX + iCX] >> iBB) & 0x1) << iBI;
      iBB--;
      iBI++;
      if (iBB < 0) {
        iCX++;
        if (iCX >= nCX) break;
        iBB = B[iCX] - 1;
      }
      if (iBI >= 8) {
        iCI++;
        iBI = 0;
      }
    }
    nCINew = MAX(nCINew, iCI+1);
  }

  *nCI = nCINew;

  dlp_free(pI);
  dlp_free(pNC);

  return ret;
}
Exemple #23
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);
    }
Exemple #24
0
INT16 CGEN_PRIVATE CProsody::PmFo(data *dPM, INT32 nSrate, INT32 nSrateF0, data *dF0)    
{
  /* Initialization */
  INT32 i = 0;
  INT32 ii = 0;
  INT32 j = 0;  
  INT32 nPitchMark = 0;         // Number of Pitch Marks  
  FLOAT64 nAuxValue = 0;         // Auxiliary value
  INT32 nSumSamplePM = 0;         // Sum of PM from (0) to last PM in (samples)
  INT32 nSrate_Ratio = 0;        // Sample Rate Ratio = nSrate / nSrateF0


  
  /* Validation of data instance dF0 */
  if (!dF0 || !dF0->IsEmpty())    // If dF0 not exist or empty then return false
    return NOT_EXEC;            // NOT_EXEC = -1 (Generic error)
 
 
  /* Definition of data instance dF0 */
  // One column for F0 values (Hz)  
    dF0->AddNcomps(T_DOUBLE, 1);
    dF0->SetCname(0, "nF0");

  
     /* Number of Pitch Marks */
  nPitchMark  = dPM->GetNRecs();  // GetNRecs returns the number of valid records in the data object 
  //fprintf(stdout,"\nNumber of Pitch Marks:   %i\n",nPitchMark);

  /* Validation of data instance dPM */
  if ( nPitchMark == 0 )    // If there is no Pitch mark
  {
    //fprintf(stdout,"\nError: There is no Pitch Marks in the speech signal.");
    //return NOT_EXEC;            // NOT_EXEC = -1 (Generic error)
    return IERROR(this,NO_PM,0,0,0);
  }  

    
  /* Validation of sample rate */
    if(nSrate == 0)
    {
      //fprintf(stdout, "\nError: Sample rate for speech signal (PM file) is not specified");
      //return NOT_EXEC;
      return IERROR(this,NO_SRate,0,0,0);
    }


  /* Convert PM data object (2 columns [nPer][anreg]) to two separate columns */
  /*----------------------------------------------------------------------- 
     Important Information:
     The output of the method (-analyze) for PMA is a PM data object of type short.
     This data object consist of two separate columns:
     nPer  : is the distance between PM in samples
       anreg : is the Anregung [ (0) for (voiceless or stimmlos) and (1) for (voiced or stimmhaft)] 
                       *** Important ***
       * The data object of PMproc class or data objects with more than one component
       * were stored in memory (record after record) (the first line, second line, third line, ...)
       * i.e. [r,c] = {[0,0],[0,1],[1,0],[1,1],[2,0],[2,1],....}
       ---------------------------------------------------------------------*/
  INT16 *idPMnPer = NULL;  // PMA [nPer] = column 1 
  INT16 *idPManreg = NULL; // PMA [anreg] = column 2
  
  idPMnPer = (INT16*)dlp_calloc(nPitchMark, sizeof(INT16));  // Allocates zero-initialize memory
  idPManreg = (INT16*)dlp_calloc(nPitchMark, sizeof(INT16));  // Allocates zero-initialize memory
  
  

  for (i = 0; i < nPitchMark; i++)
  {
    nAuxValue = CData_Dfetch(dPM,i,0);
    idPMnPer[i] = (INT16)nAuxValue;
    //fprintf(stdout,"PMA-nPer %i = %i",i,idPMnPer[i]);
      
    nAuxValue = CData_Dfetch(dPM,i,1);
    idPManreg[i] = (INT16)nAuxValue;
    //fprintf(stdout,"\t\tPMA-Anreg %i = %i\n",i,idPManreg[i]);  
  }
  
  /*
  fprintf(stdout,"\n\nThe nPer and Anreg of PM: \n");  // show data 
  //for(i=0; i<nPitchMark; i++)
  for(i=0; i<100; i++)  
    fprintf(stdout,"nPer %i = %i \t\t Anreg %i = %i \n",i,idPMnPer[i],i,idPManreg[i]);
  */


  /* Calculate the length of PM from (0) to last PM in (samples) 
     and allocate a vector with this length */
  for (i=0; i<nPitchMark; i++)
  {
    nSumSamplePM = nSumSamplePM + idPMnPer[i];
  }
  //fprintf(stdout,"\n\nNumber of samples from (0) to last PM:   %i\n",nSumSamplePM);

  
  // Allocate memory
  INT32 *idExpandPM = NULL; 
  idExpandPM = (INT32*)dlp_calloc(nSumSamplePM, sizeof(INT32));  // Allocates zero-initialize memory

  /*----- Produce Zahlenvektor for PMs -----*/
  INT16 nCurrentPMnPer = 0;    // Length of current PM in samples
  INT16 nCurrentPManreg = 0;    // Anregung of current PM
  INT16 nNextPManreg = 0;      // Anregung of next PM


  for (i = 0; i < nPitchMark-1; i++)
  {
    nCurrentPMnPer = idPMnPer[i];    // Length of current PM in samples
    nCurrentPManreg = idPManreg[i];    // Anregung of current PM
    nNextPManreg = idPManreg[i+1];    // Anregung of next PM
    
     /*----- Produce Zahlenvektor for (nPitchMark-1) PMs -----*/
     // PM current is unvoiced && PM next is unvoiced  =>  Values = 0
     if ( nCurrentPManreg == 0 && nNextPManreg == 0 )
     {
       for( ii = 0; ii < nCurrentPMnPer ; ii++ )
       {
         idExpandPM[j] = (INT32) 0;
         j++;
       }
     }
     // PM current is unvoiced && PM next is voiced  =>  Values = 0     
     else if ( nCurrentPManreg == 0 && nNextPManreg == 1 )
     {
       for( ii = 0; ii < nCurrentPMnPer ; ii++ )
       {
         idExpandPM[j] = (INT32) 0;
         j++;
       }
     }     
     // PM current is voiced && PM next is unvoiced  =>  Values = nCurrentPMnPer
     else if ( nCurrentPManreg == 1 && nNextPManreg == 0 )
     {
       for( ii = 0; ii < nCurrentPMnPer ; ii++ )
       {
         idExpandPM[j] = (INT32) nCurrentPMnPer;
         //idExpandPM[j] = (INT32) 0;
         j++;
       }
     }     
     // PM current is voiced && PM next is voiced  =>  Values = nCurrentPMnPer
     else   // else if( nCurrentPManreg == 1 && nNextPManreg == 1 )
     {
       for( ii = 0; ii < nCurrentPMnPer ; ii++ )
       {
         idExpandPM[j] = (INT32) nCurrentPMnPer;
         j++;
       }
     }     
  }



    /*----- Produce Zahlenvektor for last PM -----*/
  nCurrentPMnPer = idPMnPer[nPitchMark-1];    // Length of last PM in samples
  nCurrentPManreg = idPManreg[nPitchMark-1];    // Anregung of last PM
  
  if ( nCurrentPManreg == 1 )
  {
     for( ii = 0; ii < nCurrentPMnPer ; ii++ )
     {
       idExpandPM[j] = (INT32) nCurrentPMnPer;
       j++;
     }
  }
  else 
  {
     for( ii = 0; ii < nCurrentPMnPer ; ii++ )
     {
       idExpandPM[j] = (INT32) 0;
       j++;
     }    
  }  
  
  /*  
  fprintf(stdout,"\n\nThe expand values of PM: \n");  // show data 
  //for(i=0; i<nPitchMark; i++)
  for(i=0; i<300; i++)  
    fprintf(stdout,"Expand values of PM %i = %i \n",i,idExpandPM[i]);
  */
  
  

  /*---------- Calculate F0 values ----------*/
  // Calculate Sample Rate Ratio = nSrate / nSrateF0;
  if ( nSrateF0 == 0 )      // Divide by zero (false !!!)
  {
      //fprintf(stdout, "\nError: Divide by zero.");
      //return NOT_EXEC;
      return IERROR(this,Div_Zero,0,0,0);
  }
  else
  {
    nSrate_Ratio = (INT32) nSrate / nSrateF0;
  }
  //fprintf(stdout,"\nSample Rate Ratio:   %i\n",nSrate_Ratio);



  // Allocate memory for F0 values
  FLOAT64 *idContourF0 = NULL;

  INT32 nNumberF0 = 0;  // Number of F0 values in file

  for ( i = 0; i < (nSumSamplePM-nSrate_Ratio); i+=nSrate_Ratio )
  {
    if( idExpandPM[i+nSrate_Ratio] == 0 )
    {
      idContourF0 = (FLOAT64*)dlp_realloc(idContourF0, (nNumberF0+1), sizeof(FLOAT64));
      idContourF0[nNumberF0] = (FLOAT64) 0;
      nNumberF0 = nNumberF0 + 1;
    }
    else
    {
      idContourF0 = (FLOAT64*)dlp_realloc(idContourF0, (nNumberF0+1), sizeof(FLOAT64));
      //idContourF0[nNumberF0] = (FLOAT64) nSrate / idExpandPM[i+nSrate_Ratio];
      nAuxValue =  (FLOAT64) nSrate / idExpandPM[i+nSrate_Ratio];
      idContourF0[nNumberF0] = nAuxValue;
      nNumberF0 = nNumberF0 + 1;
    }    
    
  }

  // Delete single F0 value
  for ( i=1; i<nNumberF0-2; i++)
  {
    if(idContourF0[i]!=0 && idContourF0[i-1]==0 && idContourF0[i+1]==0)
    {
      idContourF0[i]=0;
    }
  }
  

  /* Write F0 values in struct */
    F0_CONTOUR *F0_contour = NULL;  // (F0_contour) is an object of struct (F0_CONTOUR)


  F0_contour = (F0_CONTOUR*)dlp_calloc(nNumberF0, sizeof(F0_CONTOUR));  // Allocates zero-initialize memory

  for(i = 0; i < nNumberF0; i++)  
  {
        (F0_contour + i)->nF0value = idContourF0[i];
        //fprintf( stdout,"nF0value  %i = %f\n",i,idContourF0[i] );
  }


    
  /* Copy F0 values from (struct F0_contour) to output data object (dF0) */
  dF0->AddRecs(nNumberF0, 1); // AddRecs: Appends (n) records to the end of the table (data object)  
  for( i = 0; i < nNumberF0; i++ )
  {
      dF0->Dstore((FLOAT64)(F0_contour + i)->nF0value, i, 0);
  }


  /*
  FLOAT64 nAuxCopy = 0;
  
  for (i = 0; i < nNumberF0; i++)
  {
    nAuxCopy = (FLOAT64)CData_Dfetch(dF0,i,0);
    fprintf(stdout,"F0 value %i = %f\n",i,nAuxCopy);  
  }
  */  
  
  dlp_free(idPMnPer);
  dlp_free(idPManreg);  
  dlp_free(idExpandPM);    
  dlp_free(idContourF0);
  dlp_free(F0_contour);    
      
  return O_K;
}
Exemple #25
0
/**
 * <p>Calculates roots by tracking from known roots using coefficient matching
 * method by Starer, Nehorai, 1991, Transactions - Adaptive Polynomial Factorization
 * By Coefficient Matching.</p>
 *
 * @param poly1
 *          Polynomial of predecessor
 * @param rtr1
 *          Real part of roots of predecessor.
 * @param rti1
 *          Imaginary part of roots of predecessor.
 * @param poly2
 *          Polynomial of successor where the roots are calculated from.
 * @param rtr2
 *          Real part of roots of successor to be calculated.
 * @param rti2
 *          Imaginary part of roots of successor to be calculated.
 * @param m
 *          Number of roots, i.e. size of <CODE>rtr[12]</CODE> and <CODE>rti[12]</CODE>.
 * @param n_iter
 *          Maximum number of iterations of newtons method per interim point
 * @param eps
 *          Maximum error used for breaking condition at newtons method
 * @return <code>O_K</code> if successful, a (negative) error code otherwise
 */
FLOAT64 dlm_roots_track_match_poly(COMPLEX64 poly1[], COMPLEX64 rt1[], COMPLEX64 poly2[], COMPLEX64 rt2[], INT16 m, INT16 n_iter, FLOAT64 eps) {
  INT16 i = 0;
  INT16 j = 0;
  INT16 i_iter = 0;
  FLOAT64 alpha = 1.0;
  FLOAT64 e0 = 0.0;
  FLOAT64 e1 = 0.0;
  FLOAT64 e2 = 0.0;
  COMPLEX64* poly_c = NULL;
  COMPLEX64* T = NULL;
  COMPLEX64* L = NULL;
  COMPLEX64* E = NULL;
  COMPLEX64* D = NULL;
  COMPLEX64* P1 = NULL;
  COMPLEX64* P2 = NULL;

  if (!poly1 || !poly2 || !rt1 || !rt2) return NOT_EXEC;

  poly_c = (COMPLEX64*) dlp_calloc(m+1, sizeof(COMPLEX64));
  P1 = (COMPLEX64*) dlp_calloc(m, sizeof(COMPLEX64));
  P2 = (COMPLEX64*) dlp_calloc(m, sizeof(COMPLEX64));
  E = (COMPLEX64*) dlp_calloc(m, sizeof(COMPLEX64));
  D = (COMPLEX64*) dlp_calloc(m, sizeof(COMPLEX64));
  T = (COMPLEX64*) dlp_calloc(m*m, sizeof(COMPLEX64));
  L = (COMPLEX64*) dlp_calloc(m*m, sizeof(COMPLEX64));

  dlp_memmove(rt2, rt1, m * sizeof(COMPLEX64));
  for (i = 0; i <= m; i++) {
    poly_c[i] = dlp_scalopC(poly1[i], poly1[0], OP_DIV);
  }

  for (e1 = 0.0, i = 0; i < m; i++) {
    P1[i] = rt2[i];
    E[i] =
        dlp_scalopC(dlp_scalopC(poly2[i + 1], poly2[0], OP_DIV), dlp_scalopC(poly1[i + 1], poly1[0], OP_DIV), OP_DIFF);
    e0 += E[i].x * E[i].x;
  }

  e1 = e0;

  while ((i_iter < n_iter) && (sqrt(e1 / (FLOAT64) m) > eps)) {

    for (i = 0; i < m; i++) {
      for (j = 0; j <= i; j++) {
        (*(T + (i) * m + j)).x = poly_c[i - j].x;
        (*(T + (i) * m + j)).y = poly_c[i - j].y;
      }
    }
    for (j = 0; j < m; j++) {
      (*(L + (0) * m + j)).x = 1.0;
      (*(L + (0) * m + j)).y = 0.0;
      (*(L + (1) * m + j)).x = P1[j].x;
      (*(L + (1) * m + j)).y = P1[j].y;
    }
    for (i = 2; i < m; i++) {
      for (j = 0; j < m; j++) {
        (*(L + (i) * m + j)).x = (*(L + (i - 1) * m + j)).x * P1[j].x - (*(L + (i - 1) * m + j)).y * P1[j].y;
        (*(L + (i) * m + j)).y = (*(L + (i - 1) * m + j)).x * P1[j].y + (*(L + (i - 1) * m + j)).y * P1[j].x;
      }
    }

    dlm_solve_ludC(T, m, E, 1);
    dlm_solve_ludC(L, m, E, 1);

    dlp_memmove(D, E, m * sizeof(COMPLEX64));

    alpha = 1.0;

    do {
      for (i = 0; i < m; i++) {
        P2[i].x = P1[i].x - alpha * D[i].x;
        P2[i].y = P1[i].y - alpha * D[i].y;
      }

      dlm_polyC(P2, m, poly_c);

      for (e2 = 0.0, i = 0; i < m; i++) {
        E[i].x = dlp_scalopC(poly2[i + 1], poly2[0], OP_DIV).x - poly_c[i + 1].x;
        E[i].y = -poly_c[i + 1].y;
        e2 += E[i].x * E[i].x + E[i].y * E[i].y;
      }
      alpha /= 2.0;
    } while ((alpha > 1.0e-10) && (e2 / e1 > 1.0));
    dlp_memmove(P1, P2, m * sizeof(COMPLEX64));
    e1 = e2;
    i_iter++;
  }

  for (i = 0; i < m; i++) {
    rt2[i] = P1[i];
  }

  dlp_free(D);
  dlp_free(E);
  dlp_free(P1);
  dlp_free(P2);
  dlp_free(T);
  dlp_free(L);
  dlp_free(poly_c);

  return e2 / e0;
}
Exemple #26
0
/**
 * <p>Calculates roots by tracking from known roots using homotopy method by
 * Alexander, Stonick, 1993, ICASSP - Fast Adaptive Polynomial Root Tracking
 * Using A Homotopy Continuation Method.</p>
 *
 * @param poly1
 *          Polynomial of predecessor
 * @param rtr1
 *          Real part of roots of predecessor.
 * @param rti1
 *          Imaginary part of roots of predecessor.
 * @param poly2
 *          Polynomial of successor where the roots are calculated from.
 * @param rtr2
 *          Real part of roots of successor to be calculated.
 * @param rti2
 *          Imaginary part of roots of successor to be calculated.
 * @param m
 *          Number of roots, i.e. size of <CODE>rtr[12]</CODE> and <CODE>rti[12]</CODE>.
 * @param n_step
 *          Number of interim points on the path from old to new roots
 * @param n_iter
 *          Maximum number of iterations of newtons method per interim point
 * @param eps
 *          Maximum error used for breaking condition at newtons method
 * @return <code>O_K</code> if successful, a (negative) error code otherwise
 */
INT16 dlm_roots_track_homotopy(FLOAT64 poly1[], FLOAT64 rtr1[], FLOAT64 rti1[], FLOAT64 poly2[], FLOAT64 rtr2[], FLOAT64 rti2[], INT16 m, INT16 n_step, INT16 n_iter, FLOAT64 eps) {
  INT16 i_step = 0;
  INT16 i_iter = 0;
  INT16 i = 0;
  INT16 j = 0;
  FLOAT64 pos = 0.0;
  FLOAT64 F1[2] = { 0.0, 0.0 };
  FLOAT64 F2[2] = { 0.0, 0.0 };
  FLOAT64 H[2] = { 0.0, 0.0 };
  FLOAT64 dH[2] = { 0.0, 0.0 };
  FLOAT64 delta[2] = { 0.0, 0.0 };
  FLOAT64* dP1 = NULL;
  FLOAT64* dP2 = NULL;
  FLOAT64 tmp = 0.0;
  FLOAT64* trackLen = NULL;
  FLOAT64 alpha = 0.3;

  if (!poly1 || !poly2 || !rtr1 || !rti1 || !rtr2 || !rti2) return NOT_EXEC;

  dP1 = (FLOAT64*) dlp_calloc(3*m, sizeof(FLOAT64));
  dP2 = dP1 + m;
  trackLen = dP2 + m;

  for (i = 0; i < m; i++) {
    rtr2[i] = sqrt(rtr1[i] * rtr1[i] + rti1[i] * rti1[i]);
    rti2[i] = atan2(rti1[i], rtr1[i]);
    dP1[i] = poly1[i] * (FLOAT64) (m - i);
    dP2[i] = poly2[i] * (FLOAT64) (m - i);
  }

  for (i_step = 1; i_step <= n_step; i_step++) {
    pos = (FLOAT64) i_step / (FLOAT64) n_step;
    for (i = 0; i < m; i++) {
      for (j = m, F1[0] = 0.0, F1[1] = 0.0, F2[0] = 0.0, F2[1] = 0.0; j >= 0; j--) {
        tmp = dlm_pow(rtr2[i], j);
        F1[0] += poly1[m - j] * tmp * cos(rti2[i] * (FLOAT64) j);
        F1[1] += poly1[m - j] * tmp * sin(rti2[i] * (FLOAT64) j);
        F2[0] += poly2[m - j] * tmp * cos(rti2[i] * (FLOAT64) j);
        F2[1] += poly2[m - j] * tmp * sin(rti2[i] * (FLOAT64) j);
      }
      H[0] = (1.0 - pos) * F1[0] + pos * F2[0];
      H[1] = (1.0 - pos) * F1[1] + pos * F2[1];
      tmp = H[0];
      H[0] = sqrt(H[0] * H[0] + H[1] * H[1]);
      H[1] = atan2(H[1], tmp);
      i_iter = 0;
      while ((H[0] > eps) && (i_iter < n_iter)) {
        for (j = m, F1[0] = 0.0, F1[1] = 0.0, F2[0] = 0.0, F2[1] = 0.0; j > 0; j--) {
          tmp = dlm_pow(rtr2[i], j - 1);
          F1[0] += dP1[m - j] * tmp * cos(rti2[i] * (FLOAT64) (j - 1));
          F1[1] += dP1[m - j] * tmp * sin(rti2[i] * (FLOAT64) (j - 1));
          F2[0] += dP2[m - j] * tmp * cos(rti2[i] * (FLOAT64) (j - 1));
          F2[1] += dP2[m - j] * tmp * sin(rti2[i] * (FLOAT64) (j - 1));
        }
        dH[0] = (1.0 - pos) * F1[0] + pos * F2[0];
        dH[1] = (1.0 - pos) * F1[1] + pos * F2[1];
        tmp = dH[0];
        dH[0] = sqrt(dH[0] * dH[0] + dH[1] * dH[1]);
        dH[1] = atan2(dH[1], tmp);

        delta[0] = H[0] / dH[0];
        delta[1] = H[1] - dH[1];

        trackLen[i] += delta[0];

        tmp = rtr2[i];
        rtr2[i] = rtr2[i] * cos(rti2[i]);
        rti2[i] = tmp * sin(rti2[i]);

        rtr2[i] -= alpha * delta[0] * cos(delta[1]);
        rti2[i] -= alpha * delta[0] * sin(delta[1]);
        tmp = rtr2[i];
        rtr2[i] = sqrt(rtr2[i] * rtr2[i] + rti2[i] * rti2[i]);
        rti2[i] = atan2(rti2[i], tmp);

        for (j = m, F1[0] = 0.0, F1[1] = 0.0, F2[0] = 0.0, F2[1] = 0.0; j >= 0; j--) {
          tmp = dlm_pow(rtr2[i], j);
          F1[0] += poly1[m - j] * tmp * cos(rti2[i] * (FLOAT64) j);
          F1[1] += poly1[m - j] * tmp * sin(rti2[i] * (FLOAT64) j);
          F2[0] += poly2[m - j] * tmp * cos(rti2[i] * (FLOAT64) j);
          F2[1] += poly2[m - j] * tmp * sin(rti2[i] * (FLOAT64) j);
        }
        H[0] = (1.0 - pos) * F1[0] + pos * F2[0];
        H[1] = (1.0 - pos) * F1[1] + pos * F2[1];
        tmp = H[0];
        H[0] = sqrt(H[0] * H[0] + H[1] * H[1]);
        H[1] = atan2(H[1], tmp);

        i_iter++;
      }
      if (i_iter == n_iter) {
        dlp_free(dP1);
        return NOT_EXEC;
      }
    }
  }

  for (i = 0; i < m; i++) {
    tmp = rtr2[i];
    rtr2[i] = rtr2[i] * cos(rti2[i]);
    rti2[i] = tmp * sin(rti2[i]);
  }

  for (tmp = trackLen[0], i = 1; i < m; i++)
    tmp = MAX(tmp,trackLen[i]);

  dlp_free(dP1);

  if ((tmp * alpha) > 1.0) {
    return NOT_EXEC;
  }

  return O_K;
}
Exemple #27
0
/**
 * <p>Dynamic time warping.</p>
 * This function calculates the alignment path of the two input vector sequences <code>lpSrc</code> and <code>lpDst</code>
 * by means of the minimum accumulated vector difference norm. The output <code>lpResult</code> consists of the index
 * sequence related to the vectors of <code>lpSrc</code> and the corresponding index sequence related to vectors of
 * <code>lpDst</code>. The output <code>lpError</code> contains the error at the corresponding point of the alignment path.
 *
 * @param lpSrc Pointer to reference (source) input vector sequence.
 * @param nSrcRows Number of vectors given in <code>lpSrc</code>.
 * @param lpDst Pointer to (destination) input vector sequence.
 * @param nDstRows Number of vectors given in <code>lpDst</code>.
 * @param nCols Number of vector elements of <code>lpSrc</code> and <code>lpDst</code>.
 * @param lpResult Pointer to alignment path to be calculated (must be at least <code>2*(nSrcRows+nDstRows)</code>.
 * @param nResult Pointer to the value filled with the actual size of the alignment path, so that <code>lpResult</code> and <code>lpError</code> can be reallocated by <code>nResult</code>.
 * @param lpError Pointer to the error sequence (must be at least <code>nSrcRows+nDstRows</code>.
 */
INT16 dlm_dtwC(COMPLEX64* lpSrc, INT32 nSrcRows, COMPLEX64* lpDst, INT32 nDstRows, INT32 nCols, INT32* lpResult, INT32* nResult, FLOAT64* lpError) {
  INT32 nCol;
  INT32 nSrcRow;
  INT32 nDstRow;
  FLOAT64* lpMatrix = NULL;

  DLPASSERT((lpSrc!=NULL) && (lpDst!=NULL) && (lpResult!=NULL) && (nResult!=NULL) && (lpError!=NULL));

  lpMatrix = (FLOAT64*)dlp_calloc(nSrcRows*nDstRows, sizeof(FLOAT64));

  if(lpDst != NULL) {
    for(nSrcRow = 0; nSrcRow < nSrcRows; nSrcRow++) {
      for(nDstRow = 0; nDstRow < nDstRows; nDstRow++) {
        for(nCol = 0; nCol < nCols; nCol++) {
          lpMatrix[nSrcRow*nDstRows+nDstRow] += dlp_scalopC(lpSrc[nSrcRow*nCols+nCol],lpDst[nDstRow*nCols+nCol], OP_QABSDIFF).x;
        }
        lpMatrix[nSrcRow*nDstRows+nDstRow] = sqrt(lpMatrix[nSrcRow*nDstRows+nDstRow]);
      }
    }
  }

  for(nSrcRow = 0; nSrcRow < nSrcRows; nSrcRow++) {
    for(nDstRow = 0; nDstRow < nDstRows; nDstRow++) {
      if(nSrcRow > 0) {
        if(nDstRow > 0) {
          if(lpMatrix[(nSrcRow)*nDstRows+nDstRow-1] <= lpMatrix[(nSrcRow-1)*nDstRows+nDstRow]) {
            if(lpMatrix[(nSrcRow)*nDstRows+nDstRow-1] < lpMatrix[(nSrcRow-1)*nDstRows+nDstRow-1]) {
              lpMatrix[nSrcRow*nDstRows+nDstRow] += lpMatrix[(nSrcRow)*nDstRows+nDstRow-1];
            } else {
              lpMatrix[nSrcRow*nDstRows+nDstRow] = lpMatrix[nSrcRow*nDstRows+nDstRow] + lpMatrix[(nSrcRow-1)*nDstRows+nDstRow-1];
            }
          } else if(lpMatrix[(nSrcRow-1)*nDstRows+nDstRow] < lpMatrix[(nSrcRow-1)*nDstRows+nDstRow-1]) {
            lpMatrix[nSrcRow*nDstRows+nDstRow] += lpMatrix[(nSrcRow-1)*nDstRows+nDstRow];
          } else {
            lpMatrix[nSrcRow*nDstRows+nDstRow] += lpMatrix[(nSrcRow-1)*nDstRows+nDstRow-1];
          }
        } else {
          lpMatrix[nSrcRow*nDstRows+nDstRow] += lpMatrix[(nSrcRow-1)*nDstRows+nDstRow];
        }
      } else if(nDstRow > 0) {
        lpMatrix[nSrcRow*nDstRows+nDstRow] += lpMatrix[(nSrcRow)*nDstRows+nDstRow-1];
      }
    }
  }

  nSrcRow = nSrcRows-1;
  nDstRow = nDstRows-1;
  *nResult = nSrcRows+nDstRows-1;
  lpResult[*nResult*2] = nSrcRow;
  lpResult[*nResult*2+1] = nDstRow;
  lpError[*nResult] = lpMatrix[nSrcRow*nDstRows+nDstRow];
  while(nSrcRow || nDstRow) {
    if(nSrcRow) {
      if(nDstRow) {
        if(lpMatrix[(nSrcRow-1)*nDstRows+nDstRow-1] <= lpMatrix[(nSrcRow-1)*nDstRows+nDstRow]) {
          if(lpMatrix[(nSrcRow-1)*nDstRows+nDstRow-1] <= lpMatrix[(nSrcRow)*nDstRows+nDstRow-1]) {
            nSrcRow--;
            nDstRow--;
          } else {
            nDstRow--;
          }
        } else if(lpMatrix[(nSrcRow-1)*nDstRows+nDstRow] < lpMatrix[(nSrcRow)*nDstRows+nDstRow-1]) {
          nSrcRow--;
        } else {
          nDstRow--;
        }
      } else {
        nSrcRow--;
      }
    } else if(nDstRow) {
      nDstRow--;
    }
    (*nResult)--;
    lpResult[*nResult*2] = nSrcRow;
    lpResult[*nResult*2+1] = nDstRow;
    lpError[*nResult] = lpMatrix[nSrcRow*nDstRows+nDstRow];
  }

  dlp_memmove(lpResult, lpResult+2**nResult, 2*(nSrcRows+nDstRows-*nResult)*sizeof(INT32));
  dlp_memmove(lpError,  lpError +  *nResult,   (nSrcRows+nDstRows-*nResult)*sizeof(FLOAT64));
  *nResult = nSrcRows+nDstRows - *nResult;

  dlp_free(lpMatrix);

  return O_K;
}
Exemple #28
0
INT16 CGEN_PRIVATE CProsody::EnergyContour(data *dSignal, data *dEnergy)
{
  /* Initialization */
  INT32 i = 0;
  INT32 j = 0;
  INT32 nSrate = 0;             // Sample Rate
  INT32 nSamples = 0;         // Number of samples in WAV-signal (number of records in data instance)
  INT32 nWindowShift = 0;      // Shift of Windows (samples)
  INT32 nWindowLength = 0;      // Length of Window (samples)
  INT32 nShiftNumber = 0;      // Number of Shifts in the signal
  INT32 nWindowNumber = 0;      // Number of windows
  FLOAT64 nAuxEner = 0;      // Auxiliary variable to calculate the energy for one window
  FLOAT64 *samples = NULL;         // WAV Signal in double
  FLOAT64 *dEnergyContour = NULL;  // Short Time Energy Contour
  
  
  /* Validation of data instance dEnergy */
  if (!dEnergy || !dEnergy->IsEmpty())    // If dEnergy not exist or empty then return false
    return NOT_EXEC;                  // NOT_EXEC = -1 (Generic error)
 
  /* Definition of data instance dEnergy */
  // One column is the values of energy contour  
    dEnergy->AddNcomps(T_DOUBLE, 1);
    dEnergy->SetCname(0, "nEnergy");


  
  /* Compute Sample Rate (SR) */
  //nSrate = m_nSrate;
  //nSrate  = (INT32)(1000.0/CData_GetDescr(dSignal,RINC));
  
  //# "\n Distance between two Samples = ${idSig.rinc} [msec] "  -echo;
  //# 1000 idSig.rinc / nSrate =;          # Compute Sample Rate (SR)  
  nSrate = (INT32)((1000.0/CData_GetDescr(dSignal,RINC)) + 0.5);  /* +0.5 forces cast to round up or down */    
  //fprintf(stdout,"Sample Rate:   %d Hz\n\n",nSrate);
  
  
     /* Number of samples in WAV-signal */
  nSamples  = dSignal->GetNRecs();  // GetNRecs returns the number of valid records in the data instance
  //fprintf(stdout,"Number of samples in WAV-signal:   %i\n\n",nSamples);


  /* Copies data from memory area to another memory area */
  samples = (FLOAT64*)dlp_calloc(nSamples, sizeof(FLOAT64));  // dlp_calloc(NUM,SIZE) Allocates zero-initialize memory
    dlp_memmove(samples, dSignal->XAddr(0,0), nSamples * sizeof(FLOAT64));
      
    /*
    fprintf(stdout,"\n The samples of speech signal are: \n");  // show data 
  for(i=0; i<nSamples; i++)               
    fprintf(stdout,"Signal Sample %i = %f\n",i,samples[i]);
  */

  /* Calculate the Window-Length and the Window-Shift */
  nWindowShift = nSrate / 100;      // Shift = 10 msec = 16000 / 100 = 160 samples
  nWindowLength = nWindowShift * 3;  // Window Length = 30 msec = Window Shift * 3
  
  
  nShiftNumber = nSamples / nWindowShift;    // Number of Shifts in the whole signal
  nWindowNumber = nShiftNumber - 2;      // Number of Windows
  
  if (nWindowNumber < 1)            // There is no window (signal is too short)
  {
    nWindowNumber = 1;            // Set number of windows to 1
    nWindowLength = nSamples;
  }
  
  dEnergyContour = (FLOAT64*)dlp_calloc(nWindowNumber, sizeof(FLOAT64));
  
  
  /* Fensterung des Signals und Berechnung der Energy f�r jedes Fensters */
  for (i=0; i<nWindowNumber; i++)
  {
    nAuxEner = 0;
    for (j=0; j<nWindowLength; j++)
    {
      nAuxEner = nAuxEner + samples[i*nWindowShift+j]*samples[i*nWindowShift+j];  
    }
    dEnergyContour[i] = nAuxEner;
  }
    
    

  /* Write Energy values in struct */
    STEnergy_CONTOUR *Energy_contour = NULL;  // (Energy_contour) is an object of struct (STEnergy_CONTOUR)


  Energy_contour = (STEnergy_CONTOUR*)dlp_calloc(nWindowNumber, sizeof(STEnergy_CONTOUR));  // Allocates zero-initialize memory

  for(i = 0; i < nWindowNumber; i++)  
  {
        (Energy_contour + i)->nEnergyValue = dEnergyContour[i];
        //fprintf( stdout,"nEnergyValue  %i = %f\n",i,dEnergyContour[i] );
  }


    
  /* Copy Energy values from (struct Energy_contour) to output data object (dEnergy) */
  dEnergy->AddRecs(nWindowNumber, 1); // AddRecs: Appends (n) records to the end of the table (data object)  
  for( i = 0; i < nWindowNumber; i++ )
  {
      dEnergy->Dstore((FLOAT64)(Energy_contour + i)->nEnergyValue, i, 0);
  }


  /*
  FLOAT64 nAuxCopy = 0;
  
  for (i = 0; i < nWindowNumber; i++)
  {
    nAuxCopy = (FLOAT64)CData_Dfetch(dEnergy,i,0);
    fprintf(stdout,"F0 value %i = %f\n",i,nAuxCopy);  
  }
  */  
  
  dlp_free(samples);    
  dlp_free(dEnergyContour);
  dlp_free(Energy_contour);    
      
  return O_K;
}
Exemple #29
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;
}
Exemple #30
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                */
}