コード例 #1
0
// Initialization. Models, textures, program input and graphics definitions
void init (void)
{
	glClearColor (0.0f, 0.0f, 0.0f, 0.0f);

    // Model loading based on each scale
	model1 = readModel (model1Path, model1Scale);
	model1 -> size = model1Size;
	model2 = readModel (model2Path, model2Scale);
	model2 -> size = model2Size;
    
    // Textures configuration in general
	configTextMode();

    // Read the program input (not user input) to determinw hoe many rooms
    //  and theirs objects will be drawn
	readInput();

	// Light. The light switch is made in the input.cpp.
    // Switch it pressing the key L. Do it!
    if (light)
    {
        GLfloat light_position[] = {1.0, 1.0, 1.0, 0.0};
        GLfloat light_diffuse[] = {0.9, 0.9, 0.9, 0.0};
        GLfloat light_ambient[] = {1.4, 1.4, 1.4, 0.0};
        glLightfv(GL_LIGHT0, GL_POSITION, light_position);
        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
    }

	glEnable(GL_DEPTH_TEST);

	glShadeModel(GL_SMOOTH);
}
コード例 #2
0
ファイル: splice.C プロジェクト: liutanqiu/wgs-assembler
void
Sim4::loadGlimmerModel (char *train_dir)
{
   char filename[1000];

   if (initGlimmerModel)
     return;

   /* LLL is this still needed? Yes, since it is initialized in the class Sim4*/

   sprintf(filename, "%s/%s", train_dir, Glimmer_posDonModelPath);
   readModel (&donor_pos_model, filename);

   sprintf(filename, "%s/%s", train_dir, Glimmer_negDonModelPath);
   readModel (&donor_neg_model, filename);

   sprintf(filename, "%s/%s", train_dir, Glimmer_posAccModelPath);
   readModel (&acceptor_pos_model, filename);

   sprintf(filename, "%s/%s", train_dir, Glimmer_negAccModelPath);
   readModel (&acceptor_neg_model, filename);

   donor_pos_model_len = getModelLength (donor_pos_model);
   donor_neg_model_len = getModelLength (donor_neg_model);
   acceptor_pos_model_len = getModelLength (acceptor_pos_model);
   acceptor_neg_model_len = getModelLength (acceptor_neg_model);

   if (donor_pos_model_len!=donor_neg_model_len)
     fatal ("ERROR:  Positive and negative donor model lengths differ\n");
   if (acceptor_pos_model_len!=acceptor_neg_model_len)
     fatal ("ERROR:  Positive and negative acceptor model lengths differ\n");

   initGlimmerModel = 1;
}
コード例 #3
0
void learningCurves(){
	/* *********************      Interface part      **********************/
	/* ********************* **** ************** **** **********************/
	int numTestedExamples;
	cout << endl << endl;
	cout << " ================== Learning curves  ===========" << endl;
	cout << " == Enter maximum size of training set: "; 	cin >> numTestedExamples;
	cout << " == Enter tested lambda: "; 	cin >> testedLambda;
	cout << " == Enter step size: "; 	cin >> stepSize;
	cout << " == Enter number of LBFGS iterations: "; 	cin >> numTrainingIterations;

	if (numTestedExamples < 150) numTestedExamples = 150;
	if (numTestedExamples > 40000) numTestedExamples = 40000;

	NNModel* model = readModel();

	/* *********************          Logic           **********************/
	/* ********************* **** ************** **** **********************/
	DataParser *traininSet = new DataParser(numTestedExamples, numFeatures, 10, "trainingSet.csv");
	DataParser *crossValidationSet = new DataParser(numCrossValidationExamples, numFeatures, 10, "crossValidation.csv");


	plotLearningCurves(model, traininSet, crossValidationSet, testedLambda);


	system("PAUSE");
	exit(0);
}
コード例 #4
0
ファイル: genericdao.cpp プロジェクト: koboveb/SVID.TERMINAL
QObject* GenericDAO::get(const QSqlDatabase& db, const QString& table, const QString& where, const QVariantList& bindValues)
{
    QObject* obj = NULL;
    if (db.isOpen())
    {
        QSqlQuery query(db);
        query.setForwardOnly(true);
        QString sql = QString("SELECT * FROM %1 WHERE %2").arg(table).arg(where);
        query.prepare(sql);
        int n = bindValues.size();
        for (int i = 0; i < n; i++)
        {
            query.bindValue(i, bindValues[i]);
        }

        if (query.exec())
        {
            if (query.next())
            {
                obj = readModel(query);
            }
        }
        else
            throw DatabaseException(query);
    }

    return obj;
}
コード例 #5
0
/*
 * Reading models from resource directory
 */
