Example #1
0
static int rdbLoadRow(FILE *fp, bt *btr) {
    void   *UUbuf;
    uint32  ssize;
    if ((ssize = rdbLoadLen(fp, NULL)) == REDIS_RDB_LENERR) return -1;
    void *bt_val = UU(btr) ? &UUbuf : bt_malloc(ssize, btr);
    if (fread(bt_val, ssize, 1, fp) == 0) return -1;
    if (btr->numkeys == TRANSITION_ONE_MAX) {
        btr = abt_resize(btr, TRANSITION_TWO_BTREE);
    }
    if UU(btr) bt_insert(btr, UUbuf);
    else       bt_insert(btr, bt_val);
void DataCenter::mouseStart(int input_type, std::string name, const CTM trans,
                            int4b stepX, int4b stepY, word cols, word rows)
{
   if (console::op_line == input_type) return;
   if (_TEDLIB())
   {
      _TEDLIB()->check_active();
      switch (input_type)
      {
         case console::op_dbox:   _TEDLIB()->set_tmpdata( DEBUG_NEW laydata::tdtbox()  ); break;
         case console::op_dpoly:  _TEDLIB()->set_tmpdata( DEBUG_NEW laydata::tdtpoly()) ; break;
         case console::op_cbind:
         {
            assert ("" != name);
            laydata::refnamepair striter;
            CTM eqm;
            VERIFY(DATC->getCellNamePair(name, striter));
            _TEDLIB()->set_tmpdata( DEBUG_NEW laydata::tdtcellref(striter, eqm) );
            break;
         }
         case console::op_abind:
         {
            assert ("" != name);
            assert(0 != cols);assert(0 != rows);assert(0 != stepX);assert(0 != stepY);
            laydata::refnamepair striter;
            CTM eqm;
            VERIFY(DATC->getCellNamePair(name, striter));
            laydata::ArrayProperties arrprops(stepX, stepY, cols, rows);
            _TEDLIB()->set_tmpdata( DEBUG_NEW laydata::tdtcellaref(striter, eqm, arrprops) );
            break;
         }
         case console::op_tbind:
         {
            assert ("" != name);
            CTM eqm(trans);
            eqm.Scale(1/(UU()*OPENGL_FONT_UNIT), 1/(UU()*OPENGL_FONT_UNIT));
            _TEDLIB()->set_tmpdata( DEBUG_NEW laydata::tdttext(name, eqm) );
            break;
         }
         case console::op_rotate: _TEDLIB()->set_tmpctm( trans );
         default:
         {
            if (0  < input_type)
               _TEDLIB()->set_tmpdata( DEBUG_NEW laydata::tdtwire(input_type) );
         }
      }
      initcmdlayer();
   }
   else throw EXPTNactive_DB();
}
Example #3
0
static int rdbSaveAllRows(FILE *fp, bt *btr, bt_n *x) {
    for (int i = 0; i < x->n; i++) {
        uchar *stream  = (uchar *)KEYS(btr, x, i);
        int    ssize   = getStreamMallocSize(stream, btr);
        uchar *wstream = UU(btr) ? &stream : stream;
        if (rdbSaveLen(fp, ssize)        == -1) return -1;
        if (fwrite(wstream, ssize, 1, fp) == 0) return -1;
    }

    if (!x->leaf) {
        for (int i = 0; i <= x->n; i++) {
            if (rdbSaveAllRows(fp, btr, NODES(btr, x)[i]) == -1) return -1;
        }
    }
    return 0;
}
Example #4
0
void OrthoBuilder::LUsolve( vector<vector<PL_NUM>>& AA, vector<PL_NUM>& ff, vector<PL_NUM>* xx )
{
	if( AA.size() < 1 )
	{
		cout << "ERROR in LUsolve: AA.size() is less than 1\n";
		return;
	}
	int AAsize = AA.size();

	vector<PL_NUM> storage( AAsize, 0.0 );
	PL_NUM tmpNum = 0;

	int nzRow = 0;
	if( fabs( AA[0][0] ) < ALMOST_ZERO )		//TODO may be I can join this and the next block. I mean the checks on AA[i][j] != 0
	{
		//make AA[0][0] nonzero by changing the order of rows 
		int nzFound = false;
		for( nzRow; nzRow < AAsize; ++nzRow )
		{
			if( fabs( AA[nzRow][0] ) > ALMOST_ZERO )			//CHECK, may be it is better to put != 0 here
			{
				nzFound = true;
				break;
			}
		}
		if( nzFound == false )
		{
			cout << "ERROR in LUsolve: no nonzero elements found\n";
			return;
		}

		for( int col = 0; col < AAsize; ++col )
		{
			storage[col] = AA[nzRow][col];
			AA[nzRow][col] = AA[0][col];
			AA[0][col] = storage[col];
		}
		tmpNum = ff[nzRow];
		ff[nzRow] = ff[0];
		ff[0] = tmpNum;
	}
	for( int i = 0; i < AAsize; ++i )
	{
		if( fabs( AA[i][i] ) < ALMOST_ZERO )				//TODO may be there should be fabs( ) < DELTA?
		{
			for( int row = i + 1; row < AAsize; ++row )
			{
				if( fabs( AA[row][i] ) > ALMOST_ZERO )			//TODO may be there should be fabs( ) > DELTA?
				{
					for( int col = 0; col < AAsize; ++col )
					{
						storage[col] = AA[row][col];			//TODO may be we don't need a whole vector here, just single number. (I mean storage)
						AA[row][col] = AA[i][col];
						AA[i][col] = storage[col];
					}
					tmpNum = ff[row];
					ff[row] = ff[i];
					ff[i] = tmpNum;
					break;
				}
			}
		}
	}

	for( int i = 0; i < AAsize; ++i )
	{
		if( fabs( AA[i][i] ) < ALMOST_ZERO )
		{
			cout << "alert! UFO detected!\n";
		}
	}

	vector<vector<PL_NUM>> LL( AAsize, vector<PL_NUM>( AAsize, 0.0 ) );			//TODO here we can use less memory, UU and LL are trialgular
	vector<vector<PL_NUM>> UU( AAsize, vector<PL_NUM>( AAsize, 0.0 ) );			//TODO initialization of arrays is slow

	//Crout's algorithm, theory is in book: Kincaid, Cheney - Numerical analysis: mathematics of scientific computing
	for( int k = 0; k < AAsize; ++k )
	{
		UU[k][k] = 1;
		for( int i = k; i < AAsize; ++i )
		{
			LL[i][k] = AA[i][k];
			for( int s = 0; s <= k - 1; ++s )
			{
				LL[i][k] -= LL[i][s] * UU[s][k];
			}
		}
		for( int j = k + 1; j < AAsize; ++j )
		{
			UU[k][j] = AA[k][j];
			for( int s = 0; s <= k - 1; ++s )
			{
				UU[k][j] -= LL[k][s] * UU[s][j];
			}
			UU[k][j] /= LL[k][k];
		}
	}

	//now we can find xx, by solving LL * zz = ff and then UU * x = zz; for theory look at the same book as for LU decomposition
	for( int i = 0; i < AAsize; ++i )
	{
		(*xx)[i] = ff[i];
		for( int  j = 0; j <= i - 1; ++j )
		{
			(*xx)[i] -= LL[i][j] * (*xx)[j];
		}
		(*xx)[i] /= LL[i][i];
	}
	for( int i = AAsize - 1; i >= 0; --i )
	{
		for( int  j = i + 1; j < AAsize; ++j )
		{
			(*xx)[i] -= UU[i][j] * (*xx)[j];
		}
	}
}
void
MAST::GCMMAOptimizationInterface::optimize() {
#if MAST_ENABLE_GCMMA == 1

    // make sure that all processes have the same problem setup
    _feval->sanitize_parallel();
    
    int
    N                  = _feval->n_vars(),
    M                  = _feval->n_eq() + _feval->n_ineq(),
    n_rel_change_iters = _feval->n_iters_relative_change();
    
    libmesh_assert_greater(N, 0);
    
    std::vector<Real>  XVAL(N, 0.), XOLD1(N, 0.), XOLD2(N, 0.),
    XMMA(N, 0.), XMIN(N, 0.), XMAX(N, 0.), XLOW(N, 0.), XUPP(N, 0.),
    ALFA(N, 0.), BETA(N, 0.), DF0DX(N, 0.),
    A(M, 0.), B(M, 0.), C(M, 0.), Y(M, 0.), RAA(M, 0.), ULAM(M, 0.),
    FVAL(M, 0.), FAPP(M, 0.), FNEW(M, 0.), FMAX(M, 0.),
    DFDX(M*N, 0.), P(M*N, 0.), Q(M*N, 0.), P0(N, 0.), Q0(N, 0.),
    UU(M, 0.), GRADF(M, 0.), DSRCH(M, 0.), HESSF(M*(M+1)/2, 0.),
    f0_iters(n_rel_change_iters);
    
    std::vector<int> IYFREE(M, 0);
    std::vector<bool> eval_grads(M, false);
    
    Real
    ALBEFA  = 0.1,
    GHINIT  = 0.5,
    GHDECR  = 0.7,
    GHINCR  = 1.2,
    F0VAL   = 0.,
    F0NEW   = 0.,
    F0APP   = 0.,
    RAA0    = 0.,
    Z       = 0.,
    GEPS    =_feval->tolerance();
    
    
    /*C********+*********+*********+*********+*********+*********+*********+
     C
     C  The meaning of some of the scalars and vectors in the program:
     C
     C     N  = Complex of variables x_j in the problem.
     C     M  = Complex of constraints in the problem (not including
     C          the simple upper and lower bounds on the variables).
     C ALBEFA = Relative spacing between asymptote and mode limit. Lower value
     C          will cause the move limit (alpha,beta) to move closer to asymptote
     C          values (l, u).
     C GHINIT = Initial asymptote setting. For the first two iterations the
     C          asymptotes (l, u) are defined based on offsets from the design
     C          point as this fraction of the design variable bounds, ie.
     C              l_j   =   x_j^k  - GHINIT * (x_j^max - x_j^min)
     C              u_j   =   x_j^k  + GHINIT * (x_j^max - x_j^min)
     C GHDECR = Fraction by which the asymptote is reduced for oscillating
     C          changes in design variables based on three consecutive iterations
     C GHINCR = Fraction by which the asymptote is increased for non-oscillating
     C          changes in design variables based on three consecutive iterations
     C INNMAX = Maximal number of inner iterations within each outer iter.
     C          A reasonable choice is INNMAX=10.
     C  ITER  = Current outer iteration number ( =1 the first iteration).
     C  GEPS  = Tolerance parameter for the constraints.
     C          (Used in the termination criteria for the subproblem.)
     C
     C   XVAL(j) = Current value of the variable x_j.
     C  XOLD1(j) = Value of the variable x_j one iteration ago.
     C  XOLD2(j) = Value of the variable x_j two iterations ago.
     C   XMMA(j) = Optimal value of x_j in the MMA subproblem.
     C   XMIN(j) = Original lower bound for the variable x_j.
     C   XMAX(j) = Original upper bound for the variable x_j.
     C   XLOW(j) = Value of the lower asymptot l_j.
     C   XUPP(j) = Value of the upper asymptot u_j.
     C   ALFA(j) = Lower bound for x_j in the MMA subproblem.
     C   BETA(j) = Upper bound for x_j in the MMA subproblem.
     C    F0VAL  = Value of the objective function f_0(x)
     C   FVAL(i) = Value of the i:th constraint function f_i(x).
     C  DF0DX(j) = Derivative of f_0(x) with respect to x_j.
     C   FMAX(i) = Right hand side of the i:th constraint.
     C   DFDX(k) = Derivative of f_i(x) with respect to x_j,
     C             where k = (j-1)*M + i.
     C      P(k) = Coefficient p_ij in the MMA subproblem, where
     C             k = (j-1)*M + i.
     C      Q(k) = Coefficient q_ij in the MMA subproblem, where
     C             k = (j-1)*M + i.
     C     P0(j) = Coefficient p_0j in the MMA subproblem.
     C     Q0(j) = Coefficient q_0j in the MMA subproblem.
     C      B(i) = Right hand side b_i in the MMA subproblem.
     C    F0APP  = Value of the approximating objective function
     C             at the optimal soultion of the MMA subproblem.
     C   FAPP(i) = Value of the approximating i:th constraint function
     C             at the optimal soultion of the MMA subproblem.
     C    RAA0   = Parameter raa_0 in the MMA subproblem.
     C    RAA(i) = Parameter raa_i in the MMA subproblem.
     C      Y(i) = Value of the "artificial" variable y_i.
     C      Z    = Value of the "minimax" variable z.
     C      A(i) = Coefficient a_i for the variable z.
     C      C(i) = Coefficient c_i for the variable y_i.
     C   ULAM(i) = Value of the dual variable lambda_i.
     C  GRADF(i) = Gradient component of the dual objective function.
     C  DSRCH(i) = Search direction component in the dual subproblem.
     C  HESSF(k) = Hessian matrix component of the dual function.
     C IYFREE(i) = 0 for dual variables which are fixed to zero in
     C               the current subspace of the dual subproblem,
     C           = 1 for dual variables which are "free" in
     C               the current subspace of the dual subproblem.
     C
     C********+*********+*********+*********+*********+*********+*********+*/
    
    
    /*
     *  The USER should now give values to the parameters
     *  M, N, GEPS, XVAL (starting point),
     *  XMIN, XMAX, FMAX, A and C.
     */
    // _initi(M,N,GEPS,XVAL,XMIN,XMAX,FMAX,A,C);
    // Assumed:  FMAX == A
    _feval->_init_dvar_wrapper(XVAL, XMIN, XMAX);
    // set the value of C[i] to be very large numbers
    Real max_x = 0.;
    for (unsigned int i=0; i<N; i++)
        if (max_x < fabs(XVAL[i]))
            max_x = fabs(XVAL[i]);
    std::fill(C.begin(), C.end(), std::max(1.e0*max_x, _constr_penalty));
    
    int INNMAX=_max_inner_iters, ITER=0, ITE=0, INNER=0, ICONSE=0;
    /*
     *  The outer iterative process starts.
     */
    bool terminate = false, inner_terminate=false;
    while (!terminate) {
        
        ITER=ITER+1;
        ITE=ITE+1;
        /*
         *  The USER should now calculate function values and gradients
         *  at XVAL. The result should be put in F0VAL,DF0DX,FVAL,DFDX.
         */
        std::fill(eval_grads.begin(), eval_grads.end(), true);
        _feval->_evaluate_wrapper(XVAL,
                                  F0VAL, true, DF0DX,
                                  FVAL, eval_grads, DFDX);
        if (ITER == 1)
            // output the very first iteration
            _feval->_output_wrapper(0, XVAL, F0VAL, FVAL, true);
        
        /*
         *  RAA0,RAA,XLOW,XUPP,ALFA and BETA are calculated.
         */
        raasta_(&M, &N, &RAA0, &RAA[0], &XMIN[0], &XMAX[0], &DF0DX[0], &DFDX[0]);
        asympg_(&ITER, &M, &N, &ALBEFA, &GHINIT, &GHDECR, &GHINCR,
                &XVAL[0], &XMIN[0], &XMAX[0], &XOLD1[0], &XOLD2[0],
                &XLOW[0], &XUPP[0], &ALFA[0], &BETA[0]);
        /*
         *  The inner iterative process starts.
         */
        
        // write the asymptote data for the inneriterations
        _output_iteration_data(ITER, XVAL, XMIN, XMAX, XLOW, XUPP, ALFA, BETA);

        INNER=0;
        inner_terminate = false;
        while (!inner_terminate) {
            
            /*
             *  The subproblem is generated and solved.
             */
            mmasug_(&ITER, &M, &N, &GEPS, &IYFREE[0], &XVAL[0], &XMMA[0],
                    &XMIN[0], &XMAX[0], &XLOW[0], &XUPP[0], &ALFA[0], &BETA[0],
                    &A[0], &B[0], &C[0], &Y[0], &Z, &RAA0, &RAA[0], &ULAM[0],
                    &F0VAL, &FVAL[0], &F0APP, &FAPP[0], &FMAX[0], &DF0DX[0], &DFDX[0],
                    &P[0], &Q[0], &P0[0], &Q0[0], &UU[0], &GRADF[0], &DSRCH[0], &HESSF[0]);
            /*
             *  The USER should now calculate function values at XMMA.
             *  The result should be put in F0NEW and FNEW.
             */
            std::fill(eval_grads.begin(), eval_grads.end(), false);
            _feval->_evaluate_wrapper(XMMA,
                                      F0NEW, false, DF0DX,
                                      FNEW, eval_grads, DFDX);
            
            if (INNER >= INNMAX) {
                libMesh::out
                << "** Max Inner Iter Reached: Terminating! Inner Iter = "
                << INNER << std::endl;
                inner_terminate = true;
            }
            else {
                /*
                 *  It is checked if the approximations were conservative.
                 */
                conser_( &M, &ICONSE, &GEPS, &F0NEW, &F0APP, &FNEW[0], &FAPP[0]);
                if (ICONSE == 1) {
                    libMesh::out
                    << "** Conservative Solution: Terminating! Inner Iter = "
                    << INNER << std::endl;
                    inner_terminate = true;
                }
                else {
                    /*
                     *  The approximations were not conservative, so RAA0 and RAA
                     *  are updated and one more inner iteration is started.
                     */
                    INNER=INNER+1;
                    raaupd_( &M, &N, &GEPS, &XMMA[0], &XVAL[0],
                            &XMIN[0], &XMAX[0], &XLOW[0], &XUPP[0],
                            &F0NEW, &FNEW[0], &F0APP, &FAPP[0], &RAA0, &RAA[0]);
                }
            }
        }
        
        /*
         *  The inner iterative process has terminated, which means
         *  that an outer iteration has been completed.
         *  The variables are updated so that XVAL stands for the new
         *  outer iteration point. The fuction values are also updated.
         */
        xupdat_( &N, &ITER, &XMMA[0], &XVAL[0], &XOLD1[0], &XOLD2[0]);
        fupdat_( &M, &F0NEW, &FNEW[0], &F0VAL, &FVAL[0]);
        /*
         *  The USER may now write the current solution.
         */
        _feval->_output_wrapper(ITER, XVAL, F0VAL, FVAL, true);
        f0_iters[(ITE-1)%n_rel_change_iters] = F0VAL;
        
        /*
         *  One more outer iteration is started as long as
         *  ITE is less than MAXITE:
         */
        if (ITE == _feval->max_iters()) {
            libMesh::out
            << "GCMMA: Reached maximum iterations, terminating! "
            << std::endl;
            terminate = true;
        }
        
        // relative change in objective
        bool rel_change_conv = true;
        Real f0_curr = f0_iters[n_rel_change_iters-1];
        
        for (unsigned int i=0; i<n_rel_change_iters-1; i++) {
            if (f0_curr > sqrt(GEPS))
                rel_change_conv = (rel_change_conv &&
                                   fabs(f0_iters[i]-f0_curr)/fabs(f0_curr) < GEPS);
            else
                rel_change_conv = (rel_change_conv &&
                                   fabs(f0_iters[i]-f0_curr) < GEPS);
        }
        if (rel_change_conv) {
            libMesh::out
            << "GCMMA: Converged relative change tolerance, terminating! "
            << std::endl;
            terminate = true;
        }
        
    }
    
#endif //MAST_ENABLE_GCMMA == 1
}
/*
* ==================================================================== 
* Make a (pseudo)inverse of a dense matrix using CLAPACK SVD.
*
* Note the different definitions of a matrix here (double **) and 
* in other routines (double *).
*
* The matrix A must be of size at least [max(rows,cols)][max(rows,cols)] 
* since the pseudoinverse (and not its transpose) is returned in A.
*
* Singular value decomposition is used to calculate the psuedo-inverse.
* If #rows=#cols then (an approximation of) the inverse is found. 
* Otherwise an approximation of the pseudoinverse is obtained.
*
* The return value of this routine is the estimated rank of the system.
* ==================================================================== */ 
int pinv(double **A, int rows, int cols) 
{
  char fctName[] = "pinv_new";
  int i,j,k;
  int nsv, rank;
  double tol;
  /* Variables needed for interaction with CLAPACK routines 
   * (FORTRAN style)                                                   */
  double *amat, *svals, *U,  *V, *work;
  long int lda,        ldu, ldvt, lwork, m,n,info;

  /* Short-hands for this routine only [undef'ed at end of routine]    */
#define AA(i,j)  amat[i + j * (int) lda]
#define UU(i,j)  U[i + j * (int) ldu]
#define VV(i,j)  V[i + j * (int) ldvt]

  /* Set up arrays for call to CLAPACK routine                         */
  /* Use leading dimensions large enough to calculate both under- 
   * and over-determined systems of equations. The way this is 
   * calculated, we need to store U*(Z^-1^T) in U. The array U must 
   * have at least cols columns to perform this operation, and at 
   * least rows columns to store the initial U. However, for an under-
   * determined system the last cols-rows columns of U*(Z^-1^T) will be 
   * zero. Exploiting this, the size of the array U is just mxm        */
  m = (long int) rows;
  n = (long int) cols;
  lda  = m;
  ldu  = m;
  ldvt = n;

  nsv = MIN(rows,cols);
  /* Allocate memory for:
   * amat  : The matrix to factor
   * svals : Vector of singular values 
   * U     : mxm unitary matrix
   * V     : nxn unitary matrix                                        */
  amat  = (double *) calloc((int) m*n+1, sizeof(double)); 
  svals = (double *) calloc((int) m+n,   sizeof(double)); 
  U     = (double *) calloc((int) ldu*m+1,sizeof(double));
  V     = (double *) calloc((int) ldvt*n+1, sizeof(double));
  /* In matrix form amat = U * diag(svals) * V^T                       */
  /* Leading dimensions [number of rows] of the above arrays           */
  /* Work storage */
  lwork = 100*(m+n);
  work  = (double *) calloc(lwork, sizeof(double));

  /* Copy A to temporary storage                                       */
  for (j=0; j<cols; j++) {
    for (i=0; i<rows; i++) {
      AA(i,j) = A[i][j];
    }
  }

  {
    char jobu,jobvt;
    jobu  = 'A'; /* Calculate all columns of matrix U                  */
    jobvt = 'A'; /* Calculate all columns of matrix V^T                */

    /* Note that dgesvd_ returns V^T rather than V                     */
    dgesvd_(&jobu, &jobvt, &m, &n, 
	    amat, &lda, svals, U, &ldu, V, &ldvt, 
	    work, &lwork, &info);

    /* Test info from dgesvd */
    if (info) {
      if (info<0) {
	printf("%s: ERROR: clapack routine 'dgesvd_' complained about\n"
	       "    illegal value of argument # %d\n",fctName,(int) -info);
	_EXIT_;
      }
      else{
	printf("%s: ERROR: clapack routine 'dgesvd_' complained that\n"
	       "    %d superdiagonals didn't converge.\n",
	       fctName,(int) info);
	_EXIT_;
      }
    }
  }

  /* Test the the singular values are returned in correct ordering 
   * (This is done because there were problems with this with a former 
   * implementation [using f2c'ed linpack] when high optimization 
   * was used)                                                         */
  if (svals[0]<0.0) {
    printf("%s: ERROR: First singular value returned by clapack \n"
	   "   is negative: %16.6e.\n",fctName,svals[0]);
    _EXIT_;
  }
  for (i=1; i<nsv; i++){
    if ( svals[i] > svals[i-1] ) {
      printf("%s: ERROR: Singular values returned by clapack \n"
	     "  are not approprately ordered!\n"
	     "  svals[%d] = %16.6e > svals[%d] = %16.6e",
	     fctName,i,svals[i],i-1,svals[i-1]);
      _EXIT_;
    }
  }

  /* Test rank of matrix by examining the singular values.             */
  /* The singular values of the matrix is sorted in decending order, 
   * so that svals[i] >= svals[i+1]. The first that is zero (to some 
   * precision) yields information on the rank (to some precision)     */
  rank = nsv;
  tol  = DBL_EPSILON * svals[0] * MAX(rows,cols); 
  for (i=0; i<nsv; i++){
    if ( svals[i] <= tol ){
      rank = i;
      break;
    }
  }

  /* Compute (pseudo-) inverse matrix using the computed SVD:
   *   A   = U*S*V'
   *   A^+ = V * (Zi) U'
   *       = V * (U * (Zi)')'
   *       = { (U * Zi') * V' }'
   * Here Zi is the "inverse" of the diagonal matrix S, i.e. Zi is 
   * diagonal and has the same size as S'. The non-zero entries in 
   * Zi is calculated from the non-zero entries in S as Zi_ii=1/S_ii
   * Note that Zi' is of the same size as S.        
   * The last line here is used in the present computation. This 
   * notation avoids any need to transpose the output from the CLAPACK
   * rotines (which deliver U, S and V).                               */

  /* Inverse of [non-zero part of] diagonal matrix                     */
  tol = 1.0e-10 * svals[0]; 
  for (i=0; i< nsv; i++) {
    if (svals[i] < tol)
      svals[i] = 0.0; 
    else 
      svals[i] = 1.0 / svals[i]; 
  }

  /* Calculate  UZ = U * Zi', ie. scale COLUMN j in U by 
   * the j'th singular value [nsv columns only - since the diagonal 
   * matrix in general is not square]. If rows>cols then the last 
   * columns in UZ wil be zero (no need to compute).                   */
  for (j=0; j<nsv; j++){
    for (i=0; i<rows; i++){
      UU(i,j) *= svals[j];
    }
  }
  /* U*Zi' is stored in array U. It has size (rows x nsv). 
   * If cols>rows, then it should be though of as the larger matrix 
   * (rows x cols) with zero columns added on the right.               */

  /* Zero out the full array A to avoid confusion upon return.
   * This is not abosolutely necessary, zeroin out A[j][i] could be
   * part of the next loop.                                            */
  for (i=0; i< MAX(cols,rows); i++) {
    for (j=0; j< MAX(cols,rows); j++) {
      A[i][j] = 0.0;
    }
  }

  /* Matrix-matrix multiply  (U*Zi') * V'. 
   * Only the first nsv columns in U*Zi' are non-zero, so the inner 
   * most loop will go to k=nsv (-1). 
   * The result will be the transpose of the (psuedo-) inverse of A, 
   * so store directly in A'=A[j][i]. 
   *  A[j][i] = sum_k (U*Zi)[i][k] * V'[k][j] :                        */
  for (i=0; i< rows; i++) {
    for (j=0; j< cols; j++) {
      /*A[j][i] = 0.0; */ /* Include if A is not zeroed out above      */
      for (k=0;k<nsv;k++){
	A[j][i] += UU(i,k)*VV(k,j);
      }
    }
  }

  /* Free memory allocated in this routine */
  FREE(amat);
  FREE(svals);
  FREE(U);
  FREE(V);
  FREE(work);

  return rank;

  /* Undefine macros for this routine */
#undef AA
#undef UU
#undef VV
} /* End of routine pinv */
Example #7
0
VPRIVATE double Ut(int d, int m, double *x, double t) {
    return FACt(d,m,x,t) * UU(d,m,x,t) + FAC(d,m,x,t) * UUt(d,m,x,t);
}
Example #8
0
VPRIVATE double Uxx2(int d, int m, double *x, double t) {
    if (d==2) return 0.;
    else return FACxx2(d,m,x,t) * UU(d,m,x,t)
              + 2. * FACx2(d,m,x,t) * UUx2(d,m,x,t)
              + FAC(d,m,x,t) * UUxx2(d,m,x,t);
}
Example #9
0
VPRIVATE double Uxx1(int d, int m, double *x, double t) {
    return FACxx1(d,m,x,t) * UU(d,m,x,t)
         + 2. * FACx1(d,m,x,t) * UUx1(d,m,x,t)
         + FAC(d,m,x,t) * UUxx1(d,m,x,t);
}
Example #10
0
/* ///////////////////////////////////////////////////////////////////////////
// Routine:  my_US
//
// Purpose:  The true solution of the problem
//
// Author:   Stephen Bond, after Michael Holst
/////////////////////////////////////////////////////////////////////////// */
VPRIVATE double my_US(int d, int m, double *x, double t) {
    return FAC(d,m,x,t) * UU(d,m,x,t);
}
Example #11
0
VPRIVATE double UUxx2(int d, int m, double *x, double t) {

    return -VPI*VPI*UU(d,m,x,t);

}