void Ampl_Eval_Jac(ASL_pfgh *asl_, double *varsX, double *AmplJacElts)
{
  ASL_pfgh *asl = asl_;

  fint nerror = -1;

  if(varsX){
	jacval(varsX, AmplJacElts, &nerror);
  }else{
    double *dxWrk = (double*) malloc (n_var*sizeof(double));
  	jacval(varsX, AmplJacElts, &nerror);	
    free(dxWrk);
  }
}
예제 #2
0
파일: fg_nl.c 프로젝트: Pyomo/pyomo
PetscErrorCode FormJacobian(SNES snes,Vec x,Mat jac,Mat B,void *ctx){
  Solver_ctx        *sol_ctx = (Solver_ctx*)ctx;
  ASL               *asl=(ASL*)(sol_ctx->asl);
  const PetscScalar *xx;     /* Variable vector*/
  PetscScalar       A[nzc];  /* Temporary storage for Jacobian Calc. */
  PetscErrorCode    ierr;    /* PETSc Error code */
  int               err;     /* ASL Error code */
  unsigned long int i;       /* Constraint index */
  cgrad             *cg;     /* Constraint gradient information */

  /* Compute Jacobian entries and insert into matrix. */
  ierr = VecGetArrayRead(x,&xx);CHKERRQ(ierr);
  jacval((real*)xx,(real*)A,&err);
  ierr = VecRestoreArrayRead(x,&xx);CHKERRQ(ierr);

  for(i=n_conjac[0];i<n_conjac[1]; ++i){ /*i is constraint index */
    cg = Cgrad[i];
    while(cg!=NULL){
      MatSetValue(B, i, cg->varno, A[cg->goff],INSERT_VALUES);
      cg=cg->next;
    }
  }
  /* Assemble matrix */
  ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
  ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
  return 0;
}
예제 #3
0
파일: nl21.c 프로젝트: BRAINSia/calatk
 static void
calcj(fint *N, fint *P, real *X, fint *NF, real *J,
	fint *UI, real *UR, U_fp *uf)
{
	fint nerror = 0;

	jacval(X, J, &nerror);
	if (nerror)
		*NF = 0;
	}
void
ampl_get_Jac(double *varsX, const int nzA, double *JacAelts, const int nzC, double *JacCelts)
{
  int i;
  fint nerror = -1;
  double *tempJac = (double*) malloc(nzc*sizeof(double)); 

  if(varsX){
	jacval(varsX, tempJac, &nerror);
  }else{
    double *dxWrk = (double*) malloc (n_var*sizeof(double));
  	jacval(varsX, tempJac, &nerror);	
    free(dxWrk);
  }

 doubleLexSort_ValOnly(nzA,JacAelts,nzC,JacCelts,tempJac);

 free(tempJac);

}
예제 #5
0
  bool AmplTNLP::eval_jac_g(Index n, const Number* x, bool new_x,
                            Index m, Index nele_jac, Index* iRow,
                            Index *jCol, Number* values)
  {
    DBG_START_METH("AmplTNLP::eval_jac_g",
                   dbg_verbosity);
    ASL_pfgh* asl = asl_;
    DBG_ASSERT(asl_);
    DBG_ASSERT(n == n_var);
    DBG_ASSERT(m == n_con);

    if (iRow && jCol && !values) {
      // setup the structure
      Index current_nz = 0;
      for (Index i=0; i<n_con; i++) {
        for (cgrad* cg=Cgrad[i]; cg; cg = cg->next) {
          iRow[cg->goff] = i + 1;
          jCol[cg->goff] = cg->varno + 1;
          //    iRow[current_nz] = i + 1;
          //    jCol[current_nz] = cg->varno+1;
          current_nz++;
        }
      }
      DBG_ASSERT(current_nz == nele_jac);
      return true;
    }
    else if (!iRow && !jCol && values) {
      if (!apply_new_x(new_x, n, x)) {
        return false;
      }

      jacval(const_cast<Number*>(x), values, (fint*)nerror_);
      if (nerror_ok(nerror_)) {
        return true;
      }
    }
    else {
      DBG_ASSERT(false && "Invalid combination of iRow, jCol, and values pointers");
    }

    return false;
  }
