Esempio n. 1
0
void  KinsolNonlinSolverFreeInstanceXtra()
{
  PFModule      *this_module = ThisPFModule;
  InstanceXtra  *instance_xtra = (InstanceXtra*)PFModuleInstanceXtra(this_module);


  if (instance_xtra)
  {
    PFModuleFreeInstance((instance_xtra->nl_function_eval));
    if (instance_xtra->richards_jacobian_eval != NULL)
    {
      PFModuleFreeInstance((instance_xtra->richards_jacobian_eval));
    }
    if (instance_xtra->precond != NULL)
    {
      PFModuleFreeInstance((instance_xtra->precond));
    }

    FreeVector(instance_xtra->uscale);
    FreeVector(instance_xtra->fscale);

    tfree(instance_xtra->current_state);

    KINFree((instance_xtra->kin_mem));

    if (instance_xtra->kinsol_file)
      fclose((instance_xtra->kinsol_file));

    tfree(instance_xtra);
  }
}
Esempio n. 2
0
/* Select: randomly select one from the nfoll arcs attached to n using */
int Select(NodeId n, int nfoll, LogFloat *prob)
{
   Vector wtp; /* word transition probs */
   float x,csum,sum = 0.0;
   int i,sel;
   ArcId a;

   for (i=1,a = n->foll; i<=nfoll; i++, a = a->farc) 
      sum += a->lmlike;
   if (sum==0.0) { /* no lm probs are set */
      x = RandomValue() * nfoll;
      sel = (int) (x + 1);   if (sel>nfoll) sel = nfoll;
      *prob = -log(1.0/(float)nfoll);
   }else{
      wtp = CreateVector(&gstack,nfoll);
      sum = 0.0;
      for (i=1,a = n->foll; i<=nfoll; i++, a = a->farc){
         wtp[i] = exp(a->lmlike); sum += wtp[i];
      }
      csum = 0.0;
      for (i=1; i<=nfoll; i++){
         x = wtp[i]/sum;
         wtp[i] = csum + x;  csum = wtp[i];
      }
      csum = 0.0;
      x = RandomValue();
      for (i=1,a = n->foll; i<=nfoll; i++, a = a->farc) {
         *prob = -a->lmlike;
         if (x<=wtp[i] || i==nfoll) break;
      }
      sel = i;
      FreeVector(&gstack,wtp);
   }
   return sel;
}
/* PutVFloor: output variance floor vectors */
void PutVFloor(void)
{
   int i,s;
   char outfn[MAXSTRLEN],vName[32],num[10];
   FILE *f;
   Vector v;
   
   MakeFN("vFloors",outDir,NULL,outfn);
   if ((f = fopen(outfn,"w")) == NULL)
      HError(2011,"PutVFloor: cannot create %s",outfn);
   for (s=1; s <= hset.swidth[0]; s++) {
      v = CreateVector(&gstack,hset.swidth[s]);
      sprintf(num,"%d",s); 
      strcpy(vName,"varFloor"); strcat(vName,num);
      fprintf(f,"~v %s\n",vName);
      if (fullcNeeded[s])              
         TriDiag2Vector(accs[s].squareSum.inv,v);
      else
         CopyVector(accs[s].fixed.var,v);
      for (i=1; i<=hset.swidth[s]; i++)
         v[i] *= vFloorScale;
      fprintf(f,"<Variance> %d\n",hset.swidth[s]);
      WriteVector(f,v,FALSE);
      FreeVector(&gstack,v);
   }
   fclose(f);
   if (trace&T_TOP)
      printf("Var floor macros output to file %s\n",outfn);
}
Esempio n. 4
0
/* VQNodeScore: compute VQNodeScore between v and n, smallest score is best. */
float VQNodeScore(VQNode n, Vector v, int size, CovKind ck)
{
   Vector m,iv,crow,vx;
   TriMat ic;
   float x,sum;
   int i,j;

   m = n->mean;
   switch(ck){
   case NULLC:
      sum = 0.0;
      for (i=1; i<=size; i++){
         x = v[i]-m[i]; sum += x*x;
      }
      return n->gconst+sum;
   case INVDIAGC:
      iv = (Vector)n->cov.var;
      sum = 0.0;
      for (i=1; i<=size; i++){
         x = v[i]-m[i]; sum += x*x*iv[i];
      }
      return n->gconst+sum;
   case FULLC:
      ic = (TriMat)n->cov.inv;
      vx = CreateVector(&gstack,size);
      for (i=1;i<=size;i++)
         vx[i] = v[i] - m[i];
      sum = 0.0;
      for (i=2;i<=size;i++) {
         crow = ic[i];
         for (j=1; j<i; j++)
            sum += vx[i]*vx[j]*crow[j];
      }
      sum *= 2;
      for (i=1;i<=size;i++)
         sum += vx[i] * vx[i] * ic[i][i];
      FreeVector(&gstack,vx);
      return n->gconst+sum;
   default:
      HError(6172,"VQNodeScore: bad kind %d",ck);
   }
   return 0; /* to keep compiler happy */
}
Esempio n. 5
0
/* EXPORT->RefC2LPC: transfer from ref coef to filter */
void RefC2LPC (Vector k, Vector a)
{
   Vector thisA; /* Current LP filter coefficients */
   Vector newA;  /* New LP filter coefficients */
   int i,j,p;
   float ki;
   
   p=VectorSize(k);
   thisA = CreateVector(&gstack,p);
   newA  = CreateVector(&gstack,p);
   for (i=1;i<=p;i++) { 
      ki = k[i];
      newA[i] = -ki;
      for (j=1;j<i;j++) 
         newA[j] = thisA[j] - ki * thisA[i - j];
      for (j=1;j<=i;j++)   
         thisA[j] = newA[j];
   }
   for (i=1;i<=p;i++)  a[i]=thisA[i];
   FreeVector(&gstack,thisA);
}
Esempio n. 6
0
/* EXPORT->Wave2LPC: Calculate LPCoef in a & RefC in k */
void Wave2LPC (Vector s, Vector a, Vector k, float *re, float *te)
{
   Vector thisA;     /* Current LP filter coefficients */
   Vector r;         /* AutoCorrelation Sequence */
   float E;          /* Prediction Error */
   int   p,frameSize;

   if (a==NULL && k==NULL)
      HError(5320,"Wave2LPC: Null a and k vectors in WaveToLPC");  
   if (a!=NULL) 
      p=VectorSize(a); 
   else
      p=VectorSize(k);
   r = CreateVector(&gstack,p);
   thisA = (a!=NULL)?a:CreateVector(&gstack,p);
   frameSize=VectorSize(s);
   E = AutoCorrelate(s,r,p,frameSize);
   *te = E;
   *re = Durbin(k,thisA,r,E,p);
   FreeVector(&gstack,r);
}
Esempio n. 7
0
/* EXPORT->LPC2RefC: transfer from filter to ref coef */
void LPC2RefC(Vector a, Vector k)
{
   Vector thisA; /* Current LP filter coefficients */
   Vector newA;  /* New LP filter coefficients */
   int i,j,p;
   float ki,x;
   
   p=VectorSize(a);
   thisA = CreateVector(&gstack,p);
   newA  = CreateVector(&gstack,p);
   CopyVector(a,thisA);
   for (i=p;i>=1;i--)  { 
      ki = -thisA[i];
      k[i] = ki;
      x = 1 - ki*ki;
      for (j=1;j<i;j++) 
         newA[j] = (thisA[j] + ki * thisA[i - j]) / x;
      for (j=1;j<i;j++) 
         thisA[j] = newA[j];
   }
   FreeVector(&gstack,thisA);
}
Esempio n. 8
0
/* Durbins recursion to get LP coeffs for auto values */
static float Durbin(Vector k, Vector thisA, Vector r, float E, int order)
{
   Vector newA;
   float ki;         /* Current Reflection Coefficient */
   int i,j;
 
   newA  = CreateVector(&gstack,order);
   for (i=1;i<=order;i++) {
      ki = r[i];              /* Calc next reflection coef */
      for (j=1;j<i;j++)
         ki = ki + thisA[j] * r[i - j];
      ki = ki / E;   
      if (k!=NULL) k[i] = ki;
      E *= 1 - ki*ki;         /* Update Error */
      newA[i] = -ki;          /* Calc new filter coef */
      for (j=1;j<i;j++)
         newA[j] = thisA[j] - ki * thisA[i - j];
      for (j=1;j<=i;j++)   
         thisA[j] = newA[j];
   }
   FreeVector(&gstack,newA);
   return (E);
}
Esempio n. 9
0
/* WriteStateDurations: output state duration to file */
void WriteStateDurations(char *labfn, GenInfo * genInfo)
{
   char fn[MAXFNAMELEN];
   int i, j, k, s, cnt, nState, modeldur;
   float modelMean;
   Label *label;
   FILE *durfp;
   Vector mean = NULL;
   Boolean isPipe;

   /* open file pointer for saving state durations */
   MakeFN(labfn, genDir, durExt, fn);
   if ((durfp = FOpen(fn, NoOFilter, &isPipe)) == NULL)
      HError(9911, "WriteStateDurations: Cannot create output file %s", fn);

   /* prepare mean vector */
   mean = CreateVector(genInfo->genMem, genInfo->maxStates);

   for (i = 1; i <= genInfo->labseqlen; i++) {
      label = GetLabN(genInfo->labseq->head, i);
      nState = genInfo->hmm[i]->numStates - 2;

      /* compose mean vector of the i-th state duration model */
      for (s = cnt = 1; s <= genInfo->dset->swidth[0]; s++) {
         for (k = 1; k <= genInfo->dset->swidth[s]; k++, cnt++)
            mean[cnt] = genInfo->dm[i]->svec[2].info->pdf[s].info->spdf.cpdf[1].mpdf->mean[k];
      }

      modeldur = 0;
      modelMean = 0.0;
      for (j = 1; genInfo->sindex[i][j] != 0; j++) {
         /* output state duration */
         fprintf(durfp, "%s.state[%d]: duration=%d (frame), mean=%e\n", label->labid->name, genInfo->sindex[i][j], genInfo->durations[i][j], mean[genInfo->sindex[i][j] - 1]);
         fflush(durfp);

         if (trace & T_DUR) {
            printf("%s.state[%d]: duration=%d (frame), mean=%e\n", label->labid->name, genInfo->sindex[i][j], genInfo->durations[i][j], mean[genInfo->sindex[i][j] - 1]);
            fflush(stdout);
         }

         modeldur += genInfo->durations[i][j];
         modelMean += mean[genInfo->sindex[i][j] - 1];
      }

      fprintf(durfp, "%s: duration=%d (frame), mean=%e\n", label->labid->name, modeldur, modelMean);
      fflush(durfp);

      if (trace & T_DUR) {
         printf("%s: duration=%d (frame), mean=%e\n", label->labid->name, modeldur, modelMean);
         fflush(stdout);
      }
   }

   /* dispose mean vector */
   FreeVector(genInfo->genMem, mean);

   /* close file pointer for saving state durations */
   FClose(durfp, isPipe);

   return;
}
Esempio n. 10
0
/*
 * Perfrom a fine registration using the ICP algorithm
 */
