Example #1
0
void ColladaParser::Parse(const char* colladaFileData)
{
	XmlParser p;
	p.Parse(colladaFileData);

	if (p.root.tagName != "COLLADA")
		throw "expected COLLADA as root element";

	if (!p.root.HasAttribute("xmlns", "http://www.collada.org/2005/11/COLLADASchema") || !p.root.HasAttribute("version", "1.4.1"))
		throw "expected COLLADA as root element";

	XmlElement* root = &p.root;

	{
		auto v = root->Child("library_geometries")->Childs("geometry");

		for (int ia = 0; ia < v.size(); ia++)
			ReadGeometry(v[ia]);
	}

	if (root->HasChild("library_animations"))
	{
		auto v = root->Child("library_animations")->Childs("animation");

		for (int ia = 0; ia < v.size(); ia++)
			ReadAnimations(v[ia]);
	}

	{
		auto v = root->Child("library_visual_scenes")->Childs("visual_scene");

		for (int ia = 0; ia < v.size(); ia++)
		{
			ReadScene(v[ia]);
		}
	}

	auto sceneId = ReadId(root->Child("scene")->Child("instance_visual_scene")->Attribute("url"));
	currentScene = &scenes[sceneId];
	int x = 2;
}
Example #2
0
void OgreXmlSerializer::ReadSubMesh(MeshXml *mesh)
{
    static const std::string anMaterial          = "material";
    static const std::string anUseSharedVertices = "usesharedvertices";
    static const std::string anCount             = "count";
    static const std::string anV1                = "v1";
    static const std::string anV2                = "v2";
    static const std::string anV3                = "v3";
    static const std::string anV4                = "v4";

    SubMeshXml* submesh = new SubMeshXml();

    if (HasAttribute(anMaterial)) {
        submesh->materialRef = ReadAttribute<std::string>(anMaterial);
    }
    if (HasAttribute(anUseSharedVertices)) {
        submesh->usesSharedVertexData = ReadAttribute<bool>(anUseSharedVertices);
    }

    DefaultLogger::get()->debug(Formatter::format() << "Reading SubMesh " << mesh->subMeshes.size());
    DefaultLogger::get()->debug(Formatter::format() << "  - Material: '" << submesh->materialRef << "'");
    DefaultLogger::get()->debug(Formatter::format() << "  - Uses shared geometry: " << (submesh->usesSharedVertexData ? "true" : "false"));

    // TODO: maybe we have always just 1 faces and 1 geometry and always in this order. this loop will only work correct, when the order
    // of faces and geometry changed, and not if we have more than one of one
    /// @todo Fix above comment with better read logic below

    bool quadWarned = false;

    NextNode();
    while(m_currentNodeName == nnFaces     ||
          m_currentNodeName == nnGeometry  ||
          m_currentNodeName == nnTextures  ||
          m_currentNodeName == nnBoneAssignments)
    {
        if (m_currentNodeName == nnFaces)
        {
            submesh->indexData->faceCount = ReadAttribute<uint32_t>(anCount);
            submesh->indexData->faces.reserve(submesh->indexData->faceCount);

            NextNode();
            while(m_currentNodeName == nnFace)
            {
                aiFace face;
                face.mNumIndices = 3;
                face.mIndices = new unsigned int[3];
                face.mIndices[0] = ReadAttribute<uint32_t>(anV1);
                face.mIndices[1] = ReadAttribute<uint32_t>(anV2);
                face.mIndices[2] = ReadAttribute<uint32_t>(anV3);

                /// @todo Support quads if Ogre even supports them in XML (I'm not sure but I doubt it)
                if (!quadWarned && HasAttribute(anV4)) {
                    DefaultLogger::get()->warn("Submesh <face> has quads with <v4>, only triangles are supported at the moment!");
                    quadWarned = true;
                }

                submesh->indexData->faces.push_back(face);

                // Advance
                NextNode();
            }

            if (submesh->indexData->faces.size() == submesh->indexData->faceCount)
            {
                DefaultLogger::get()->debug(Formatter::format() << "  - Faces " << submesh->indexData->faceCount);
            }
            else
            {
                throw DeadlyImportError(Formatter::format() << "Read only " << submesh->indexData->faces.size() << " faces when should have read " << submesh->indexData->faceCount);
            }
        }
        else if (m_currentNodeName == nnGeometry)
        {
            if (submesh->usesSharedVertexData) {
                throw DeadlyImportError("Found <geometry> in <submesh> when use shared geometry is true. Invalid mesh file.");
            }

            submesh->vertexData = new VertexDataXml();
            ReadGeometry(submesh->vertexData);
        }
        else if (m_currentNodeName == nnBoneAssignments)
        {
            ReadBoneAssignments(submesh->vertexData);
        }
        // Assimp incompatible/ignored nodes
        else
            SkipCurrentNode();
    }

    submesh->index = mesh->subMeshes.size();
    mesh->subMeshes.push_back(submesh);
}
Example #3
0
int main(int argc, char* argv[])
{
	char filename[100], suffix[20];
	UINT N_T = 1000;
	UINT outer_points = 25;
	UINT Lagrange_degree = 1;
	bool cheat = false, add_suffix = false, compute_scattered_field = false;

	// Parse arguments
	argc -= (argc > 0); argv += (argc > 0); // skip program name argv[0] if present
	option::Stats stats(usage, argc, argv);
	std::vector<option::Option> options(stats.options_max);
	std::vector<option::Option> buffer(stats.buffer_max);
	option::Parser parse(usage, argc, argv, &options[0], &buffer[0]);

	if (parse.error())
		return 1;

	if (options[HELP] || argc == 0)
	{
		int columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80;
		option::printUsage(fwrite, stdout, usage, columns);
		return 0;
	}

	string temp_str;
	for (int i = 0; i < parse.optionsCount(); ++i)
	{
		option::Option& opt = buffer[i];
		switch (opt.index())
		{
		case HELP:
			// not possible - handled above
		case CHEAT:
			cheat = true;
			break;
		case SCATTERED:
			compute_scattered_field = true;
			break;
		case NUM_TIMESTEPS:
			if (opt.arg)
				N_T = strtol(opt.arg, NULL, 10);
			break;
		case QUAD_POINTS:
			if (opt.arg)
				outer_points = strtol(opt.arg, NULL, 10);
			break;
		case FILENAME:
			temp_str = opt.arg;
			strcpy(filename, temp_str.c_str());
			break;
		case DEGREE:
			Lagrange_degree = strtol(opt.arg, NULL, 10);
			break;
		case SUFFIX:
			temp_str = opt.arg;
			strcpy(suffix, temp_str.c_str());
			add_suffix = true;
			break;
		case UNKNOWN:
			// not possible because Arg::Unknown returns ARG_ILLEGAL
			// which aborts the parse with an error
			break;
		}
	}

	// Check for tests
	for (option::Option* o = options[TESTS]; o; o = o->next())
	{
		string this_arg = o->arg;

		if (this_arg == "computeConvolutions")
		{
			if (!computeConvolutions_example()){ return -1; }
		}
		else {
			printf("Not enough or invalid arguments, please try again.\n");
			return 1;
		}
		// tests completed
		return 0;
	}

	// Load the geometry
	printf("Opening geometry file: %s.mat", filename);
	GEOMETRY geometry; double dt, c, num_shapes_, dual_;
	string str1 = "./input/"; str1 = str1 + filename + ".mat";
	// read:  'boundary', 'dt', 'c', 'num_shapes', 'dual'
	if (!ReadGeometry(geometry, dt, c, num_shapes_, dual_, str1.c_str()))
	{
		fprintf(stderr, "\n\nError opening file. \n"); return false;
	}
	// if computing scattered field, read 'rho'
	GRID rho; MATRIX M, J; double material_parameter;
	if (compute_scattered_field)
	{
		if (!ReadScatteredFieldGeometry(M, J, rho, material_parameter, N_T, str1.c_str()))
		{
			fprintf(stderr, "\n\nError opening file for scattered field. \n");
			return false;
		}
	}
	UINT num_shapes = (UINT)num_shapes_;
	UINT dual = (UINT)dual_;
	printf("\t- done. \nNumber of distinct shapes = %i\n", num_shapes);
	printf("Using dual basis functions = %s\n", dual ? "true" : "false");

	// Output filename
	string str2 = "./results/";
	string str3 = str2 + filename;
	if (add_suffix)	str3 = str3 + suffix;
	str3 += ".mat";
	char result_file[124];
	strcpy(result_file, str3.c_str());

	// Create Z_matrices object
	Zmatrices Z_matrices = Zmatrices(N_T, dt, geometry, c);
	if (cheat == true)
	{
		Z_matrices.use_cheat(); omp_set_num_threads(1); printf("\nUsing cheat!\n");
	}

	// Basis and test functions applied to each segment
	// S = transverse plane, Z = z-directed, d = S divergence
	// 2nd argument (true/false) defines whether to scale by edge length
	CBasisFunction BasisFunction;
	if (dual_ == 1)
	{
		Z_matrices.basis_function_Z = BasisFunction.createDualSquare(geometry, false);
		Z_matrices.basis_function_S = BasisFunction.createDualHat(geometry, false, num_shapes);
		Z_matrices.test_function_Z = BasisFunction.createDualSquare(geometry, true);
		Z_matrices.test_function_S = BasisFunction.createDualHat(geometry, true, num_shapes);
	}
	else
	{
		Z_matrices.basis_function_Z = BasisFunction.createSquare(geometry, true);
		Z_matrices.basis_function_S = BasisFunction.createHat(geometry, false, num_shapes);
		Z_matrices.test_function_Z = BasisFunction.createSquare(geometry, true);
		Z_matrices.test_function_S = BasisFunction.createHat(geometry, true, num_shapes);
	}


	// Find out how many computing nodes we can use, then use them all (if not using cheat)
	setup_omp();


	// Perform computation
	if (compute_scattered_field)
		run_Zmatrices_calculation_scattered_field(Z_matrices, Lagrange_degree,
			M, J, rho, material_parameter, result_file);
	else
		run_Zmatrices_calculation(Z_matrices, Lagrange_degree, outer_points, result_file);


	return 0;
}
OGRGeoJSONLayer* OGRGeoJSONReader::ReadLayer( const char* pszName,
                                              OGRGeoJSONDataSource* poDS )
{
    CPLAssert( NULL == poLayer_ );

    if( NULL == poGJObject_ )
    {
        CPLDebug( "GeoJSON",
                  "Missing parset GeoJSON data. Forgot to call Parse()?" );
        return NULL;
    }
        
    poLayer_ = new OGRGeoJSONLayer( pszName, NULL,
                                   OGRGeoJSONLayer::DefaultGeometryType,
                                   NULL, poDS );

    if( !GenerateLayerDefn() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
            "Layer schema generation failed." );

        delete poLayer_;
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Translate single geometry-only Feature object.                  */
/* -------------------------------------------------------------------- */
    GeoJSONObject::Type objType = OGRGeoJSONGetType( poGJObject_ );

    if( GeoJSONObject::ePoint == objType
        || GeoJSONObject::eMultiPoint == objType
        || GeoJSONObject::eLineString == objType
        || GeoJSONObject::eMultiLineString == objType
        || GeoJSONObject::ePolygon == objType
        || GeoJSONObject::eMultiPolygon == objType
        || GeoJSONObject::eGeometryCollection == objType )
    {
        OGRGeometry* poGeometry = NULL;
        poGeometry = ReadGeometry( poGJObject_ );
        if( !AddFeature( poGeometry ) )
        {
            CPLDebug( "GeoJSON",
                      "Translation of single geometry failed." );
            delete poLayer_;
            return NULL;
        }
    }
/* -------------------------------------------------------------------- */
/*      Translate single but complete Feature object.                   */
/* -------------------------------------------------------------------- */
    else if( GeoJSONObject::eFeature == objType )
    {
        OGRFeature* poFeature = NULL;
        poFeature = ReadFeature( poGJObject_ );
        if( !AddFeature( poFeature ) )
        {
            CPLDebug( "GeoJSON",
                      "Translation of single feature failed." );

            delete poLayer_;
            return NULL;
        }
    }
/* -------------------------------------------------------------------- */
/*      Translate multi-feature FeatureCollection object.               */
/* -------------------------------------------------------------------- */
    else if( GeoJSONObject::eFeatureCollection == objType )
    {
        OGRGeoJSONLayer* poThisLayer = NULL;
        poThisLayer = ReadFeatureCollection( poGJObject_ );
        CPLAssert( poLayer_ == poThisLayer );
    }
    else
    {
        CPLError( CE_Failure, CPLE_AppDefined,
            "Unrecognized GeoJSON structure." );

        delete poLayer_;
        return NULL;
    }

    OGRSpatialReference* poSRS = NULL;
    poSRS = OGRGeoJSONReadSpatialReference( poGJObject_ );
    if (poSRS == NULL ) {
        // If there is none defined, we use 4326
        poSRS = new OGRSpatialReference();
        if( OGRERR_NONE != poSRS->importFromEPSG( 4326 ) )
        {
            delete poSRS;
            poSRS = NULL;
        }
        poLayer_->SetSpatialRef( poSRS );
        delete poSRS;
    }
    else {
        poLayer_->SetSpatialRef( poSRS );
        delete poSRS;
    }

    // TODO: FeatureCollection

    return poLayer_;
}
  bool GAMESSUKOutputFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv) {

	/*
	 
	Read in coordinates after any reorientation due to the symmetry code
	- if there is a field called "input z-matrix" then we read the initial zmatrix in here
	  This geometry is not needed if we are optimising as we can use the optimised geometry
	  However, we need to keep this geometry as it's the only one we have if it's not an opt.
	  
	- if there is no zmat, we need to read the "molecular geometry" field. This geometry
	  only needs to be used if we are not in an optimisation.
	  
	 Read the RUN TYPE field to work out whether we need to use the first geometry.
	 
	 If it's a single point caculation, we can return the molecule at this point
	 
	 If it's some form of structure search, we need to go and find the final structure

	 */

	OBMol* pmol = dynamic_cast<OBMol*>(pOb);
	if (pmol==NULL)
		return false;

	//Define some references so we can use the old parameter names
	istream& ifs = *pConv->GetInStream();
	OBMol &mol = *pmol;
	
	// Get a default title as the filename
    const char* title = pConv->GetTitle();    
    mol.BeginModify();
    mol.SetTitle(title);
    mol.EndModify();

	vector<string> tokens, geomList; // list of lines and list of tokens on a line
	string line; // For convenience so we can refer to lines from the iterator as 'line'
	//ReadMode_t ReadMode=SKIP;
	
	enum RunType_t { UNKNOWN, SINGLEPOINT, OPTXYZ, OPTZMAT, SADDLE };
	RunType_t RunType=UNKNOWN;
	bool ok;
	
	while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
		
		/* The zmatrix entered by the user
		 * REM:  need to add stuff for "automatic z-matrix generation" as we currently
		 * ignore the zmatrix & just read the cartesian coordinates 
		 */
		
		if (strstr(buffer,"                              input z-matrix") != NULL){
			
			// Set Runtype to SINGLEPOINT so we don't read in the cartesians
			RunType=SINGLEPOINT;
			
			geomList.clear();
			
			// skip 2 lines
			ifs.getline(buffer, BUFF_SIZE) && ifs.getline(buffer, BUFF_SIZE);
			
			// Stick a header line first
			geomList.push_back("zmatrix bohr");
			
			// Read zmatrix into list until blank line 
			while (ifs.good() && ifs.getline(buffer, BUFF_SIZE) && strlen(buffer) != 0){
				line = buffer;
				// transform(method.begin(), method.end(), method.begin(), ::tolower);
				ToLower(line);
				Trim(line);
				geomList.push_back(line);
			}
			
			// Skip 3 lines
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE);
			
			// Read in the variables till we hit blank line
			if (! ReadVariables(ifs, BOHR_TO_ANGSTROM, "")) return false;
			
			// Now go and process the geometry
			ok = ReadGeometry(mol, geomList);
					
		} // End Reading user z-matrix
		
		// Read the cartesian coordinates if we've not read in the ZMATRIX
		if (strstr(buffer,"*            charge       x             y              z       shells") != NULL &&
				RunType==UNKNOWN){
			
			// Skip 3 lines
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE);
			
			// Create regex for the coords
			regex_t *myregex = new regex_t;
			int iok;
			iok = regcomp( myregex,
					//     ------label--------   -------charge-------- < seems enough for a match
					" *\\* *[a-zA-Z]{1,2}[0-9]* *[0-9]{1,3}\\.[0-9]{1}",
					REG_EXTENDED | REG_NOSUB);
			if (iok !=0) cerr << "Error compiling regex in GUK OUTPUT!\n";
			
			// Read in the coordinates - we process them directly rather 
			// then use ReadGeometry as we probably should do...
			mol.BeginModify();
			while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)){
				
				// End of geometry block
				if (strstr(buffer,"*************************")!=NULL)break;
				
				if (regexec( myregex, buffer, 0, 0, 0)==0) {
					//cerr << "Got Coord line: " << buffer << endl;
					OBAtom *atom = mol.NewAtom();
					tokenize(tokens,buffer," ");
					atom->SetAtomicNum(atoi(tokens[2].c_str()));
					double x=atof(tokens[3].c_str())*BOHR_TO_ANGSTROM;
					double y=atof(tokens[4].c_str())*BOHR_TO_ANGSTROM;
					double z=atof(tokens[5].c_str())*BOHR_TO_ANGSTROM;
					atom->SetVector(x, y, z);
				}
			}
			mol.EndModify();			
			regfree(myregex);
			
		} // End Read Cartesian Coords
		
		
		// Determine the RunType - affects how we move on from here.
		if (strstr(buffer," * RUN TYPE") != NULL){
			tokenize(tokens,buffer," \t\n");
			
			if(tokens[3].compare(0,6,"optxyz")==0){
				//cerr << "runtype is optxyz\n";
				RunType=OPTXYZ;
				break;
			} else if (tokens[3].compare(0,8,"optimize")==0){
				//cerr << "runtype is optimise\n";
				RunType=OPTZMAT;
				break;
			} else if (tokens[3].compare(0,6,"saddle")==0){
				//cerr << "runtype is optimise\n";
				RunType=SADDLE;
				break;
			} else {
				RunType=SINGLEPOINT;
				break;
			}
		}
	} // End First Reading loop
	
	
	if(RunType==SINGLEPOINT){
		// We can return the molecule that we've read in
		if (mol.NumAtoms() == 0) { // e.g., if we're at the end of a file PR#1737209
			mol.EndModify();
			return false;
		} else {
			return true;
		}
	}
	
	
	// Clear the Molecule as we're going to start from scratch again.
	mol.BeginModify();
	mol.Clear();
	mol.EndModify();
	
	// Start trundling through the file again - just get the last geometry
	while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
		if (strstr(buffer,"optimization converged") != NULL)
		{	
			if (RunType==OPTXYZ){
				//cerr << "Got converged for OPTXYZ\n";
				
				// FF to start of coordinate specification
				while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
					if (strstr(buffer,
							"atom     znuc       x             y             z") != NULL) break;
				}
				
				// Skip 3 lines - should then be at the coordinates
				ifs.getline(buffer, BUFF_SIZE) && 
				ifs.getline(buffer, BUFF_SIZE) && 
				ifs.getline(buffer, BUFF_SIZE);
				
				// Read in the coordinates - we process them directly rather 
				// then use ReadGeometry as we probably should do...
				mol.BeginModify();
				while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)){
					
					// End of geometry block
					if (strstr(buffer,"*************************")!=NULL)break;
					
					//cerr << "Got Coord line: " << buffer << endl;
					OBAtom *atom = mol.NewAtom();
					tokenize(tokens,buffer," ");
					atom->SetAtomicNum(atoi(tokens[2].c_str()));
					double x=atof(tokens[3].c_str())*BOHR_TO_ANGSTROM;
					double y=atof(tokens[4].c_str())*BOHR_TO_ANGSTROM;
					double z=atof(tokens[5].c_str())*BOHR_TO_ANGSTROM;
					atom->SetVector(x, y, z);
				}
				
				mol.EndModify();
				return true;
				
				
			} else if (RunType==OPTZMAT || RunType==SADDLE) {
				// Original geometry specification should still be in geomList
				// So just update the variables
				//cerr << "Got converged for OPTZMAT\n";				
				
				// FF to variable specification
				while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
					if (strstr(buffer,
							" variable           value                hessian") != NULL) break;
				}
				// Skip a line - should then be at variable specification
				ifs.getline(buffer, BUFF_SIZE);
				
				// Process them
				if (! ReadVariables(ifs, BOHR_TO_ANGSTROM,
						"===============================================")) return false;
				
				// Now go and process with the geometry we read before
				return ReadGeometry(mol, geomList);
				
			}
		}
		
	} // End Second Reading loop		

	return true;

} // End GAMESSUKOutputFormat::ReadMolecule
	bool GAMESSUKInputFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)