예제 #6
0
static bool eval_jac_g(void * amplInfo, int  n, const double * x, bool new_x,
                       double * values)
{
    CbcAmplInfo * info = (CbcAmplInfo *) amplInfo;
    ASL_pfgh* asl = info->asl_;
    assert(n == n_var);

    assert (values);
    if (!apply_new_x(info, new_x, n, x)) {
        return false;
    }

    jacval(info->non_const_x_, values, (fint*)&info->nerror_);
    if (!info->nerror_) {
        return true;
    } else {
        abort();
    }
    return false;
}
예제 #7
0
파일: spamfunc.c 프로젝트: ampl/mp
 void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	ASL_pfgh *asl = (ASL_pfgh*)cur_ASL;
	FILE *nl;
	Jmp_buf err_jmp0;
	cgrad *cg, **cgp;
	char *buf1, buf[512], *what, **whatp;
	fint *hcs, *hr, i, nerror;
	int *cs;
	mwIndex *Ir, *Jc;
	real *H, *He, *J1, *W, *c, *f, *g, *v, *t, *x;
	static fint n, nc, nhnz, nz;
	static real *Hsp;
	static char ignore_complementarity[] =
		"Warning: ignoring %d complementarity conditions.\n";

	if (nrhs == 1 && mxIsChar(prhs[0])) {
		if (nlhs < 6 || nlhs > 7)
			usage();
		if (mxGetString(prhs[0], buf1 = buf, sizeof(buf)))
			mexErrMsgTxt("Expected 'stub' as argument\n");
		at_end();
		mexAtExit(at_end);
		asl = (ASL_pfgh*)ASL_alloc(ASL_read_pfgh);
		return_nofile = 1;
		if (!(nl = jac0dim(buf1,strlen(buf)))) {
			sprintf(msgbuf, "Can't open %.*s\n",
				sizeof(msgbuf)-20, buf);
			mexErrMsgTxt(msgbuf);
			}
		if (n_obj <= 0)
			printf("Warning: objectve == 0\n");
		n = n_var;
		nc = n_con;
		nz = nzc;
		X0 = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL));
		LUv = mxGetPr(plhs[1] = mxCreateDoubleMatrix(n, 1, mxREAL));
		Uvx = mxGetPr(plhs[2] = mxCreateDoubleMatrix(n, 1, mxREAL));
		pi0 = mxGetPr(plhs[3] = mxCreateDoubleMatrix(nc, 1, mxREAL));
		LUrhs = mxGetPr(plhs[4] = mxCreateDoubleMatrix(nc, 1, mxREAL));
		Urhsx = mxGetPr(plhs[5] = mxCreateDoubleMatrix(nc, 1, mxREAL));
		if (nlhs == 7) {
			cvar = (int*)M1alloc(nc*sizeof(int));
			plhs[6] = mxCreateDoubleMatrix(nc, 1, mxREAL);
			x = mxGetPr(plhs[6]);
			}
		else if (n_cc)
			printf(ignore_complementarity, n_cc);
		pfgh_read(nl, ASL_findgroups);
		if (nlhs == 7)
			for(i = 0; i < nc; i++)
				x[i] = cvar[i];

		/* Arrange to compute the whole sparese Hessian */
		/* of the Lagrangian function (both triangles). */

		nhnz = sphsetup(0, 0, nc > 0, 0);
		Hsp = (real *)M1alloc(nhnz*sizeof(real));
		return;
		}

	if (!asl)
		mexErrMsgTxt("spamfunc(\"stub\") has not been called\n");
	nerror = -1;
	err_jmp1 = &err_jmp0;
	what = "(?)";
	whatp = &what;
	if (nlhs == 2) {
		if (nrhs != 2)
			usage();
		x = sizechk(prhs[0],"x",n);
		t = sizechk(prhs[1],"0 or 1", 1);
		if (setjmp(err_jmp0.jb)) {
			sprintf(msgbuf, "Trouble evaluating %s\n", *whatp);
			mexErrMsgTxt(msgbuf);
			}
		if (t[0] == 0.) {
			f = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL));
			c = mxGetPr(plhs[1] = mxCreateDoubleMatrix(nc, 1, mxREAL));
			what = "f";
			*f = n_obj > 0 ? objval(0, x, &nerror) : 0;
			what = "c";
			conval(x, c, &nerror);
			return;
			}
		g = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL));
		J1 = mxGetPr(plhs[1] = mxCreateSparse(nc, n, nz, mxREAL));
		what = "g";
		if (n_obj > 0)
			objgrd(0, x, g, &nerror);
		else
			memset(g, 0, n*sizeof(real));
		if (nc) {
			what = "J";
			jacval(x, J1, &nerror);
			Ir = mxGetIr(plhs[1]);
			/*memcpy(mxGetJc(plhs[1]), A_colstarts, (n+1)*sizeof(int));*/
			for(Jc = mxGetJc(plhs[1]), cs = A_colstarts, i = 0; i <= n; ++i)
				Jc[i] = cs[i];
			cgp = Cgrad;
			for(i = 0; i < nc; i++)
				for(cg = *cgp++; cg; cg = cg->next)
					Ir[cg->goff] = i;
			}
		return;
		}
	if (nlhs == 0 && (nrhs == 3 || nrhs == 4)) {
		/* eval2('solution message', x, v): x = primal, v = dual */
		/* optional 4th arg = solve_result_num */
		if (!mxIsChar(prhs[0]))
			usage();
		x = sizechk(prhs[1],"x",n);
		v = sizechk(prhs[2],"v",nc);
		if (mxGetString(prhs[0], buf, sizeof(buf)))
			mexErrMsgTxt(
			 "Expected 'solution message' as first argument\n");
		solve_result_num = nrhs == 3 ? -1 /* unknown */
			: (int)*sizechk(prhs[3],"solve_result_num",1);
		write_sol(buf, x, v, 0);
		return;
		}
	if (nlhs != 1 || nrhs != 1)
		usage();
	v = sizechk(prhs[0],"v",nc);
	W = mxGetPr(plhs[0] = mxCreateSparse(n, n, nhnz, mxREAL));

	what = "W";
	sphes(H = Hsp, 0, 0, v);

	/* Expand the Hessian lower triangle into the full Hessian... */

	Ir = mxGetIr(plhs[0]);
	Jc = mxGetJc(plhs[0]);
	hcs = sputinfo->hcolstarts;
	hr = sputinfo->hrownos;
	for(i = 0; i <= n; i++)
		Jc[i] = hcs[i];
	He = H + hcs[n];
	while(H < He) {
		*W++ = *H++;
		*Ir++ = *hr++;
		}
	}