void FineRegistration(void)
{
  int         i, j, count;
  int         num_p, num_q;
  point_xyz   *p, *q, cp;
  matrix      *R;
  vector      *t;
  double      Mf[16];

  // compute total number of points
  num_p = num_q = 0;
  for (i=0; i<num_rdata_anc; i++) num_q += rd_anc[i].num_pt;
  for (i=0; i<num_rdata_mov; i++) num_p += rd_mov[i].num_pt;

  // allocate memory
  R = AllocateMatrix(3, 3);
  t = AllocateVector(3);
  p = (point_xyz *) malloc (num_p * sizeof(point_xyz));
  q = (point_xyz *) malloc (num_q * sizeof(point_xyz));

  // copy xyz values
  count = 0;
  for (i=0; i<num_rdata_anc; i++) {
    
    for (j=0; j<rd_anc[i].num_pt; j++) {
      cp.x = rd_anc[i].xyz[3*j];
      cp.y = rd_anc[i].xyz[3*j+1];
      cp.z = rd_anc[i].xyz[3*j+2];
      // transform with its modeling transformation matrix
      q[count].x = cp.x * rd_anc[i].M[0] + cp.y * rd_anc[i].M[4] +
                   cp.z * rd_anc[i].M[8] + rd_anc[i].M[12];
      q[count].y = cp.x * rd_anc[i].M[1] + cp.y * rd_anc[i].M[5] +
                   cp.z * rd_anc[i].M[9] + rd_anc[i].M[13];
      q[count].z = cp.x * rd_anc[i].M[2] + cp.y * rd_anc[i].M[6] +
                   cp.z * rd_anc[i].M[10] + rd_anc[i].M[14]; 
      count++;
    }
  }
  count = 0;
  for (i=0; i<num_rdata_mov; i++) {
    // use modelview just for matrix multiplication
    
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glMultMatrixd(new_M);
    glMultMatrixd(rd_mov[i].M);
    glGetDoublev(GL_MODELVIEW_MATRIX, Mf);
    glPopMatrix();

    for (j=0; j<rd_mov[i].num_pt; j++) {
      // transform 
      cp.x = rd_mov[i].xyz[3*j];
      cp.y = rd_mov[i].xyz[3*j+1];
      cp.z = rd_mov[i].xyz[3*j+2];
      
      p[count].x = cp.x*Mf[0] + cp.y*Mf[4] + cp.z*Mf[8] + Mf[12];
      p[count].y = cp.x*Mf[1] + cp.y*Mf[5] + cp.z*Mf[9] + Mf[13];
      p[count].z = cp.x*Mf[2] + cp.y*Mf[6] + cp.z*Mf[10] + Mf[14]; 
      count++;
    }
  }

  // perform ICP
  //ICPalgorithm(R, t, p, num_p, q, num_q, 5, 5.0, 100, 0.10, 0.0005);
  ICPalgorithm(R, t, p, num_p, q, num_q, 5, 5.0, 1000, 0.010, 0.000005);
  Mf[0] = R->entry[0][0]; Mf[4] = R->entry[0][1]; Mf[8] = R->entry[0][2];
  Mf[1] = R->entry[1][0]; Mf[5] = R->entry[1][1]; Mf[9] = R->entry[1][2];
  Mf[2] = R->entry[2][0]; Mf[6] = R->entry[2][1]; Mf[10] = R->entry[2][2];
  Mf[12] = t->entry[0];   Mf[13] = t->entry[1];   Mf[14] = t->entry[2];
  Mf[3] = Mf[7] = Mf[11] = 0; Mf[15] = 1;

  // update new_M
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  glMultMatrixd(Mf);
  glMultMatrixd(new_M);
  glGetDoublev(GL_MODELVIEW_MATRIX, new_M);
  glPopMatrix();

  // free memory
  FreeMatrix(R); FreeVector(t);
  free(p); free(q);
}
Esempio n. 11
0
/*
 * Peform a course registration using selected corresponding points by user
 */
