コード例 #1
0
ファイル: Decode_Chain.cpp プロジェクト: cran/CRF
SEXP Decode_Chain(SEXP _crf)
{
	CRF crf(_crf);
	crf.Init_Labels();
	crf.Decode_Chain();
	return(crf._labels);
}
コード例 #2
0
ファイル: Infer_Chain.cpp プロジェクト: cran/CRF
SEXP Infer_Chain(SEXP _crf)
{
	CRF crf(_crf);
	crf.Init_Belief();
	crf.Infer_Chain();
	return(crf._belief);
}
コード例 #3
0
ファイル: Decode_Tree.cpp プロジェクト: cran/CRF
SEXP Decode_Tree(SEXP _crf)
{
	CRF crf(_crf);
	crf.Init_Labels();
	crf.Init_NodeBel();
	crf.Decode_Tree();
	return(crf._labels);
}
コード例 #4
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	double x_std, y_std, w_smooth;
	double x_std_b, y_std_b, r_std, g_std, b_std, w_bilateral;
	int width, height, labels;

	// check input and output parameters

	if (nrhs < 12 ) {
		mexErrMsgTxt("12 inputs required (unary, color_image, x_std, y_std, w_smooth, x_std_bilateral, y_std_bilateral, r_std, g_std, b_std, w_bilateral, img_width, img_height)");
	}

	// unary (be careful about c++ index and matlab index)
	if(!mxIsSingle(prhs[0])) {
		mexErrMsgTxt("Input matrix 1 must be float.");
	}
	float *unary = (float *) mxGetData(prhs[0]);
	labels = mxGetM(prhs[0]);
	
	if (!mxIsUint8(prhs[1])) {
		mexErrMsgTxt("Input matrix 2 must be uint8.");	
	}
	if (mxGetM(prhs[1]) != 3) {
		mexErrMsgTxt("Input matrix 2 must have 3 channels (channel  * width * height).");	
	}
	unsigned char * img = (unsigned char *) mxGetPr(prhs[1]);

	x_std = mxGetScalar(prhs[2]); 
	y_std = mxGetScalar(prhs[3]); 
	w_smooth = mxGetScalar(prhs[4]);

	x_std_b = mxGetScalar(prhs[5]); 
	y_std_b = mxGetScalar(prhs[6]); 
	r_std = mxGetScalar(prhs[7]);
	g_std = mxGetScalar(prhs[8]);
	b_std = mxGetScalar(prhs[9]);
	w_bilateral = mxGetScalar(prhs[10]);

	width = mxGetScalar(prhs[11]);
	height = mxGetScalar(prhs[12]);

	plhs[0] = mxCreateNumericMatrix(height, width, mxINT32_CLASS, mxREAL);
	plhs[1] = mxCreateNumericMatrix(height*width*labels, 1, mxSINGLE_CLASS, mxREAL);

	int *map = (int *)mxGetData(plhs[0]);
	float *prob = (float *)mxGetData(plhs[1]);

	int iter = 10;

	DenseCRF2D crf(width, height, labels);

	crf.setUnaryEnergy( unary);

	crf.addPairwiseGaussian( x_std, y_std, w_smooth);
	
	crf.addPairwiseBilateral( x_std_b, y_std_b, r_std, g_std, b_std, img, w_bilateral);

	crf.map(iter, map, prob);
}
コード例 #5
0
ファイル: Sample_Cutset.cpp プロジェクト: cran/CRF
SEXP Sample_Cutset(SEXP _crf, SEXP _size, SEXP _engine)
{
	CRFclamped crf(_crf);
	crf.Init_Belief();
	crf.Init_Samples(1);
	crf.original.Init_Samples(_size);
	crf.Sample_Cutset(INTEGER_POINTER(AS_INTEGER(_size))[0], INTEGER_POINTER(AS_INTEGER(_engine))[0]);
	return(crf.original._samples);
}
コード例 #6
0
ファイル: Infer_TRBP.cpp プロジェクト: rforge/crf
SEXP Infer_TRBP(SEXP _crf, SEXP _maxIter, SEXP _cutoff, SEXP _verbose)
{
	int maxIter = INTEGER_POINTER(AS_INTEGER(_maxIter))[0];
	double cutoff = NUMERIC_POINTER(AS_NUMERIC(_cutoff))[0];
	int verbose = INTEGER_POINTER(AS_INTEGER(_verbose))[0];

	CRF crf(_crf);
	crf.Init_Belief();
	crf.Infer_TRBP(maxIter, cutoff, verbose);

	return(crf._belief);
}
コード例 #7
0
ファイル: Train.cpp プロジェクト: rforge/crf
SEXP MRF_Stat(SEXP _crf, SEXP _instances)
{
	CRF crf(_crf);

	int nInstances = INTEGER_POINTER(GET_DIM(_instances))[0];
	int nPar = INTEGER_POINTER(AS_INTEGER(GetVar(_crf, "n.par")))[0];

	PROTECT(_instances = AS_NUMERIC(_instances));
	double *instances = NUMERIC_POINTER(_instances);

	SEXP _nodePar;
	PROTECT(_nodePar = AS_INTEGER(GetVar(_crf, "node.par")));
	int *nodePar = INTEGER_POINTER(_nodePar);

	SEXP _edgePar = GetVar(_crf, "edge.par");
	int **edgePar = (int **) R_alloc(crf.nEdges, sizeof(int *));
	SEXP _edgeParI, _temp;
	PROTECT(_edgeParI = NEW_LIST(crf.nEdges));
	for (int i = 0; i < crf.nEdges; i++)
	{
		SET_VECTOR_ELT(_edgeParI, i, _temp = AS_INTEGER(GetListElement(_edgePar, i)));
		edgePar[i] = INTEGER_POINTER(_temp);
	}

	SEXP _stat;
	PROTECT(_stat = NEW_NUMERIC(nPar));
	double *stat = NUMERIC_POINTER(_stat);
	SetValues(_stat, stat, 0.0);

	int *y = (int *) R_allocVector<int>(crf.nNodes);

	for (int n = 0; n < nInstances; n++)
	{
		for (int i = 0; i < crf.nNodes; i++)
		{
			y[i] = instances[n + nInstances * i] - 1;
			int p = nodePar[i + crf.nNodes * y[i]] - 1;
			if (p >= 0 && p < nPar)
				stat[p]++;
		}

		for (int i = 0; i < crf.nEdges; i++)
		{
			int p = edgePar[i][y[crf.EdgesBegin(i)] + crf.nStates[crf.EdgesBegin(i)] * y[crf.EdgesEnd(i)]] - 1;
			if (p >= 0 && p < nPar)
				stat[p]++;
		}
	}

	UNPROTECT(4);

	return(_stat);
}
コード例 #8
0
ファイル: Decode_LBP.cpp プロジェクト: cran/CRF
SEXP Decode_LBP(SEXP _crf, SEXP _maxIter, SEXP _cutoff, SEXP _verbose)
{
	int maxIter = INTEGER_POINTER(AS_INTEGER(_maxIter))[0];
	double cutoff = NUMERIC_POINTER(AS_NUMERIC(_cutoff))[0];
	int verbose = INTEGER_POINTER(AS_INTEGER(_verbose))[0];

	CRF crf(_crf);
	crf.Init_Labels();
	crf.Init_NodeBel();
	crf.Decode_LBP(maxIter, cutoff, verbose);

	return(crf._labels);
}
コード例 #9
0
ファイル: flow.cpp プロジェクト: ThomasWDonnelly/xbox360-emu
bool cmpx(State *state, Instruction instr)
{
   auto flags = 0;
   Type a, b;

   if (instr.l == 0) {
      if (std::numeric_limits<Type>::is_signed) {
         a = little_endian::signExtend<32, Type>(gpr(instr.rA));
      } else {
         a = little_endian::zeroExtend<32, Type>(gpr(instr.rA));
      }
   } else {
      a = static_cast<Type>(gpr(instr.rA));
   }

   if (Flags & CmpxImmediate) {
      if (std::numeric_limits<Type>::is_signed) {
         b = little_endian::signExtend<16, Type>(instr.simm);
      } else {
         b = instr.uimm;
      }
   } else if (instr.l == 0) {
      if (std::numeric_limits<Type>::is_signed) {
         b = little_endian::signExtend<32, Type>(gpr(instr.rB));
      } else {
         b = little_endian::zeroExtend<32, Type>(gpr(instr.rB));
      }
   } else {
      b = static_cast<Type>(gpr(instr.rB));
   }

   if (a < b) {
      flags |= ppc::Cr::Negative;
   } else if (a > b) {
      flags |= ppc::Cr::Positive;
   } else {
      flags |= ppc::Cr::Zero;
   }

   flags |= state->reg.xer.so;
   crf(instr.crfD) = flags;

   return true;
}
コード例 #10
0
ファイル: ringo_shadow_table.cpp プロジェクト: mojca/indigo
void RingoShadowTable::addReaction (OracleEnv &env, RingoIndex &index, const char *rowid, int blockno, int offset)
{
   OracleLOB crf(env);

   crf.createTemporaryBLOB();

   crf.write(0, index.getCrf());

   OracleStatement statement(env);

   statement.append("INSERT INTO %s VALUES(:rxnrowid, :blockno, :offset, :crf, :rxnhash)",
      _table_name.ptr());

   statement.prepare();
   statement.bindStringByName(":rxnrowid", rowid, strlen(rowid) + 1);
   statement.bindIntByName(":blockno", &blockno);
   statement.bindIntByName(":offset", &offset);
   statement.bindBlobByName(":crf", crf);
   statement.bindStringByName(":rxnhash", index.getHashStr(), strlen(index.getHashStr()) + 1);

   statement.execute();
}
コード例 #11
0
int main( int argc, char* argv[]){
	if (argc<4){
		printf("Usage: %s image annotations output\n", argv[0] );
		return 1;
	}
	// Number of labels
	const int M = 21;
	// Load the color image and some crude annotations (which are used in a simple classifier)
	int W, H, GW, GH;
	unsigned char * im = readPPM( argv[1], W, H );
	if (!im){
		printf("Failed to load image!\n");
		return 1;
	}
	unsigned char * anno = readPPM( argv[2], GW, GH );
	if (!anno){
		printf("Failed to load annotations!\n");
		return 1;
	}
	if (W!=GW || H!=GH){
		printf("Annotation size doesn't match image!\n");
		return 1;
	}
	
	/////////// Put your own unary classifier here! ///////////
  Eigen::MatrixXf unary = computeUnary( getLabeling( anno, W*H, M ), M );
	///////////////////////////////////////////////////////////
	
	// Setup the CRF model
	DenseCRF2D crf(W, H, M);
	// Specify the unary potential as an array of size W*H*(#classes)
	// packing order: x0y0l0 x0y0l1 x0y0l2 .. x1y0l0 x1y0l1 ...
	crf.setUnaryEnergy( unary );
	// add a color independent term (feature = pixel location 0..W-1, 0..H-1)
	// x_stddev = 3
	// y_stddev = 3
	// weight = 3
	crf.addPairwiseGaussian( 3, 3, new PottsCompatibility( 3 ) );
	// add a color dependent term (feature = xyrgb)
	// x_stddev = 60
	// y_stddev = 60
	// r_stddev = g_stddev = b_stddev = 20
	// weight = 10
	crf.addPairwiseBilateral( 80, 80, 13, 13, 13, im, new PottsCompatibility( 10 ) );
	
	// Do map inference
// 	Eigen::MatrixXf Q = crf.startInference(), t1, t2;
// 	printf("kl = %f\n", crf.klDivergence(Q) );
// 	for( int it=0; it<5; it++ ) {
// 		crf.stepInference( Q, t1, t2 );
// 		printf("kl = %f\n", crf.klDivergence(Q) );
// 	}
// 	VectorXs map = crf.currentMap(Q);
	VectorXs map = crf.map(5);
	// Store the result
	unsigned char *res = colorize( map, W, H );
	writePPM( argv[3], W, H, res );
	
	delete[] im;
	delete[] anno;
	delete[] res;
}
コード例 #12
0
ファイル: Train.cpp プロジェクト: rforge/crf
SEXP MRF_Update(SEXP _crf)
{
	CRF crf(_crf);
	crf.Update_Pot();
	return (_crf);
}
コード例 #13
0
// *****************************************
// Gateway routine
void mexFunction(int nlhs, mxArray * plhs[],    // output variables
                int nrhs, const mxArray * prhs[]) // input variables
{
    
    // Macros declarations 
    // For the outputs
    #define PAIRSWISEKERNELS_OUT   plhs[0]
    // For the inputs
    #define HEIGHT_IN              prhs[0]
    #define WIDTH_IN               prhs[1]
    #define LABELING_IN            prhs[2]
    #define PAIRWISEFEATURES_IN    prhs[3]
    #define NUMPAIRWISES_IN        prhs[4]
	#define HSTD_IN 			   prhs[5]
    #define WSTD_IN        		   prhs[6]
    #define THETA_P_X_IN        		   prhs[7]
    #define THETA_P_Y_IN        		   prhs[8]
    
    // Check the input parameters
    if (nrhs < 1 || nrhs > 9)
        mexErrMsgTxt("Wrong number of input parameters.");
    
    // Get the size of the image
    int height = (int) mxGetScalar(HEIGHT_IN);
    int width = (int) mxGetScalar(WIDTH_IN); 
    
    // Get the labeling
    short * labelingIn = (short *) mxGetData(LABELING_IN);
    
    // Get the pairwise features
    float * pairwiseFeaturesIn = (float *) mxGetData(PAIRWISEFEATURES_IN);
    
	// Get the standard deviations of the (x,y) coordinates
    float hstd_in = (float) mxGetScalar(HSTD_IN);
	float wstd_in = (float) mxGetScalar(WSTD_IN);
	
    // Get the theta_p
    int theta_p_x = (float) mxGetScalar(THETA_P_X_IN);
    int theta_p_y = (float) mxGetScalar(THETA_P_Y_IN);
    
    // Create the CRF to compute the pairwise potentials. height and width 
    // represents the size of the image, and 2 is the amount of classes
    // (background and vessels) 
    DenseCRF2D crf(height, width, 2);
    
    // Get the pairwise features
    int numPairwiseFeatures = (int) mxGetScalar(NUMPAIRWISES_IN);
    float * pairwiseFeatures = (float *) mxGetData(PAIRWISEFEATURES_IN);
    // Assign the pairwise features
    for (int pairw = 0; pairw < numPairwiseFeatures; pairw++) {
        // Encode the pairwise features
        float * single_PairwiseFeatures = new float[width * height * 3];
		float mean_h = height / 2;
		float mean_w = width / 2;
        for (int h = 0; h < height; h++) {    
            for (int w = 0; w < width; w++) {
                single_PairwiseFeatures[(w+h*width)*3+0] = pairwiseFeatures[h + height * (w + width * pairw)];
				single_PairwiseFeatures[(w+h*width)*3+1] = (((float) (h - mean_h)) / hstd_in) / theta_p_y; 
				single_PairwiseFeatures[(w+h*width)*3+2] = (((float) (w - mean_w)) / wstd_in) / theta_p_x;
            }
        }
        //Assign the pairwise features
        crf.addPairwiseEnergy(single_PairwiseFeatures, 3, 1.0);
        delete [] single_PairwiseFeatures;
    }
    
    // Declare the output variables
    mwSize dims[3] = {height, width, numPairwiseFeatures};
    PAIRSWISEKERNELS_OUT = mxCreateNumericArray(3, dims, mxSINGLE_CLASS, mxREAL);
    float * pairwiseKernels = (float *) mxGetData(PAIRSWISEKERNELS_OUT);
    
    // Compute the pairwise energy
    for (int pairw = 0; pairw < numPairwiseFeatures; pairw++) {
        float * pairwiseEnergy = new float[width * height];
        crf.pairwiseEnergy(labelingIn, pairwiseEnergy, pairw);
        for (int w = 0; w < width; w++) {
            for (int h = 0; h < height; h++) {  
                pairwiseKernels[h + height * (w + width * pairw)] = (float) pairwiseEnergy[w + width * h];
            }
        }
        delete [] pairwiseEnergy;
    }
    
    return;
    
}
コード例 #14
0
int main( int argc, char* argv[]){
	if (argc<4){
		printf("Usage: %s image annotations output\n", argv[0] );
		return 1;
	}
	// Number of labels [use only 4 to make our lives a bit easier]
	const int M = 4;
	// Load the color image and some crude annotations (which are used in a simple classifier)
	int W, H, GW, GH;
	unsigned char * im = readPPM( argv[1], W, H );
	if (!im){
		printf("Failed to load image!\n");
		return 1;
	}
	unsigned char * anno = readPPM( argv[2], GW, GH );
	if (!anno){
		printf("Failed to load annotations!\n");
		return 1;
	}
	if (W!=GW || H!=GH){
		printf("Annotation size doesn't match image!\n");
		return 1;
	}
	// Get the labeling
	VectorXs labeling = getLabeling( anno, W*H, M );
	const int N = W*H;
	
	// Get the logistic features (unary term)
	// Here we just use the color as a feature
  Eigen::MatrixXf logistic_feature( 4, N ), logistic_transform( M, 4 );
	logistic_feature.fill( 1.f );
	for( int i=0; i<N; i++ )
		for( int k=0; k<3; k++ )
			logistic_feature(k,i) = im[3*i+k] / 255.;
	
	for( int j=0; j<logistic_transform.cols(); j++ )
		for( int i=0; i<logistic_transform.rows(); i++ )
			logistic_transform(i,j) = 0.01*(1-2.*random()/RAND_MAX);
	
	// Setup the CRF model
	DenseCRF2D crf(W, H, M);
	// Add a logistic unary term
	crf.setUnaryEnergy( logistic_transform, logistic_feature );
	
	// Add simple pairwise potts terms
	crf.addPairwiseGaussian( 3, 3, new PottsCompatibility( 1 ) );
	// Add a longer range label compatibility term
  crf.addPairwiseBilateral( 80.0f, 80.0f, 13.0f, 13.0f, 13.0f, &*im, new MatrixCompatibility::MatrixCompatibility( Eigen::MatrixXf::Identity(M,M) ) );
	
	// Choose your loss function
// 	LogLikelihood objective( labeling, 0.01 ); // Log likelihood loss
// 	Hamming objective( labeling, 0.0 ); // Global accuracy
// 	Hamming objective( labeling, 1.0 ); // Class average accuracy
// 	Hamming objective( labeling, 0.2 ); // Hamming loss close to intersection over union
	IntersectionOverUnion objective( labeling ); // Intersection over union accuracy
	
	int NIT = 5;
	const bool verbose = true;
	
  Eigen::MatrixXf learning_params( 3, 3 );
	// Optimize the CRF in 3 phases:
	//  * First unary only
	//  * Unary and pairwise
	//  * Full CRF
	learning_params<<1,0,0,
	                 1,1,0,
					 1,1,1;
	
	for( int i=0; i<learning_params.rows(); i++ ) {
		// Setup the energy
		CRFEnergy energy( crf, objective, NIT, learning_params(i,0), learning_params(i,1), learning_params(i,2) );
		energy.setL2Norm( 1e-3 );
		
		// Minimize the energy
		Eigen::VectorXf p = minimizeLBFGS( energy, 2, true );
		
		// Save the values
		int id = 0;
		if( learning_params(i,0) ) {
			crf.setUnaryParameters( p.segment( id, crf.unaryParameters().rows() ) );
			id += crf.unaryParameters().rows();
		}
		if( learning_params(i,1) ) {
			crf.setLabelCompatibilityParameters( p.segment( id, crf.labelCompatibilityParameters().rows() ) );
			id += crf.labelCompatibilityParameters().rows();
		}
		if( learning_params(i,2) )
			crf.setKernelParameters( p.segment( id, crf.kernelParameters().rows() ) );
	}
	// Return the parameters
	std::cout<<"Unary parameters: "<<crf.unaryParameters().transpose()<<std::endl;
	std::cout<<"Pairwise parameters: "<<crf.labelCompatibilityParameters().transpose()<<std::endl;
	std::cout<<"Kernel parameters: "<<crf.kernelParameters().transpose()<<std::endl;
	
	// Do map inference
	VectorXs map = crf.map(NIT);
	
	// Store the result
	unsigned char *res = colorize( map, W, H );
	writePPM( argv[3], W, H, res );
	
	delete[] im;
	delete[] anno;
	delete[] res;
}
コード例 #15
0
ファイル: Train.cpp プロジェクト: rforge/crf
SEXP MRF_NLL(SEXP _crf, SEXP _par, SEXP _instances, SEXP _infer, SEXP _env)
{
	CRF crf(_crf);

	int nInstances = INTEGER_POINTER(GET_DIM(_instances))[0];
	int nPar = INTEGER_POINTER(AS_INTEGER(GetVar(_crf, "n.par")))[0];

	PROTECT(_par = AS_NUMERIC(_par));
	double *par = NUMERIC_POINTER(_par);
	double *crfPar = NUMERIC_POINTER(GetVar(_crf, "par"));
	for (int i = 0; i < nPar; i++)
		crfPar[i] = par[i];

	SEXP _parStat;
	PROTECT(_parStat = AS_NUMERIC(GetVar(_crf, "par.stat")));
	double *parStat = NUMERIC_POINTER(_parStat);

	SEXP _nll = GetVar(_crf, "nll");
	double *nll = NUMERIC_POINTER(_nll);
	*nll = 0.0;

	double *gradient = NUMERIC_POINTER(GetVar(_crf, "gradient"));
	for (int i = 0; i < nPar; i++)
		gradient[i] = 0.0;

	crf.Update_Pot();

	SEXP _belief;
	PROTECT(_belief = eval(_infer, _env));

	*nll = NUMERIC_POINTER(AS_NUMERIC(GetListElement(_belief, "logZ")))[0] * nInstances;
	for (int i = 0; i < nPar; i++)
	{
		*nll -= par[i] * parStat[i];
		gradient[i] = -parStat[i];
	}

	SEXP _nodePar, _nodeBel;
	PROTECT(_nodePar = AS_INTEGER(GetVar(_crf, "node.par")));
	PROTECT(_nodeBel = AS_NUMERIC(GetListElement(_belief, "node.bel")));
	int *nodePar = INTEGER_POINTER(_nodePar);
	double *nodeBel = NUMERIC_POINTER(_nodeBel);
	for (int i = 0; i < crf.nNodes; i++)
	{
		for (int k = 0; k < crf.nStates[i]; k++)
		{
			int p = nodePar[i + crf.nNodes * k] - 1;
			if (p >= 0 && p < nPar)
			{
				gradient[p] += nodeBel[i + crf.nNodes * k] * nInstances;
			}
		}
	}

	SEXP _edgePar = GetVar(_crf, "edge.par");
	SEXP _edgeBel = GetListElement(_belief, "edge.bel");
	SEXP _edgeParI, _edgeBelI, _temp;
	PROTECT(_edgeParI = NEW_LIST(crf.nEdges));
	PROTECT(_edgeBelI = NEW_LIST(crf.nEdges));
	for (int i = 0; i < crf.nEdges; i++)
	{
		SET_VECTOR_ELT(_edgeParI, i, _temp = AS_INTEGER(GetListElement(_edgePar, i)));
	  int *edgePar = INTEGER_POINTER(_temp);
	  SET_VECTOR_ELT(_edgeBelI, i, _temp = AS_NUMERIC(GetListElement(_edgeBel, i)));
		double *edgeBel = NUMERIC_POINTER(_temp);
		for (int k = 0; k < crf.nEdgeStates[i]; k++)
		{
			int p = edgePar[k] - 1;
			if (p >= 0 && p < nPar)
			{
				gradient[p] += edgeBel[k] * nInstances;
			}
		}
	}

	UNPROTECT(7);

	return(_nll);
}
コード例 #16
0
ファイル: Train.cpp プロジェクト: rforge/crf
SEXP CRF_NLL(SEXP _crf, SEXP _par, SEXP _instances, SEXP _nodeFea, SEXP _edgeFea, SEXP _nodeExt, SEXP _edgeExt, SEXP _infer, SEXP _env)
{
	CRF crf(_crf);

	int nInstances = INTEGER_POINTER(GET_DIM(_instances))[0];
	int nPar = INTEGER_POINTER(AS_INTEGER(GetVar(_crf, "n.par")))[0];
	int nNodeFea = INTEGER_POINTER(AS_INTEGER(GetVar(_crf, "n.nf")))[0];
	int nEdgeFea = INTEGER_POINTER(AS_INTEGER(GetVar(_crf, "n.ef")))[0];

	PROTECT(_par = AS_NUMERIC(_par));
	double *par = NUMERIC_POINTER(_par);
	double *crfPar = NUMERIC_POINTER(GetVar(_crf, "par"));
	for (int i = 0; i < nPar; i++)
		crfPar[i] = par[i];

	PROTECT(_instances = AS_NUMERIC(_instances));
	double *instances = NUMERIC_POINTER(_instances);

	SEXP _nodePar;
	PROTECT(_nodePar = AS_INTEGER(GetVar(_crf, "node.par")));
	int *nodePar = INTEGER_POINTER(_nodePar);

	SEXP _edgePar = GetVar(_crf, "edge.par");
	int **edgePar = (int **) R_alloc(crf.nEdges, sizeof(int *));
	SEXP _edgeParI, _temp;
	PROTECT(_edgeParI = NEW_LIST(crf.nEdges));
	for (int i = 0; i < crf.nEdges; i++)
	{
		SET_VECTOR_ELT(_edgeParI, i, _temp = AS_INTEGER(GetListElement(_edgePar, i)));
		edgePar[i] = INTEGER_POINTER(_temp);
	}

	SEXP _nll = GetVar(_crf, "nll");
	double *nll = NUMERIC_POINTER(_nll);
	*nll = 0.0;

	double *gradient = NUMERIC_POINTER(GetVar(_crf, "gradient"));
	for (int i = 0; i < nPar; i++)
		gradient[i] = 0.0;

	int *y = (int *) R_allocVector<int>(crf.nNodes);

	SEXP _nodeFeaN = _nodeFea;
	SEXP _edgeFeaN = _edgeFea;
	SEXP _nodeExtN = _nodeExt;
	SEXP _edgeExtN = _edgeExt;
	for (int n = 0; n < nInstances; n++)
	{
		if (!isNull(_nodeFea) && isNewList(_nodeFea)) _nodeFeaN = GetListElement(_nodeFea, n);
		if (!isNull(_edgeFea) && isNewList(_edgeFea)) _edgeFeaN = GetListElement(_edgeFea, n);
		if (!isNull(_nodeExt) && isNewList(_nodeExt)) _nodeExtN = GetListElement(_nodeExt, n);
		if (!isNull(_edgeExt) && isNewList(_edgeExt)) _edgeExtN = GetListElement(_edgeExt, n);

		crf.Update_Pot(_nodeFeaN, _edgeFeaN, _nodeExtN, _edgeExtN);

		for (int i = 0; i < crf.nNodes; i++)
			y[i] = instances[n + nInstances * i] - 1;

		SEXP _belief;
		PROTECT(_belief = eval(_infer, _env));

		SEXP _nodeBel;
		PROTECT(_nodeBel = AS_NUMERIC(GetListElement(_belief, "node.bel")));
		double *nodeBel = NUMERIC_POINTER(_nodeBel);

		SEXP _edgeBel = GetListElement(_belief, "edge.bel");
		double **edgeBel = (double **) R_alloc(crf.nEdges, sizeof(double *));
		SEXP _edgeBelI, _temp;
		PROTECT(_edgeBelI = NEW_LIST(crf.nEdges));
		for (int i = 0; i < crf.nEdges; i++)
		{
			SET_VECTOR_ELT(_edgeBelI, i, _temp = AS_NUMERIC(GetListElement(_edgeBel, i)));
			edgeBel[i] = NUMERIC_POINTER(_temp);
		}

		*nll += NUMERIC_POINTER(AS_NUMERIC(GetListElement(_belief, "logZ")))[0] - crf.Get_LogPotential(y);

    if (!isNull(_nodeFeaN))
    {
  		PROTECT(_nodeFeaN = AS_NUMERIC(_nodeFeaN));
  		double *nodeFea = NUMERIC_POINTER(_nodeFeaN);
  		if (!ISNAN(nodeFea[0]))
  		{
  			for (int i = 0; i < crf.nNodes; i++)
  			{
  				int s = y[i];
  				for (int j = 0; j < nNodeFea; j++)
  				{
  					double f = nodeFea[j + nNodeFea * i];
  					if (f != 0)
  					{
  						for (int k = 0; k < crf.nStates[i]; k++)
  						{
  							int p = nodePar[i + crf.nNodes * (k + crf.maxState * j)] - 1;
  							if (p >= 0 && p < nPar)
  							{
  								if (k == s)
  								{
  									gradient[p] -= f;
  								}
  								gradient[p] += f * nodeBel[i + crf.nNodes * k];
  							}
  						}
  					}
  				}
  			}
  		}
      UNPROTECT(1);
    }

    if (!isNull(_edgeFeaN))
    {
  		PROTECT(_edgeFeaN = AS_NUMERIC(_edgeFeaN));
  		double *edgeFea = NUMERIC_POINTER(_edgeFeaN);
  		if (!ISNAN(edgeFea[0]))
  		{
  			for (int i = 0; i < crf.nEdges; i++)
  			{
  				int s = y[crf.EdgesBegin(i)] + crf.nStates[crf.EdgesBegin(i)] * y[crf.EdgesEnd(i)];
  				for (int j = 0; j < nEdgeFea; j++)
  				{
  					double f = edgeFea[j + nEdgeFea * i];
  					if (f != 0)
  					{
  						for (int k = 0; k < crf.nEdgeStates[i]; k++)
  						{
  							int p = edgePar[i][k + crf.nEdgeStates[i] * j] - 1;
  							if (p >= 0 && p < nPar)
  							{
  								if (k == s)
  								{
  									gradient[p] -= f;
  								}
  								gradient[p] += f * edgeBel[i][k];
  							}
  						}
  					}
  				}
  			}
  		}
      UNPROTECT(1);
    }

		if (!isNull(_nodeExtN) && isNewList(_nodeExtN))
		{
			for (int i = 0; i < nPar; i++)
			{
				SEXP _nodeExtI = GetListElement(_nodeExtN, i);
        if (!isNull(_nodeExtI))
        {
  				PROTECT(_nodeExtI = AS_NUMERIC(_nodeExtI));
  				double *nodeExt = NUMERIC_POINTER(_nodeExtI);
  				if (!ISNAN(nodeExt[0]))
  				{
  					for (int j = 0; j < crf.nNodes; j++)
  					{
  						int s = y[j];
  						for (int k = 0; k < crf.nStates[j]; k++)
  						{
  							double f = nodeExt[j + crf.nNodes * k];
  							if (k == s)
  							{
  								gradient[i] -= f;
  							}
  							gradient[i] += f * nodeBel[j + crf.nNodes * k];
  						}
  					}
  				}
          UNPROTECT(1);
        }
			}
		}

		if (!isNull(_edgeExtN) && isNewList(_edgeExtN))
		{
			for (int i = 0; i < nPar; i++)
			{
				SEXP _edgeExtI = GetListElement(_edgeExtN, i);
				if (!isNull(_edgeExtI) && isNewList(_edgeExtI))
				{
					for (int j = 0; j < crf.nEdges; j++)
					{
						SEXP _edgeExtII = GetListElement(_edgeExtI, j);
            if (!isNull(_edgeExtII))
            {
  						PROTECT(_edgeExtII = AS_NUMERIC(_edgeExtII));
  						double *edgeExt = NUMERIC_POINTER(_edgeExtII);
  						if (!ISNAN(edgeExt[0]))
  						{
  							int s = y[crf.EdgesBegin(j)] + crf.nStates[crf.EdgesBegin(j)] * y[crf.EdgesEnd(j)];
  							for (int k = 0; k < crf.nEdgeStates[j]; k++)
  							{
  								double f = edgeExt[k];
  								if (k == s)
  								{
  									gradient[i] -= f;
  								}
  								gradient[i] += f * edgeBel[j][k];
  							}
  						}
              UNPROTECT(1);
            }
					}
				}
			}
		}

		UNPROTECT(3);
	}

	UNPROTECT(4);

	return(_nll);
}
コード例 #17
0
ファイル: Train.cpp プロジェクト: rforge/crf
SEXP CRF_Update(SEXP _crf, SEXP _nodeFea, SEXP _edgeFea, SEXP _nodeExt, SEXP _edgeExt)
{
	CRF crf(_crf);
	crf.Update_Pot(_nodeFea, _edgeFea, _nodeExt, _edgeExt);
	return (_crf);
}
コード例 #18
0
ファイル: test.cpp プロジェクト: ThomasWDonnelly/xbox360-emu
/* Get register by name */
Test::Register Test::getRegister(ppc::Interpreter::State &state, const std::string &name)
{
   std::smatch smatch;

   /* General Purpose Register */
   std::regex gpr("%r([0-9]+)");

   if (std::regex_match(name, smatch, gpr) && smatch.size() == 2) {
      auto reg = std::stol(smatch[1].str());

      if (reg >= 0 && reg <= 31) {
         return Register(RegisterType::Integer64, &state.reg.gpr[reg]);
      }
   }

   /* FPU Register */
   std::regex fpr("%f([0-9]+)");

   if (std::regex_match(name, smatch, fpr) && smatch.size() == 2) {
      auto reg = std::stol(smatch[1].str());

      if (reg >= 0 && reg <= 31) {
         return Register(RegisterType::Double64, &state.reg.fpr[reg]);
      }
   }

   /* XER Link Register */
   if (name.compare("%lr") == 0) {
      return Register(RegisterType::Integer64, &state.reg.lr);
   }

   /* XER Carry */
   if (name.compare("%xer[ca]") == 0) {
      return Register(RegisterType::BitField64, little_endian::make_bit_field(state.reg.xer.value, 34, 35));
   }

   /* XER Overflow */
   if (name.compare("%xer[ov]") == 0) {
      return Register(RegisterType::BitField64, little_endian::make_bit_field(state.reg.xer.value, 33, 34));
   }

   /* Condition Register Field */
   std::regex crf("%crf([0-9]+)");

   if (std::regex_match(name, smatch, crf) && smatch.size() == 2) {
      auto field = std::stol(smatch[1].str());

      if (field >= 0 && field <= 8) {
         return Register(RegisterType::BitField32, state.reg.cr.crn[field]);
      }
   }

   /* Condition Register Bit */
   std::regex crb("%crb([0-9]+)");

   if (std::regex_match(name, smatch, crb) && smatch.size() == 2) {
      auto bit = std::stol(smatch[1].str());

      if (bit >= 0 && bit <= 31) {
         return Register(RegisterType::BitField32, little_endian::make_bit_field(state.reg.cr.value, bit, bit));
      }
   }

   return Register();
}