예제 #8
0
파일: main.c 프로젝트: IainNZ/NLTester
int main(int argc, char **argv)
{
	FILE *nl;
	char *stub;
	ASL *asl;
	fint nerror = 0;
	real *X;
	real objVal;
	int i, j, k, je;
	real* J;
	cgrad *cg;
	char *fmt;

	if (argc < 2) {
		printf("Usage: %s stub\n", argv[0]);
		return 1;
	}
	
	double t0 = clock_now();
	asl = ASL_alloc(ASL_read_fg);
	stub = argv[1];
	nl = jac0dim(stub, (fint)strlen(stub));
	fg_read(nl,0);
	
	J = (real *)Malloc(nzc*sizeof(real));
	X = (real *)Malloc(n_var*sizeof(real));
	for (i = 0; i < n_var; i++) X[i] = 1.0;

	// include one jacobian call for consistency
	jacval(X, J, &nerror);

	t0 = clock_now() - t0;
	
	//objVal = objval(0, X, &nerror);
	//printf("Objective %.5f\n", objVal);
	
	double jactime = 1e30;
	for (k = 0; k < 10; k++) {
		double t1 = clock_now();
		jacval(X, J, &nerror);
		t1 = clock_now() - t1;
		jactime = (t1 < jactime) ? t1 : jactime;
	}

	double norm = 0;
	for (i = 0; i < nzc; i++) {
		norm += J[i]*J[i];
	}
	norm = sqrt(norm);


	char *bname = basename(argv[1]);
	// Initialization time, 1 jacobian evaluation
	printf("### %s %f %g\n",bname,t0,jactime);
	printf("## %s Jacobian norm: %.10g (nnz = %d)\n",bname,norm,nzc);


	
	/*printf("nzc %d\n",nzc);
	for(i = 0; i < nzc; i++) {
		printf("%d %g\n",i,J[i]);
	}*/
	/*
	for(i = 0; i < n_con; i++) {
		printf("\nRow %d:", i+1);
		//fmt = " J[%d]=%g*X%d";
		//for(cg = Cgrad[i]; cg; cg = cg->next, fmt = " + J[%d]=%g*X%d") {
		//	printf(fmt, cg->goff, J[cg->goff], cg->varno+1);
		//}
		fmt = " %g*X%d";
		for(cg = Cgrad[i]; cg; cg = cg->next, fmt = " + %g*X%d") {
			printf(fmt, J[cg->goff], cg->varno+1);
		}
		printf("\n");
	}*/

	return 0;
}
예제 #9
0
파일: spamfun4.c 프로젝트: BRAINSia/calatk
 void
mexFunction(int nlhs, Matrix **plhs, int nrhs, Matrix **prhs)
{
	FILE *nl;
	char *buf1, buf[512], *what;
	static fint n, nc, nz;
	fint nerror;
	real *J1, *W, *c, *f, *g, *v, *t, *x;
	static real *J;
	cgrad *cg, **cgp;
	static size_t Jsize;
	Jmp_buf err_jmp0;
	ASL_pfgh *asl = (ASL_pfgh*)cur_ASL;
	static fint nhnz;
	static real *Hsp;
	real *H, *He;
	int *Ir, *Jc;
	fint *hcs, *hr, i;

	if (nrhs == 1 && mxIsString(prhs[0])) {
		if (nlhs != 6)
			usage();
		if (mxGetString(prhs[0], buf1 = buf, sizeof(buf)))
			mexErrMsgTxt("Expected 'stub' as argument\n");
		at_end();
		mexAtExit(at_end);
		asl = (ASL_pfgh*)ASL_alloc(ASL_read_pfgh);
		return_nofile = 1;
		if (!(nl = jac0dim(buf1,strlen(buf)))) {
			sprintf(msgbuf, "Can't open %.*s\n",
				sizeof(msgbuf)-20, buf);
			mexErrMsgTxt(msgbuf);
			}
		if (n_obj <= 0)
			printf("Warning: objectve == 0\n");
		n = n_var;
		nc = n_con;
		nz = nzc;
		J = (real *)M1alloc(nz*sizeof(real));
		X0 = mxGetPr(plhs[0] = mxCreateFull(n, 1, REAL));
		LUv = mxGetPr(plhs[1] = mxCreateFull(n, 1, REAL));
		Uvx = mxGetPr(plhs[2] = mxCreateFull(n, 1, REAL));
		pi0 = mxGetPr(plhs[3] = mxCreateFull(nc, 1, REAL));
		LUrhs = mxGetPr(plhs[4] = mxCreateFull(nc, 1, REAL));
		Urhsx = mxGetPr(plhs[5] = mxCreateFull(nc, 1, REAL));
		pfgh_read(nl, ASL_findgroups);
		Jsize = nc*n*sizeof(real);

		/* Arrange to compute the whole sparese Hessian */
		/* of the Lagrangian function (both triangles). */

		nhnz = sphsetup(0, 0, nc > 0, 0);
		Hsp = (real *)M1alloc(nhnz*sizeof(real));
		return;
		}

	if (!filename)
		mexErrMsgTxt("spamfunc(\"stub\") has not been called\n");
	nerror = -1;
	err_jmp1 = &err_jmp0;
	if (nlhs == 2) {
		if (nrhs != 2)
			usage();
		x = sizechk(prhs[0],"x",n);
		t = sizechk(prhs[1],"0 or 1", 1);
		if (t[0] == 0.) {
			f = mxGetPr(plhs[0] = mxCreateFull(1, 1, REAL));
			c = mxGetPr(plhs[1] = mxCreateFull(nc, 1, REAL));
			if (setjmp(err_jmp0.jb)) {
				sprintf(msgbuf, "Trouble evaluating %s\n",
					what);
				mexErrMsgTxt(msgbuf);
				}
			what = "f";
			*f = objval(0, x, &nerror);
			what = "c";
			conval(x, c, &nerror);
			return;
			}
		g = mxGetPr(plhs[0] = mxCreateFull(n, 1, REAL));
		J1 = mxGetPr(plhs[1] = mxCreateSparse(nc, n, nz, REAL));
		what = "g";
		objgrd(0, x, g, &nerror);
		if (nc) {
			what = "J";
			jacval(x, J1, &nerror);
			Ir = mxGetIr(plhs[1]);
			memcpy(mxGetJc(plhs[1]), A_colstarts, (n+1)*sizeof(int));
			cgp = Cgrad;
			for(i = 0; i < nc; i++)
				for(cg = *cgp++; cg; cg = cg->next)
					Ir[cg->goff] = i;
			}
		return;
		}
	if (nlhs == 0 && nrhs == 3) {
		/* eval2('solution message', x, v): x = primal, v = dual */
		if (!mxIsString(prhs[0]))
			usage();
		x = sizechk(prhs[1],"x",n);
		v = sizechk(prhs[2],"v",nc);
		if (mxGetString(prhs[0], buf, sizeof(buf)))
			mexErrMsgTxt(
			 "Expected 'solution message' as first argument\n");
		write_sol(buf, x, v, 0);
		return;
		}
	if (nlhs != 1 || nrhs != 1)
		usage();
	v = sizechk(prhs[0],"v",nc);
	W = mxGetPr(plhs[0] = mxCreateSparse(n, n, nhnz, REAL));

	what = "W";
	sphes(H = Hsp, 0, 0, v);

	/* Expand the Hessian lower triangle into the full Hessian... */

	Ir = mxGetIr(plhs[0]);
	Jc = mxGetJc(plhs[0]);
	hcs = sputinfo->hcolstarts;
	hr = sputinfo->hrownos;
	for(i = 0; i <= n; i++)
		Jc[i] = hcs[i];
	He = H + hcs[n];
	while(H < He) {
		*W++ = *H++;
		*Ir++ = *hr++;
		}
	}