void CourseRegistration(void)
{
  register int  i;
  double        Sxx, Sxy, Sxz,
                Syx, Syy, Syz,
                Szx, Szy, Szz; 
  double        max_eval;
  point_xyz     *p, *q;
  point_xyz     mean_corres_p,
                mean_corres_q;  
  int           num_corres; 
  matrix        *Q, *R;
  vector        *max_evec, *t;

  // initialize values
  Sxx = Sxy = Sxz = Syx = Syy = Syz = Szx = Szy = Szz = 0.0;
  mean_corres_p.x = mean_corres_p.y = mean_corres_p.z = 0.0;
  mean_corres_q.x = mean_corres_q.y = mean_corres_q.z = 0.0;

  // take the smaller one
  num_corres = (num_corres_anc<num_corres_mov)?num_corres_anc:num_corres_mov;

  // allocate memory
  Q = AllocateMatrix(4, 4);
  R = AllocateMatrix(3, 3);
  max_evec = AllocateVector(4);
  t = AllocateVector(3);
  p = (point_xyz *) malloc (num_corres * sizeof(point_xyz));
  q = (point_xyz *) malloc (num_corres * sizeof(point_xyz));
  
  // transform
  for (i=0; i<num_corres; i++) {
    p[i].x = (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]] *
              rd_mov[corres_rd_mov[i]].M[0]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+1] *
              rd_mov[corres_rd_mov[i]].M[4]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+2] *
              rd_mov[corres_rd_mov[i]].M[8]) +
              rd_mov[corres_rd_mov[i]].M[12];
    p[i].y = (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]] *
              rd_mov[corres_rd_mov[i]].M[1]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+1] *
              rd_mov[corres_rd_mov[i]].M[5]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+2] *
              rd_mov[corres_rd_mov[i]].M[9]) +
              rd_mov[corres_rd_mov[i]].M[13];
    p[i].z = (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]] *
              rd_mov[corres_rd_mov[i]].M[2]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+1] *
              rd_mov[corres_rd_mov[i]].M[6]) +
             (rd_mov[corres_rd_mov[i]].xyz[3*corres_pt_mov[i]+2] *
              rd_mov[corres_rd_mov[i]].M[10]) +
              rd_mov[corres_rd_mov[i]].M[14];

    q[i].x = (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]] *
              rd_anc[corres_rd_anc[i]].M[0]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+1] *
              rd_anc[corres_rd_anc[i]].M[4]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+2] *
              rd_anc[corres_rd_anc[i]].M[8]) +
              rd_anc[corres_rd_anc[i]].M[12];
    q[i].y = (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]] *
              rd_anc[corres_rd_anc[i]].M[1]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+1] *
              rd_anc[corres_rd_anc[i]].M[5]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+2] *
              rd_anc[corres_rd_anc[i]].M[9]) +
              rd_anc[corres_rd_anc[i]].M[13];
    q[i].z = (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]] *
              rd_anc[corres_rd_anc[i]].M[2]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+1] *
              rd_anc[corres_rd_anc[i]].M[6]) +
             (rd_anc[corres_rd_anc[i]].xyz[3*corres_pt_anc[i]+2] *
              rd_anc[corres_rd_anc[i]].M[10]) +
              rd_anc[corres_rd_anc[i]].M[14];

    //printf("%d: %f %f %f\n", i, q[i].x, q[i].y, q[i].z);
  }
 
  
  for (i=0; i<num_corres; i++) {
    mean_corres_p.x += p[i].x;
    mean_corres_p.y += p[i].y;
    mean_corres_p.z += p[i].z;
      
    mean_corres_q.x += q[i].x;
    mean_corres_q.y += q[i].y;
    mean_corres_q.z += q[i].z;
  }
  mean_corres_p.x /= (double)num_corres;
  mean_corres_p.y /= (double)num_corres;
  mean_corres_p.z /= (double)num_corres;
  mean_corres_q.x /= (double)num_corres;
  mean_corres_q.y /= (double)num_corres;
  mean_corres_q.z /= (double)num_corres;

     
  for (i=0; i<num_corres; i++) {
    Sxx += p[i].x * q[i].x;
    Sxy += p[i].x * q[i].y;
    Sxz += p[i].x * q[i].z;
    Syx += p[i].y * q[i].x;
    Syy += p[i].y * q[i].y;
    Syz += p[i].y * q[i].z;
    Szx += p[i].z * q[i].x;
    Szy += p[i].z * q[i].y;
    Szz += p[i].z * q[i].z;
  }

  Sxx = Sxx / (double)num_corres - (mean_corres_p.x * mean_corres_q.x);
  Sxy = Sxy / (double)num_corres - (mean_corres_p.x * mean_corres_q.y);
  Sxz = Sxz / (double)num_corres - (mean_corres_p.x * mean_corres_q.z);
  Syx = Syx / (double)num_corres - (mean_corres_p.y * mean_corres_q.x);
  Syy = Syy / (double)num_corres - (mean_corres_p.y * mean_corres_q.y);
  Syz = Syz / (double)num_corres - (mean_corres_p.y * mean_corres_q.z);
  Szx = Szx / (double)num_corres - (mean_corres_p.z * mean_corres_q.x);
  Szy = Szy / (double)num_corres - (mean_corres_p.z * mean_corres_q.y);
  Szz = Szz / (double)num_corres - (mean_corres_p.z * mean_corres_q.z);

  // construct N
  Q->entry[0][0] = Sxx + Syy + Szz;
  Q->entry[1][0] = Q->entry[0][1] = Syz - Szy;
  Q->entry[2][0] = Q->entry[0][2] = Szx - Sxz;
  Q->entry[3][0] = Q->entry[0][3] = Sxy - Syx;
  Q->entry[1][1] = Sxx - Syy - Szz;
  Q->entry[1][2] = Q->entry[2][1] = Sxy + Syx;
  Q->entry[1][3] = Q->entry[3][1] = Szx + Sxz;
  Q->entry[2][2] = -Sxx + Syy - Szz;
  Q->entry[2][3] = Q->entry[3][2] = Syz + Szy;
  Q->entry[3][3] = -Sxx - Syy + Szz;

  // --- compute largest eigenvalues and eigenvectors of Q ---
  SymmetricLargestEigens(Q, max_evec, &max_eval); 
  // make sure max_evec[0] > 0
  if (max_evec->entry[0] < 0) {
    for (i=0; i<4; i++) max_evec->entry[i] *= -1.0;
  }
  // --- compute rotation matrix ---
  RotationQuaternion(max_evec, R);
 
  // --- compute translation vector ---
  t->entry[0] = mean_corres_q.x - 
                R->entry[0][0] * mean_corres_p.x -
                R->entry[0][1] * mean_corres_p.y -
                R->entry[0][2] * mean_corres_p.z;
  t->entry[1] = mean_corres_q.y - 
                R->entry[1][0] * mean_corres_p.x -
                R->entry[1][1] * mean_corres_p.y -
                R->entry[1][2] * mean_corres_p.z;
  t->entry[2] = mean_corres_q.z - 
                R->entry[2][0] * mean_corres_p.x -
                R->entry[2][1] * mean_corres_p.y -
                R->entry[2][2] * mean_corres_p.z;

  //PrintMatrix(R);
  //PrintVector(t);

  new_M[0] = R->entry[0][0]; new_M[4] = R->entry[0][1]; new_M[8] = R->entry[0][2];
  new_M[1] = R->entry[1][0]; new_M[5] = R->entry[1][1]; new_M[9] = R->entry[1][2];
  new_M[2] = R->entry[2][0]; new_M[6] = R->entry[2][1]; new_M[10] = R->entry[2][2];
  new_M[12] = t->entry[0];   new_M[13] = t->entry[1];   new_M[14] = t->entry[2];
  new_M[3] = new_M[7] = new_M[11] = 0; new_M[15] = 1;

  // free memory
  FreeMatrix(Q); FreeMatrix(R);
  FreeVector(max_evec); FreeVector(t);
  free(p); free(q);
}
Esempio n. 12
0
// 余额划拨-划出
int PaymentInfo::DeductBalanceInfo(PaymentInfoALLCCR &pPaymentInfoCCR,PaymentInfoALLCCA &pPaymentInfoCCA)
{
	bool bState=false;
	int iRet=0;
	long lPaymentAmount=0L;
	long m_lBalance=0L;

	vector<AcctBalanceInfo*>vAcctBalanceInfo;
	vector<BalanceSourceInfo *>vBalanceSourceInfo;
	vAcctBalanceInfo.clear();
	vBalanceSourceInfo.clear();
	StructPaymentSeqInfo  sStructPaymentSeqInfo={0};
	
	try 
	{
		//查询余额帐本明细
		iRet=m_poSql->QueryAcctBalanceInfo(pPaymentInfoCCR,vAcctBalanceInfo);
		if(iRet!=0)
		{
			__DEBUG_LOG1_(0, "QueryAcctBalanceInfo==[%d]",iRet);
			throw iRet;
		}
		__DEBUG_LOG1_(0, "QueryAcctBalanceInfo.size==[%d]",vAcctBalanceInfo.size());
		
		//校验是否足够扣费
		for(vector<AcctBalanceInfo*>::iterator it=vAcctBalanceInfo.begin();it!=vAcctBalanceInfo.end();it++)
			m_lBalance+=(*it)->m_lBalance;
			
		__DEBUG_LOG1_(0, "余额帐本总金额m_lBalance==[%d]",m_lBalance);	
		__DEBUG_LOG1_(0, "需划出金额m_lBalance==[%d]",0-pPaymentInfoCCR.m_lPayAmount);
		
		// 帐户剩余金额
		pPaymentInfoCCA.m_lAcctBalance = m_lBalance + pPaymentInfoCCR.m_lPayAmount;
		
		if( (m_lBalance) < (0-pPaymentInfoCCR.m_lPayAmount))
		{
			__DEBUG_LOG0_(0, "余额划出 - 帐本余额不足以划拨!");
			throw -1;
		}
		//查询业务流水 - PaymentSeq
		iRet=m_poSql->QueryPaySeq(sStructPaymentSeqInfo,bState);
		if(iRet!=0)
		{
			__DEBUG_LOG0_(0, "余额划出 - 生成业务流水号失败");
			throw iRet;
		}
		// 响应信息
		pPaymentInfoCCA.m_lPaymentID=sStructPaymentSeqInfo.m_lPaymentSeq;  // 业务流水号
		
		//记录业务信息表
		iRet=m_poSql->InsertPaymentInfo(pPaymentInfoCCR,sStructPaymentSeqInfo); // 插入业务记录信息
		
		if(iRet!=0)
		{
			__DEBUG_LOG0_(0, "余额划出 - 插入业务信息表失败");
			throw iRet;
		}
		
		// 更新余额帐本金额
		long lPayAmount = 0 - pPaymentInfoCCR.m_lPayAmount; // 划拨金额
		long lBalance;
		BalanceSourceInfo balanceSourceInfo;
		for(vector<AcctBalanceInfo*>::iterator iter=vAcctBalanceInfo.begin();iter!=vAcctBalanceInfo.end();iter++)
		{
			__DEBUG_LOG1_(0, " vAcctBalanceInfo.m_lAcctBalanceID=[%d] ",(*iter)->m_lAcctBalanceID);

			lBalance = (*iter)->m_lBalance; // 余额帐本金额
			
			if(lPayAmount==0)	// 无需划拨
				break;
			
			if(lPayAmount >= lBalance)
			{
				lPayAmount = lPayAmount - lBalance; // 待划拨金额
				sStructPaymentSeqInfo.m_lPaymentAmount = lBalance;
				balanceSourceInfo.m_lAmount = 0-lBalance;
			}
			else
			{
				sStructPaymentSeqInfo.m_lPaymentAmount = lPayAmount; // 每次划拨金额
				balanceSourceInfo.m_lAmount = 0-lPayAmount; // 余额来源记录金额
				lPayAmount=0;	
			}
				
			//查询业务流水 - 余额来源记录流水
			bState = true;
			iRet=m_poSql->QueryPaySeq(sStructPaymentSeqInfo,bState);
			if(iRet!=0)
			{
				__DEBUG_LOG0_(0, "余额划出 - 生成业务流水号失败");
				throw iRet;
			}

			// 更新余额帐本表 - 余额帐本扣费
			iRet=m_poSql->updateAcctBalance(sStructPaymentSeqInfo,*iter);
			if(iRet!=0)
			{
		        	__DEBUG_LOG0_(0, "余额划出 - 更新余额帐本失败");
				throw iRet;
        		}
			
			// 余额来源表插入一条对应扣费的负值
			// 余额来源数据准备
			
			// 插入余额来源记录表
			// 记录余额来源表 - 记录一笔负钱
			// 余额来源赋值
			balanceSourceInfo.m_lOperIncomeID = sStructPaymentSeqInfo.m_lBalanceSourceSeq;
			balanceSourceInfo.m_lAcctBalanceId = (*iter)->m_lAcctBalanceID;
			
			
			pPaymentInfoCCA.m_lAcctBalanceId = (*iter)->m_lAcctBalanceID; // 扣费账本标识
			pPaymentInfoCCA.m_lDeductAmountAll = sStructPaymentSeqInfo.m_lPaymentAmount; // 账本划拨金额
			// 账本剩余金额
			pPaymentInfoCCA.m_lAcctBalanceAmount = lBalance - pPaymentInfoCCA.m_lDeductAmountAll;
			
			//balanceSourceInfo.m_lAmount = -10;
			strcpy(balanceSourceInfo.m_sSourceType,"5VH");// 划出余额类型
			strcpy(balanceSourceInfo.m_sSourceDesc,"余额划拨");
			balanceSourceInfo.m_lPaymentID=sStructPaymentSeqInfo.m_lPaymentSeq;
			balanceSourceInfo.m_lBalance=balanceSourceInfo.m_lAmount;
			strcpy(balanceSourceInfo.m_sAllowDraw,"ADY");
	
			iRet = m_poSql->insertBalanceSource(balanceSourceInfo);
			if(iRet!=0)
			{
				__DEBUG_LOG0_(0, "余额划出 - 插入余额来源失败");
				throw iRet;
			}	
		}
	}
	catch(TTStatus oSt) 
	{
		iRet=BALANCE_PAYOUT_TT_ERR;
		__DEBUG_LOG1_(0, "PaymentInfo::DeductBalanceInfo oSt.err_msg=%s", oSt.err_msg);
	}
	catch(int &value ) 
	{
		iRet=value;
		__DEBUG_LOG1_(0, "PaymentInfo::DeductBalanceInfo value=%d",value);
	}
	FreeVector(vAcctBalanceInfo);
	FreeVector(vBalanceSourceInfo);
	return iRet;
Esempio n. 13
0
//根据用户标识查询账户明细,校验是否足够余额扣费(划拨),记录业务记录信息表,
//查询余额来源信息,每条来源信息更新此条来源的当前余额,记录余额支出表,记录余额来源支出关系表,更新余额账本表
int PaymentInfo::RecodePaymentInfo(PaymentInfoALLCCR &pPaymentInfoCCR,PaymentInfoALLCCA &pPaymentInfoCCA)
{

	bool bState=false;
	int iRet=0;
	long lPaymentAmount=0L;
	long m_lBalance=0L;
	char sDate[15];
	string  m_sOperType;


	vector<AcctBalanceInfo*>vAcctBalanceInfo;
	vector<BalanceSourceInfo *>vBalanceSourceInfo;
	vAcctBalanceInfo.clear();
	vBalanceSourceInfo.clear();
	StructPaymentSeqInfo  sStructPaymentSeqInfo={0};
	
	try 
	{

		
		//取当前系统时间
		memset(sDate,'\0',sizeof(sDate));
		GetDate(sDate);

		//查询账户明细
		iRet=m_poSql->QueryAcctBalanceInfo(pPaymentInfoCCR,vAcctBalanceInfo);
		if(iRet!=0)
		{
			__DEBUG_LOG1_(0, "支付,查询账户明细失败==[%d]",iRet);
			throw iRet;
		}
		__DEBUG_LOG1_(0, "支付,查询账户明细结果.size==[%d]",vAcctBalanceInfo.size());
		
		//校验是否足够扣费
		for(vector<AcctBalanceInfo*>::iterator it=vAcctBalanceInfo.begin();it!=vAcctBalanceInfo.end();it++)
		{
			if(((strlen((*it)->m_sEffDate)>=8)&&(memcmp((*it)->m_sEffDate,sDate,8)>0))||((strlen((*it)->m_sExDate)>=8)&&(memcmp((*it)->m_sExDate,sDate,8)<0)))
			{
				continue;
			}

			m_lBalance+=(*it)->m_lBalance;
		}
		if( (m_lBalance) < (pPaymentInfoCCR.m_lPayAmount) )
		{
			__DEBUG_LOG0_(0, "支付,账本余额不足以支付!");
			throw BALANCE_NOT_PAYMENT_ERR;
		}
		//查询业务流水
		iRet=m_poSql->QueryPaySeq(sStructPaymentSeqInfo,bState);
		if(iRet!=0)
        	{
			__DEBUG_LOG0_(0, "支付,查询业务流水失败!");
			throw iRet;
        	}
		pPaymentInfoCCA.m_lPaymentID=sStructPaymentSeqInfo.m_lPaymentSeq;
		//记录业务信息表
		iRet=m_poSql->InsertPaymentInfo(pPaymentInfoCCR,sStructPaymentSeqInfo);
		if(iRet!=0)
        	{
			__DEBUG_LOG0_(0, "支付,记录业务信息表失败!");
			throw iRet;
        	}
		for(vector<AcctBalanceInfo*>::iterator it=vAcctBalanceInfo.begin();it!=vAcctBalanceInfo.end();it++)
		{
			__DEBUG_LOG1_(0, " 支付,账本m_lAcctBalanceID=[%d] ",(*it)->m_lAcctBalanceID);
			FreeVector(vBalanceSourceInfo);
			//判断账户有效期
			if(((strlen((*it)->m_sEffDate)>=8)&&(memcmp((*it)->m_sEffDate,sDate,8)>0))||((strlen((*it)->m_sExDate)>=8)&&(memcmp((*it)->m_sExDate,sDate,8)<0)))
			{
			    	__DEBUG_LOG0_(0, "支付账户已失效!");
			    	__DEBUG_LOG2_(0, "支付账户已失效,生效时间=[%s],当前时间=[%s]!",(*it)->m_sEffDate,sDate);
			    	__DEBUG_LOG2_(0, "支付账户已失效,失效时间=[%s],当前时间=[%s]!",(*it)->m_sExDate,sDate);
				continue;

			}
			//查询余额来源表
			iRet=m_poSql->QueryBalanceSourceInfo((*it)->m_lAcctBalanceID,vBalanceSourceInfo);
			if(iRet!=0)
            		{
			    	__DEBUG_LOG0_(0, "支付,查询余额来源表失败!");
				throw iRet;
            		}
			//循环更新来源信息表当前余额
			vector<BalanceSourceInfo*>::iterator iter=vBalanceSourceInfo.begin();
			while((pPaymentInfoCCR.m_lPayAmount)>0&&(iter!=vBalanceSourceInfo.end()))
			{
				if( (*iter)->m_lBalance<=0 )
				{
					__DEBUG_LOG1_(0, "支付来源余额不足支付,继续寻找一下支付来源,seq=[%d]!",(*iter)->m_lOperIncomeID);
					continue;
				}
				if((pPaymentInfoCCR.m_lPayAmount)>=((*iter)->m_lBalance))
				{
					sStructPaymentSeqInfo.m_lPaymentAmount=(*iter)->m_lBalance;
					pPaymentInfoCCR.m_lPayAmount =pPaymentInfoCCR.m_lPayAmount-(*iter)->m_lBalance;
				}
				else
				{
					sStructPaymentSeqInfo.m_lPaymentAmount=pPaymentInfoCCR.m_lPayAmount;
					pPaymentInfoCCR.m_lPayAmount=0;
				}
				bState=true;
				//查询业务流水
				iRet=m_poSql->QueryPaySeq(sStructPaymentSeqInfo,bState);
				if(iRet!=0)
                		{
			        	__DEBUG_LOG0_(0, "支付,查询业务流水失败!");
					throw iRet;
                		}
				__DEBUG_LOG1_(0, "支付:m_lPaymentSeq[%d]!",sStructPaymentSeqInfo.m_lPaymentSeq);
				__DEBUG_LOG1_(0, "支付:m_lBalanceSourceSeq [%d]!",sStructPaymentSeqInfo.m_lBalanceSourceSeq);
				__DEBUG_LOG1_(0, "支付:m_lBalancePayoutSeq [%d]!",sStructPaymentSeqInfo.m_lBalancePayoutSeq);
				__DEBUG_LOG1_(0, "支付:m_lSourcePayoutSeq [%d]!",sStructPaymentSeqInfo.m_lSourcePayoutSeq);
				__DEBUG_LOG1_(0, "待支付:m_lPaymentAmount [%d]!",sStructPaymentSeqInfo.m_lPaymentAmount);
				__DEBUG_LOG1_(0, "未支付:m_lPaymentAmount [%d]!",pPaymentInfoCCR.m_lPayAmount);
				//记录余额支出表
				m_sOperType.clear();
				m_sOperType="5UI";
				iRet=m_poSql->InsertBalancePayout(sStructPaymentSeqInfo,*iter,m_sOperType);
				if(iRet!=0)
                		{
			        	__DEBUG_LOG0_(0, "支付,记录余额支出表失败!");
					throw iRet;
                		}
				//记录来源支出关系表
				iRet=m_poSql->InsertBalanceSourcePayoutRela(sStructPaymentSeqInfo,*iter);
				if(iRet!=0)
                		{	
			        	__DEBUG_LOG0_(0, "支付,记录来源支出关系表失败!");
					throw iRet;
                 		}
				//更新余额账本表
				iRet=m_poSql->updateAcctBalance(sStructPaymentSeqInfo,*it);
				if(iRet!=0)
                		{
			        	__DEBUG_LOG0_(0, "支付,更新余额账本表失败!");
					throw iRet;
                		}
				//更新余额来源表
				iRet=m_poSql->updateBalanceSource(sStructPaymentSeqInfo,*iter);
				if(iRet!=0)
                		{
			        	__DEBUG_LOG0_(0, "支付,更新余额来源表失败!");
					throw iRet;
                		}
				iter++;
			}
		}
	}
	catch(TTStatus oSt) 
	{
		iRet=PAYMENT_TT_ERR;
		__DEBUG_LOG1_(0, "支付失败::oSt.err_msg=%s", oSt.err_msg);
	}
	catch(int &value ) 
	{
		iRet=value;
		__DEBUG_LOG1_(0, "支付失败:: value=%d",value);
	}
	FreeVector(vAcctBalanceInfo);
	FreeVector(vBalanceSourceInfo);
	return iRet;

}
Esempio n. 14
0
int main(int argc, char *argv[])
{
  if (argc < 3)
  {
    printf("Invalid input parameters\n");
    return 1;
  }
  
  int N = atoi(argv[1]);
  int NZ = atoi(argv[2]);
  char *mtxFileName = NULL;
  char *vecFileName = NULL;
  if (argc > 3 && argc < 6)
  {
      mtxFileName = argv[3];
      vecFileName = argv[4];
  }

  if ((NZ > N) || (N <= 0) || (NZ <= 0))
  {
    printf("Incorrect arguments of main\n");
    return 1;
  }

  crsMatrix A;
  double *x, *b, *bm;
  double timeM=0, timeM1=0, diff=0;

  if (ReadMatrix(A, mtxFileName) != 0)
  {
    GenerateRegularCRS(1, N, NZ, A);
    WriteMatrix(A, "mtx.txt");
  }
  if (ReadVector(&x, N, vecFileName) != 0)
  {
    GenerateVector(2, N, &x);
    WriteVector(x, N, "vec.txt");
  }

  InitializeVector(N, &b);
  Multiplicate(A, x, b, timeM);

  InitializeVector(N, &bm);
  SparseMKLMult(A, x, bm, timeM1);

  CompareVectors(b, bm, N, diff);

  if (diff < EPSILON)
    printf("OK\n");
  else
    printf("not OK\n");
  printf("%d %d\n", A.N, A.NZ);
  printf("%.3f %.3f\n", timeM, timeM1);

  FreeMatrix(A);
  FreeVector(&b);
  FreeVector(&bm);
  FreeVector(&x);

  return 0;
}
Esempio n. 15
0
/* WriteParms: write generated parameter vector sequences */
void WriteParms(char *labfn, GenInfo * genInfo)
{
   int p, t, v, k;
   char ext[MAXSTRLEN], fn[MAXFNAMELEN];
   float ig;
   Vector igvec;
   TriMat igtm;
   FILE *parmfp = NULL, *pdffp = NULL;
   Boolean isPipe1, isPipe2;
   PdfStream *pst;

   /* get ignore value for MSD */
   ig = ReturnIgnoreValue();

   /* save generated parameters */
   for (p = 1; p <= genInfo->nPdfStream[0]; p++) {
      /* p-th PdfStream */
      pst = &(genInfo->pst[p]);

      /* create ignore value vector/triangular matrix */
      igvec = CreateVector(&genStack, pst->vSize);
      igtm = CreateTriMat(&genStack, pst->vSize);
      for (v = 1; v <= pst->vSize; v++) {
         igvec[v] = ig;
         for (k = 1; k <= v; k++)
            igtm[v][k] = ig;
      }

      /* open file pointer for saving generated parameters */
      MakeFN(labfn, genDir, pst->ext, fn);
      if ((parmfp = FOpen(fn, NoOFilter, &isPipe1)) == NULL)
         HError(9911, "WriteParms: Cannot create ouput file %s", fn);

      /* open file pointer for saving pdf parameters */
      if (outPdf) {
         sprintf(ext, "%s_%s", pst->ext, pdfExt);
         MakeFN(labfn, genDir, ext, fn);
         if ((pdffp = FOpen(fn, NoOFilter, &isPipe2)) == NULL)
            HError(9911, "WriteParms: Cannot create output file %s", fn);
      }

      /* output generated parameter sequence */
      for (t = pst->t = 1; t <= genInfo->tframe; t++) {
         if (pst->ContSpace[t]) {
            /* output generated parameters */
            WriteVector(parmfp, pst->C[pst->t], inBinary);

            /* output pdfs */
            if (outPdf) {
               WriteVector(pdffp, pst->mseq[pst->t], inBinary);
               if (pst->fullCov)
                  WriteTriMat(pdffp, pst->vseq[pst->t].inv, inBinary);
               else
                  WriteVector(pdffp, pst->vseq[pst->t].var, inBinary);
            }

            pst->t++;
         } else {
            /* output ignoreValue symbol for generated parameters */
            WriteFloat(parmfp, &igvec[1], pst->order, inBinary);

            /* output ignoreValue symbol for pdfs */
            if (outPdf) {
               WriteVector(pdffp, igvec, inBinary);
               if (pst->fullCov)
                  WriteTriMat(pdffp, igtm, inBinary);
               else
                  WriteVector(pdffp, igvec, inBinary);
            }
         }
      }

      /* close file pointer */
      if (outPdf)
         FClose(pdffp, isPipe2);
      FClose(parmfp, isPipe1);

      /* free igvec */
      FreeVector(&genStack, igvec);
   }

   return;
}
Esempio n. 16
0
//信道自适应,特征域
bool GMMMapScore::LFACompensateFeat(float * &p_pfSrcDesFeatBuf,int p_nFrmNum,
									  GMMStatistic &p_Statistic,
									  float *p_pfProbBuf,float **p_ppfProbBufBuf,float *p_pfIPPBuf_VecSize4)
{
	if(p_nFrmNum<=0||p_pfSrcDesFeatBuf==NULL)
	{
		return false;
	}

	// 分配空间
	FMatrix			AMatrix;							// m_nRankNum*m_nRankNum
	FVector			BVector,xVector;					// m_nRankNum*1
	FVector			UxVector;

	if (!AllocMatrix(AMatrix,m_nRankNum,m_nRankNum))	
		return false;
	if (!AllocVector(xVector,m_nRankNum))
	{
		FreeMatrix(AMatrix);	
		return false;
	}
	if (!AllocVector(BVector,m_nRankNum))
	{
		FreeMatrix(AMatrix);			
		FreeVector(xVector);
		return false;
	}
	if (!AllocVector(UxVector,m_nVecSize))
	{
		FreeMatrix(AMatrix);			
		FreeVector(xVector);
		FreeVector(BVector);
		return false;
	}

	ZeroMatrix(AMatrix);
	ZeroVector(BVector);
	for (int nn=0;nn<m_nRankNum;nn++)	// 初始化为I矩阵
		AMatrix.pBuf[nn*m_nRankNum+nn] = m_D.pBuf[nn];
	ResetStatisticBuf(p_Statistic);
	printf("Prob before LFA : ");
	// 计算统计量
	if (!ComputeStatistic_LFA(p_pfSrcDesFeatBuf,p_nFrmNum,p_Statistic,p_pfProbBuf,p_ppfProbBufBuf,p_pfIPPBuf_VecSize4,AMatrix,BVector))
	{
		FreeMatrix(AMatrix);
		FreeVector(BVector);
		FreeVector(xVector);
		FreeVector(UxVector);
		return false;
	}
	
	// 计算信道因子
	if (!Compute_X(AMatrix,BVector,xVector))
	{
		FreeMatrix(AMatrix);
		FreeVector(BVector);
		FreeVector(xVector);
		FreeVector(UxVector);
		return false;
	}

	// 特征转换
	for(int m=0;m<m_nMixNum;m++)
	{
		ZeroVector(UxVector);
		for(int d=0;d<m_nVecSize;d++)
		{
			for(int r=0;r<m_nRankNum;r++)
				UxVector.pBuf[d] += m_V.pBlockBuf[m][d*m_nRankNum+r]*xVector.pBuf[r];
		}
		for(int t=0;t<p_nFrmNum;t++)
		{
			if (p_ppfProbBufBuf[m][t]<1.0e-5)	continue;
			
			for(int d=0;d<m_nVecSize;d++)
			{
				p_pfSrcDesFeatBuf[t*m_nVecSizeStore+d] -= p_ppfProbBufBuf[m][t]*UxVector.pBuf[d];
			}
		}
	}
	printf("Prob after LFA : ");
	//xxiao add for debug
//	ComputeStatistic_LFA(p_pfSrcDesFeatBuf,p_nFrmNum,p_Statistic,p_pfProbBuf,p_ppfProbBufBuf,p_pfIPPBuf_VecSize4,AMatrix,BVector);
	// 释放空间
	FreeMatrix(AMatrix);
	FreeVector(BVector);
	FreeVector(xVector);
	FreeVector(UxVector);

	return true;
}
Esempio n. 17
0
File: it.c Progetto: cran/PET
/***************************************************************
[NAME]
main

[SYNOPSIS]
void main(int argc, char *argv[])

[DESCRIPTION]
This is the main function which controls the program.

[USAGE]
{\tt it test.ini}

Starts the main program with the parameteres specified in {\tt test.ini}.

[REVISION]
March 96, JJJ and PT\\
April 2, 96 PT (Moved last call to clock - error in SGI CC)
July 2006,  Modification of the complete routine for the R calling.
***************************************************************/
void it(double *InImage, double *OutImage, int *StartImageTrue, double *StartImage, char **mode, int *UseFast, char **RadonKernel, char **IterationsType, int *Iterations, int *SaveIterations, char **SaveIterationsName, double *LowestALevel, double *ConstrainMin, double *ConstrainMax, double *Alpha, double *Beta, double *Regularization, int *KernelFileSave, char **KernelFileName, char **RefFileName, int *ThetaSamples, double *ThetaMin, double *DeltaTheta, int *RhoSamples, double *RhoMin, double *DeltaRho, double *Xmin, double *Ymin, double *DeltaX, double *DeltaY, int *XSamples, int *YSamples, int *OverSamp, char **DebugLevel )
{
  int RealTid1,RealTid2,n;
  float Tid, tempsuma, tempsumb, mean;
  char Value[100];
  Vector *xvector, *tempvector, *bvector;

  GetDateTime(Value,_RealTime);
  sscanf(Value,"%i",&RealTid1);
  Tid=clock();

  if (strstr(*DebugLevel,"HardCore")) DebugNiveau=_DHardCore;
  else DebugNiveau=_DNormal;
      
  Print(_DNormal,"\n********************************************\n\n");
  Print(_DNormal,"Iterative Reconstruction program version 2.0\n");
  Print(_DNormal,"    Peter Toft and Jesper James Jensen\n");
  Print(_DNormal,"     Implemented in R by Joern Schulz\n");
  Print(_DNormal,"\n********************************************\n");


  ReadItArgs("InputData", *mode, UseFast, *RadonKernel, *IterationsType, Iterations, SaveIterations, *SaveIterationsName, LowestALevel, ConstrainMin, ConstrainMax, Alpha, Beta, Regularization, KernelFileSave, *KernelFileName, *RefFileName, ThetaSamples, ThetaMin, DeltaTheta, RhoSamples,  RhoMin, DeltaRho, Xmin, Ymin, DeltaX, DeltaY, XSamples, YSamples, OverSamp, *DebugLevel);  
  
  // ==================================================================
  // Initialization of radon-image and the System-Matrix A
  
  if (itINI.IsFast)  AMatrix=GenerateAMatrix();
  
  bvector=DoubleToFloatVector(InImage, itINI.ThetaSamples, itINI.RhoSamples);

  // ==================================================================
  // Regularisation and initialisation of a Start-Image

  /* If regularisation is used, concatenate the bvector with zeroes */
  if (itINI.Regularization>0) 
    VectorCat(bvector,InitVector(AMatrix->M-bvector->N));

  if (*StartImageTrue) {
    Print(_DDetail, "A StartImage was specified. \n");
    xvector=DoubleToFloatVector(StartImage, itINI.XSamples, itINI.YSamples);
  }
  else {
    xvector=InitVector(itINI.XSamples*itINI.YSamples);
    if (itINI.IsFast) {
      /* The fast version, we can use the a-matrix */
      tempsuma=0; tempsumb=0;
      tempvector=SumRowSparseMatrix(AMatrix);
      for(n=0; n<tempvector->N; n++)
        tempsuma+=tempvector->value[n];
      for(n=0; n<bvector->N; n++)
        tempsumb+=bvector->value[n];
      mean=tempsumb/tempsuma;
      for(n=0; n<xvector->N; n++)
        xvector->value[n]=mean;
    } else {
      /* we have to estimate the mean value */
      tempsumb=0;
      for(n=0; n<bvector->N; n++)
        tempsumb+=bvector->value[n];
      mean=tempsumb/(itINI.ThetaSamples*itINI.RhoSamples*itINI.XSamples*itINI.DeltaX);
      for(n=0; n<xvector->N; n++)
        xvector->value[n]=mean;
    }    
    //Print(_DNormal,"Estimated mean of output image: %f \n",mean);
    Print(_DNormal,"Image-Initialization with: %f \n",mean);
  }

  // ==================================================================
  // Choice the corresponding Algorithm
  
  switch (itINI.Algorithm){           /* Main choice of algorithm */
    case _CG:   
      if (itINI.IsFast)
        MyImage=FAST_CG(AMatrix,xvector,bvector);
      else
        MyImage=SLOW_CG(xvector,bvector);                       
      break;
    case _EM:
      if (itINI.IsFast)
        MyImage=FAST_EM(AMatrix,xvector, bvector);                       
      else
        MyImage=SLOW_EM(xvector, bvector);                       
      break;
    case _ART:   
      if (itINI.IsFast)
        MyImage=FAST_ART(AMatrix,xvector,bvector);
      else
        MyImage=SLOW_ART(xvector,bvector);
      break;
  }
  
  ScaleImage(MyImage);
  Print(_DDetail,"\n");
  PrintStats(_DDetail, MyImage);

  // ==================================================================
  // Storage of reconstructed data and empty out the memory.
  
  ImageToFloat(OutImage, MyImage);
  FreeImage(MyImage);
  FreeVector(xvector);
  FreeVector(bvector);
  if (itINI.IsFast)
    FreeSparseMatrix(AMatrix);
  
  // ==================================================================
  // Calculation of the time-consuming.
  
  Tid=(clock()-Tid)/(float)CLOCKS_PER_SEC;
  GetDateTime(Value,_RealTime);
  sscanf(Value,"%i",&RealTid2);
  Print(_DNormal,"IT: Program was active for %.2f seconds\n",Tid) ;
  Print(_DNormal,"    World time elapsed %d seconds\n",
	(RealTid2-RealTid1));
  Print(_DNormal,"    Program used %.2f %% cpu time\n",
         Tid/((float)RealTid2-RealTid1)*100);
  Print(_DNormal,"\n");

}
Esempio n. 18
0
File: art.c Progetto: cran/PET
/****************************************************************************
[NAME]
SLOW\_ART

[SYNOPSIS]
Image *SLOW_ART(Vector *xvector,
                Vector *bvector)

[DESCRIPTION]
This function will iterate towards a solution for the sparse system of 
equations \mb{b}=\mb{A x}, where \mb{b} is the sinogram (Radon domain)
and \mb{x} is the reconstructed image to be found. The function uses a 
slow version of ART (Algebraric Reconstruction Techniques) where the 
transformation matrix is calculated on the fly.

[USAGE]
{\tt Image=ART(TestMatrix, TestSinogram);}

Reconstructs the sinogram {\tt TestSinogram}, returns it as an image.

[REVISION]
Jan. 95, JJJ and PT
July 06, J.Schulz, Modification of ReadRefImage and the condition to
                   SaveIterions
****************************************************************************/
Image *SLOW_ART(Vector *xvector, Vector *bvector)
{
  int ARows,ACols,currentrow,currentiteration,TotalIterations,AntPrint,UseRefImage;
  float denom,lambda,brk;
  //refxdev=0.0;
  float *tempXv,*tempBv;
  char DiffFileName[200];
  FILE *DiffFile=NULL;
  Vector *refxvector=NULL,*AVector;
  Image *Recon,*RefImage=NULL;

  ARows=bvector->N;
  ACols=xvector->N;

  Print(_DNormal,"Using ART (slow) to solve %i equations with %i unknowns\n",
	ARows,ACols);

  UseRefImage=(strlen(itINI.RefFileName)!=0);
  if (UseRefImage!=0) {
    RefImage=ReadRefImage(itINI.RefFileName);
    refxvector=ImageToVector(RefImage);
    FreeImage(RefImage);
    //refxdev=DeviationVector(refxvector);
    strcpy(DiffFileName,itINI.RefFileName);
    strcat(DiffFileName,".dif");
    DiffFile=fopen(DiffFileName,"wt");
    Print(_DNormal,"Logging differences in `%s' \n", DiffFileName);
  }

  tempXv=xvector->value;
  tempBv=bvector->value;
  //srand((int)clock());
  lambda=itINI.Alpha/itINI.Beta;

  TotalIterations=itINI.Iterations*ARows;
  AntPrint=(int)(TotalIterations/93);

  InitArrays();

  for (currentiteration=0;currentiteration<TotalIterations;currentiteration++)
  { 
    if (currentiteration%ARows==0) lambda*=itINI.Beta;
    if (currentiteration%AntPrint==0)
      Print(_DNormal,"Iterating %6.2f %% done\r",
	    (currentiteration+1)*100.0/TotalIterations); 
    if (itINI.IterationType==1)
      currentrow=currentiteration%ARows; 
    else {
      //currentrow=(int)(ARows*(float)rand()/(RAND_MAX+1.0));
      GetRNGstate();
      currentrow = (int)(ARows*runif(0, 1));
      //currentrow = (int)(ARows*runif(0, RAND_MAX)/(RAND_MAX+1.0));
      PutRNGstate();
    }

    AVector=GenerateAMatrixRow(currentrow); 
    denom=MultVectorVector(AVector,AVector);
    if (fabs(denom)>1e-9)
    {
      brk=lambda*(tempBv[currentrow]-MultVectorVector(AVector,xvector))/denom;       
      ARTUpdateAddVector2(xvector, AVector, brk);
    }      
    FreeVector(AVector);

    if ( (itINI.SaveIterations) && (currentiteration != 0) && (!(currentiteration%(ARows*(itINI.SaveIterations)))) )
      SaveIteration(xvector,(int)(currentiteration/ARows),itINI.SaveIterationsName);
    
    if (UseRefImage==1)
      if (currentiteration%AntPrint==0)
	  fprintf(DiffFile,"%f %f\n",(double)currentiteration/ARows,
		    (double)L2NormVector(refxvector,xvector)); 
	  /*fprintf(DiffFile,"%f %f\n",(double)currentiteration/ARows,
		    (double)L2NormVector(refxvector,xvector,refxdev));*/
  }
  Print(_DNormal,"                                                  \r");
  Recon=VectorToImage(xvector,itINI.XSamples,itINI.YSamples);
  if (UseRefImage==1){
    Print(_DNormal,"L2 = %9.6f \n",L2NormVector(refxvector,xvector));
    //Print(_DNormal,"L2 = %9.6f \n",L2NormVector(refxvector,xvector,refxdev));
    FreeVector(refxvector);
    fclose(DiffFile);
  }
  
  RenameImage(Recon,"ReconstructedImage");
  Recon->DeltaX=itINI.DeltaX;
  Recon->DeltaY=itINI.DeltaY;
  Recon->Xmin=itINI.Xmin;
  Recon->Ymin=itINI.Ymin;
  
  return Recon;
}