Example #1
0
void MayaMeshWriter::writeColor()
{

    MStatus status = MS::kSuccess;
    MFnMesh lMesh( mDagPath, &status );
    if ( !status )
    {
        MGlobal::displayError(
            "MFnMesh() failed for MayaMeshWriter::writeColor" );
        return;
    }

    //Write colors
    std::vector<Alembic::AbcGeom::OC4fGeomParam>::iterator rgbaIt;
    std::vector<Alembic::AbcGeom::OC4fGeomParam>::iterator rgbaItEnd;
    rgbaIt = mRGBAParams.begin();
    rgbaItEnd = mRGBAParams.end();

    for (; rgbaIt != rgbaItEnd; ++rgbaIt)
    {
        std::vector<float> colors;
        std::vector< Alembic::Util::uint32_t > colorIndices;

        MString colorSetName(rgbaIt->getName().c_str());
        getColorSet(lMesh, &colorSetName, true, colors, colorIndices);

        //cast the vector to the sample type
        Alembic::AbcGeom::OC4fGeomParam::Sample samp(
            Alembic::Abc::C4fArraySample(
                (const Imath::C4f *) &colors.front(), colors.size()/4),
            Alembic::Abc::UInt32ArraySample(colorIndices),
            Alembic::AbcGeom::kFacevaryingScope );

        rgbaIt->set(samp);
    }

    std::vector<Alembic::AbcGeom::OC3fGeomParam>::iterator rgbIt;
    std::vector<Alembic::AbcGeom::OC3fGeomParam>::iterator rgbItEnd;
    rgbIt = mRGBParams.begin();
    rgbItEnd = mRGBParams.end();
    for (; rgbIt != rgbItEnd; ++rgbIt)
    {

        std::vector<float> colors;
        std::vector< Alembic::Util::uint32_t > colorIndices;

        MString colorSetName(rgbIt->getName().c_str());
        getColorSet(lMesh, &colorSetName, false, colors, colorIndices);

        //cast the vector to the sample type
        Alembic::AbcGeom::OC3fGeomParam::Sample samp(
            Alembic::Abc::C3fArraySample(
                (const Imath::C3f *) &colors.front(), colors.size()/3),
            Alembic::Abc::UInt32ArraySample(colorIndices),
            Alembic::AbcGeom::kFacevaryingScope);

        rgbIt->set(samp);
    }
}
//Add a training sample
void LearningInterface::addTrainingSample(FeatureSet &features, double label)
{
    sample_type samp;
//    samp(0) = (double)features.bandwidth();
//    samp(1) = (double)features.contentType();
    for(int i = 0; i < FEATURE_SET_NUM_FEATURES; i++)
        samp(i) = features.getFeatureByIndex((FeatureSetIndexType) i);

    m_training_set.push_back(samp);
    if(label == 1.0)
        m_labels.push_back(+1);
    else
        m_labels.push_back(-1);

    m_num_training_samples++;

    //Test to see if user falls into only one class
    if(m_one_class_only)
    {
        //This is the first sample
        if(m_single_class_val == -2)
        {
            //Set this as the single class value
            m_single_class_val = (int) label;
        }
        //See if this is the other class
        else if((int)label != m_single_class_val)
        {
            //Lower flags
            m_one_class_only = false;
        }
    }
}
Example #3
0
// write the frame ranges and statistic string on the root
// Also call the post callbacks
void AbcWriteJob::postCallback(double iFrame)
{
	std::string statsStr = "";

	addToString(statsStr, "TransStaticNum", mStats.mTransStaticNum);
	addToString(statsStr, "TransAnimNum", mStats.mTransAnimNum);
	addToString(statsStr, "TransColNum", mStats.mTransColNum);

	if (statsStr.length() > 0)
	{
		Alembic::Abc::OStringProperty stats(mRoot.getTop().getProperties(),
			"statistics");
		stats.set(statsStr);
	}

	if (mTransTimeIndex != 0)
	{
		MString propName;
		propName += static_cast<int>(mTransTimeIndex);
		propName += ".samples";
		Alembic::Abc::OUInt32Property samp(mRoot.getTop().getProperties(),
			propName.asChar());
		samp.set(mTransSamples);
	}

	MBoundingBox bbox;

	processCallback(mArgs.melPostCallback, true, iFrame, bbox);
	processCallback(mArgs.pythonPostCallback, false, iFrame, bbox);
}
Example #4
0
File: ptr.c Project: shylesh/mycode
int main()
{

	char *src = (char *) malloc (3);
	src = "hi";

	samp(&src);

	printf ("%s", src);
}
//-*****************************************************************************
// much like lib/Alembic/Abc/OTypedProperty.cpp, this is just a compile test,
// due to the implementation being in the .h file, due to templates.
void __testOGeomParamCompile( Abc::OCompoundProperty &iParent )
{
    OV2fGeomParam uvs( iParent, "uv", false, kVertexScope, 1 );

    std::vector<V2f> vec;

    vec.push_back( V2f( 1.0f, 2.0f ) );

    V2fArraySample val( vec );

    OV2fGeomParam::Sample samp( val, kUnknownScope );

    uvs.set( samp );
}
Example #6
0
/* PARAM width, height : width and height of image plane
   PARAM depth : the depth of recursion
   PARAM outputFileName : the output file name that film needs to create the PNG output file.
   PARAM Sampler : needs Sampler object to get access to a Sample and the Camera */