예제 #10
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    //Possible Inputs
    char fpath[FLEN];
    char msg[FLEN];
    char cmd[FLEN]; //user commmand 
    int sp = 0;
    
    //Outputs
    const char *fnames[15] = {"H","f","lb","ub","A","cl","cu","Q","l","qcind","x0","v0","sense","objbias","conlin"};
    double *sizes;
    
    //Internal Vars
    int ii; size_t i,j,k;       //indexing vars
    char *what, **whatp;        //error message vars
    static FILE *nl;            //file handle
    ASL *asl = cur_ASL;         //Current ASL instance
    int icmd = ASLCMD_ERROR;    //Command Integer
    double *sense;              //Objective sense
    double *objbias;            //Objective bias
    int obj_lin;                //linearity of the objectiuve (see ASL_DEGREE_ defines)
    double *con_lin;            //linearity of the constraints (see ASL_DEGREE_ defines)  
    double *isopen;             //Is ASL open
    bool nlcon = false;         //indicates whether any constraint is nonlinear
    double *x;                  //Evaluation point
    double *f, *g, *c = NULL;   //Return pointers
    int nerror;                 //eval errors

    //Sparse Indexing
    mwIndex *Ir, *Jc;
    double *Pr;

    //QP Checking Vars
    int nqpz = 0;               //number of nzs in quadratic objective
    int nqc_con = 0;            //number of quadratic constraints
    int *QP_ir, *QP_jc;         //Pointers used when calling nqpcheck
    double *QP_pr;
    double *pqi;                //pointer to quadratic index vector
    ograd *og;                  //objective gradient structure
            
    //Jacobian Vars
    static double *J = NULL;        //Memory to store intermediate Jacobian Values when using Dense Mode
    static double *J1 = NULL;       //Memory to store Jacobian Values 
    cgrad *cg, **cgp, **cgpe;       //constraint gradient structures
    int *cs;                        //Column starts
    
    //Hessian Vars
    static double *Hsp = NULL;      //Memory to store Hessian Values
    static int nhnz;                //Number of Hessian nz
    double *s, *v;                  //Sigma, Lambda
	int *hcs, *hr;                  //Hessian column starts, row indexs
	double *H, *He,  *W;    	      
    
    //Error catching
    Jmp_buf err_jmp0;
    
    //If no inputs, just return info
    if(nrhs < 1) 
    {
        if (nlhs >= 1)
        {
            sprintf(msgbuf,"%s %s",__TIME__,__DATE__);
            plhs[0] = mxCreateString(msgbuf);
            plhs[1] = mxCreateDoubleScalar(OPTI_VER);
        }
        else
        {
            printUtilityInfo();
        }
        return;
    }
        
    //Get User Command
    icmd = getCommand(prhs[0]);
    
    //Switch Yard for Command
    switch(icmd)
    {
        case ASLCMD_ISOPEN:
            isopen = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL));
            if(asl)
                *isopen = 1;
            else
                *isopen = 0;
            break;
        
        case ASLCMD_OPEN:
            //Check for Errors
            if(nrhs < 2)
                mexErrMsgTxt("Expected two arguments to open a file! [x0,v0,lb,ub,cl,cu,sense,sizes] = asl('open','file path')\n");
            if(!mxIsChar(prhs[1]))
                mexErrMsgTxt("File path must be a char array!");
            //Get String
            CHECK(mxGetString(prhs[1], fpath, FLEN) == 0,"error reading file path!");
            //Clear any existing objects
            if (cur_ASL)
                ASL_free(&cur_ASL);
            //Set MEX exit function
            mexAtExit(mexExit);
            
            //Open file for LP/QP/QCQP checking
            asl = ASL_alloc(ASL_read_fg);               //allocate for qp read
            return_nofile = 1;                          //return 0 if stub doesn't exist
            nl = jac0dim(fpath,(ftnlen)strlen(fpath));  //read in passed file
            //Check we got the file
            if(!nl) {
                sprintf(msgbuf, "Can't open (or error opening) %s\n", fpath);
                mexErrMsgTxt(msgbuf);
			}
            //Allocate Vector Memory
            pPROB = mxCreateStructMatrix(1,1,15,fnames);
            mxSetField(pPROB,0,fnames[eX0],mxCreateDoubleMatrix(n_var,1, mxREAL));      
            mxSetField(pPROB,0,fnames[eV0],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eLB],mxCreateDoubleMatrix(n_var, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eUB],mxCreateDoubleMatrix(n_var, 1, mxREAL));            
            mxSetField(pPROB,0,fnames[eCL],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eCU],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eSENSE],mxCreateDoubleMatrix(1, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eOBJBIAS],mxCreateDoubleMatrix(1, 1, mxREAL));
            mxSetField(pPROB,0,fnames[eCONLIN],mxCreateDoubleMatrix(n_con, 1, mxREAL));
            //Get Fields (ASL will fill)       
            X0 = mxGetPr(mxGetField(pPROB,0,fnames[eX0]));   
            pi0 = mxGetPr(mxGetField(pPROB,0,fnames[eV0]));  
            LUv = mxGetPr(mxGetField(pPROB,0,fnames[eLB]));  
            Uvx = mxGetPr(mxGetField(pPROB,0,fnames[eUB]));              
            LUrhs = mxGetPr(mxGetField(pPROB,0,fnames[eCL]));  
            Urhsx = mxGetPr(mxGetField(pPROB,0,fnames[eCU]));  
            sense = mxGetPr(mxGetField(pPROB,0,fnames[eSENSE])); 
            objbias = mxGetPr(mxGetField(pPROB,0,fnames[eOBJBIAS]));
            con_lin = mxGetPr(mxGetField(pPROB,0,fnames[eCONLIN]));  
            //Other Output Args
            sizes = mxGetPr(pSIZE = mxCreateDoubleMatrix(16, 1, mxREAL));
                     
            //Check for complementarity problems
            if(n_cc)
                mexWarnMsgTxt("Ignoring Complementarity Constraints!");
            //Assign asl problem sizes
            sizes[0] = (double)n_var; sizes[1] = (double)n_con; sizes[2] = (double)nzc;
            sizes[3] = (double)lnc; sizes[4] = (double)nbv; sizes[5] = (double)niv;
            sizes[6] = (double)nlc; sizes[7] = (double)nlnc; sizes[8] = (double)nlo;
            sizes[9] = (double)nlvb; sizes[10] = (double)nlvc; sizes[11] = (double)nlvo;
            sizes[12] = (double)nlvbi; sizes[13] = (double)nlvci; sizes[14] = (double)nlvoi;
            sizes[15] = (double)nwv; 
            //Read In For QP Checking
            qp_read(nl,0); 
            //Assign sense
            if(objtype[0] == 1)
                *sense = -1; //max
            else
                *sense = 1; //min  
                      
            //Determine Objective Linearity
            obj_lin = linCheck(asl, 0);
            //Determine Constraints Linearity
            for(ii = 0; ii < n_con; ii++) {
                con_lin[ii] = linCheck(asl, -(ii+1));
                //Check if nonlinear or quadratic
                if(con_lin[ii] >= ASL_DEGREE_NLIN)
                    nlcon = true;
                else if(con_lin[ii] == ASL_DEGREE_QUAD)
                {
                    //con_lin indicates quadratic constraint, ensure is inequality
                    if(LUrhs[ii] != Urhsx[ii])
                        nqc_con++;
                    else
                        nlcon = true; //quadratic equalities not currently handled by any explicit QCQP solver (I know of), make nl
                }                    
            }
    
            //Check to force to read as nonlinear problem
            if(nrhs > 2 && *mxGetPr(prhs[2])==1)
                nlcon = true;
            
            //If objective or any constraint is nonlinear, then we have to process as an NLP
            if(obj_lin == ASL_DEGREE_NLIN || nlcon) {
                //Free the QP read memory
                ASL_free(&asl);
                //Re-open for full NLP read
                asl = ASL_alloc(ASL_read_pfgh);                 //allocate memory for pfgh read
                nl = jac0dim(fpath,(ftnlen)strlen(fpath));      //read passed file (full nl read)
                //Allocate Jacobian Memory [note use M1alloc to let ASL clean it up if multiple instances opened]
                J = (double*)M1alloc(nzc*sizeof(double));       //Memory to store Jacobian nzs  
                //Assign memory for saving obj + con x
                objx = (double*)M1alloc(n_var*sizeof(double));
                conx = (double*)M1alloc(n_var*sizeof(double));
                //Read File (f + g + H)
                pfgh_read(nl, ASL_findgroups); 
                //Assign Hessian Memory
                nhnz = sphsetup(1, 1, n_con > 0, 0);            //one obj, use sigma, optionally use lambda, full hessian
                Hsp = (double*)M1alloc(nhnz*sizeof(double));    //memory to store hessian nzs
            }
            //Otherwise we can process as a LP, QP or QCQP
            else {                
                //Assign objective bias
                *objbias = objconst(0);
                //Check for quadratic objective
                if(obj_lin == ASL_DEGREE_QUAD) {
                    //Capture Pointers
                    nqpz = nqpcheck(0, &QP_ir, &QP_jc, &QP_pr); //check objective for qp
                    //Create QP H
                    mxSetField(pPROB,0,fnames[eH],mxCreateSparse(n_var,n_var,nqpz,mxREAL));                   
                    //Copy in Objective Quadratic Elements (copy-cast where appropriate)
                    memcpy(mxGetPr(mxGetField(pPROB,0,fnames[eH])),QP_pr,nqpz*sizeof(double));
                    Jc = mxGetJc(mxGetField(pPROB,0,fnames[eH]));
                    Ir = mxGetIr(mxGetField(pPROB,0,fnames[eH]));
                    for(i = 0; i <= n_var; i++)
                        Jc[i] = (mwIndex)QP_jc[i];
                    for(i = 0; i < nqpz; i++)
                        Ir[i] = (mwIndex)QP_ir[i];                       
                }
                else //create an empty sparse matrix
                    mxSetField(pPROB,0,fnames[eH],mxCreateSparse(n_var,n_var,0,mxREAL));
                
                //Create QP f
                mxSetField(pPROB,0,fnames[eF],mxCreateDoubleMatrix(n_var,1,mxREAL));
                Pr = mxGetPr(mxGetField(pPROB,0,fnames[eF]));
                //Copy in Objective Linear Elements
                for( og = Ograd[0]; og; og = og->next )
                    Pr[og->varno] = og->coef;
                
                //Create A (linear constraints)
                mxSetField(pPROB,0,fnames[eA],mxCreateSparse(n_con, n_var, nzc, mxREAL));
                if(n_con) {
                    Pr = mxGetPr(mxGetField(pPROB,0,fnames[eA]));
                    Ir = mxGetIr(mxGetField(pPROB,0,fnames[eA]));;                    
                    //Fill in A (will double on quadratic linear sections, but easier to remove once in MATLAB)
                    for(Jc = mxGetJc(mxGetField(pPROB,0,fnames[eA])), cs = A_colstarts, i = 0; i <= n_var; ++i)
                        Jc[i] = (mwIndex)cs[i];
                    cgp = Cgrad;
                    for(i = 0; i < n_con; i++)
                        for(cg = *cgp++; cg; cg = cg->next) {
                            Ir[cg->goff] = (mwIndex)i; 
                            Pr[cg->goff] = cg->coef;
                        }
                }
                
                //Add quadratic constraints if present
                if(nqc_con) {
                    //Allocate a Cell Array to store the quadratic constraint Qs, and vector to store indices
                    mxSetField(pPROB,0,fnames[eQ],mxCreateCellMatrix(nqc_con,1)); //Q
                    mxSetField(pPROB,0,fnames[eL],mxCreateDoubleMatrix(n_var, nqc_con,mxREAL)); //l
                    mxSetField(pPROB,0,fnames[eQCIND],mxCreateDoubleMatrix(nqc_con,1,mxREAL)); //ind                   
                    pqi = mxGetPr(mxGetField(pPROB,0,fnames[eQCIND]));
                    //Fill In Constraints
                    for(ii=0,j=0;ii<n_con;ii++) {
                        //Quadratic Constraints
                        if(con_lin[ii] == ASL_DEGREE_QUAD) {
                            //Create index
                            pqi[j] = ii+1; //increment for matlab index
                            //Capture Pointers
                            nqpz = nqpcheck(-(ii+1), &QP_ir, &QP_jc, &QP_pr); //check constraint for qp;
                            if(nqpz <= 0)
                                mexErrMsgTxt("Error reading quadratic constraints. Assumed constraint was quadratic based on prescan, now appears not?");
                            //Create QC Q
                            mxSetCell(mxGetField(pPROB,0,fnames[eQ]),j,mxCreateSparse(n_var,n_var,nqpz,mxREAL));                   
                            //Copy in Constraint Quadratic Elements (copy-cast where appropriate)
                            Pr = mxGetPr(mxGetCell(mxGetField(pPROB,0,fnames[eQ]),j));
                            Jc = mxGetJc(mxGetCell(mxGetField(pPROB,0,fnames[eQ]),j));
                            Ir = mxGetIr(mxGetCell(mxGetField(pPROB,0,fnames[eQ]),j));
                            for(k = 0; k <= n_var; k++)
                                Jc[k] = (mwIndex)QP_jc[k];
                            for(k = 0; k < nqpz; k++) {
                                Ir[k] = (mwIndex)QP_ir[k];
                                Pr[k] = 0.5*QP_pr[k];  //to QP form
                            }
                            //Create QC l (not sure why we can't extract this from Jacobian, values are wrong)
                            Pr = mxGetPr(mxGetField(pPROB,0,fnames[eL]));
                            for( cg = Cgrad[ii]; cg; cg = cg->next )
                                Pr[j*n_var + cg->varno] = cg->coef;
                            //Increment for next cell / col
                            j++;
                        }
                    } 
                }
                //Put back into function eval mode (just in case)
                qp_opify();
                
            }
            break;
            
        case ASLCMD_CLOSE:
            //Check for Errors
            CHECKASL(asl);
            //Call Exit Function
            mexExit();          
            break;                    
            
        case ASLCMD_FUN:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);             
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var); 
            //Save x
            if(objx) memcpy(objx,x,n_var*sizeof(double));                   
            //Create objective val memory and get it from ASL       
            SETERRJMP(); what = "objective";            
			f = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL));            
			*f = objval(0, x, &nerror);        
            break;
            
        case ASLCMD_GRAD:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);            
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var);
            //Save x
            if(objx) memcpy(objx,x,n_var*sizeof(double));            
            //Create objective grad memory and get it from ASL     
            SETERRJMP(); what = "gradient";            
			g = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, n_var, mxREAL));            
			objgrd(0, x, g, &nerror);            
            break;
            
        case ASLCMD_CON:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);            
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var);
            //Save x
            if(conx) memcpy(conx,x,n_var*sizeof(double));                        
            //Create constraint memory and get it from ASL  
            SETERRJMP(); what = "constraints";
			c = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n_con, 1, mxREAL));   
            if(n_con)
                conval(x, c, &nerror);            
            break;
            
        case ASLCMD_JAC:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2);   
            //Get x and check dimensions
            x = sizechk(prhs[1],"x",n_var);
            //Save x
            if(conx) memcpy(conx,x,n_var*sizeof(double));            
            //Create constraint jac memory and get it from ASL
            SETERRJMP(); what = "Jacobian";            
            //Check for sparsity
            if(nrhs > 2 && *mxGetPr(prhs[2])) {
                sp = 1;
                J1 = mxGetPr(plhs[0] = mxCreateSparse(n_con, n_var, nzc, mxREAL));
            }
            else {
                sp = 0;
                J1 = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n_con, n_var, mxREAL));
            }        
            //Evaluate if we have constraints
            if (n_con) {                
                //Sparse
                if(sp) {
                    jacval(x, J1, &nerror);
                    Ir = mxGetIr(plhs[0]);
                    for(Jc = mxGetJc(plhs[0]), cs = A_colstarts, i = 0; i <= n_var; ++i)
                        Jc[i] = (mwIndex)cs[i];
                    cgp = Cgrad;
                    for(i = 0; i < n_con; i++)
                        for(cg = *cgp++; cg; cg = cg->next)
                            Ir[cg->goff] = (mwIndex)i;  
                }
                //Dense
                else {      
                    jacval(x, J, &nerror);
                    cgp = Cgrad;
                    for(cgpe = cgp + n_con; cgp < cgpe; J1++)
                        for(cg = *cgp++; cg; cg = cg->next)
                            J1[n_con*cg->varno] = J[cg->goff];
                }
            }                        
            break;
            
        case ASLCMD_JACSTR:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,1);            
            //Create constraint jacstr memory and get it from ASL
            SETERRJMP(); what = "Jacobian Structure)";                       
            J1 = mxGetPr(plhs[0] = mxCreateSparse(n_con, n_var, nzc, mxREAL));
            //Fill In Structure
            for(i=0;i<nzc;i++)
                J1[i] = 1.0;
            for(Jc = mxGetJc(plhs[0]), cs = A_colstarts, i = 0; i <= n_var; ++i)
                Jc[i] = (mwIndex)cs[i];
            cgp = Cgrad;
            Ir = mxGetIr(plhs[0]);
            for(i = 0; i < n_con; i++)
                for(cg = *cgp++; cg; cg = cg->next)
                    Ir[cg->goff] = (mwIndex)i;                
            break;
            
        case ASLCMD_HES:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,4); //assume hess(x,sigma,lambda) and optionally sparse            
            //Check dimensions & get args
            x = sizechk(prhs[1],"x",n_var);
            s = sizechk(prhs[2],"sigma",1);
            v = sizechk(prhs[3],"lambda",n_con);
            
            //Check for sparsity
            if(nrhs > 4 && *mxGetPr(prhs[4])) {
                sp = 1;
                W = mxGetPr(plhs[0] = mxCreateSparse(n_var, n_var, nhnz, mxREAL));
            }
            else {
                sp = 0;    
                W = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n_var, n_var, mxREAL));
            }
            //Check if we need to recalculate objective / constraints
            if(!comp_x(objx,x,n_var)) {
                //Setup Error Catching
                SETERRJMP(); what = "Objective for Hessian";                
                //Re-evaluate Objective
                objval(0, x, &nerror);                
            }            
            if(!comp_x(conx,x,n_var)){
                if(!c)
                    c = mxGetPr(mxCreateDoubleMatrix(n_con, 1, mxREAL));                
                //Setup Error Catching
                SETERRJMP(); what = "Constraints for Hessian";                
                //Re-evaluate Constraints
                conval(x, c, &nerror);
            }            
            //Setup Error Catching
            SETERRJMP(); what = "Hessian";
            
            //Sparse
            if(sp) {
                //This function returns the full (symmetric) Hessian as setup above
                sphes(H = Hsp, 1, s, v);                
                Ir = mxGetIr(plhs[0]);
                Jc = mxGetJc(plhs[0]);
                hcs = sputinfo->hcolstarts;
                hr = sputinfo->hrownos;
                for(i = 0; i <= n_var; i++)
                    Jc[i] = (mwIndex)hcs[i];
                He = H + hcs[n_var];
                while(H < He) {
                    *W++ = *H++;
                    *Ir++ = (mwIndex)*hr++;
                }	
            }
            //Dense
            else
                fullhes(W, n_var, 1, s, v);            
            break;
            
        case ASLCMD_HESSTR:
            //mexPrintf("CMD: Get Hessian Structure\n");
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,1);            
            //Create hessianstr memory and get it from ASL
            SETERRJMP(); what = "Hessian Structure";
            W = mxGetPr(plhs[0] = mxCreateSparse(n_var, n_var, nhnz, mxREAL));
            Ir = mxGetIr(plhs[0]);
            Jc = mxGetJc(plhs[0]);
            //Get Sparse Info
            hcs = sputinfo->hcolstarts;
            hr = sputinfo->hrownos;
            //Assign col starts
            for(i = 0; i <= n_var; i++)
                Jc[i] = (mwIndex)hcs[i];
            //Assign rows + 1.0 for nz positions
            H = Hsp;                //Start of nz Hsp elements
            He = H + hcs[n_var];    //End of nz Hsp elements
            while(H < He) {
                *W++ = 1.0;                
                *Ir++ = (mwIndex)*hr++;
                *H++; //increment nz element position
            }	                        
            break;           
            
        case ASLCMD_WRITESOL:
            //Check for Errors
            CHECKASL(asl);
            CHECKNRHS(nrhs,2); //asl('writesol',msg,x)            
            //Get Input Args
            CHECK(mxGetString(prhs[1], msg, FLEN) == 0,"error reading message!");
            x = sizechk(prhs[2],"x",n_var);            
            //Write to solution stub file
            write_sol(msg,x,NULL,NULL);
            break;
            
        default:
            mexExit(); //clean up
            mxGetString(prhs[0], cmd, FLEN);
            sprintf(msgbuf, "ASL Command Error! Unknown Command: '%s'\n", cmd);
            mexErrMsgTxt(msgbuf);
            break;
    }
}
예제 #11
0
파일: amplfunc.c 프로젝트: BRAINSia/calatk
 void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	FILE *nl;
	char *buf1, buf[512], *what, **whatp;
	static fint n, nc, nz;
	fint i, nerror;
	real *J1, *W, *c, *f, *g, *v, *t, *x;
	static real *J;
	cgrad *cg, **cgp, **cgpe;
	static size_t Jsize;
	Jmp_buf err_jmp0;
	ASL *asl = cur_ASL;
	static char ignore_complementarity[] =
		"Warning: ignoring %d complementarity conditions.\n";

	if (nrhs == 1 && mxIsChar(prhs[0])) {
		if (nlhs < 6 || nlhs > 7)
			usage();
		if (mxGetString(prhs[0], buf1 = buf, sizeof(buf)))
			mexErrMsgTxt("Expected 'stub' as argument\n");
		at_end();
		mexAtExit(at_end);
		asl = ASL_alloc(ASL_read_pfgh);
		return_nofile = 1;
		if (!(nl = jac0dim(buf1,strlen(buf)))) {
			sprintf(msgbuf, "Can't open %.*s\n",
				sizeof(msgbuf)-20, buf);
			mexErrMsgTxt(msgbuf);
			}
		if (n_obj <= 0)
			printf("Warning: objectve == 0\n");
		n = n_var;
		nc = n_con;
		nz = nzc;
		J = (real *)M1alloc(nz*sizeof(real));
		X0 = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL));
		LUv = mxGetPr(plhs[1] = mxCreateDoubleMatrix(n, 1, mxREAL));
		Uvx = mxGetPr(plhs[2] = mxCreateDoubleMatrix(n, 1, mxREAL));
		pi0 = mxGetPr(plhs[3] = mxCreateDoubleMatrix(nc, 1, mxREAL));
		LUrhs = mxGetPr(plhs[4] = mxCreateDoubleMatrix(nc, 1, mxREAL));
		Urhsx = mxGetPr(plhs[5] = mxCreateDoubleMatrix(nc, 1, mxREAL));
		if (nlhs == 7) {
			cvar = (int*)M1alloc(nc*sizeof(int));
			plhs[6] = mxCreateDoubleMatrix(nc, 1, mxREAL);
			x = mxGetPr(plhs[6]);
			}
		else if (n_cc)
			printf(ignore_complementarity, n_cc);
		pfgh_read(nl, ASL_findgroups);
		Jsize = nc*n*sizeof(real);
		if (nlhs == 7)
			for(i = 0; i < nc; i++)
				x[i] = cvar[i];
		return;
		}

	if (!asl)
		mexErrMsgTxt("amplfunc(\"stub\") has not been called\n");
	nerror = -1;
	err_jmp1 = &err_jmp0;
	what = "(?)";
	whatp = &what;
	if (nlhs == 2) {
		if (nrhs != 2)
			usage();
		x = sizechk(prhs[0],"x",n);
		t = sizechk(prhs[1],"0 or 1", 1);
		if (setjmp(err_jmp0.jb)) {
			sprintf(msgbuf, "Trouble evaluating %s\n", *whatp);
			mexErrMsgTxt(msgbuf);
			}
		if (t[0] == 0.) {
			f = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL));
			c = mxGetPr(plhs[1] = mxCreateDoubleMatrix(nc, 1, mxREAL));
			what = "f";
			*f = objval(0, x, &nerror);
			what = "c";
			conval(x, c, &nerror);
			return;
			}
		g = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL));
		J1 = mxGetPr(plhs[1] = mxCreateDoubleMatrix(nc, n, mxREAL));
		what = "g";
		objgrd(0, x, g, &nerror);
		if (nc) {
			memset(J1, 0, Jsize);
			what = "J";
			jacval(x, J, &nerror);
			cgp = Cgrad;
			for(cgpe = cgp + nc; cgp < cgpe; J1++)
				for(cg = *cgp++; cg; cg = cg->next)
					J1[nc*cg->varno] = J[cg->goff];
			}
		return;
		}
	if (nlhs == 0 && (nrhs == 3 || nrhs == 4)) {
		/* eval2('solution message', x, v): x = primal, v = dual */
		/* optional 4th arg = solve_result_num */
		if (!mxIsChar(prhs[0]))
			usage();
		x = sizechk(prhs[1],"x",n);
		v = sizechk(prhs[2],"v",nc);
		if (mxGetString(prhs[0], buf, sizeof(buf)))
			mexErrMsgTxt(
			 "Expected 'solution message' as first argument\n");
		solve_result_num = nrhs == 3 ? -1 /* unknown */
			: (int)*sizechk(prhs[3],"solve_result_num",1);
		write_sol(buf, x, v, 0);
		return;
		}
	if (nlhs != 1 || nrhs != 1)
		usage();
	v = sizechk(prhs[0],"v",nc);
	W = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n, n, mxREAL));

	what = "W";
	fullhes(W, n, 0, 0, v);
	}