bool LinemodInterface::readModels(const std::string &resourcePath)
{
  DIR *dp;
  struct dirent *dirp;
  struct stat fileStat;

  if((dp  = opendir(resourcePath.c_str())) ==  NULL)
  {
    outError("path (" << resourcePath << ") does not exist!");
    return false;
  }

  std::vector<std::string> modelNames;
  std::vector<std::vector<std::string> > modelFiles;

  while((dirp = readdir(dp)) != NULL)
  {
    if(dirp->d_type != DT_DIR || dirp->d_name[0] == '.')
    {
      continue;
    }


    std::string name = dirp->d_name;
    std::string path = resourcePath + "/" + name + "/linemod.yml.gz";

    if(!stat(path.c_str(), &fileStat) && S_ISREG(fileStat.st_mode))
    {
      outDebug("read model: " << path);
      readModel(path);
    }
  }
  closedir(dp);
  return true;
}
コード例 #6
0
std::list<std::shared_ptr<I_Object>> SceneSettingReader::readObjects()
{
    std::list<std::shared_ptr<I_Object>> objects;
    settings_.beginGroup(OBJECTS_GROUP);
    const int size = settings_.beginReadArray("objects");
    for (int i = 0; i < size; ++i)
    {
        settings_.setArrayIndex(i);
        if (settings_.value("type").toString() == "sphere")
        {
            objects.push_back(std::shared_ptr<I_Object>(readSphere()));
        }
        else if (settings_.value("type").toString() == "triangle")
        {
            objects.push_back(std::shared_ptr<I_Object>(readTriangle()));
        }
        else if (settings_.value("type").toString() == "quad")
        {
            objects.push_back(std::shared_ptr<I_Object>(readQuad()));
        }
        else if (settings_.value("type").toString() == "model")
        {
            objects.push_back(std::shared_ptr<I_Object>(readModel()));
        }
        else
        {
            std::cout << "Error: object type is not valid"
                << settings_.value("type").toString().toStdString() << std::endl;
        }
    }
    settings_.endArray();
    settings_.endGroup();
    return objects;
}
コード例 #7
0
ファイル: synscandriver.cpp プロジェクト: azwing/indi
bool SynscanDriver::Handshake()
{
    char res[SYN_RES] = {0};
    if (!echo())
        return false;

    // We can only proceed if the mount is aligned.
    if (!sendCommand("J", res))
        return false;

    if (res[0] == 0)
    {
        LOG_ERROR("Mount is not aligned. Please align the mount first and connect again.");
        return false;
    }

    readModel();

    if (m_isAltAz)
    {
        SetTelescopeCapability(GetTelescopeCapability() & ~TELESCOPE_HAS_PIER_SIDE, 10);
    }

    return true;
}
コード例 #8
0
bool MlMaximumEntropyModel::readModel(const char* path)
{
	ifstream ifs(path);
	if (! ifs.good())
		return false;

	bool retVal = readModel(ifs);
	ifs.close();
	return retVal;
}
コード例 #9
0
ファイル: triangulate.cpp プロジェクト: dbc/pyPolyCSG
int main(int argc, char **argv) {
  options.parse(argc, argv);

  carve::poly::Polyhedron *poly = readModel(options.file);
  if (!poly) exit(1);

  std::vector<carve::poly::Vertex<3> > out_vertices = poly->vertices;
  std::vector<carve::poly::Face<3> > out_faces;

  size_t N = 0;
  for (size_t i = 0; i < poly->faces.size(); ++i) {
    carve::poly::Face<3> &f = poly->faces[i];
    N += f.nVertices() - 2;
  }
  out_faces.reserve(N);

  for (size_t i = 0; i < poly->faces.size(); ++i) {
    carve::poly::Face<3> &f = poly->faces[i];
    std::vector<carve::triangulate::tri_idx> result;

    std::vector<const carve::poly::Polyhedron::vertex_t *> vloop;
    f.getVertexLoop(vloop);

    carve::triangulate::triangulate(carve::poly::p2_adapt_project<3>(f.project), vloop, result);
    if (options.improve) {
      carve::triangulate::improve(carve::poly::p2_adapt_project<3>(f.project), vloop, result);
    }

    for (size_t j = 0; j < result.size(); ++j) {
      out_faces.push_back(carve::poly::Face<3>(
            &out_vertices[poly->vertexToIndex_fast(vloop[result[j].a])],
            &out_vertices[poly->vertexToIndex_fast(vloop[result[j].b])],
            &out_vertices[poly->vertexToIndex_fast(vloop[result[j].c])]
            ));
    }
  }

  carve::poly::Polyhedron *result = new carve::poly::Polyhedron(out_faces, out_vertices);

  if (options.canonicalize) result->canonicalize();

  if (options.obj) {
    writeOBJ(std::cout, result);
  } else if (options.vtk) {
    writeVTK(std::cout, result);
  } else {
    writePLY(std::cout, result, options.ascii);
  }

  delete result;
  delete poly;
}
コード例 #10
0
ファイル: Model.cpp プロジェクト: latuya23/rt2
Model::Model(const char* fileName, Material m, glm::dmat4 transform, bool ccw){
  faceList = NULL;
  m_triangles = NULL;
  m_mins = glm::dvec3(std::numeric_limits<int>::max());
  m_maxs = glm::dvec3(std::numeric_limits<int>::min());
  m_transform = transform;
  m_invTT = glm::inverseTranspose(m_transform);
  m_material = m;
  m_fName = fileName;
  m_rootKdTree = new KdNode();
  //std::cout <<"start reading model"<<std::endl;
  if (readModel(ccw)){
    std::cout << "read model successfully"<<std::endl;
  }
}
コード例 #11
0
ファイル: Reader.cpp プロジェクト: Kartonschachtel/public
Model* Reader::readOBJ(const char* fileName){	
	file.open(fileName);
	if(file.fail()){
		cout << "Input file not found.  (" << fileName << ")" << endl;
		exit(-1);
	}
	
	scale = 0.1f;	
	face = new int[3];

	readModel();

	file.clear();
	file.close();

	delete [] face;
	return model;
}
コード例 #12
0
void ContiguousMS::ReadModel(std::complex<float>* buffer)
{
	if(!_isModelColumnPrepared)
		prepareModelColumn();
	
	readMeta();
	readModel();
	readWeights();
	size_t startChannel, endChannel;
	if(_selection.HasChannelRange())
	{
		startChannel = _selection.ChannelRangeStart();
		endChannel = _selection.ChannelRangeEnd();
	}
	else {
		startChannel = 0;
		endChannel = _bandData[_dataDescId].ChannelCount();
	}
	copyData(buffer,  startChannel, endChannel, _inputPolarizations, _modelArray, _polOut);
}
コード例 #13
0
ファイル: main.cpp プロジェクト: defaultstr/CUDAQsort
/**
* Tries all model distributions ITERATIONS times
*/
void testModels(char* uniid)
{
	char* names[] = {"norm-dragon.dat","norm-happy.dat","norm-lucy.dat","norm-manuscript.dat","norm-rgbdragon.dat","norm-statuette.dat"};
	unsigned int run = 0;
	element* data2 = new element[16027872];

	// Try the 6 different models
	for(int i=0;i<6;i++)
	{
		// several times
		for(int q=0;q<ITERATIONS;q++)
		{
			double timerValue;
			int testsize;

			// Read sequence from file
			unsigned int* data = readModel(testsize,names[i]);
			// Store copy for later validation
			memcpy(data2,data,testsize*sizeof(element));

			int threads   =0;
			int maxblocks =0;
			int sbsize    =0;

			// Sort it
			if(gpuqsort(data,testsize,&timerValue,maxblocks,threads,sbsize,0)!=0)
			{
				printf("Error! (%s)\n",getGPUSortErrorStr());
				exit(1);
			}

			// Validate the result
			if(!validate(data2,data,testsize))
				exit(1); 
			saveResults(testsize,names[i],(float)timerValue,threads,maxblocks,sbsize,uniid,0,2);
			printf("%d/%d!\n",run++,6*ITERATIONS);
			free(data);
		}
	}
}
コード例 #14
0
ファイル: AHalfLifeDecoder.cpp プロジェクト: laulandne/src
void AHalfLifeDecoder::readBodyParts()
{
  DEBUG_OUT<<"AHalfLifeDecoder::readBodyParts()...\n";
  if(!fd) return;
  //if(errorFlag) return;
  DEBUG_OUT<<"There are "<<numbodyparts<<" bodyparts.\n";
  if(!numbodyparts) return;
  fseek(fd,bodypartsOffset,SEEK_SET);
  char name[64];
  unsigned long nummodels,base,modelOffset;
  for(unsigned int i=0;i<numbodyparts;i++) {
    fread(name,64,1,fd);
    nummodels=readLongL();
    base=readLongL();
    modelOffset=readLongL();
    DEBUG_OUT<<"bodypart "<<i<<": "<<name<<" "<<nummodels<<" "<<base<<" "<<modelOffset<<"\n";
    for(unsigned int j=0;j<nummodels;j++) {
      fseek(fd,modelOffset,SEEK_SET);
      readModel();
    }
  }
}
コード例 #15
0
Ogre::SceneNode* AssetLoader::readAsset(Ogre::SceneManager* sceneMgr, const char* assetFileName, const char* assetName)
{
	Assimp::Importer importer;
	const aiScene* scene = importer.ReadFile(assetFileName, aiProcessPreset_TargetRealtime_Quality|aiProcess_FlipUVs);
	if (!scene) {
		return false;
	}

//	this->createCamera(sceneMgr, Ogre::String("camera1"));

	Ogre::SceneNode* rootNode = sceneMgr->getRootSceneNode();
	Ogre::SceneNode* scnNode = rootNode->createChildSceneNode(assetName);

	for (size_t i = 0; i < scene->mRootNode->mNumChildren; i++)
	{	
		aiNode* cnd = scene->mRootNode->mChildren[i];
		Ogre::SceneNode* node = createChildSceneNodeWithTransform(scnNode, cnd);

		readModel(sceneMgr, node, scene, cnd);
	}

	return scnNode;
}
コード例 #16
0
ファイル: raytime.c プロジェクト: JanThorbecke/OpenSource
int main(int argc, char **argv)
{
	modPar mod;
	recPar rec;
	srcPar src;
	shotPar shot;
	rayPar ray;
    float *velocity, *slowness, *smooth, *trueslow, **inter;
	double t0, t1, t2, tinit, tray, tio;
	size_t size;
	int nw, n1, ix, iz, ir, ixshot, izshot;
	int nt, ntfft, nfreq, ig;
	int irec, sbox, ipos, nrx, nrz, nr;
    fcoord coordsx, coordgx, Time;
    icoord grid, isrc; 
    float Jr, *ampl, *time, *ttime, *ttime_p, cp_average, *wavelet, dw, dt;
	float dxrcv, dzrcv, rdelay, tr, dt_tmp;
    segy hdr;
    char filetime[1024], fileamp[1024], *method, *file_rcvtime, *file_src;
    size_t  nwrite, nread;
	int verbose;
    complex *cmute, *cwav;
    FILE *fpt, *fpa, *fpwav, *fprcv;

	t0= wallclock_time();
	initargs(argc,argv);
	requestdoc(0);

	if(!getparint("verbose",&verbose)) verbose=0;
    if(!getparint("sbox", &sbox)) sbox = 1;
    if(!getparstring("method", &method)) method="jesper";
	if (!getparfloat("rec_delay",&rdelay)) rdelay=0.0;

	getParameters(&mod, &rec, &src, &shot, &ray, verbose);

    /* read file_src if file_rcvtime is defined */

    if (!getparstring("file_rcvtime",&file_rcvtime)) file_rcvtime=NULL;

	if (file_rcvtime != NULL) {
    	if (!getparstring("file_src",&file_src)) file_src=NULL;
		if (!getparfloat("dt",&dt)) dt=0.004;
		if (file_src != NULL ) {
        	fpwav = fopen( file_src, "r" );
        	assert( fpwav != NULL);
        	nread = fread( &hdr, 1, TRCBYTES, fpwav );
        	assert(nread == TRCBYTES);
			ntfft = optncr(MAX(hdr.ns, rec.nt));
 			wavelet = (float *)calloc(ntfft,sizeof(float));
			/* read first trace */
        	nread = fread(wavelet, sizeof(float), hdr.ns, fpwav);
        	assert (nread == hdr.ns);
        	fclose(fpwav);
		}
		else {
			ntfft = optncr(rec.nt);
 			wavelet = (float *)calloc(ntfft,sizeof(float));
			wavelet[0] = 1.0;
		}
    	nfreq = ntfft/2+1;
    	cwav    = (complex *)calloc(nfreq,sizeof(complex));
    	cmute   = (complex *)calloc(nfreq,sizeof(complex));
        rc1fft(wavelet,cwav,ntfft,-1);
    	dw      = 2*M_PI/(ntfft*dt);
	}

	/* allocate arrays for model parameters: the different schemes use different arrays */

	n1 = mod.nz;
    if(!strcmp(method,"fd")) nw = 0;
    else nw = ray.smoothwindow;

	velocity = (float *)calloc(mod.nx*mod.nz,sizeof(float));
	slowness = (float *)calloc((mod.nx+2*nw)*(mod.nz+2*nw),sizeof(float));
    trueslow = (float *)calloc(mod.nx*mod.nz,sizeof(float));

    if(!strcmp(method,"fd")) {
		ttime = (float *)calloc(mod.nx*mod.nz,sizeof(float));
	}

	/* read velocity and density files */
	readModel(mod, velocity, slowness, nw);

	/* allocate arrays for wavefield and receiver arrays */

	size = shot.n*rec.n;
    time = (float *)calloc(size,sizeof(float));
    ampl = (float *)calloc(size,sizeof(float));

	/* Sinking source and receiver arrays: 
	   If P-velocity==0 the source and receiver 
	   postions are placed deeper until the P-velocity changes. 
	   Setting the option rec.sinkvel only sinks the receiver position 
       (not the source) and uses the velocity 
	   of the first receiver to sink through to the next layer. */

/* sink receivers to value different than sinkvel */
	for (ir=0; ir<rec.n; ir++) {
		iz = rec.z[ir];
		ix = rec.x[ir];
		while(velocity[(ix)*n1+iz] == rec.sinkvel) iz++;
		rec.z[ir]=iz+rec.sinkdepth;
		rec.zr[ir]=rec.zr[ir]+(rec.z[ir]-iz)*mod.dz;
//		rec.zr[ir]=rec.z[ir]*mod.dz;
		if (verbose>3) vmess("receiver position %d at grid[ix=%d, iz=%d] = (x=%f z=%f)", ir, ix, rec.z[ir], rec.xr[ir]+mod.x0, rec.zr[ir]+mod.z0);
	}
		vmess("   - method for ray-tracing       = %s", method);
/*
*/

/* sink sources to value different than zero */
	for (izshot=0; izshot<shot.nz; izshot++) {
		for (ixshot=0; ixshot<shot.nx; ixshot++) {
			iz = shot.z[izshot];
			ix = shot.x[ixshot];
			while(velocity[(ix)*n1+iz] == 0.0) iz++;
			shot.z[izshot]=iz+src.sinkdepth; 
		}
	}

	if (verbose>3) writeSrcRecPos(&mod, &rec, &src, &shot);

    /* smooth slowness grid */
    grid.x = mod.nx;
    grid.z = mod.nz;
    grid.y = 1;
    if ( nw != 0 ) { /* smooth slowness */ 
        smooth = (float *)calloc(grid.x*grid.z,sizeof(float));
        applyMovingAverageFilter(slowness, grid, nw, 2, smooth);
        memcpy(slowness,smooth,grid.x*grid.z*sizeof(float));
        free(smooth);
	}

    /* prepare output file and headers */
    strcpy(filetime, rec.file_rcv);
    name_ext(filetime, "_time");
    fpt = fopen(filetime, "w");
    assert(fpt != NULL);

	if (ray.geomspread) {
        strcpy(fileamp, rec.file_rcv);
        name_ext(fileamp, "_amp");
        fpa = fopen(fileamp, "w");
        assert(fpa != NULL);
	}
	if (file_rcvtime != NULL) {
        fprcv = fopen(file_rcvtime, "w");
        assert(fprcv != NULL);
	}

    memset(&hdr,0,sizeof(hdr));
    hdr.scalco = -1000;
    hdr.scalel = -1000;
    hdr.trid   = 0;

	t1=wallclock_time();
	tinit = t1-t0;
    tray=0.0;
    tio=0.0;

	/* Outer loop over number of shots */
	for (izshot=0; izshot<shot.nz; izshot++) {
		for (ixshot=0; ixshot<shot.nx; ixshot++) {

	        t2=wallclock_time();
        	if (verbose) {
            	vmess("Modeling source %d at gridpoints ix=%d iz=%d", (izshot*shot.n)+ixshot, shot.x[ixshot], shot.z[izshot]);
            	vmess(" which are actual positions x=%.2f z=%.2f", mod.x0+mod.dx*shot.x[ixshot], mod.z0+mod.dz*shot.z[izshot]);
            	vmess("Receivers at gridpoint x-range ix=%d - %d", rec.x[0], rec.x[rec.n-1]);
            	vmess(" which are actual positions x=%.2f - %.2f", mod.x0+rec.xr[0], mod.x0+rec.xr[rec.n-1]);
            	vmess("Receivers at gridpoint z-range iz=%d - %d", rec.z[0], rec.z[rec.n-1]);
            	vmess(" which are actual positions z=%.2f - %.2f", mod.z0+rec.zr[0], mod.z0+rec.zr[rec.n-1]);
        	}

        	coordsx.x = shot.x[ixshot]*mod.dx;
        	coordsx.z = shot.z[izshot]*mod.dz;
        	coordsx.y = 0;

	        t1=wallclock_time();
            tio += t1-t2;

            if (!strcmp(method,"jesper")) {
#pragma omp parallel for default(shared) \
private (coordgx,irec,Time,Jr) 
        		for (irec=0; irec<rec.n; irec++) {
            		coordgx.x=rec.xr[irec];
            		coordgx.z=rec.zr[irec];
            		coordgx.y = 0;
		
            		getWaveParameter(slowness, grid, mod.dx, coordsx, coordgx, ray, &Time, &Jr);
	
            		time[((izshot*shot.nx)+ixshot)*rec.n + irec] = Time.x + Time.y + 0.5*Time.z;
            		ampl[((izshot*shot.nx)+ixshot)*rec.n + irec] = Jr;
            		if (verbose>4) vmess("JS: shot=%f,%f receiver at %f,%f T0=%f T1=%f T2=%f Jr=%f",coordsx.x, coordsx.z, coordgx.x, coordgx.z, Time.x, Time.y, Time.z, Jr); 
        		}
			}
            else if(!strcmp(method,"fd")) {
	            int mzrcv;

                isrc.x = shot.x[ixshot];
                isrc.y = 0;
                isrc.z = shot.z[izshot];

                mzrcv = 0;
                for (irec = 0; irec < rec.n; irec++) mzrcv = MAX(rec.z[irec], mzrcv);

                vidale(ttime,slowness,&isrc,grid,mod.dx,sbox, mzrcv);
        		for (irec=0; irec<rec.n; irec++) {
            		coordgx.x=mod.x0+rec.xr[irec];
            		coordgx.z=mod.z0+rec.zr[irec];
            		coordgx.y = 0;
					ipos = ((izshot*shot.nx)+ixshot)*rec.n + irec;
	
            		time[ipos] = ttime[rec.z[irec]*mod.nx+rec.x[irec]];
					/* compute average velocity between source and receiver */
 					nrx = (rec.x[irec]-isrc.x);
 					nrz = (rec.z[irec]-isrc.z);
 					nr = abs(nrx) + abs(nrz);
					cp_average = 0.0;
        			for (ir=0; ir<nr; ir++) {
						ix = isrc.x + floor((ir*nrx)/nr);
						iz = isrc.z + floor((ir*nrz)/nr);
						//fprintf(stderr,"ir=%d ix=%d iz=%d velocity=%f\n", ir, ix, iz, velocity[ix*mod.nz+iz]);
						cp_average += velocity[ix*mod.nz+iz];
					}
					cp_average = cp_average/((float)nr);
            		ampl[ipos] = sqrt(time[ipos]*cp_average);
            		if (verbose>4) vmess("FD: shot=%f,%f receiver at %f(%d),%f(%d) T=%e V=%f Ampl=%f",coordsx.x, coordsx.z, coordgx.x, rec.x[irec], coordgx.z, rec.z[irec], time[ipos], cp_average, ampl[ipos]); 
        		}
            }
	        t2=wallclock_time();
            tray += t2-t1;

        	hdr.sx     = 1000*(mod.x0+mod.dx*shot.x[ixshot]);
        	hdr.sdepth = 1000*(mod.z0+mod.dz*shot.z[izshot]);
        	hdr.selev  = (int)(-1000.0*(mod.z0+mod.dz*shot.z[izshot]));
        	hdr.fldr   = ((izshot*shot.nx)+ixshot)+1;
        	hdr.tracl  = ((izshot*shot.nx)+ixshot)+1;
        	hdr.tracf  = ((izshot*shot.nx)+ixshot)+1;
        	hdr.ntr    = shot.n;
    		hdr.dt     = (unsigned short)1;
    		hdr.trwf   = shot.n;
    		hdr.ns     = rec.n;
        	//hdr.d1     = (rec.x[1]-rec.x[0])*mod.dx; // discrete
        	hdr.d1     = (rec.xr[1]-rec.xr[0]);
        	hdr.f1     = mod.x0+rec.x[0]*mod.dx;
        	hdr.d2     = (shot.x[MIN(shot.n-1,1)]-shot.x[0])*mod.dx;
        	hdr.f2     = mod.x0+shot.x[0]*mod.dx;
			dt_tmp = (fabs(hdr.d1*((float)hdr.scalco)));
			hdr.dt	   = (unsigned short)dt_tmp;
    
        	nwrite = fwrite( &hdr, 1, TRCBYTES, fpt);
        	assert(nwrite == TRCBYTES);
        	nwrite = fwrite( &time[((izshot*shot.nx)+ixshot)*rec.n], sizeof(float), rec.n, fpt);
        	assert(nwrite == rec.n);
	    	fflush(fpt);
	    	if (ray.geomspread) {
            	nwrite = fwrite( &hdr, 1, TRCBYTES, fpa);
            	assert(nwrite == TRCBYTES);
            	nwrite = fwrite( &ampl[((izshot*shot.nx)+ixshot)*rec.n], sizeof(float), rec.n, fpa);
            	assert(nwrite == rec.n);
	        	fflush(fpa);
        	}
			if (file_rcvtime != NULL) {
    			hdr.ns     = rec.nt;
    			hdr.trwf   = rec.n;
    			hdr.ntr    = ((izshot*shot.nx)+ixshot+1)*rec.n;
    			hdr.dt     = dt*1000000;
    			hdr.d1     = dt;
        		hdr.f1     = 0.0;
        		hdr.d2     = (rec.xr[1]-rec.xr[0]);
    			hdr.f2     = mod.x0+rec.x[0]*mod.dx;

        		for (irec=0; irec<rec.n; irec++) {
					ipos = ((izshot*shot.nx)+ixshot)*rec.n + irec;
        			hdr.tracf  = irec+1;
        			hdr.tracl  = ((izshot*shot.nx)+ixshot*shot.nz)+irec+1;
        			hdr.gx     = 1000*(mod.x0+rec.xr[irec]);
        			hdr.offset = (rec.xr[irec]-shot.x[ixshot]*mod.dx);
        			hdr.gelev  = (int)(-1000*(mod.z0+rec.zr[irec]));

					tr = time[ipos]+rdelay;
                    for (ig=0; ig<nfreq; ig++) {
                        cmute[ig].r = (cwav[ig].r*cos(ig*dw*tr-M_PI/4.0)-cwav[ig].i*sin(ig*dw*tr-M_PI/4.0))/(ntfft*ampl[ipos]);
                        cmute[ig].i = (cwav[ig].i*cos(ig*dw*tr-M_PI/4.0)+cwav[ig].r*sin(ig*dw*tr-M_PI/4.0))/(ntfft*ampl[ipos]);
                    }
                	cr1fft(cmute,wavelet,ntfft,-1);
        			nwrite = fwrite( &hdr, 1, TRCBYTES, fprcv);
        			nwrite = fwrite( wavelet, sizeof(float), rec.nt, fprcv );
				}
			}
	        t1=wallclock_time();
            tio += t1-t2;
    	} /* end of ixshot loop */
	} /* end of loop over number of shots */
	fclose(fpt);
	if (file_rcvtime != NULL) fclose(fprcv);
	if (ray.geomspread) fclose(fpa);

	t1= wallclock_time();
	if (verbose) {
		vmess("*******************************************");
		vmess("************* runtime info ****************");
		vmess("*******************************************");
		vmess("Total compute time ray-tracing    = %.2f s.", t1-t0);
		vmess("   - intializing arrays and model = %.3f", tinit);
		vmess("   - ray tracing                  = %.3f", tray);
		vmess("   - writing data to file         = %.3f", tio);
	}

	/* free arrays */

	initargs(argc,argv); /* this will free the arg arrays declared */
	free(velocity);
	free(slowness);
	
	return 0;
}
コード例 #17
0
ファイル: xparser.c プロジェクト: somebloke/flame-xparser
/** \fn int main(int argc, char * argv[])
 * \brief Main program function.
 * \param argc Argument count.
 * \param argv Pointer Pointer to Argument vector
 * \return system int
 */