void render(int width, int height, int depth, std::string outputFileName, 
	    Sampler *sampler){

  //Initializing a sample object to cam.ul coordinates:
  Sample samp(sampler->camera->ul.at(0), sampler->camera->ul.at(1), sampler->camera->ul.at(2));

  for(int j = 0; j < height; j++) {
    for(int i = 0; i < width; i++) {
      //using GenerateRay to create a ray shooting to the sample position
      Ray outRay = sampler->camera->generateRay(samp);

      //getting the rgb value returned by calling raytracer.trace
      samp.rgb = sampler->raytracer->trace(outRay, 5);

      // Progress
      if (i + j * width == 0)
	printf("...0%%  done...\n");
      if (i + j * width == (height*width)/5)
	printf("...20%% done...\n");
      if (i + j * width == (2*height*width)/5)
	printf("...40%% done...\n");
      if (i + j * width == (3*height*width)/5)
	printf("...60%% done...\n");
      if (i + j * width == (4*height*width)/5)
	printf("...80%% done...\n");
      
      //Passing the rgb value to film (this rgb value will to be saved in the Film.bitmap)
      sampler->film->setPixel(i, height - 1 - j, samp.rgb);

      // Increment samp.x, samp.y, and samp.z by cam->right
      samp.x += sampler->camera->right.at(0);
      samp.y += sampler->camera->right.at(1);
      samp.z += sampler->camera->right.at(2);
    }

    // Reset the i portion
    samp.x -= sampler->camera->right.at(0) * width;
    samp.y -= sampler->camera->right.at(1) * width;
    samp.z -= sampler->camera->right.at(2) * width;

    // Increment samp.x, samp.y, and samp.z by cam->down
    samp.x += sampler->camera->down.at(0);
    samp.y += sampler->camera->down.at(1);
    samp.z += sampler->camera->down.at(2);
  }

  /* film->outputImage is called to print the image and complete the program.
   * the bitmap should be completely filled by now */
  sampler->film->outputImage(outputFileName);
}
void MayaMeshWriter::writePoly(
    const Alembic::AbcGeom::OV2fGeomParam::Sample & iUVs)
{
    MStatus status = MS::kSuccess;
    MFnMesh lMesh( mDagPath, &status );
    if ( !status )
    {
        MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" );
    }


    std::vector<float> points;
    std::vector<Alembic::Util::int32_t> facePoints;
    std::vector<Alembic::Util::int32_t> pointCounts;

    fillTopology(points, facePoints, pointCounts);

    Alembic::AbcGeom::ON3fGeomParam::Sample normalsSamp;
    std::vector<float> normals;
    getPolyNormals(normals);
    if (!normals.empty())
    {
        normalsSamp.setScope( Alembic::AbcGeom::kFacevaryingScope );
        normalsSamp.setVals(Alembic::AbcGeom::N3fArraySample(
            (const Imath::V3f *) &normals.front(), normals.size() / 3));
    }

    Alembic::AbcGeom::OPolyMeshSchema::Sample samp(
        Alembic::Abc::V3fArraySample((const Imath::V3f *)&points.front(),
            points.size() / 3),
        Alembic::Abc::Int32ArraySample(facePoints),
        Alembic::Abc::Int32ArraySample(pointCounts), iUVs, normalsSamp);

    // if this mesh is animated, write out the animated geometry
    if (mIsGeometryAnimated)
    {
        mPolySchema.set(samp);
    }
    else
    {
        mPolySchema.set(samp);
    }
    writeColor();
}
Example #8
0
// generate samples from a distribution using inverse CDF sampling
// pdf input is expected to be an Nx2 matrix with col 1 = values and col 2 = probabilities of those values
// step size scales pdf to equal 1, set equal 
Matrix invCDFsample(const int& samples, const double& step,
					const Matrix& pdf)
{

	Matrix samp(samples,1);
	double tempSamp = 0.;
	int j = 0;

	// integrate to generate CDF
	Matrix CDF(pdf.rows(),1);
	CDF[0][0] = pdf[0][1]*step;
	for(int i=0;i<CDF.rows()-1;i++)
	{
    //cout << "CDF[i] = " << CDF[i][0] << " pdf[i] = " << pdf[i][1] << endl;
    CDF[i+1][0] = CDF[i][0] + pdf[i+1][1];	
    //cout << "CDF[i+1] = " << CDF[i+1][0] << endl;
  }

	// multiply by step size to scale integral correctly
	CDF = CDF*step;
	//CDF.print();
  
	// choose sample from uniform generator according to CDF 
	for(int i=0;i<samples;i++)
	{
		j = 0;
		tempSamp = rvStdUniform();
		
		while( CDF[j][0] < tempSamp )
		{
			j++;
		}
		
		if( j == 0 )
			samp[i][0] = pdf[j][0];
		else
			samp[i][0] = (pdf[j-1][0]+pdf[j][0])/2;	
	}
	
	return samp;
	
}
Example #9
0
int main (int argc, char * argv[]) {

  /* System parameters */
  int ** F;       /* The 2D array of spins */
  int L = 1000;     /* The sidelength of the array */
  int N;          /* The total number of spins = L*L */
  double T = 1.0; /* Dimensionless temperature = (T*k)/J */

  /* Run parameters */
  int nCycles = 1000000; /* number of MC cycles to run; one cycle is N 
			    consecutive attempted spin flips */
  int fSamp = 1000;      /* Frequency with which samples are taken */

  /* Computational variables */
  int nSamp;      /* Number of samples taken */
  int de;         /* energy change due to flipping a spin */
  double b;       /* Boltzman factor */
  double x;       /* random number */
  int i,j,a,c;    /* loop counters */

  /* Observables */
  double s=0.0, ssum=0.0;    /* average magnetization */
  double e=0.0, esum=0.0;    /* average energy per spin */

  /* This line creates a random number generator
     of the "Mersenne Twister" type, which is much
     better than the default random number generator. */
  gsl_rng * r = gsl_rng_alloc(gsl_rng_mt19937);
  unsigned long int Seed = 23410981;

  /* Here we parse the command line arguments */
  for (i=1;i<argc;i++) {
    if (!strcmp(argv[i],"-L")) L=atoi(argv[++i]);
    else if (!strcmp(argv[i],"-T")) T=atof(argv[++i]);
    else if (!strcmp(argv[i],"-nc")) nCycles = atoi(argv[++i]);
    else if (!strcmp(argv[i],"-fs")) fSamp = atoi(argv[++i]);
    else if (!strcmp(argv[i],"-s")) Seed = (unsigned long)atoi(argv[++i]);
  }
  
  /* Output some initial information */
  /*fprintf(stdout,"# command: ");
  for (i=0;i<argc;i++) fprintf(stdout,"%s ",argv[i]);
  fprintf(stdout,"\n");
  fprintf(stdout,"# ISING simulation, NVT Metropolis Monte Carlo\n");
  fprintf(stdout,"# L = %i, T = %.3lf, nCycles %i, fSamp %i, Seed %u\n",
	  L,T,nCycles,fSamp,Seed);*/

  /* Seed the random number generator */
  gsl_rng_set(r,Seed);

  /* Compute the number of spins */
  N=L*L;

  /* Allocate memory for the system */
  F=(int**)malloc(L*sizeof(int*));
  for (i=0;i<L;i++) F[i]=(int*)malloc(L*sizeof(int));

  /* Generate an initial state */
  init(F,L,r);

  /* For computational efficiency, convert T to reciprocal T */
  T=1.0/T;

  s = 0.0;
  e = 0.0;
  nSamp = 0;

  for (c=0;c<nCycles;c++) {
    /* Make N flip attempts */
    #pragma omp parallel for private(i,j,de,b,x) shared(F)
    for (a=0;a<N;a++) {
      /* randomly select a spin */
      i=(int)gsl_rng_uniform_int(r,L);
      j=(int)gsl_rng_uniform_int(r,L);
      /* get the "new" energy as the incremental change due
         to flipping spin (i,j) */
      de = E(F,L,i,j);
      /* compute the Boltzmann factor; recall T is now
         reciprocal temperature */
      b = exp(de*T);
      /* pick a random number between 0 and 1 */
      x = gsl_rng_uniform(r);
      /* accept or reject this flip */
      if (x<b) { /* accept */
	/* flip it */
	F[i][j]*=-1;
      }
    }
    /* Sample and accumulate averages */
    if (!(c%fSamp)) {
      samp(F,L,&s,&e);
      //fprintf(stdout,"%i %.5le %.5le\n",c,s,e);
      fflush(stdout);
      ssum+=s;
      esum+=e;
      nSamp++;
    }
    #pragma omp barrier
  }
  fprintf(stdout,"# The average magnetization is %.5lf\n",ssum/nSamp);
  fprintf(stdout,"# The average energy per spin is %.5lf\n",esum/nSamp);
  fprintf(stdout,"# Program ends.\n");
}
Example #10
0
void hist2(double M[16], unsigned char g[], unsigned char f[], const int dg[3], const int df[3], 
double H[65536], float s[3])
{
	static float ran[] = {0.656619,0.891183,0.488144,0.992646,0.373326,0.531378,0.181316,0.501944,0.422195,
	                      0.660427,0.673653,0.95733,0.191866,0.111216,0.565054,0.969166,0.0237439,0.870216,
	                      0.0268766,0.519529,0.192291,0.715689,0.250673,0.933865,0.137189,0.521622,0.895202,
	                      0.942387,0.335083,0.437364,0.471156,0.14931,0.135864,0.532498,0.725789,0.398703,
	                      0.358419,0.285279,0.868635,0.626413,0.241172,0.978082,0.640501,0.229849,0.681335,
	                      0.665823,0.134718,0.0224933,0.262199,0.116515,0.0693182,0.85293,0.180331,0.0324186,
	                      0.733926,0.536517,0.27603,0.368458,0.0128863,0.889206,0.866021,0.254247,0.569481,
	                      0.159265,0.594364,0.3311,0.658613,0.863634,0.567623,0.980481,0.791832,0.152594,
	                      0.833027,0.191863,0.638987,0.669,0.772088,0.379818,0.441585,0.48306,0.608106,
	                      0.175996,0.00202556,0.790224,0.513609,0.213229,0.10345,0.157337,0.407515,0.407757,
	                      0.0526927,0.941815,0.149972,0.384374,0.311059,0.168534,0.896648};
	int iran=0;
	float z;
	for(z=1.0; z<dg[2]-s[2]; z+=s[2])
	{
		float y;
		for(y=1.0; y<dg[1]-s[1]; y+=s[1])
		{
			float x;
			for(x=1.0; x<dg[0]-s[0]; x+=s[0])
			{
				float rx, ry, rz, xp, yp, zp;

				rx  = x + ran[iran = (iran+1)%97]*s[0];
				ry  = y + ran[iran = (iran+1)%97]*s[1];
				rz  = z + ran[iran = (iran+1)%97]*s[2];

				xp  = M[0]*rx + M[4]*ry + M[ 8]*rz + M[12];
				yp  = M[1]*rx + M[5]*ry + M[ 9]*rz + M[13];
				zp  = M[2]*rx + M[6]*ry + M[10]*rz + M[14];

				if (zp>=1.0 && zp<df[2] && yp>=1.0 && yp<df[1] && xp>=1.0 && xp<df[0])
				{
					float vf;
					int   ivf, ivg;
					vf  = samp(df, f, xp,yp,zp);
					ivf = floor(vf);
					ivg = floor(samp(dg, g, rx,ry,rz)+0.5);
					H[ivf+ivg*256] += (1-(vf-ivf));
					if (ivf<255)
						H[ivf+1+ivg*256] += (vf-ivf);

					/*
					float vf, vg;
					int ivf, ivg;
					vg  = samp(dg, g, rx,ry,rz);
					vf  = samp(df, f, xp,yp,zp);
					ivg = floor(vg);
					ivf = floor(vf);
					H[ivf+ivg*256] += (1-(vf-ivf))*(1-(vg-ivg));
					if (ivf<255)
						H[ivf+1+ivg*256] += (vf-ivf)*(1-(vg-ivg));
					if (ivg<255)
					{
						H[ivf+(ivg+1)*256] += (1-(vf-ivf))*(vg-ivg);
						if (ivf<255)
							H[ivf+1+(ivg+1)*256] += (vf-ivf)*(vg-ivg);
					}
					*/
				}
			}
		}
	}
}
Example #11
0
	void Recoloring::Recolor(Mat& _source, Mat& source_mask, Mat& _target, Mat& target_mask) {
		Mat source; _source.convertTo(source,CV_32F,1.0/255.0);
		Mat target; _target.convertTo(target,CV_32F,1.0/255.0);

		CvEM source_model,target_model;

		//cvtColor(target,target,CV_BGR2Lab);
		//cvtColor(source,source,CV_BGR2Lab);

		TrainGMM(source_model,source,source_mask);
		TrainGMM(target_model,target,target_mask);

		vector<int> match = MatchGaussians(source_model,target_model);
		

		Mat target_32f; 
		//if(target.type() != CV_32F)
		//	target.convertTo(target_32f,CV_32F,1.0/255.0);
		//else
		target.copyTo(target_32f);

		const CvMat** target_covs = target_model.get_covs();
		const CvMat** source_covs = source_model.get_covs();
		Mat sMu(source_model.get_means()); Mat sMu_64f; sMu.convertTo(sMu_64f,CV_64F);
		Mat tMu(target_model.get_means()); Mat tMu_64f; tMu.convertTo(tMu_64f,CV_64F);

		int num_g = target_model.get_nclusters();

		Mat pr; Mat samp(1,3,CV_32FC1);
		for(int y=0;y<target.rows;y++) {
			Vec3f* row = target_32f.ptr<Vec3f>(y);
			uchar* mask_row = target_mask.ptr<uchar>(y);
			for(int x=0;x<target.cols;x++) {
				if(mask_row[x] > 0) {
					memcpy(samp.data,&(row[x][0]),3*sizeof(float)); 
					float res = target_model.predict(samp,&pr);
					
					//cout << res << ":" << ((float*)pr.data)[0] << "," <<
					//	((float*)pr.data)[1] << "," <<
					//	((float*)pr.data)[2] << "," <<
					//	((float*)pr.data)[3] << "," <<
					//	((float*)pr.data)[4] << "," << endl;

					Mat samp_64f; samp.convertTo(samp_64f,CV_64F);

					//From Shapira09: Xnew = Sum_i { pr(i) * Sigma_source_i * (Sigma_target_i)^-1 * (x - mu_target) + mu_source }
					Mat Xnew(1,3,CV_64FC1,Scalar(0));
					for(int i=0;i<num_g;i++) {
						if(((float*)pr.data)[i] <= 0) continue;
						Mat A = /*Mat(*/
							//Mat(target_covs[i]) * 
							//Mat(source_covs[match[i]]).inv() *
							Mat(samp_64f - tMu_64f(Range(i,i+1),Range(0,3))).t();
						Mat B = sMu_64f(Range(match[i],match[i]+1),Range(0,3)).t();
						Xnew += Mat((A + B) * (double)(((float*)pr.data)[i])).t();
					}

					Mat _tmp; Xnew.convertTo(_tmp,CV_32F);

					//allow for mask with alpha
					float* _d = ((float*)_tmp.data);
					float alpha = mask_row[x] / 255.0f;
					for(int cl=0;cl<3;cl++)
						_d[cl] = _d[cl] * (alpha) + row[x][cl] * (1-alpha);
					
					memcpy(&(row[x][0]),_tmp.data,sizeof(float)*3);
				}
			}
		}

		//cvtColor(target,target,CV_Lab2BGR);
		//cvtColor(source,source,CV_Lab2BGR);
		//cvtColor(target_32f,target_32f,CV_Lab2BGR);

		if(!this->m_p.no_gui) {
			namedWindow("orig target");
			imshow("orig target",target);
			namedWindow("source orig");
			imshow("source orig",source);
			namedWindow("source masked");
			Mat _tmp_S; source.copyTo(_tmp_S,source_mask);
			imshow("source masked",_tmp_S);
			namedWindow("dest target");
			imshow("dest target",target_32f);

			waitKey(this->m_p.wait_time);
		}

		target_32f.convertTo(_target,CV_8UC3,255.0);
	}