{
	/*
	 * Stuff to think about:
	 * - At outset check whether we are in zmatrix, cartesian or nw-chem format
	 *   (we currently only suppot homogeneous formats - not mixed).
	 * 
	 * For each line need to check:
	 * - Is this a comment (?,#)
	 * - Are the tokens separated by commas, if so use tokenize to split at commas
	 * - Is there an 'end' token on the line
	 * 
	 * For each line we want to check that we haven't hit a change from c to zm or vv
	 * 
	 */

	OBMol* pmol = dynamic_cast<OBMol*>(pOb);
	if (pmol==NULL)
		return false;

	//Define some references so we can use the old parameter names
	istream& ifs = *pConv->GetInStream();
	OBMol &mol = *pmol;
	
	// Get a default title as the filename
    const char* title = pConv->GetTitle();    
    mol.BeginModify();
    mol.SetTitle(title);
    mol.EndModify();

	vector<string> geomList, tokens; // list of lines and list of tokens on a line
	string line; // For convenience so we can refer to lines from the iterator as 'line'
	ReadMode_t ReadMode=SKIP;
	double factor=BOHR_TO_ANGSTROM;
	
	// Read File and copy geometry specification into geomList
	while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
		
		// Skip commnents
		if (EQn(buffer, "#", 1) || EQn(buffer, "?", 1)) continue;

		// Copy line to a C++ string and convert to lower case
		// & remove leading and trailing spaces
		line = buffer;
		// transform(method.begin(), method.end(), method.begin(), ::tolower);
		ToLower(line);
		Trim(line);

		// Start of coordinate specifiation
		if (line.compare(0, 4, "zmat")==0) {
			ReadMode=ZMATRIX;
			geomList.push_back(line);
			continue;
		} else if (line.compare(0, 4, "geom")==0) {
			ReadMode=CARTESIAN;
			geomList.push_back(line);
			continue;
		}

		
		// Reading the coordinate specification into the list
		if (ReadMode==ZMATRIX || ReadMode==CARTESIAN) {
		
			// Variables specification - process directly from filestream
			// and then remove from the geometry specification
			if (line.compare(0, 4, "vari")==0 || line.compare(0, 4, "const")==0) {
				
				// Check for commas & split with that as the separator if necessary
				if (line.find(',')!=string::npos) {
					tokenize(tokens, line, ",");
				} else {
					tokenize(tokens, line, " \t\n");
				}	

				// See if we need to rescale
				if (IsUnits(tokens[1])) factor=Rescale(tokens[1]);	
				
				if (! ReadVariables(ifs, factor, "end")) return false;
				ReadMode=SKIP;
				geomList.push_back("end\n");	
				continue;
			}
			
			if (line.compare(0, 3, "end")==0) ReadMode=SKIP;			
			geomList.push_back(line);
		}

	}// End while reading loop

	// Now go and process the coordinate specification if we got any
	bool ok = ReadGeometry(mol, geomList);
	
    if (mol.NumAtoms() == 0) { // e.g., if we're at the end of a file PR#1737209
    	mol.EndModify();
    	return false;
    } else {
    	return ok;
    }

} // End ReadMolecule	
Example #7
0
int main(int argc, char *argv[]){
    
    int p_order = 2;
    int n_threads = 0;
    TPZGeoMesh * gmesh = ReadGeometry();

#ifdef PZDEBUG
    PrintGeometry(gmesh);
#endif
    
    TPZCompMesh *cmesh      = CMeshFooting2D(gmesh, p_order);
    TPZAnalysis *analysis   = Analysis(cmesh,n_threads);
    
#ifdef USING_BOOST
    boost::posix_time::ptime post_proc_t1 = boost::posix_time::microsec_clock::local_time();
#endif
    
    /// Creation of a post-process analysis
    TPZPostProcAnalysis * post_processor = new TPZPostProcAnalysis;
    post_processor->SetCompMesh(cmesh);
    
    int n_regions = 1;
    TPZManVector<int,10> post_mat_id(n_regions);
    post_mat_id[0] = ERock;
    
    TPZStack<std::string> scalar_names,vector_names, tensor_names;
    vector_names.Push("Displacement");
    tensor_names.Push("Strain");
    tensor_names.Push("StrainPlastic");
    tensor_names.Push("Stress");
    
    TPZStack<std::string> var_names;
    for (auto i : scalar_names) {
        var_names.Push(i);
    }
    for (auto i : vector_names) {
        var_names.Push(i);
    }
    for (auto i : tensor_names) {
        var_names.Push(i);
    }
    
    post_processor->SetPostProcessVariables(post_mat_id, var_names);
    TPZFStructMatrix structmatrix(post_processor->Mesh());
    structmatrix.SetNumThreads(n_threads);
    post_processor->SetStructuralMatrix(structmatrix);
    
#ifdef USING_BOOST
    boost::posix_time::ptime post_proc_t2 = boost::posix_time::microsec_clock::local_time();
#endif
    
#ifdef USING_BOOST
    REAL case_solving_time = boost::numeric_cast<double>((post_proc_t2-post_proc_t1).total_milliseconds());
    std::cout << "Created post-processing in :" << setw(10) <<  case_solving_time/1000.0 << setw(5)   << " seconds." << std::endl;
    std::cout << std::endl;
#endif

#ifdef USING_BOOST
    boost::posix_time::ptime case_t1 = boost::posix_time::microsec_clock::local_time();
#endif
    
    std::string plotfile = "footing_elast.vtk";
    // For a single step
    REAL dt = 0.1;
    int n_steps = 10;
    for (int it = 1; it <= n_steps; it++) {
        
        REAL t = it*dt;
        LoadingRamp(t,cmesh);
        FindRoot(analysis);
        AcceptSolution(cmesh, analysis);
        
#ifdef USING_BOOST
        boost::posix_time::ptime post_l2_projection_proc_t1 = boost::posix_time::microsec_clock::local_time();
#endif
        post_processor->TransferSolution();
        
#ifdef USING_BOOST
        boost::posix_time::ptime post_l2_projection_proc_t2 = boost::posix_time::microsec_clock::local_time();
        REAL l2_projection_time = boost::numeric_cast<double>((post_l2_projection_proc_t2-post_l2_projection_proc_t1).total_milliseconds());
        std::cout << "L2 projection post-processing in :" << setw(10) <<  l2_projection_time/1000.0 << setw(5)   << " seconds." << std::endl;
        std::cout << std::endl;
#endif


#ifdef USING_BOOST
        boost::posix_time::ptime post_vtk_proc_t1 = boost::posix_time::microsec_clock::local_time();
#endif
        PostProcess(post_processor,scalar_names,vector_names,tensor_names,plotfile);
        
#ifdef USING_BOOST
        boost::posix_time::ptime post_vtk_proc_t2 = boost::posix_time::microsec_clock::local_time();
        REAL vtk_drawing_time = boost::numeric_cast<double>((post_vtk_proc_t2-post_vtk_proc_t1).total_milliseconds());
        std::cout << "Drawing vtk file in :" << setw(10) <<  vtk_drawing_time/1000.0 << setw(5)   << " seconds." << std::endl;
        std::cout << std::endl;
#endif
        
    }
    
#ifdef USING_BOOST
    boost::posix_time::ptime case_t2 = boost::posix_time::microsec_clock::local_time();
    REAL case_time = boost::numeric_cast<double>((case_t2-case_t1).total_milliseconds());
    std::cout << "Execution complete in :" << setw(10) <<  case_time/1000.0 << setw(5)   << " seconds." << std::endl;
    std::cout << std::endl;
#endif
    
    std::cout << "Execution complete." << std::endl;
	return 0;
}
Example #8
0
void clGeometryReader::ReadFile(clGeometry &geometry) const
{
  fstream file;

  // Open file for input
  file.open(fileName, ios::in);

  if(!file)
  {
    throw clExceptionTree("clGeometryReader", "ReadFile", "Could not open file.");
  }
  else
  {
    try
    {
      // Read line
      char line[LINE_SIZE];
      file.getline(line, LINE_SIZE);

      while(!file.eof() && file.good())
      {
        // Check first character in trimmed line
        switch(*strtrim(line))
        {
          case '#':
          case '*':
            // Comment line
            file.getline(line, LINE_SIZE);
            break;
          case '$':
          case '&':
          {
            // Block specifier
            int blockCommand = GetBlockSpec(line);

            switch(blockCommand)
            {
              case UNKNOWN_SPEC:
                throw clExceptionTree("clGeometryReader", "ReadFile", "Unknown block specifier.");
                break;
              case POINT_SPEC:
                // Start of point block
                throw clExceptionTree("clGeometryReader", "ReadFile", "Unexpected start of block POINT.");
                break;
              case PATCH_SPEC:
                // Start of patch block
                throw clExceptionTree("clGeometryReader", "ReadFile", "Unexpected start of block PATCH.");
                break;
              case SURFACE_SPEC:
                // Start of surface block
                throw clExceptionTree("clGeometryReader", "ReadFile", "Unexpected start of block SURFACE.");
                break;
              case GEOMETRY_SPEC:
                // Start of geometry block
                ReadGeometry(file, geometry);
                file.getline(line, LINE_SIZE);
                break;
              case END_SPEC:
                // End of block specification
                throw clExceptionTree("clGeometryReader", "ReadFile", "Unexpected EndOfBlock specification.");
                break;
              default:
                throw clExceptionTree("clGeometryReader", "ReadFile", "Function GetBlockSpec returned unknown value.");
                break;
            }

            break;
          }
          case '/':
            // End of block specification
            throw clExceptionTree("clGeometryReader", "ReadFile", "Unexpected EndOfBlock specification.");
            break;
          default:
            file.getline(line, LINE_SIZE);
            break;
        }
      }

      // Close file
      file.close();
    }

    catch(clExceptionTree EX)
    {
      // Make sure to close the file
      file.close();
      EX.AddMethodToTree("clGeometryReader::ReadFile");
      throw EX;
    }
  }
}