int main(int argc, char * argv[])
{
	/* Variables for parsing directories */
	int lastd;
	int i;
	/* Error value */
	int rc;
	
	/* Variable to read in command line input */
	char inputfile[1000];
	char directory[1000];
	char filename[1000];
	char templatename[1000];
	char templatedirectory[1000];
	
	/* For reading input files */
	input_file * current_input_file;
	/* Structure to hold model data */
	model_data * modeldata;
	
	/* Hold modeldata data */
	xmachine * xmachines;
	xmachine_message * xmessage;
	variable * envvar;
	env_func * envfunc;
	variable * envdefine;
	variable * allvars;
	variable * constant_filter_vars;
	f_code * it_end_code;
	layer * layers;
	flame_communication * communications;
	model_datatype * datatypes;
	time_data * time_units;
	input_file * temp_input_file;
	
	/* Allocate memory for modeldata */
	modeldata = (model_data *)malloc(sizeof(model_data));
	/* 0=serial(default) 1=parallel 2=grid */
	modeldata->code_type = 0;
	/* 0=dgraph.dot 1=stategraph.dot */
	modeldata->depends_style = 0;
	modeldata->debug_mode = 1;

	inputfile[1]='\0';
	
	/* Initialise pointers */
	modeldata->name = NULL;
	modeldata->p_xmachines = &xmachines;
	xmachines = NULL;
	modeldata->p_xmessages = &xmessage;
	xmessage = NULL;
	modeldata->p_envvars = &envvar;
	envvar = NULL;
	modeldata->p_envfuncs = &envfunc;
	envfunc = NULL;
	modeldata->p_envdefines = &envdefine;
	envdefine = NULL;
	modeldata->p_allvars = &allvars;
	allvars = NULL;
	modeldata->p_it_end_code = &it_end_code;
	it_end_code = NULL;
	modeldata->p_layers = &layers;
	layers = NULL;
	modeldata->p_communications = &communications;
	communications = NULL;
	modeldata->p_datatypes = &datatypes;
	datatypes = NULL;
	modeldata->p_time_units = &time_units;
	time_units = NULL;
	modeldata->p_files = &temp_input_file;
	temp_input_file = NULL;
	modeldata->p_constant_filter_vars = &constant_filter_vars;
	constant_filter_vars = NULL;
	
	printf("xparser (Version %d.%d.%d)\n", VERSIONMAJOR, VERSIONMINOR, VERSIONMICRO);
	
	/* Must be at least the input file name */
	if(argc < 2)
	{
		printf("Usage: xparser [XMML file] [-s | -p] [-f]\n");
		printf("\t-s\tSerial mode\n");
		printf("\t-p\tParallel mode\n");
		printf("\t-f\tFinal production mode\n");
		free_modeldata(modeldata);
		return 0;
	}
	
	/* Copy location of xparser */
	strcpy(templatedirectory,argv[0]);
	
	/* parser command line */
	while(argc >1){
		if(argv[1][0] == '-') {
			switch (argv[1][1]){
			case 's': modeldata->code_type = 0;
				  break;
			case 'p': modeldata->code_type = 1;
				  break;
			case 'f' : modeldata->debug_mode = 0;
				  break;
			default:  printf("xparser: Error - unknown option %s\n",argv[1]);
				free_modeldata(modeldata);
				return 0;
			}
		}
		else
		{
			strcpy(inputfile,argv[1]);
			/* printf("XMML input file : %s\n",argv[1]); */
		}
		argc--;
		argv++;
	}
	
	if(inputfile[1] == '\0') {
		printf("xparser: Error - XMML must be specified\n");
		free_modeldata(modeldata);
		return 0;
	}
	
	/* Print what type of code writing */
    printf("\n");
    printf("Code type       : ");
	if(modeldata->code_type == 0) printf("Serial");
	if(modeldata->code_type == 1) printf("Parallel");
	if(modeldata->debug_mode == 1) printf(" (DEBUG)");
    printf("\n");
	
	/* Calculate directory to write files to */
	i = 0;
	lastd = 0;
	while(inputfile[i] != '\0')
	{
	/* For windows directories */
		if(inputfile[i] == '\\') lastd=i;
	/* For unix directories */
		if(inputfile[i] == '/') lastd=i;
		i++;
	}
	/* If a directory is in the path */
	if(lastd != 0)
	{
		strcpy(directory, inputfile);
		directory[lastd+1] = '\0';
	}
	else directory[0] = '\0';
	
	/* Calculate directory where xparser and template files are */
	i = 0;
	lastd = 0;
	while(templatedirectory[i] != '\0')
	{
		/* For windows directories */
		if(templatedirectory[i] == '\\') lastd=i;
		/* For unix directories */
		if(templatedirectory[i] == '/') lastd=i;
		i++;
	}
	/* If a directory is in the path */
	if(lastd != 0)
	{
		templatedirectory[lastd+1] = '\0';
	}
	else templatedirectory[0] = '\0';
	
	/* Appending templates subdir */
	strcat(templatedirectory, "templates/");
	
	printf("Input XMML file : %s\n", inputfile);
	printf("Model root dir  : %s\n", directory);
	printf("Template dir    : %s\n", templatedirectory);
    printf("\n");
	
	current_input_file = add_input_file(modeldata->p_files);
	current_input_file->fullfilepath = copystr(inputfile);
	current_input_file->fulldirectory = copystr(directory);
	current_input_file->localdirectory = copystr("");
	
	/* Read model from model xml file */
	current_input_file = * modeldata->p_files;
	while(current_input_file)
	{
		if(current_input_file->enabled == 1)
			readModel(current_input_file, directory, modeldata);
		
		current_input_file = current_input_file->next;
	}
	rc = checkmodel(modeldata);
	if(rc == -1)
	{
		free_modeldata(modeldata);
		return 0;
	}
	
	/* Calculate dependency graph for model functions */
	rc = create_dependency_graph(directory, modeldata);
	if(rc == -1)
	{
		free_modeldata(modeldata);
		return 0;
	}
	
	/* Looping through Template Directory searching for *.tmpl files */
	DIR *dir = opendir (templatedirectory);
	struct dirent *dp;          /* returned from readdir() */
	if (dir == NULL)
	{
		printf("Error: Opening %s directory failed.\n", templatedirectory);
	    return 0;            /* opendir() failed */
	}
	
	printf("Processing %s Directory.\n",templatedirectory);
	/* Loop through the directory. */
	while ((dp = readdir (dir)) != NULL)
	{
		int len = (int)strlen(dp->d_name);
		if(dp->d_name[len-1] == 'l' &&
			dp->d_name[len-2] == 'p' &&
			dp->d_name[len-3] == 'm' &&
			dp->d_name[len-4] == 't' &&
			dp->d_name[len-5] == '.')		/* if file ends with *.tmpl */
		{
			strcpy(templatename, templatedirectory); strcat(templatename, dp->d_name);
			strcpy(filename, directory); strcat(filename, dp->d_name);
			filename[strlen(filename)-5] = '\0';
			
			/* Parse templates to output files */
			parseTemplate(filename, templatename, modeldata);
			
		}
	}
	parseAgentHeaderTemplate(directory, modeldata);
	/*parseUnittest(directory, modeldata);*/
	/*parser0dtd(directory, modeldata);*/
	/*parser0xsd(directory, modeldata);*/
	
	free_modeldata(modeldata);
	
	printf("\n--- xparser finished ---\n\n");
    
    printf("To compile and run the generated code, you will need:\n");
    printf(" * libmboard (version %s or newer)\n", LIBMBOARD_MINVER_STR);
	
	/* Exit successfully by returning zero to Operating System */
	return 0;
}
コード例 #18
0
void XmlParser::readCubes(Renderer * renderer ,Scene * scene, XmlNode * cubeNode) {
    // Read all cubes from scene
    while(cubeNode) {
        // Create cube
        Cube * c = new Cube();
        // Read shaders and init it
        int basicShader = renderer->getDefaultBasicShader();
        int lightShader = renderer->getDefaultLightShader();
        XmlNode * basicShaderNode = cubeNode->first_node("basic-shader");
        XmlNode * lightShaderNode = cubeNode->first_node("light-shader");
        
        // If there is a basic shader node
        if (basicShaderNode) {
            XmlAttr * vert, * frag;
            xmlAttribute(vert, basicShaderNode);
            xmlAttribute(frag, basicShaderNode);
            // Create new shader
            basicShader = renderer->createShaderProg(vert->value(), frag->value());
        }

        // If there is a light shader node
        if (lightShaderNode) {
            XmlAttr * vert, * frag;
            xmlAttribute(vert, lightShaderNode);
            xmlAttribute(frag, lightShaderNode);
            // Create new shader
            lightShader = renderer->createShaderProg(vert->value(), frag->value());
        }

        // Init cube
        c->init(basicShader, lightShader);
        
        // Try to read model
        readModel(c, cubeNode->first_node("model"));


        // Add c to scene
        scene->addGameObject(c);

        // Set texture
        XmlNode * texture = cubeNode->first_node("texture");
        if (texture) {
            // Get file name
            XmlAttr * file;
            xmlAttribute(file, texture);

            // Create texture
            Texture texture(GL_TEXTURE0, std::string(file->value()));

            // Set texture
            c->setTexture(texture);
        }

        // Set material
        XmlNode * material = cubeNode->first_node("material");
        if (material) {
        	// Create material
        	Material * m = new Material();

        	// Set emissive
        	XmlNode * emissive = material->first_node("emissive");
			if (emissive) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, emissive);
				xmlAttribute(g, emissive);
				xmlAttribute(b, emissive);
				// Set diffuse
				m->setEmissive(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read ambient
			XmlNode * ambient = material->first_node("ambient");
			if (ambient) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, ambient);
				xmlAttribute(g, ambient);
				xmlAttribute(b, ambient);
				// Set diffuse
				m->setAmbient(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read diffuse
			XmlNode * diffuse = material->first_node("diffuse");
			if (diffuse) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, diffuse);
				xmlAttribute(g, diffuse);
				xmlAttribute(b, diffuse);
				// Set diffuse
				m->setDiffuse(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read specular
			XmlNode * specular = material->first_node("specular");
			if (specular) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, specular);
				xmlAttribute(g, specular);
				xmlAttribute(b, specular);
				// Set diffuse
				m->setSpecular(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read specular
			XmlNode * shininess = material->first_node("shininess");
			if (shininess) {
				XmlAttr * value;
				xmlAttribute(value, shininess);
				// Set diffuse
				m->setShininess(atof(value->value()));
			}

			// Set material
			c->setMaterial(m);
        }

        // Read Scripts
        XmlNode * scripts = cubeNode->first_node("scripts");
        readScripts(scene, c, scripts);

        // Get next cube
        cubeNode = cubeNode->next_sibling("cube");
    }
}
コード例 #19
0
ファイル: fdelmodc.c プロジェクト: whu-pzhang/OpenSource
int main(int argc, char **argv)
{
	modPar mod;
	recPar rec;
	snaPar sna;
	wavPar wav;
	srcPar src;
	bndPar bnd;
	shotPar shot;
	float **src_nwav;
	float *rox, *roz, *l2m, *lam, *mul;
	float *tss, *tes, *tep, *p, *q, *r;
	float *vx, *vz, *tzz, *txz, *txx;
	float *rec_vx, *rec_vz, *rec_p;
	float *rec_txx, *rec_tzz, *rec_txz;
	float *rec_pp, *rec_ss;
	float *rec_udp, *rec_udvz;
	float *beam_vx, *beam_vz, *beam_p;
	float *beam_txx, *beam_tzz, *beam_txz;
	float *beam_pp, *beam_ss;	
	float sinkvel;
	double t0, t1, t2, t3, tt, tinit;
	size_t size, sizem, nsamp, memsize;
	int n1, ix, iz, ir, ishot, i;
	int ioPx, ioPz;
	int it0, it1, its, it, fileno, isam;
	int ixsrc, izsrc;
	int verbose;

	t0= wallclock_time();
	initargs(argc,argv);
	requestdoc(0);

	if (!getparint("verbose",&verbose)) verbose=0;
	getParameters(&mod, &rec, &sna, &wav, &src, &shot, &bnd, verbose);

	/* allocate arrays for model parameters: the different schemes use different arrays */

	n1 = mod.naz;
	sizem=mod.nax*mod.naz;

	rox = (float *)calloc(sizem,sizeof(float));
	roz = (float *)calloc(sizem,sizeof(float));
	l2m = (float *)calloc(sizem,sizeof(float));
	if (mod.ischeme==2) {
		tss = (float *)calloc(sizem,sizeof(float));
		tep = (float *)calloc(sizem,sizeof(float));
		q = (float *)calloc(sizem,sizeof(float));
	}
	if (mod.ischeme>2) {
		lam = (float *)calloc(sizem,sizeof(float));
		mul = (float *)calloc(sizem,sizeof(float));
	}
	if (mod.ischeme==4) {
		tss = (float *)calloc(sizem,sizeof(float));
		tes = (float *)calloc(sizem,sizeof(float));
		tep = (float *)calloc(sizem,sizeof(float));
		r = (float *)calloc(sizem,sizeof(float));
		p = (float *)calloc(sizem,sizeof(float));
		q = (float *)calloc(sizem,sizeof(float));
	}

	/* read velocity and density files */

	readModel(mod, bnd, rox, roz, l2m, lam, mul, tss, tes, tep);

	/* read and/or define source wavelet(s) */

	/* Using a random source, which can have a random length 
	   for each source position, a pointer array with variable 
	   length (wav.nsamp[i]) is used.
	   The total length of all the source lengths together is wav.nst */
	
	if (wav.random) {
		src_nwav = (float **)calloc(wav.nx,sizeof(float *));
		src_nwav[0] = (float *)calloc(wav.nst,sizeof(float));
		assert(src_nwav[0] != NULL);
		nsamp = 0;
		for (i=0; i<wav.nx; i++) {
			src_nwav[i] = (float *)(src_nwav[0] + nsamp);
			nsamp += wav.nsamp[i];
		}
	}
	else {
		src_nwav = (float **)calloc(wav.nx,sizeof(float *));
		src_nwav[0] = (float *)calloc(wav.nt*wav.nx,sizeof(float));
		assert(src_nwav[0] != NULL);
		for (i=0; i<wav.nx; i++) {
			src_nwav[i] = (float *)(src_nwav[0] + wav.nt*i);
		}
	}

	defineSource(wav, src, src_nwav, mod.grid_dir, verbose);

	/* allocate arrays for wavefield and receiver arrays */

	vx  = (float *)calloc(sizem,sizeof(float));
	vz  = (float *)calloc(sizem,sizeof(float));
	tzz = (float *)calloc(sizem,sizeof(float)); /* =P field for acoustic */
	if (mod.ischeme>2) {
		txz = (float *)calloc(sizem,sizeof(float));
		txx = (float *)calloc(sizem,sizeof(float));
	}
	if (rec.type.vz)  rec_vz  = (float *)calloc(size,sizeof(float));
	
	size = rec.n*rec.nt;
	if (rec.type.vz)  rec_vz  = (float *)calloc(size,sizeof(float));
	if (rec.type.vx)  rec_vx  = (float *)calloc(size,sizeof(float));
	if (rec.type.p)   rec_p   = (float *)calloc(size,sizeof(float));
	if (rec.type.txx) rec_txx = (float *)calloc(size,sizeof(float));
	if (rec.type.tzz) rec_tzz = (float *)calloc(size,sizeof(float));
	if (rec.type.txz) rec_txz = (float *)calloc(size,sizeof(float));
	if (rec.type.pp)  rec_pp  = (float *)calloc(size,sizeof(float));
	if (rec.type.ss)  rec_ss  = (float *)calloc(size,sizeof(float));
    if (rec.type.ud) { /* get velcity and density at first receiver location */
		ir = mod.ioZz + rec.z[0]+(rec.x[0]+mod.ioZx)*n1;
		rec.rho = mod.dt/(mod.dx*roz[ir]);
		rec.cp  = sqrt(l2m[ir]*(roz[ir]))*mod.dx/mod.dt;
		rec_udvz  = (float *)calloc(mod.nax*rec.nt,sizeof(float));
		rec_udp   = (float *)calloc(mod.nax*rec.nt,sizeof(float));
	}
	
	if(sna.beam) {
		size = sna.nz*sna.nx;
		if (sna.type.vz)  beam_vz  = (float *)calloc(size,sizeof(float));
		if (sna.type.vx)  beam_vx  = (float *)calloc(size,sizeof(float));
		if (sna.type.p)   beam_p   = (float *)calloc(size,sizeof(float));
		if (sna.type.txx) beam_txx = (float *)calloc(size,sizeof(float));
		if (sna.type.tzz) beam_tzz = (float *)calloc(size,sizeof(float));
		if (sna.type.txz) beam_txz = (float *)calloc(size,sizeof(float));
		if (sna.type.pp)  beam_pp  = (float *)calloc(size,sizeof(float));
		if (sna.type.ss)  beam_ss  = (float *)calloc(size,sizeof(float));
	}

	t1= wallclock_time();
	if (verbose) {
		tinit = t1-t0;
		vmess("*******************************************");
		vmess("************* runtime info ****************");
		vmess("*******************************************");
		vmess("CPU time for intializing arrays and model = %f", tinit);
	}

	/* Sinking source and receiver arrays: 
	   If P-velocity==0 the source and receiver 
	   postions are placed deeper until the P-velocity changes. 
	   The free-surface position is stored in bnd.surface[ix].
	   Setting the option rec.sinkvel only sinks the receiver position 
       (not the source) and uses the velocity 
	   of the first receiver to sink through to the next layer. */

    ioPx=mod.ioPx;
    ioPz=mod.ioPz;
    if (bnd.lef==4 || bnd.lef==2) ioPx += bnd.ntap;
    if (bnd.top==4 || bnd.top==2) ioPz += bnd.ntap;
	if (rec.sinkvel) sinkvel=l2m[(rec.x[0]+ioPx)*n1+rec.z[0]+ioPz];
	else sinkvel = 0.0;

/* sink receivers to value different than sinkvel */
	for (ir=0; ir<rec.n; ir++) {
		iz = rec.z[ir];
		ix = rec.x[ir];
		while(l2m[(ix+ioPx)*n1+iz+ioPz] == sinkvel) iz++;
		rec.z[ir]=iz+rec.sinkdepth;
		rec.zr[ir]=rec.zr[ir]+(rec.z[ir]-iz)*mod.dz;
//		rec.zr[ir]=rec.z[ir]*mod.dz;
		if (verbose>3) vmess("receiver position %d at grid[ix=%d, iz=%d] = (x=%f z=%f)", ir, ix+ioPx, rec.z[ir]+ioPz, rec.xr[ir]+mod.x0, rec.zr[ir]+mod.z0);
	}

/* sink sources to value different than zero */
	for (ishot=0; ishot<shot.n; ishot++) {
		iz = shot.z[ishot];
		ix = shot.x[ishot];
		while(l2m[(ix+ioPx)*n1+iz+ioPz] == 0.0) iz++;
		shot.z[ishot]=iz+src.sinkdepth; 
	}

	/* scan for free surface boundary in case it has a topography */
	for (ix=0; ix<mod.nx; ix++) {
		iz = ioPz;
		while(l2m[(ix+ioPx)*n1+iz] == 0.0) iz++;
		bnd.surface[ix+ioPx] = iz;
		if ((verbose>3) && (iz != ioPz)) vmess("Topgraphy surface x=%.2f z=%.2f", mod.x0+mod.dx*ix, mod.z0+mod.dz*(iz-ioPz));
	}
	for (ix=0; ix<ioPx; ix++) {
		bnd.surface[ix] = bnd.surface[ioPx];
	}
	for (ix=ioPx+mod.nx; ix<mod.iePx; ix++) {
		bnd.surface[ix] = bnd.surface[mod.iePx-1];
	}
	if (verbose>3) writeSrcRecPos(&mod, &rec, &src, &shot);

	/* Outer loop over number of shots */
	for (ishot=0; ishot<shot.n; ishot++) {

		izsrc = shot.z[ishot];
		ixsrc = shot.x[ishot];
		fileno= 0;

		memset(vx,0,sizem*sizeof(float));
		memset(vz,0,sizem*sizeof(float));
		memset(tzz,0,sizem*sizeof(float));
		if (mod.ischeme==2) {
			memset(q,0,sizem*sizeof(float));
		}
		if (mod.ischeme>2) {
			memset(txz,0,sizem*sizeof(float));
			memset(txx,0,sizem*sizeof(float));
		}
		if (mod.ischeme==4) {
			memset(r,0,sizem*sizeof(float));
			memset(p,0,sizem*sizeof(float));
			memset(q,0,sizem*sizeof(float));
		}
		if (verbose) {
			if (!src.random) {
				vmess("Modeling source %d at gridpoints ix=%d iz=%d", ishot, shot.x[ishot], shot.z[ishot]);
				vmess(" which are actual positions x=%.2f z=%.2f", mod.x0+mod.dx*shot.x[ishot], mod.z0+mod.dz*shot.z[ishot]);
			}
			vmess("Receivers at gridpoint x-range ix=%d - %d", rec.x[0], rec.x[rec.n-1]);
			vmess(" which are actual positions x=%.2f - %.2f", mod.x0+rec.xr[0], mod.x0+rec.xr[rec.n-1]);
			vmess("Receivers at gridpoint z-range iz=%d - %d", rec.z[0], rec.z[rec.n-1]);
			vmess(" which are actual positions z=%.2f - %.2f", mod.z0+rec.zr[0], mod.z0+rec.zr[rec.n-1]);
		}

		if (mod.grid_dir) { /* reverse time modeling */
			it0=-mod.nt+1;
			it1=0;
			its=-1;

			it0=0;
			it1=mod.nt;
			its=1;
		}
		else {
			it0=0;
			it1=mod.nt;
			its=1;
		}

		/* Main loop over the number of time steps */
		for (it=it0; it<it1; it++) {

#pragma omp parallel default (shared) \
shared (rox, roz, l2m, lam, mul, txx, txz, tzz, vx, vz) \
shared (tss, tep, tes, r, q, p) \
shared (tinit, it0, it1, its) \
shared(beam_vx, beam_vz, beam_txx, beam_tzz, beam_txz, beam_p, beam_pp, beam_ss) \
shared(rec_vx, rec_vz, rec_txx, rec_tzz, rec_txz, rec_p, rec_pp, rec_ss) \
private (tt, t2, t3) \
shared (shot, bnd, mod, src, wav, rec, ixsrc, izsrc, it, src_nwav, verbose)
{
			switch ( mod.ischeme ) {
				case 1 : /* Acoustic FD kernel */
					if (mod.iorder==2) {
						acoustic2(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
							vx, vz, tzz, rox, roz, l2m, verbose);
					}
					else if (mod.iorder==4) {
                        if (mod.sh) {
                            acousticSH4(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
                                  vx, vz, tzz, rox, roz, l2m, verbose);
                        }
                        else {
                            acoustic4(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
                                      vx, vz, tzz, rox, roz, l2m, verbose);
                        }
					}
					else if (mod.iorder==6) {
						acoustic6(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
							vx, vz, tzz, rox, roz, l2m, verbose);
					}
					break;
				case 2 : /* Visco-Acoustic FD kernel */
					viscoacoustic4(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
							vx, vz, tzz, rox, roz, l2m, tss, tep, q, verbose);
					break;
				case 3 : /* Elastic FD kernel */
                    if (mod.iorder==4) {
                        elastic4(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
                            vx, vz, tzz, txx, txz, rox, roz, l2m, lam, mul, verbose);
					}
					else if (mod.iorder==6) {
                        elastic6(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
							vx, vz, tzz, txx, txz, rox, roz, l2m, lam, mul, verbose);
                    }
					break;
				case 4 : /* Visco-Elastic FD kernel */
					viscoelastic4(mod, src, wav, bnd, it, ixsrc, izsrc, src_nwav, 
						vx, vz, tzz, txx, txz, rox, roz, l2m, lam, mul, 
						tss, tep, tes, r, q, p, verbose);
					break;
			}

			/* write samples to file if rec.nt samples are calculated */

#pragma omp master
{
			if ( (((it-rec.delay) % rec.skipdt)==0) && (it >= rec.delay) ) {
				int writeToFile, itwritten;

				writeToFile = ! ( (((it-rec.delay)/rec.skipdt)+1)%rec.nt );
				itwritten   = fileno*(rec.nt)*rec.skipdt;
				isam        = (it-rec.delay-itwritten)/rec.skipdt;

				/* store time at receiver positions */
				getRecTimes(mod, rec, bnd, it, isam, vx, vz, tzz, txx, txz, 
					rec_vx, rec_vz, rec_txx, rec_tzz, rec_txz, 
					rec_p, rec_pp, rec_ss, rec_udp, rec_udvz, verbose);
			
				/* at the end of modeling a shot, write receiver array to output file(s) */
				if (writeToFile && (it+rec.skipdt <= it1-1) ) {
					fileno = ( ((it-rec.delay)/rec.skipdt)+1)/rec.nt;
					writeRec(rec, mod, bnd, wav, ixsrc, izsrc, isam+1, ishot, fileno,
						rec_vx, rec_vz, rec_txx, rec_tzz, rec_txz, 
						rec_p, rec_pp, rec_ss, rec_udp, rec_udvz, verbose);
				}
			}

			/* write snapshots to output file(s) */
			if (sna.nsnap) {
				writeSnapTimes(mod, sna, ixsrc, izsrc, it, vx, vz, tzz, txx, txz, verbose);
			}

			/* calculate beams */
			if(sna.beam) {
				getBeamTimes(mod, sna, vx, vz, tzz, txx,  txz, 
					beam_vx, beam_vz, beam_txx, beam_tzz, beam_txz, 
					beam_p, beam_pp, beam_ss, verbose);
			}
}
					
			/* taper the edges of the model */
//			taperEdges(mod, bnd, vx, vz, verbose);

#pragma omp master
{
			if (verbose) {
				if (it==it0+100*its) t2=wallclock_time();
				if (it==(it0+500*its)) {
					t3=wallclock_time();
					tt=(t3-t2)*(((it1-it0)*its)/400.0);
					vmess("Estimated compute time = %.2f s. per shot.",tt);
					vmess("Estimated total compute time = %.2f s.",tinit+shot.n*tt);
				}
			}
}
} /* end of OpenMP parallel section */

		} /* end of loop over time steps it */

		/* write output files: receivers and or beams */
		if (fileno) fileno++;
		
		if (rec.scale==1) { /* scale receiver with distance src-rcv */
			float xsrc, zsrc, Rrec, rdx, rdz;
			int irec;
			xsrc=mod.x0+mod.dx*ixsrc;
			zsrc=mod.z0+mod.dz*izsrc;
			for (irec=0; irec<rec.n; irec++) {
				rdx=mod.x0+rec.xr[irec]-xsrc;
				rdz=mod.z0+rec.zr[irec]-zsrc;
				Rrec = sqrt(rdx*rdx+rdz*rdz);
				fprintf(stderr,"Rec %d is scaled with distance %f R=%.2f,%.2f S=%.2f,%.2f\n", irec, Rrec,rdx,rdz,xsrc,zsrc);
				for (it=0; it<rec.nt; it++) {
					rec_p[irec*rec.nt+it] *= sqrt(Rrec);
				}
			}
		}
		writeRec(rec, mod, bnd, wav, ixsrc, izsrc, isam+1, ishot, fileno,
			rec_vx, rec_vz, rec_txx, rec_tzz, rec_txz, 
			rec_p, rec_pp, rec_ss, rec_udp, rec_udvz, verbose);
		
		writeBeams(mod, sna, ixsrc, izsrc, ishot, fileno, 
				   beam_vx, beam_vz, beam_txx, beam_tzz, beam_txz, 
				   beam_p, beam_pp, beam_ss, verbose);
		

	} /* end of loop over number of shots */


	t1= wallclock_time();
	if (verbose) {
		vmess("Total compute time FD modelling = %.2f s.", t1-t0);
	}

	/* free arrays */
	
	free(rox);
	free(roz);
	free(l2m);
	free(src_nwav[0]);
	free(src_nwav);
	free(vx);
	free(vz);
	free(tzz);
	if (rec.type.vz)  free(rec_vz);
	if (rec.type.vx)  free(rec_vx);
	if (rec.type.p)   free(rec_p);
	if (rec.type.txx) free(rec_txx);
	if (rec.type.tzz) free(rec_tzz);
	if (rec.type.txz) free(rec_txz);
	if (rec.type.pp)  free(rec_pp);
	if (rec.type.ss)  free(rec_ss);
	if (rec.type.ud)  {
		free(rec_udvz);
		free(rec_udp);
	}
	if(sna.beam) {
		if (sna.type.vz)  free(beam_vz);
		if (sna.type.vx)  free(beam_vx);
		if (sna.type.p)   free(beam_p);
		if (sna.type.txx) free(beam_txx);
		if (sna.type.tzz) free(beam_tzz);
		if (sna.type.txz) free(beam_txz);
		if (sna.type.pp)  free(beam_pp);
		if (sna.type.ss)  free(beam_ss);
	}
	
	if (mod.ischeme==2) {
		free(tss);
		free(tep);
		free(q);
	}
	if (mod.ischeme>2) {
		free(lam);
		free(mul);
		free(txz);
		free(txx);
	}
	if (mod.ischeme==4) {
		free(tss);
		free(tes);
		free(tep);
		free(r);
		free(p);
		free(q);
	}


	return 0;
}
コード例 #20
0
void XmlParser::loadFromXml(const char * fileName, int * argc, char ** argv) {
    XmlFile xmlFile(fileName);
    XmlDocument doc;
    doc.parse<0>(xmlFile.data());
    int W, H;

    XmlNode * rtNode = doc.first_node("ge");

    /*** Read window information ***/
    XmlNode * windowNode = rtNode->first_node("window");
    if (windowNode) {
        // Try to read window name
        XmlNode * name;
        xmlElement(name, windowNode);

        // Read width and height
        XmlNode * width, *height;
        xmlElement(width, windowNode);
        xmlElement(height, windowNode);

        W = atoi(width->value());
        H = atoi(height->value());

        // Set window parameters
        GameWindow::setWindow((name) ? name->value() : "GE", W, H);
    } else {
        W = 512;
        H = 512;

        GameWindow::setWindow("GE", W, H);
    }
    // Init gamewindow and light
    GameWindow::init(argc, argv);
    Light::init();
    Material::init();
    Input::init();
    GBuffer::init(W,H);
    // Load noise texture
    glActiveTexture(GL_TEXTURE11);
    LoadTexBMP("textures/noise.bmp");
    /*** Read Scene ***/
    // Reference to scene node
    XmlNode * sceneNode = rtNode->first_node("scene");
    // Instantiate scene    
    Scene * scene = new Scene();
    // Instantiate renderer
    Renderer * renderer = new Renderer();
    // Set renderer
    GameWindow::setRenderer(renderer);
    renderer->setScene(scene);

	// Create camera
	Camera * camera = new Camera();
	// Set camera
	renderer->setCamera(camera);
	camera->setAspectRatio(W/H);

	// Read Camera
	XmlNode * cameraNode = rtNode->first_node("camera");
	if (cameraNode) {
		readModel(camera, cameraNode->first_node("model"));
//		// Set position
//		XmlNode * position = cameraNode->first_node("position");
//		if (position) {
//			// Get coordinates
//			XmlAttr * x, *y, *z;
//			xmlAttribute(x, position);
//			xmlAttribute(y, position);
//			xmlAttribute(z, position);
//			camera->setPosition(atof(x->value()), atof(y->value()), atof(z->value()));
//		}
//
//		// Set direction
//		XmlNode * direction= cameraNode->first_node("direction");
//		if (direction) {
//			// Get coordinates
//			XmlAttr * x, *y, *z;
//			xmlAttribute(x, direction);
//			xmlAttribute(y, direction);
//			xmlAttribute(z, direction);
//			camera->setDirection(atof(x->value()), atof(y->value()),
//					atof(z->value()));
//		}
//
//
//		// Set direction
//		XmlNode * up = cameraNode->first_node("up");
//		if (up) {
//			// Get coordinates
//			XmlAttr * x, *y, *z;
//			xmlAttribute(x, up);
//			xmlAttribute(y, up);
//			xmlAttribute(z, up);
//			camera->setUp(atof(x->value()), atof(y->value()),
//					atof(z->value()));
//		}

		// Read scripts
		XmlNode * scriptsNode = cameraNode->first_node("scripts");
		readScripts(scene, camera, scriptsNode);
	}

    // Light shadow map must be initialized after renderer has a camera
    Light::initShadowMap(renderer->createShaderProg("shaders/shadow.vert", "shaders/shadow.frag"));

    // Read objects
    XmlNode * objectsNode = sceneNode->first_node("objects");
    if (objectsNode) {
        // Read all cubes
        XmlNode * cubeNode = objectsNode->first_node("cube");
        readCubes(renderer, scene, cubeNode);

        // Read all mesh from scene
        XmlNode * meshNode = objectsNode->first_node("mesh");
        readMeshs(renderer, scene, meshNode);
        
    } else {
        printf("No objects\n");
    }

    // Read Lights
    XmlNode * lights = sceneNode->first_node("lights");
    readLights(scene, lights);
}
コード例 #21
0
void AssetLoader::readModel(Ogre::SceneManager* sceneMgr, Ogre::SceneNode* scnNode, const aiScene* scene, aiNode* nd)
{
	for (size_t n = 0; n < nd->mNumChildren; n++) 
	{	
		aiNode* cnd = nd->mChildren[n];
		Ogre::SceneNode* cnode = createChildSceneNodeWithTransform(scnNode, cnd);

		for (size_t i = 0; i < cnd->mNumMeshes; i++) {
			aiMesh* m = scene->mMeshes[cnd->mMeshes[i]];	
			aiMaterial* mat = scene->mMaterials[m->mMaterialIndex];

			std::string nodeName = getFullPathName(cnd);
			Ogre::MaterialPtr omat = createMaterial(Ogre::String(nodeName), m->mMaterialIndex, mat);

			aiVector3D* vec  = m->mVertices;
			aiVector3D* norm = m->mNormals;
			aiVector3D* uv   = m->mTextureCoords[0];
			aiColor4D*  vcol = NULL;	
			if (m->HasVertexColors(0)) vcol = m->mColors[0];

			// 頂点情報の読み込み
			Ogre::AxisAlignedBox aab;
			Ogre::ManualObject* mobj = new Ogre::ManualObject(nodeName+"_MObj");
			mobj->begin(omat->getName());
			//mobj->begin("Ogre/Skin");
			for (size_t n = 0; n < m->mNumVertices; n ++) {
				Ogre::Vector3 position(vec->x, vec->y, vec->z);
				aab.merge(position);

				mobj->position(vec->x, vec->y, vec->z); 
				vec++;  

				mobj->normal(norm->x, norm->y, norm->z);
				norm++; 

				if (uv)   { 
					mobj->textureCoord(uv->x, uv->y);        
					uv++;   
				}
				if (vcol) { 
					mobj->colour(vcol->r, vcol->g, vcol->b, vcol->a); 
					vcol++;
				}
			}

			// ポリゴンの構築
			for (size_t n = 0; n < m->mNumFaces; n++) {
				aiFace* face = &m->mFaces[n];
				for (size_t k = 0; k < face->mNumIndices; k++) {
					mobj->index(face->mIndices[k]);
				}
			}
			mobj->end();
			mobj->setBoundingBox(aab);

			Ogre::String meshName(nodeName+"_Mesh");
			mobj->convertToMesh(meshName);
			delete mobj;

			Ogre::String entityName(nodeName+"_Entity");
			std::cout << "entity: " << entityName << std::endl;
			Ogre::Entity* ent = sceneMgr->createEntity(entityName, meshName);
			cnode->attachObject(ent);
		}

		readModel(sceneMgr, cnode, scene, cnd);
	}
}
コード例 #22
0
ファイル: sxplot.c プロジェクト: gwowen/seismicunix
int main (int argc, char **argv)
{
	int nTic1,nTic2,width,height;
	float smin,smax,bclip,wclip,x1beg,x1end,x2beg,x2end;
	char *edgecolor="cyan",*tricolor="yellow",*cmap="gray",
		*label1="",*label2="",*title="",
		*labelFont="",*titleFont="",
		*axesColor="",*gridColor="",*titleColor="",
		*style="seismic",*grid1="none",*grid2="none";
	Model *model;
	XrmValue from,to;
	ExposeCD exposeCD;
	Widget toplevel,axes;
	Display *dpy;
	Window win;
	Arg args[100];
	int nargs;
	float bhue=0,whue=240,sat=1,bright=1;

	/* initialize getpar */
	initargs(argc,argv);
        requestdoc(0);

	
	/* read model */
	model = readModel(stdin);
	
	/* determine minimum and maximum s(x,y) */
	minmax(model,&smin,&smax);
	
	/* get optional parameters */
	getparstring("edgecolor",&edgecolor);
	getparstring("tricolor",&tricolor);
	bclip = smin; getparfloat("bclip",&bclip);
	wclip = smax; getparfloat("wclip",&wclip);
        getparstring("cmap",&cmap);   

	/* initialize toolkit intrinsics and set toplevel parameters */
	toplevel = XtInitialize(argv[0],"Sxplot",NULL,0,&argc,argv);
	nargs = 0;
	if (getparint("width",&width))
		{XtSetArg(args[nargs],XtNwidth,width); nargs++;}
	if (getparint("height",&height))
		{XtSetArg(args[nargs],XtNheight,height); nargs++;}
	XtSetValues(toplevel,args,nargs);

	/* create axes and set axes parameters */
	axes = XtCreateManagedWidget("axes",xtcwpAxesWidgetClass,
		toplevel,NULL,0);


	nargs = 0;
	if (getparstring("grid1",&grid1)) {
		from.addr = (char *)grid1;
		XtConvertAndStore(axes,XtRString,&from,XtcwpRAxesGrid,&to);
		if (to.addr) XtSetArg(args[nargs],XtNgrid1,*((int*)to.addr));
		nargs++;
	}
	if (getparstring("grid2",&grid2)) {
		from.addr = (char *)grid2;
		XtConvertAndStore(axes,XtRString,&from,XtcwpRAxesGrid,&to);
		if (to.addr) XtSetArg(args[nargs],XtNgrid2,*((int*)to.addr));
		nargs++;
	}
	if (getparint("nTic1",&nTic1))
		{XtSetArg(args[nargs],XtNnTic1,nTic1); nargs++;}
	if (getparint("nTic2",&nTic2))
		{XtSetArg(args[nargs],XtNnTic2,nTic2); nargs++;}
	if (getparstring("label1",&label1))
		{XtSetArg(args[nargs],XtNlabel1,label1); nargs++;}
	if (getparstring("label2",&label2))
		{XtSetArg(args[nargs],XtNlabel2,label2); nargs++;}
	if (getparstring("title",&title))
		{XtSetArg(args[nargs],XtNtitle,title); nargs++;}
	if (getparstring("style",&style)) {
		from.size = (unsigned int) strlen(style);  from.addr = (char *)style;
		XtConvertAndStore(axes,XtRString,&from,XtcwpRAxesStyle,&to);
		if (to.addr) XtSetArg(args[nargs],XtNstyle,*((int*)to.addr));
		nargs++;
	}
	if (getparstring("axesColor",&axesColor)) {
		from.addr = (char *)axesColor;
		XtConvertAndStore(axes,XtRString,&from,XtRPixel,&to);
		if (to.addr) XtSetArg(args[nargs],XtNaxesColor,
			*((unsigned long*)to.addr));
		nargs++;
	}
	if (getparstring("gridColor",&gridColor)) {
		from.addr = (char *)gridColor;
		XtConvertAndStore(axes,XtRString,&from,XtRPixel,&to);
		if (to.addr) XtSetArg(args[nargs],XtNgridColor,
			*((unsigned long*)to.addr));
		nargs++;
	}
	if (getparstring("titleColor",&titleColor)) {
		from.addr = (char *)titleColor;
		XtConvertAndStore(axes,XtRString,&from,XtRPixel,&to);
		if (to.addr) XtSetArg(args[nargs],XtNtitleColor,
			*((unsigned long*)to.addr));
		nargs++;
	}
	if (getparstring("labelFont",&labelFont)) {
		from.addr = (char *)labelFont;
		XtConvertAndStore(axes,XtRString,&from,XtRFont,&to);
		if (to.addr) XtSetArg(args[nargs],XtNlabelFont,
			*((Font*)to.addr));
		nargs++;
	}
	if (getparstring("titleFont",&titleFont)) {
		from.addr = (char *)titleFont;
		XtConvertAndStore(axes,XtRString,&from,XtRFont,&to);
		if (to.addr) XtSetArg(args[nargs],XtNtitleFont,
			*((Font*)to.addr));
		nargs++;
	}
	XtSetValues(axes,args,nargs);
	x1beg = model->xmin; getparfloat("x1beg",&x1beg);
	x1end = model->xmax; getparfloat("x1end",&x1end);
	x2beg = model->ymin; getparfloat("x2beg",&x2beg);
	x2end = model->ymax; getparfloat("x2end",&x2end);
	XtcwpSetAxesValues(axes,x1beg,x1end,x2beg,x2end);

	/* add callbacks to axes widget */
	XtAddCallback(axes,XtNresizeCallback,(XtCallbackProc) resizeCB,NULL);
	exposeCD.model = model;
	exposeCD.edgecolor = edgecolor;
	exposeCD.tricolor = tricolor;
	exposeCD.bclip = bclip;
	exposeCD.wclip = wclip;
	XtAddCallback(axes,XtNexposeCallback,(XtCallbackProc) exposeCB,&exposeCD);
	XtAddCallback(axes,XtNinputCallback,(XtCallbackProc) inputCB,NULL);

	/* realize widgets */
	XtRealizeWidget(toplevel);

	/* if necessary, create private colormap */
	dpy = XtDisplay(toplevel);
	win = XtWindow(toplevel);

	if (STREQ(cmap,"gray")) {
	  XSetWindowColormap(dpy,win,XtcwpCreateGrayColormap(dpy,win));
	} else if (STREQ(cmap,"hue")) {
	  XSetWindowColormap(dpy,win,XtcwpCreateHueColormap(dpy,win,
														bhue,whue,sat,bright)); /* see Note below */
	}
	
	/* go */
	XtMainLoop();

	return EXIT_SUCCESS;
}
コード例 #23
0
void XmlParser::readMeshs(Renderer * renderer ,Scene * scene, XmlNode * meshNode) {
    // Read mesh
    while(meshNode) {
        // Create cube
        glm::mat4 id;
        MeshObject * mesh = new MeshObject(id);
        // Read shaders and init it
        int basicShader = renderer->getDefaultBasicShader();
        int lightShader = renderer->getDefaultLightShader();
        XmlNode * basicShaderNode = meshNode->first_node("basic-shader");
        XmlNode * lightShaderNode = meshNode->first_node("light-shader");
        
        // If there is a basic shader node
        if (basicShaderNode) {
            XmlAttr * vert, * frag;
            xmlAttribute(vert, basicShaderNode);
            xmlAttribute(frag, basicShaderNode);
            // Create new shader
            basicShader = renderer->createShaderProg(vert->value(), frag->value());
        }

        // If there is a light shader node
        if (lightShaderNode) {
            XmlAttr * vert, * frag;
            xmlAttribute(vert, lightShaderNode);
            xmlAttribute(frag, lightShaderNode);
            // Create new shader
            lightShader = renderer->createShaderProg(vert->value(), frag->value());
        }

        // Init mesh
        mesh->init(basicShader, lightShader);

        // Load file (it must exist)
        XmlAttr * file;
        xmlAttribute(file, meshNode);
        mesh->loadFromFile(file->value());
        
        // Try to read model
        readModel(mesh, meshNode->first_node("model"));

        // Add c to scene
        scene->addGameObject(mesh);

        // Set texture
        XmlNode * textureNode = meshNode->first_node("texture");
        if (textureNode) {
            // Get file name
            XmlAttr * file;
            xmlAttribute(file, textureNode);

            // Create texture
            Texture texture(GL_TEXTURE0, std::string(file->value()));

            // Set texture
            mesh->setTexture(texture);
        }

        // Set normal map
        XmlNode * normalMapNode = meshNode->first_node("normal-map");
        if (normalMapNode) {
            // Get file name
            XmlAttr * file;
            xmlAttribute(file, normalMapNode);

            // Create texture
            Texture normalMap(GL_TEXTURE2, std::string(file->value()));

            // Set texture
            mesh->setNormalMap(normalMap);
        }

        // Set material
		XmlNode * material = meshNode->first_node("material");
		if (material) {
			// Create material
			Material * m = new Material();

			// Set emissive
			XmlNode * emissive = material->first_node("emissive");
			if (emissive) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, emissive);
				xmlAttribute(g, emissive);
				xmlAttribute(b, emissive);
				// Set diffuse
				m->setEmissive(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read ambient
			XmlNode * ambient = material->first_node("ambient");
			if (ambient) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, ambient);
				xmlAttribute(g, ambient);
				xmlAttribute(b, ambient);
				// Set diffuse
				m->setAmbient(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read diffuse
			XmlNode * diffuse = material->first_node("diffuse");
			if (diffuse) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, diffuse);
				xmlAttribute(g, diffuse);
				xmlAttribute(b, diffuse);
				// Set diffuse
				m->setDiffuse(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read specular
			XmlNode * specular = material->first_node("specular");
			if (specular) {
				XmlAttr * r, *g, *b;
				xmlAttribute(r, specular);
				xmlAttribute(g, specular);
				xmlAttribute(b, specular);
				// Set diffuse
				m->setSpecular(atof(r->value()), atof(g->value()),
						atof(b->value()));
			}

			// Read specular
			XmlNode * shininess = material->first_node("shininess");
			if (shininess) {
				XmlAttr * value;
				xmlAttribute(value, shininess);
				// Set diffuse
				m->setShininess(atof(value->value()));
			}

			// Set material
			mesh->setMaterial(m);
		}

        // Read Scripts
        XmlNode * scripts = meshNode->first_node("scripts");
        readScripts(scene, mesh, scripts);

        // Get next cube
        meshNode = meshNode->next_sibling("mesh");
    }
}
コード例 #24
0
ファイル: smoClassify.c_pre.c プロジェクト: venkatesh20/SVM
int main(int argc, char *argv[ ]) {

     FILE *modelIn, *dataIn, *out;


          init_data(example, sv, lambda, svNonZeroFeature, nonZeroFeature, target, weight, output, zeroFeatureExample, rbfConstant, degree
                    , b, numSv, numExample, kernelType, maxFeature);

          char* mfile = "C:\\Users\\Owner\\Desktop\\SVM\\SMO\\smosynth\\smosynth\\linear_results\\model.dat";

           if(( modelIn = fopen( mfile, "r" ) ) == ((void *)0) ) {
            fprintf( (&_iob[2]), "Can't open %s\n", mfile);
             exit(2);
           }

           char* tfile = "C:\\Users\\Owner\\Desktop\\SVM\\SMO\\smosynth\\smosynth\\linear_results\\test.dat";

           if(( dataIn = fopen( tfile, "r" ) ) == ((void *)0) ) {
               fprintf( (&_iob[2]), "Can't open %s\n", tfile );
               exit(2);
           }

           char* pfile = "C:\\Users\\Owner\\Desktop\\SVM\\SMO\\smosynth\\smosynth\\linear_results\\pred.dat";
         if(( out = fopen( pfile, "w" ) ) == ((void *)0) ) {
           fprintf( (&_iob[2]), "Can't open %s\n", pfile );
           exit(2);
         }

           if( ! readModel( modelIn, example, sv, lambda, svNonZeroFeature, nonZeroFeature, target, weight, output, zeroFeatureExample, rbfConstant, degree
                    , b, numSv, numExample, kernelType, maxFeature ) ) {
              fprintf( (&_iob[2]), "Error in reading model file %s\n", mfile );
              exit (3);
           } else fclose( modelIn );
            printf("Finish reading model file\n");

         if( !readData( dataIn, example, sv, lambda, svNonZeroFeature, nonZeroFeature, target, weight, output, zeroFeatureExample, rbfConstant, degree
                    , b, numSv, numExample, kernelType, maxFeature )) {
            printf("Error reading data file\n");
            exit(4);
         }
           fclose( dataIn );
           printf("Finish reading test data file\n");

          int ret=synth_top(example, sv, lambda, svNonZeroFeature, nonZeroFeature, weight, output, 0);

           if ( ret==0 )
             printf("Classification is completed\n");
           else
           fprintf( (&_iob[2]), "Classification process failed\n");

       write_result(out, output, b);

       fclose( out );

         ret = diff_files();
        printf("RETURN VALUE %d\n", ret);

   if (ret != 0) {
      printf("Test failed %d!!!\n", ret);
      return 1;
   } else {
      printf("Test passed %d!\n", ret);
      return 0;
   }

}
コード例 #25
0
ファイル: elatriuni.c プロジェクト: JOravetz/SeisUnix
/* the main program */
int main (int argc, char **argv)
{
	int nx,nz,ix,iz;
	float dx,fx,dz,fz,x,z,xmin,xmax,zmin,zmax;
	float **a1111,**a3333,**a1133,**a1313,**a1113;
	float **a1212,**a2323,**a1223,**rho;
	float **a3313;
	Tri *t;
	TriAttributes *ta;
	Model *m;
	char *a1111file, *a3333file, *a1133file;
	char *a1313file, *a1113file, *a3313file;
	char *a1212file, *a1223file, *a2323file;
	char *rhofile;
	FILE *a1111fp=NULL, *a3333fp=NULL, *a1133fp=NULL;
	FILE *a1313fp=NULL, *a1113fp=NULL, *a3313fp=NULL;
	FILE *a1212fp=NULL, *a1223fp=NULL, *a2323fp=NULL;
	FILE *rhofp=NULL;
	/* hook up getpar to handle the parameters */
	initargs(argc,argv);
	requestdoc(0);
	
	/* get required parameters */
	if (!getparint("nx",&nx)) err("must specify nx!");
	if (!getparint("nz",&nz)) err("must specify nz!");
	
	/* get optional parameters */
	if (!getparfloat("dx",&dx)) dx = 1.0;
	if (!getparfloat("dz",&dz)) dz = 1.0;
	if (!getparfloat("fx",&fx)) fx = 0.0;
	if (!getparfloat("fz",&fz)) fz = 0.0;
	
	if(getparstring("a1111file",&a1111file))
		 	a1111fp = efopen(a1111file,"w");
	else a1111fp = efopen("a1111.bin","w");

	if(getparstring("a3333file",&a3333file))
		 	a3333fp = efopen(a3333file,"w");
	else a3333fp = efopen("a3333.bin","w");

	if(getparstring("a1133file",&a1133file))
		 	a1133fp = efopen(a1133file,"w");
	else a1133fp = efopen("a1133.bin","w");

	if(getparstring("a1313file",&a1313file))
		 	a1313fp = efopen(a1313file,"w");
	else a1313fp = efopen("a1313.bin","w");

	if(getparstring("a1113file",&a1113file))
		 	a1113fp = efopen(a1113file,"w");
	else a1113fp = efopen("a1113.bin","w");

	if(getparstring("a3313file",&a3313file))
		 	a3313fp = efopen(a3313file,"w");
	else a3313fp = efopen("a3313.bin","w");

	if(getparstring("a1212file",&a1212file))
		 	a1212fp = efopen(a1212file,"w");
	else a1212fp = efopen("a1212.bin","w");

	if(getparstring("a2323file",&a2323file))
		 	a2323fp = efopen(a2323file,"w");
	else a2323fp = efopen("a2323.bin","w");

	if(getparstring("a1223file",&a1223file))
		 	a1223fp = efopen(a1223file,"w");
	else a1223fp = efopen("a1223.bin","w");

	if(getparstring("rhofile",&rhofile))
		 	rhofp = efopen(rhofile,"w");
	else rhofp = efopen("rho.bin","w");

        checkpars();


	/* read input triangulated sloth model */
	m = readModel(stdin);
	
	/* determine min and max x and z coordinates */
	xmin = m->ymin;
	xmax = m->ymax;
	zmin = m->xmin;
	zmax = m->xmax;
	
	/* allocate space for uniformly sampled stiffnesses */
	a1111 = ealloc2float(nz,nx);
	a3333 = ealloc2float(nz,nx);
	a1133 = ealloc2float(nz,nx);
	a1313 = ealloc2float(nz,nx);
	a1113 = ealloc2float(nz,nx);
	a3313 = ealloc2float(nz,nx);
	a1212 = ealloc2float(nz,nx);
	a1223 = ealloc2float(nz,nx);
	a2323 = ealloc2float(nz,nx);
	rho = ealloc2float(nz,nx);

	/* loop over all samples */
	for (ix=0,x=fx,t=NULL; ix<nx; ++ix,x+=dx) {
		if (x<xmin || x>xmax)
			err("x=%g must be between xmin=%g and xmax=%g",
				x,xmin,xmax);
		for (iz=0,z=fz; iz<nz; ++iz,z+=dz) {
			if (z<zmin || z>zmax)
				err("z=%g must be between zmin=%g and zmax=%g",
					z,zmin,zmax);
			t = insideTriInModel(m,t,z,x);
			ta = (TriAttributes*)t->fa;
			a1111[ix][iz] = ta->a1111;
			a3333[ix][iz] = ta->a3333;
			a1133[ix][iz] = ta->a1133;
			a1313[ix][iz] = ta->a1313;
			a1113[ix][iz] = ta->a1113;
			a3313[ix][iz] = ta->a3313;
			a1212[ix][iz] = ta->a1212;
			a2323[ix][iz] = ta->a2323;
			a1223[ix][iz] = ta->a1223;
			rho[ix][iz] = ta->rho;

		}
	}
	
	/* write uniformly sampled sloth */
	fwrite(a1111[0],sizeof(float),nz*nx,a1111fp);
	fwrite(a3333[0],sizeof(float),nz*nx,a3333fp);
	fwrite(a1133[0],sizeof(float),nz*nx,a1133fp);
	fwrite(a1313[0],sizeof(float),nz*nx,a1313fp);
	fwrite(a1113[0],sizeof(float),nz*nx,a1113fp);
	fwrite(a3313[0],sizeof(float),nz*nx,a3313fp);
	fwrite(a1212[0],sizeof(float),nz*nx,a1212fp);
	fwrite(a2323[0],sizeof(float),nz*nx,a2323fp);
	fwrite(a1223[0],sizeof(float),nz*nx,a1223fp);
	fwrite(rho[0],sizeof(float),nz*nx,rhofp);

	return 1;
}
コード例 #26
0
ファイル: elacheck.c プロジェクト: JohnWStockwellJr/SeisUnix
/* the main program */
int main (int argc, char **argv)
{
	/* int want,mindex=0; */
	int want;
	float x,z,a1111,a3333,a1133,a1313,a1113,a3313,v_p,v_s;
	float a1212,a2323,a1223,rho;
	Model *m;
	Face *t;
	FaceAttributes *fa;
	char *mfile;
	FILE *mfp;

	want=1;

	/* hook up getpar to handle the parameters */
	initargs(argc,argv);
	requestdoc(0);

	if (!getparstring("file",&mfile))
		err("ERROR: No modelfile defined");
        mfp = efopen(mfile,"r");

        checkpars();

	a1111=a3333=a1133=a1313=a1113=a3313=v_p=v_s=0;
	a1212=a1223=a2323=rho=0;

	/* read model */
	m = readModel(mfp);

 	fprintf (stderr," **********************************************\n");
 	fprintf (stderr," *********check stiffness coefficients*********\n");
 	fprintf (stderr," **********************************************\n\n");

	do {
		want = 1;
 		fprintf (stderr," Enter x-coordinate \n");
 		scanf  ("%f", &x);

 		fprintf (stderr," Enter z-coordinate \n");
 		scanf  ("%f", &z);

		/* determine triangle containing point (x,z) */

		if(x > m->ymax || x < m->ymin || z > m->xmax || z < m->xmin){ 
			fprintf (stderr," Coordinate outside of model \n\n");
			continue;
		}

		t = insideTriInModel(m,NULL,z,x);

		if ((fa=t->fa)!=NULL){
	 		a1111 = fa->a1111;
	 		a3333 = fa->a3333;
	 		a1133 = fa->a1133;
	 		a1313 = fa->a1313;
	 		a1113 = fa->a1113;
	 		a3313 = fa->a3313;
			v_p = sqrt(a3333);
			v_s = sqrt(a1313);

			a1212 = fa->a1212;
			a1223 = fa->a1223;
			a2323 = fa->a2323;
			rho   = fa->rho;
			/* mindex  = fa->mindex; */


		}
		fprintf(stderr,"\n ----Coordinates x=%g \t z=%g ----\n\n",x,z); 
  		/* fprintf(stderr,"\t\t mindex=%i \n ",mindex); */

		fprintf(stderr,"\t\t a1111=%g \n",a1111);   
		fprintf(stderr,"\t\t a3333=%g \n",a3333);   
		fprintf(stderr,"\t\t a1133=%g \n",a1133);   
		fprintf(stderr,"\t\t a1313=%g \n",a1313);   
		fprintf(stderr,"\t\t a1113=%g \n",a1113);   
		fprintf(stderr,"\t\t a3313=%g \n",a3313);  
		fprintf(stderr,"\t\t a1212=%g \n",a1212);   
		fprintf(stderr,"\t\t a1223=%g \n",a1223);   
		fprintf(stderr,"\t\t a2323=%g \n",a2323);  
 
 		fprintf(stderr,"\t\t rho=%g \n",rho);   

		fprintf(stderr,"\t\t   v_p=%g \n",v_p);   
		fprintf(stderr,"\t\t   v_s=%g \n\n",v_s);

		fprintf (stderr," More checks type: 1 if yes, 0 if no \n");
 		scanf  ("%i", &want);
	} while (want!=0);

	return 1;

}
コード例 #27
0
ファイル: qwzm.cpp プロジェクト: ArtemusRus/warzone2100
void QWzmViewer::actionOpen()
{
	static QString lastDir; // Convenience HACK to remember last succesful directory a model was loaded from.
	filename = QFileDialog::getOpenFileName(this, tr("Choose a PIE or WZM file"), lastDir, tr("All Compatible (*.wzm *.pie);;WZM models (*.wzm);;PIE models (*.pie)"));
	if (!filename.isEmpty())
	{
		QFileInfo theFile(filename);
		MODEL *tmpModel = NULL;

		if (theFile.completeSuffix().compare(QString("wzm"), Qt::CaseInsensitive) == 0)
		{
			tmpModel = readModel(filename.toAscii().constData(), 0);
		}
		else if (theFile.completeSuffix().compare(QString("pie"), Qt::CaseInsensitive) == 0)
		{
			tmpModel = loadPIE(filename);
		}
		else
		{
			return;
		}

		if (tmpModel)
		{

			QFileInfo texPath(theFile.absoluteDir(), tmpModel->texPath);

			// Try to find texture automatically
			if (!texPath.exists())
			{
				texPath.setFile(QString("../../data/base/texpages/"), tmpModel->texPath);
				if (!texPath.exists())
				{
					texPath.setFile(QFileDialog::getExistingDirectory(this, tr("Specify texture directory"), QString::null), tmpModel->texPath);
					if (!texPath.exists())
					{
						QMessageBox::warning(this, tr("Oops..."), "Could not find texture", QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
						freeModel(tmpModel);
						return;
					}
				}
			}
			if (psModel)
			{
				freeModel(psModel);
			}
			psModel = tmpModel;
			setModel(texPath);
			ui->actionSave->setEnabled(true);
			lastDir = theFile.absolutePath();
			fileNameLabel->setText(theFile.fileName());
			fileNameLabel->setToolTip(filename);
		}
		else
		{
			qWarning("Failed to create model!");

			ui->statusBar->showMessage(tr("Failed to create model!"), 3000);
		}
	}
}
コード例 #28
0
ファイル: wzmviewer.c プロジェクト: RodgerNO1/warzone2100
int main(int argc, char **argv)
{
    MODEL *psModel;
    const int width = 640, height = 480;
    SDL_Event event;
    GLfloat angle = 0.0f;
    const float aspect = (float)width / (float)height;
    bool quit = false;
    float dimension = 0.0f;
    int i;
    char path[PATH_MAX];

    parse_args(argc, argv);

    /* Initialize SDL */
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0)
    {
        fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    atexit(SDL_Quit);

    psModel = readModel(input, SDL_GetTicks());
    strcpy(path, texPath);
    strcat(path, psModel->texPath);
    psModel->pixmap = readPixmap(path);

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    /* Initialize the display */
    screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL|SDL_ANYFORMAT);
    if (screen == NULL)
    {
        fprintf(stderr, "Couldn't initialize display: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    printf("OpenGL version: %s\n", glGetString(GL_VERSION));
    printf("OpenGL renderer: %s\n", glGetString(GL_RENDERER));
    printf("OpenGL vendor: %s\n", glGetString(GL_VENDOR));

    resizeWindow(width, height);
    glEnable(GL_TEXTURE_2D);
    glDisable(GL_FOG);
    glDisable(GL_LIGHTING);
    glEnable(GL_BLEND);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glClearDepth(1.0f);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0f, aspect, 0.1f, 500.0f);
    glMatrixMode(GL_MODELVIEW);

    prepareModel(psModel);
    for (i = 0; i < psModel->meshes; i++)
    {
        int j;
        MESH *psMesh = &psModel->mesh[i];

        for (j = 0; j < psMesh->vertices * 3; j++)
        {
            dimension = MAX(fabs(psMesh->vertexArray[j]), dimension);
        }
    }

    /* Find model size */

    while (!quit)
    {
        now = SDL_GetTicks();
        while (SDL_PollEvent(&event))
        {
            SDL_keysym *keysym = &event.key.keysym;

            switch (event.type)
            {
            case SDL_VIDEORESIZE:
                resizeWindow(event.resize.w, event.resize.h);
                break;
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_KEYDOWN:
                switch (keysym->sym)
                {
                case SDLK_F1:
                    glEnable(GL_CULL_FACE);
                    printf("Culling enabled.\n");
                    break;
                case SDLK_F2:
                    glDisable(GL_CULL_FACE);
                    printf("Culling disabled.\n");
                    break;
                case SDLK_F3:
                    glDisable(GL_TEXTURE_2D);
                    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                    printf("Wireframe mode.\n");
                    break;
                case SDLK_F4:
                    glEnable(GL_TEXTURE_2D);
                    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
                    printf("Texturing mode.\n");
                    break;
                case SDLK_ESCAPE:
                    quit = true;
                    break;
                case SDLK_KP_PLUS:
                case SDLK_PLUS:
                    for (i = 0; i < psModel->meshes; i++)
                    {
                        MESH *psMesh = &psModel->mesh[i];

                        if (!psMesh->teamColours)
                        {
                            continue;
                        }

                        if (psMesh->currentTextureArray < 7)
                        {
                            psMesh->currentTextureArray++;
                        }
                        else
                        {
                            psMesh->currentTextureArray = 0;
                        }
                    }
                    break;
                default:
                    break;
                }
                break;
            }
        }

        glLoadIdentity();
        glTranslatef(0.0f, -30.0f, -50.0f + -(dimension * 2.0f));;
        glRotatef(angle, 0, 1, 0);
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
        drawModel(psModel, now);
        SDL_GL_SwapBuffers();
        SDL_Delay(10);
        angle += 0.1;
        if (angle > 360.0f)
        {
            angle = 0.0f;
        }
    }

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    freeModel(psModel);

    return 0;
}
コード例 #29
0
void MlMaximumEntropyModel::learnLMBFGS(MlTrainingContainer* params)
{
	params->initialize();

	const MlDataSet* trainingDataSet = params->getTrainingDataSet();
	const MlDataSet* testDataSet     = params->getTestDataSet();
	const vector<size_t>& trainingIdxs = params->getTrainingIdxs();
	const vector<size_t>& testIdxs	   = params->getTestIdxs();
	const size_t numSamples = trainingIdxs.size();
	const bool performTest = (testDataSet && testIdxs.size()>0);

	if (trainingDataSet->getNumClasess() < 2)
		error("learnLMBFGS accepts only datasets with 2 or more classes, yor data has ",
			trainingDataSet->getNumClasess());

	const double  lambda  = params->getLambda();
	const size_t memorySize = params->getLmBfgsMemorySize(); 
	const size_t reportFrequency = params->getVerboseLevel();
	const double perplexityDelta  = params->getPerplexityDelta();
	const size_t numClasses  = trainingDataSet->getNumClasess();
	const size_t numFeatures = trainingDataSet->getNumBasicFeatures(); // F
	const size_t numTraining = trainingIdxs.size();    // N

	const size_t numRestarts=3;

	// data structures used for training
	vector< vector<double> >& w = weights_; // class X features
	vector< vector<double> > wOld(numClasses, vector<double>(numFeatures,0.0)); // class X features
	vector< vector<double> > wtx(numClasses, vector<double>(numTraining, 0.0));  // class X samples
	vector< vector<double> > qtx(numClasses, vector<double>(numTraining, 0.0));  // class X samples
	vector< vector<double> > q(numClasses, vector<double>(numFeatures,0.0));       // class X features
	vector< vector<double> > g(numClasses, vector<double>(numFeatures,0.0));       // class X features
	vector< vector<double> > gOld(numClasses, vector<double>(numFeatures,0.0));  // class X features

	vector< vector<float> > trainingProbs(numClasses, vector<float>(numTraining));
	vector< vector<float> > testProbs(numClasses, vector<float>(numTraining));
	vector< vector<double> > bestW(numClasses, vector<double>(numFeatures));

	// initialize weights
	if (params->getInputPath().length() > 1)
	{
		const string modelFile = params->getInputPath() + "_scr.txt";
		if (readModel(modelFile.c_str()))
			params->setIndClearWeights(false);
	}

	if (params->getIndClearWeights())
		weights_.clear();

	weights_.resize(numClasses, vector<double>(numFeatures,0.0));

	double previousPerplexity = MAX_FLOAT;
	float  bestTestError=1.0;
	size_t bestTestRound=0;
	float  bestTrainingError=1.0;
	size_t bestTrainingRound=0;

	bool terminateTraining = false;
	size_t totalRounds=0;
	size_t megaRound=0;
	for ( megaRound=0; megaRound<numRestarts; megaRound++)
	{
		// first round
		computeGradient(trainingDataSet, trainingIdxs, w, wtx, lambda, g);

		const double gtg = computeDotProduct(g,g);
		const double denominator = 1.0 / sqrt(gtg);
		for (size_t c=0; c<numClasses; c++)
			for (size_t i=0; i<numFeatures; i++)
				q[c][i]=g[c][i]*denominator;

		// qtx <- qTx
		for (size_t c=0; c<numClasses; c++)
			for (size_t i=0; i<numSamples; i++)
			{
				const MlSample& sample = trainingDataSet->getSample(trainingIdxs[i]);
				qtx[c][i]=computeDotProduct(q[c],sample.pairs);
			}

		// eta <- lineSearch(...)
		double eta = lineSearch(trainingDataSet, trainingIdxs, w, wtx, qtx, g, q, lambda);
		//cout << "eta = " << eta << endl;

		// update wtx <- wtx + eta*qtx
		for (size_t c=0; c<numClasses; c++)
			for (size_t i=0; i<wtx[c].size(); i++)
				wtx[c][i]+=eta*qtx[c][i];

		// update wOld<- w ; w <- w + eta *q ; gOld<-g
		for (size_t c=0; c<numClasses; c++)
		{
			memcpy(&wOld[c][0],&w[c][0],sizeof(double)*w[c].size());
			memcpy(&gOld[c][0],&g[c][0],sizeof(double)*g[c].size());
			for (size_t i=0; i<numFeatures; i++)
				w[c][i]+= eta*q[c][i];
		}


		// initialize memory
		vector< vector< vector<double> > > memoryU(memorySize, vector< vector<double> >(numClasses));
		vector< vector< vector<double> > > memoryD(memorySize, vector< vector<double> >(numClasses));
		vector< double > memoryAlpha(memorySize);
		size_t nextMemPosition=0;
		size_t numMemPushes=0;
		
		// iterate until convergence
		size_t round=1;
		while (round<10000)
		{
			// compute errors and report round results
			{
				double trainingLogLikelihood=0.0, testLogLikelihood=0.0;
				const double trainingError = calcErrorRateWithLogLikelihood(trainingDataSet, trainingIdxs,
																		false, &trainingLogLikelihood);
				double testError=1.0;
				if (performTest)
					testError = calcErrorRateWithLogLikelihood(testDataSet, testIdxs, false, &testLogLikelihood);

				if (reportFrequency>0 && round % reportFrequency == 0)
				{
					cout << round << "\t" << scientific << setprecision(5) << trainingLogLikelihood << "\t" << fixed << setprecision(5) << trainingError;
					if (performTest)
						cout <<"\t" << scientific << testLogLikelihood << "\t" << fixed << setprecision(5)<< testError;
					cout << endl;
				}
				
				if (performTest)
				{
					if (testError<=bestTestError)
					{
						bestTestRound=round;
						bestTestError=testError;
						for (size_t c=0; c<numClasses; c++)
							memcpy(&bestW[c][0],&w[c][0],numFeatures*sizeof(double)); // copy weights
					}
				}
				
				if (trainingError<=bestTrainingError)
				{
					bestTrainingRound=round;
					bestTrainingError=trainingError;
					if (! performTest)
					{
						for (size_t c=0; c<numClasses; c++)
							memcpy(&bestW[c][0],&w[c][0],numFeatures*sizeof(double)); // copy weights
					}
				}		
			}

			// Train new round

			computeGradient(trainingDataSet, trainingIdxs, w, wtx, lambda, g);

			double alpha=0.0;
			double sigma=0.0;
			double utu=0.0;

			// write u=g'-g and d=w'-w onto memory, use them to compute alpha and sigma
			vector< vector<double> >& u = memoryU[nextMemPosition];
			vector< vector<double> >& d = memoryD[nextMemPosition];
			for (size_t c=0; c<numClasses; c++)
			{
				const size_t numFeatures = g[c].size();
				u[c].resize(numFeatures);
				d[c].resize(numFeatures);
				for (size_t i=0; i<numFeatures; i++)
				{
					const double gDiff = g[c][i]-gOld[c][i];
					const double wDiff = w[c][i]-wOld[c][i];
					u[c][i]=gDiff;
					d[c][i]=wDiff;
					alpha += gDiff*wDiff;
					utu += gDiff*gDiff;
				}
			}
			sigma = alpha / utu;
			memoryAlpha[nextMemPosition]=alpha;

			// update memory position
			nextMemPosition++;
			if (nextMemPosition == memorySize)
				nextMemPosition = 0;
			numMemPushes++;

			// q<-g
			for (size_t c=0; c<numClasses; c++)
				memcpy(&q[c][0],&g[c][0],g[c].size()*sizeof(double));
			
			// determine memory evaluation order 1..M (M is the newest)
			vector<size_t> memOrder;
			if (numMemPushes<=memorySize)
			{
				for (size_t i=0; i<numMemPushes; i++)
					memOrder.push_back(i);
			}
			else
			{
				for (size_t i=0; i<memorySize; i++)
					memOrder.push_back((i+nextMemPosition) % memorySize);
			}

			vector<double> beta(memOrder.size(),0.0);
			for (int i=memOrder.size()-1; i>=0; i--)
			{
				const size_t m = memOrder[static_cast<size_t>(i)];
				const double alpha = memoryAlpha[m];
				
				const vector< vector<double> >& dM = memoryD[m];
				double& betaM = beta[m];

				// compute beta[m] = (memory_d[m] dot g)/alpha[m]
				for (size_t c=0; c<dM.size(); c++)
					for (size_t i=0; i<dM[c].size(); i++)
						betaM += dM[c][i]*g[c][i];
				betaM/=alpha;
				
				// q <- q - beta[m]*memory_u[m]
				const vector< vector<double> >& uM = memoryU[m]; 
				for (size_t c=0; c<q.size(); c++)
					for (size_t i=0; i<q[c].size(); i++)
						q[c][i] -= betaM * uM[c][i];

			}

			// q <- sigma*q
			for (size_t c=0; c<q.size(); c++)
				for (size_t i=0; i<q[c].size(); i++)
					q[c][i]*=sigma;


			for (size_t i=0; i<memOrder.size(); i++)
			{
				const size_t m = memOrder[static_cast<size_t>(i)];
				const vector< vector<double> >& uM = memoryU[m];
				const vector< vector<double> >& dM = memoryD[m]; 
				const double betaM = beta[m];
				const double oneOverAlpha = 1.0 / memoryAlpha[m];
				double umq = computeDotProduct(uM,q);
				for (size_t c=0; c<numClasses; c++)
					for (size_t j=0; j<q[c].size(); j++)
					{
						const double dq = dM[c][j] * (betaM - umq*oneOverAlpha);
						umq += uM[c][j]*dq;
						q[c][j] += dq;
					}
		
			}

			// q<- -q
			for (size_t c=0; c<numClasses; c++)
				for (size_t i=0; i<q[c].size(); i++)
					q[c][i]=-q[c][i];
			
			// qtx = q*X
			for (size_t i=0; i<trainingIdxs.size(); i++)
			{
				const MlSample& sample = trainingDataSet->getSample(trainingIdxs[i]);
				for (size_t c=0; c<numClasses; c++)
					qtx[c][i]=computeDotProduct(q[c],sample.pairs);
			}
			

			bool needToRestart=false;
			eta = lineSearch(trainingDataSet, trainingIdxs, w, wtx, qtx, g, q, lambda);
			if (eta<= 0.0)
			{
				// restart ?
				needToRestart = true;
			}

			// update wOld<- w ; w <- w + eta *q ; gOld<- g
			for (size_t c=0; c<numClasses; c++)
			{
				memcpy(&wOld[c][0],&w[c][0],sizeof(double)*w[c].size());
				memcpy(&gOld[c][0],&g[c][0],sizeof(double)*g[c].size());
				for (size_t i=0; i<numFeatures; i++)
					w[c][i]+= eta*q[c][i];
			}

			for (size_t c=0; c<numClasses; c++)
				for (size_t i=0; i<numSamples; i++)
					wtx[c][i]+=eta*qtx[c][i];

			round++;
			totalRounds++;
			if (terminateTraining || needToRestart)
				break;
		}
		
		if (terminateTraining)
			break;
	}

	if (! params->getIndHadInternalError())
	{
		params->setIndNormalTermination(true);
	}
	else
		cout << "Warning: encountered mathemtical error while training!" << endl;

	weights_ = bestW;

	cout << "W=" << endl;
	printVector(weights_);
	cout << endl;

	cout << "Terminated after " << totalRounds << " rounds (" << megaRound << " restarts)" << endl;
	cout << "Best training error  " << fixed << setprecision(8) << bestTrainingError << " (round " << bestTrainingRound << ")" << endl;
	if (performTest)
	cout << "Best test error      "  << bestTestError     << " (round " << bestTestRound << ")" << endl;

	indWasInitialized_ = true;

	//this->calcErrorRateWithPerplexity(trainingDataSet, trainingIdxs, true, NULL);
}