// write the frame ranges and statistic string on the root
// Also call the post callbacks
void AbcWriteJob::postCallback(double iFrame)
{
    std::string statsStr = "";

    addToString(statsStr, "SubDStaticNum", mStats.mSubDStaticNum);
    addToString(statsStr, "SubDAnimNum", mStats.mSubDAnimNum);
    addToString(statsStr, "SubDStaticCVs", mStats.mSubDStaticCVs);
    addToString(statsStr, "SubDAnimCVs", mStats.mSubDAnimCVs);
    addToString(statsStr, "SubDStaticFaces", mStats.mSubDStaticFaces);
    addToString(statsStr, "SubDAnimFaces", mStats.mSubDAnimFaces);

    addToString(statsStr, "PolyStaticNum", mStats.mPolyStaticNum);
    addToString(statsStr, "PolyAnimNum", mStats.mPolyAnimNum);
    addToString(statsStr, "PolyStaticCVs", mStats.mPolyStaticCVs);
    addToString(statsStr, "PolyAnimCVs", mStats.mPolyAnimCVs);
    addToString(statsStr, "PolyStaticFaces", mStats.mPolyStaticFaces);
    addToString(statsStr, "PolyAnimFaces", mStats.mPolyAnimFaces);

    addToString(statsStr, "CurveStaticNum", mStats.mCurveStaticNum);
    addToString(statsStr, "CurveStaticCurves", mStats.mCurveStaticCurves);
    addToString(statsStr, "CurveAnimNum", mStats.mCurveAnimNum);
    addToString(statsStr, "CurveAnimCurves", mStats.mCurveAnimCurves);
    addToString(statsStr, "CurveStaticCVs", mStats.mCurveStaticCVs);
    addToString(statsStr, "CurveAnimCVs", mStats.mCurveAnimCVs);

    addToString(statsStr, "PointStaticNum", mStats.mPointStaticNum);
    addToString(statsStr, "PointAnimNum", mStats.mPointAnimNum);
    addToString(statsStr, "PointStaticCVs", mStats.mPointStaticCVs);
    addToString(statsStr, "PointAnimCVs", mStats.mPointAnimCVs);

    addToString(statsStr, "NurbsStaticNum", mStats.mNurbsStaticNum);
    addToString(statsStr, "NurbsAnimNum", mStats.mNurbsAnimNum);
    addToString(statsStr, "NurbsStaticCVs", mStats.mNurbsStaticCVs);
    addToString(statsStr, "NurbsAnimCVs", mStats.mNurbsAnimCVs);

    addToString(statsStr, "TransStaticNum", mStats.mTransStaticNum);
    addToString(statsStr, "TransAnimNum", mStats.mTransAnimNum);

    addToString(statsStr, "LocatorStaticNum", mStats.mLocatorStaticNum);
    addToString(statsStr, "LocatorAnimNum", mStats.mLocatorAnimNum);

    addToString(statsStr, "CameraStaticNum", mStats.mCameraStaticNum);
    addToString(statsStr, "CameraAnimNum", mStats.mCameraAnimNum);

    if (statsStr.length() > 0)
    {
        Alembic::Abc::OStringProperty stats(mRoot.getTop().getProperties(),
            "statistics");
        stats.set(statsStr);
    }

    if (mTransTimeIndex != 0)
    {
        MString propName;
        propName += static_cast<int>(mTransTimeIndex);
        propName += ".samples";
        Alembic::Abc::OUInt32Property samp(mRoot.getTop().getProperties(),
            propName.asChar());
        samp.set(mTransSamples);
    }

    if (mShapeTimeIndex != 0 && mShapeTimeIndex != mTransTimeIndex)
    {
        MString propName;
        propName += static_cast<int>(mShapeTimeIndex);
        propName += ".samples";
        Alembic::Abc::OUInt32Property samp(mRoot.getTop().getProperties(),
            propName.asChar());
        samp.set(mShapeSamples);
    }

    MBoundingBox bbox;

    if (mArgs.melPostCallback.find("#BOUNDS#") != std::string::npos ||
        mArgs.pythonPostCallback.find("#BOUNDS#") != std::string::npos ||
        mArgs.melPostCallback.find("#BOUNDSARRAY#") != std::string::npos ||
        mArgs.pythonPostCallback.find("#BOUNDSARRAY#") != std::string::npos)
    {
        util::ShapeSet::const_iterator it = mArgs.dagPaths.begin();
        const util::ShapeSet::const_iterator end = mArgs.dagPaths.end();
        for (; it != end; it ++)
        {
            mCurDag = *it;

            MMatrix eMInvMat;
            if (mArgs.worldSpace)
            {
                eMInvMat.setToIdentity();
            }
            else
            {
                eMInvMat = mCurDag.exclusiveMatrixInverse();
            }

            bbox.expand(getBoundingBox(iFrame, eMInvMat));
        }
    }

    processCallback(mArgs.melPostCallback, true, iFrame, bbox);
    processCallback(mArgs.pythonPostCallback, false, iFrame, bbox);
}
Example #13
0
void MayaMeshWriter::writeSubD(
    const Alembic::AbcGeom::OV2fGeomParam::Sample & iUVs)
{
    MStatus status = MS::kSuccess;
    MFnMesh lMesh( mDagPath, &status );
    if ( !status )
    {
        MGlobal::displayError( "MFnMesh() failed for MayaMeshWriter" );
    }

    std::vector<float> points;
    std::vector<Alembic::Util::int32_t> facePoints;
    std::vector<Alembic::Util::int32_t> pointCounts;

    fillTopology(points, facePoints, pointCounts);

    Alembic::AbcGeom::OSubDSchema::Sample samp(
        Alembic::AbcGeom::V3fArraySample((const Imath::V3f *)&points.front(),
            points.size() / 3),
        Alembic::Abc::Int32ArraySample(facePoints),
        Alembic::Abc::Int32ArraySample(pointCounts));
    samp.setUVs( iUVs );

    MPlug plug = lMesh.findPlug("faceVaryingInterpolateBoundary");
    if (!plug.isNull())
        samp.setFaceVaryingInterpolateBoundary(plug.asInt());

    plug = lMesh.findPlug("interpolateBoundary");
    if (!plug.isNull())
        samp.setInterpolateBoundary(plug.asInt());

    plug = lMesh.findPlug("faceVaryingPropagateCorners");
    if (!plug.isNull())
        samp.setFaceVaryingPropagateCorners(plug.asInt());

    std::vector <Alembic::Util::int32_t> creaseIndices;
    std::vector <Alembic::Util::int32_t> creaseLengths;
    std::vector <float> creaseSharpness;

    std::vector <Alembic::Util::int32_t> cornerIndices;
    std::vector <float> cornerSharpness;

    MUintArray edgeIds;
    MDoubleArray creaseData;
    if (lMesh.getCreaseEdges(edgeIds, creaseData) == MS::kSuccess)
    {
        unsigned int numCreases = creaseData.length();
        creaseIndices.resize(numCreases * 2);
        creaseLengths.resize(numCreases, 2);
        creaseSharpness.resize(numCreases);
        for (unsigned int i = 0; i < numCreases; ++i)
        {
            int verts[2];
            lMesh.getEdgeVertices(edgeIds[i], verts);
            creaseIndices[2 * i] = verts[0];
            creaseIndices[2 * i + 1] = verts[1];
            creaseSharpness[i] = static_cast<float>(creaseData[i]);
        }

        samp.setCreaseIndices(Alembic::Abc::Int32ArraySample(creaseIndices));
        samp.setCreaseLengths(Alembic::Abc::Int32ArraySample(creaseLengths));
        samp.setCreaseSharpnesses(
            Alembic::Abc::FloatArraySample(creaseSharpness));
    }

    MUintArray cornerIds;
    MDoubleArray cornerData;
    if (lMesh.getCreaseVertices(cornerIds, cornerData) == MS::kSuccess)
    {
        unsigned int numCorners = cornerIds.length();
        cornerIndices.resize(numCorners);
        cornerSharpness.resize(numCorners);
        for (unsigned int i = 0; i < numCorners; ++i)
        {
            cornerIndices[i] = cornerIds[i];
            cornerSharpness[i] = static_cast<float>(cornerData[i]);
        }
        samp.setCornerSharpnesses(
            Alembic::Abc::FloatArraySample(cornerSharpness));

        samp.setCornerIndices(
            Alembic::Abc::Int32ArraySample(cornerIndices));
    }

#if MAYA_API_VERSION >= 201100
    MUintArray holes = lMesh.getInvisibleFaces();
    unsigned int numHoles = holes.length();
    std::vector <Alembic::Util::int32_t> holeIndices(numHoles);
    for (unsigned int i = 0; i < numHoles; ++i)
    {
        holeIndices[i] = holes[i];
    }

    if (!holeIndices.empty())
    {
        samp.setHoles(holeIndices);
    }
#endif

    mSubDSchema.set(samp);
    writeColor();
    writeUVSets();
}
Example #14
0
void squaring(int dm[], int k, int save_transf, double b[], double A[], double t0[], double t1[], double J0[], double J1[])
{
    int i, j, m = dm[0]*dm[1];
    double *ptr = t0;

    for(i=0; i<k; i++)
    {
        double *buf1, *buf2;
        buf1 = t1; /* Re-use some memory */
        buf2 = J1;

        for(j=0; j<m; j++)
        {
            double tmp00, tmp01, tmp11, tmp1, tmp2, tmp3, tmp4;
            double x, y;
            double j11, j21, j12, j22, dt;

            x   = t0[j  ]-1.0;
            y   = t0[j+m]-1.0;
            j11 = J0[j  ]; j12 = J0[j+2*m];
            j21 = J0[j+m]; j22 = J0[j+3*m];
            dt  = j11*j22 - j12*j21;

         /* if (dt < 1e-9) dt = 1e-9;
            if (dt > 1e9 ) dt = 1e9; */

            tmp1      = samp(dm,b  ,x,y);
            tmp2      = samp(dm,b+m,x,y);

            buf1[j  ] = dt*(tmp1*j11+tmp2*j21);
            buf1[j+m] = dt*(tmp1*j12+tmp2*j22);

            tmp00 = samp(dm,A    ,x,y);
            tmp11 = samp(dm,A+  m,x,y);
            tmp01 = samp(dm,A+2*m,x,y);

            tmp1  = tmp00*j11+tmp01*j21;
            tmp2  = tmp01*j11+tmp11*j21;
            tmp3  = tmp00*j12+tmp01*j22;
            tmp4  = tmp01*j12+tmp11*j22;

         /* if (dt < 1e-9) dt = 1e-9; */
         /* if (dt > 1e9 ) dt = 1e9; */

            buf2[j    ] = dt*(tmp1*j11+tmp2*j21);
            buf2[j+  m] = dt*(tmp3*j12+tmp4*j22);
            buf2[j+2*m] = dt*(tmp1*j12+tmp2*j22);
        }
        for(j=0; j<2*m; j++) b[j] += buf1[j];
        for(j=0; j<3*m; j++) A[j] += buf2[j];

        if (save_transf || (i<k-1))
        {
            double *tmpp;
            composition_jacobian(dm, t0, J0, t0, J0, t1, J1);
            tmpp = t0; t0   = t1; t1   = tmpp;
            tmpp = J0; J0   = J1; J1   = tmpp;
        }
    }
    if (save_transf && ptr!=t0)
    {
        for(j=0; j<m*2; j++) t1[j] = t0[j];
        for(j=0; j<m*4; j++) J1[j] = J0[j];
    }
}
Example #15
0
int run_sampler(unsigned epochs,float alpha,unsigned batch_size){

    //load sampler
    string training_path = "PPAttachData/training.lemma";
    string param_path = "PPAttachData/wordsketches/";
    string vpath = param_path + string("vdistrib");
    string x1vpath = param_path + string("x1givenv");
    string pvpath = param_path + string("pgivenv");
    string x2vppath = param_path + string("x2givenvp");
    string px1path = param_path + string("pgivenx1");
    string x2x1ppath = param_path + string("x2givenx1p");  
    DataSampler samp(training_path.c_str(),
		   vpath.c_str(),
		   x1vpath.c_str(),
		   pvpath.c_str(),
		   x2vppath.c_str(),
		   px1path.c_str(),
		   x2x1ppath.c_str());

    //load dev and test
    PPADataEncoder dev_set("PPAttachData/devset.lemma");
    PPADataEncoder test_set("PPAttachData/test.lemma");

    //load Word vectors 
    Word2vec w2v;
    vector<string> wvdict;
    af::array w2v_embeddings;
    w2v.load_dictionary("PPAttachData/embeddings/deps.words.lemmatized");
    //w2v.filter(xdict);

    //make network
    vector<string> ydict;
    samp.getYdictionary(ydict);
    SymbolicFeedForwardNetwork<string,string> net;
    net.set_output_layer("loss",new SoftMaxLoss<string>(ydict));
    net.add_layer("top",new LinearLayer());  
    net.add_layer("hidden",new ReLUActivation(400));
    net.add_layer("A",new LinearLayer());
    net.add_input_layer("lookupA",new LinearLookup<string>(w2v.get_keys(),w2v.get_values(),4,false));
    net.connect_layers("loss","top");
    net.connect_layers("top","hidden");
    net.connect_layers("hidden","A");
    net.connect_layers("A","lookupA");

    for(int E = 0; E < epochs;++E){
      vector<string> ydata;
      vector<vector<string>> xdata;
      //af::timer start1 = af::timer::start();
      samp.generate_sample(ydata,xdata,batch_size);
      //printf("elapsed seconds (sampling): %g\n", af::timer::stop(start1));

      PPADataEncoder sampdata(ydata,xdata);
      vector<string> enc_ydata;
      vector<vector<string>> enc_xdata(1,vector<string>());
      sampdata.getYdata(enc_ydata);
      sampdata.getXdata(enc_xdata[0]);

      //af::timer start2 = af::timer::start();
      net.set_batch_data(enc_ydata,enc_xdata);
      float loss = net.train_one(alpha,true,true);
      //printf("elapsed seconds (backprop): %g\n", af::timer::stop(start2));


      if (E % 20 == 0){
	vector<string> devy;
	vector<vector<string>> devx(1,vector<string>());
	dev_set.getYdata(devy);	
	dev_set.getXdata(devx[0]);	
	float acc = net.eval_avg(devy,devx);        //auto-eval on dev data
        cout << "epoch " << E << ", loss= " << loss << ", eval (dev) = " << acc << endl;
      }else {
	cout << "epoch" << E <<endl;
      }
	      
    }
    vector<string> testy;
    vector<vector<string>> testx(1,vector<string>());
    test_set.getYdata(testy);	
    test_set.getXdata(testx[0]);	
    float acc = net.eval_avg(testy,testx); 
    cout << "final eval (test) = " << acc << endl;
    return 0;
}
Example #16
0
//-*****************************************************************************
void SpwImpl::setSample( const void *iSamp )
{
    // Make sure we aren't writing more samples than we have times for
    // This applies to acyclic sampling only
    ABCA_ASSERT(
        !m_header->header.getTimeSampling()->getTimeSamplingType().isAcyclic()
        || m_header->header.getTimeSampling()->getNumStoredTimes() >
        m_header->nextSampleIndex,
        "Can not write more samples than we have times for when using "
        "Acyclic sampling." );

    AbcA::ArraySample samp( iSamp, m_header->header.getDataType(),
                            AbcA::Dimensions(1) );

     // The Key helps us analyze the sample.
     AbcA::ArraySample::Key key = samp.getKey();

     // mask out the non-string POD since Ogawa can safely share the same data
     // even if it originated from a different POD
     // the non-fixed sizes of our strings (plus added null characters) makes
     // determing the sie harder so strings are handled seperately
    if ( key.origPOD != Alembic::Util::kStringPOD &&
         key.origPOD != Alembic::Util::kWstringPOD )
    {
        key.origPOD = Alembic::Util::kInt8POD;
        key.readPOD = Alembic::Util::kInt8POD;
    }

    // We need to write the sample
    if ( m_header->nextSampleIndex == 0  ||
        !( m_previousWrittenSampleID &&
            key == m_previousWrittenSampleID->getKey() ) )
    {

        // we only need to repeat samples if this is not the first change
        if (m_header->firstChangedIndex != 0)
        {
            // copy the samples from after the last change to the latest index
            for ( index_t smpI = m_header->lastChangedIndex + 1;
                smpI < m_header->nextSampleIndex; ++smpI )
            {
                assert( smpI > 0 );
                CopyWrittenData( m_group, m_previousWrittenSampleID );
            }
        }

        // Write this sample, which will update its internal
        // cache of what the previously written sample was.
        AbcA::ArchiveWriterPtr awp = this->getObject()->getArchive();

        // Write the sample.
        // This distinguishes between string, wstring, and regular arrays.
        m_previousWrittenSampleID =
            WriteData( GetWrittenSampleMap( awp ), m_group, samp, key );

        if (m_header->firstChangedIndex == 0)
        {
            m_header->firstChangedIndex = m_header->nextSampleIndex;
        }
        // this index is now the last change
        m_header->lastChangedIndex = m_header->nextSampleIndex;
    }

    if ( m_header->nextSampleIndex == 0 )
    {
        m_hash = m_previousWrittenSampleID->getKey().digest;
    }
    else
    {
        Util::Digest digest = m_previousWrittenSampleID->getKey().digest;
        Util::SpookyHash::ShortEnd( m_hash.words[0], m_hash.words[1],
                                    digest.words[0], digest.words[1] );
    }

    m_header->nextSampleIndex ++;
}