コード例 #1
0
ファイル: root.c プロジェクト: wolfwood/dmd
Files *File::match(FileName *n)
{
#if POSIX
    return NULL;
#elif _WIN32
    HANDLE h;
    WIN32_FIND_DATAA fileinfo;
    Files *a;
    char *c;
    char *name;

    a = new Files();
    c = n->toChars();
    name = n->name();
    h = FindFirstFileA(c,&fileinfo);
    if (h != INVALID_HANDLE_VALUE)
    {
        do
        {
            // Glue path together with name
            char *fn;
            File *f;

            fn = (char *)mem.malloc(name - c + strlen(fileinfo.cFileName) + 1);
            memcpy(fn, c, name - c);
            strcpy(fn + (name - c), fileinfo.cFileName);
            f = new File(fn);
            f->touchtime = mem.malloc(sizeof(WIN32_FIND_DATAA));
            memcpy(f->touchtime, &fileinfo, sizeof(fileinfo));
            a->push(f);
        } while (FindNextFileA(h,&fileinfo) != FALSE);
        FindClose(h);
    }
    return a;
#else
    assert(0);
#endif
}
コード例 #2
0
ファイル: Utils.cpp プロジェクト: dreamsxin/PcManager
void DumpFiles( const Files& files, BOOL bOnlyFileName )
{
	if(files.empty())
	{
		_tprintf(_T("Empty Files\r\n"));
	}
	else
	{
		int i=0; 
		for(Files::const_iterator it=files.begin(); it!=files.end(); ++it)
		{
			++i;
			LPCTSTR szFile = *it;
			if(bOnlyFileName)
			{
				LPCTSTR szName = _tcsrchr(szFile, _T('\\'));
				if(szName)
					szFile = ++szName;
			}
			_tprintf(_T("%d/%d %s\r\n"), i, files.size(), szFile);
		}
	}
}
コード例 #3
0
ファイル: NCSF.cpp プロジェクト: soneek/SDATStuff
// Get a list of files in the given directory
Files GetFilesInDirectory(const std::string &path, const std::vector<std::string> &extensions)
{
	DIR *dir;
	dirent *entry;
	Files files;

	std::string finalPath = path;
	if (finalPath[path.size() - 1] != '/')
		finalPath += '/';

	if ((dir = opendir(path.c_str())))
	{
		while ((entry = readdir(dir)))
		{
			std::string filename = std::string(entry->d_name);
			if (filename == "." || filename == "..")
				continue;
			std::string fullPath = finalPath + filename;
			// Although the following function is for checking if a directory
			// exists, it can also be used to check if a path is a directory,
			// saving a little bit of extra code
			if (DirExists(fullPath))
				continue;
			// We want to skip any files not matching the extensions we gave, if any
			std::string thisExtension = GetExtension(filename);
			auto extensionMatch = std::find_if(extensions.begin(), extensions.end(), [&](const std::string &extension)
			{
				return extension == thisExtension;
			});
			if (extensions.empty() || extensionMatch != extensions.end())
				files.push_back(fullPath);
		}
		closedir(dir);
	}

	return files;
}
コード例 #4
0
  Files ParallelEnergyPlusSplitJob::outputFilesImpl() const
  {
    // Save off the set of requiredfiles, see below
    std::vector<std::pair<QUrl, openstudio::path> > requiredFiles = inputFile().requiredFiles;
    std::vector<openstudio::path> files = generateFileNames(outdir(), m_numSplits);

    Files retval;

    for (std::vector<openstudio::path>::const_iterator itr = files.begin();
         itr != files.end();
         ++itr)
    {
      if (boost::filesystem::exists(*itr))
      {
        FileInfo fi = RunManager_Util::dirFile(*itr);
        // we want to carry along the set of required files used in the original IDF to the children
        // (ie, the epw file)
        fi.requiredFiles = requiredFiles;
        retval.append(fi);
      }
    }

    return retval;
  }
コード例 #5
0
ファイル: io.cpp プロジェクト: schulmar/filestats
/**
 * @brief Get the statistics and print them if necessary
 */
static Files &files() {
  static std::ofstream log(logFileName);
  static Files sinceLast;
  static Files total;
  // print the final statistics on exit
  static DestructionExecutor finalExecutor([&]() {
    log << "Statistics for thread " << getCurrentThreadId() << "\n";
    printStatistics(log, sinceLast);
    log << "Total statistics for thread " << getCurrentThreadId() << ":\n";
    total += sinceLast;
    printStatistics(log, total);
  });
  static DeltaTimeExecutor executor([&]() {
                                      log << "Statistics for thread "
                                          << getCurrentThreadId() << "\n";
                                      printStatistics(log, sinceLast);
                                      total += sinceLast;
                                      sinceLast.resetStatistics();
                                    },
                                    std::chrono::microseconds(1000 * 1000 *
                                                              10));
  executor.callIfTimeOver();
  return sinceLast;
}
コード例 #6
0
  EnergyPlusPreProcessJob::EnergyPlusPreProcessJob(const UUID &t_uuid,
      const Tools &tools,
      const JobParams &params,
      const Files &files,
      const JobState &t_restoreData)
    : Job_Impl(t_uuid, JobType::EnergyPlusPreProcess, tools, params, files, t_restoreData)
  {
    try {
      m_idf = files.getLastByExtension("idf");
      resetFiles(m_files, m_idf);
    } catch (const std::runtime_error &) {
    }

    m_description = buildDescription("idf");
  }
コード例 #7
0
ファイル: Workflow_GTest.cpp プロジェクト: jtanaa/OpenStudio
TEST_F(RunManagerTestFixture, Workflow_FromWorkItems)
{
  ToolInfo ti("tool", openstudio::toPath("somepath"));
  Tools tis;
  tis.append(ti);

  JobParam param("param1");
  JobParams params;
  params.append(param);

  FileInfo fi(openstudio::toPath("somefile.txt"), "txt");
  Files fis;
  fis.append(fi);

  std::vector<WorkItem> wi;
  wi.push_back(WorkItem(JobType::Null, tis, params, fis));
  wi.push_back(WorkItem(JobType::EnergyPlus));

  Workflow wf(wi);

  EXPECT_EQ(tis, wf.tools());
  EXPECT_EQ(params, wf.params());
  EXPECT_EQ(fis, wf.files());
} 
コード例 #8
0
  ModelToRadPreProcessJob::ModelToRadPreProcessJob(const UUID &t_uuid,
          const Tools &tools,
          const JobParams &params,
          const Files &files,
      const JobState &t_restoreData)
    : Job_Impl(t_uuid, JobType::ModelToRadPreProcess, tools, params, files, t_restoreData)
  {
    try {
      m_osm = files.getLastByExtension("osm");
      resetFiles(m_files, m_osm);
    } catch (const std::exception &) {
    }

    m_description = buildDescription("osm");
  }
コード例 #9
0
  ModelToRadJob::ModelToRadJob(const UUID &t_uuid,
          const Tools &tools,
          const JobParams &params,
          const Files &files,
      const JobState &t_restoreData)
    : Job_Impl(t_uuid, JobType::ModelToRad, tools, params, files, t_restoreData)
  {
    try {
      m_model = files.getLastByExtension("osm");
      resetFiles(m_files, m_model);
    } catch (const std::runtime_error &) {
    }

    m_description = buildDescription("osm");
  }
コード例 #10
0
ファイル: main.cpp プロジェクト: Doodle3D/Doodle3D
    void print(bool exportOnly=false) {
        ofxSimplifyPath(path,simplifyIterations,simplifyMinNumPoints,simplifyMinDistance);

        string hourMinutes = ofxFormatDateTime(ofxGetDateTime(),"%H.%M");
        string outputFilename = gcodeFolder+files.getFilename()+"_"+hourMinutes+".gcode";
        printer.print(outputFilename, resourceFolder+"gcode/start.gcode",resourceFolder+"gcode/end.gcode");

        if (exportOnly) return;
        
//        outputFilename = "/Users/rick/Documents/Doodle3D/gcode/hilde-mannetje.svg_19.47.gcode";
        
        cout << "print from file: " << outputFilename << endl;
        
        ultimaker.sendCommandsFromFile(outputFilename);
    }
コード例 #11
0
  OpenStudioPostProcessJob::OpenStudioPostProcessJob(const UUID &t_uuid,
          const Tools &tools,
          const JobParams &params,
          const Files &files,
      const JobState &t_restoreData)
    : Job_Impl(t_uuid, JobType::OpenStudioPostProcess, tools, params, files, t_restoreData)
  {
    try {
      m_sql = files.getLastByFilename("eplusout.sql");
      resetFiles(m_files, m_sql);
    } catch (const std::runtime_error &) {
    }

    // what should this be?
    m_description = buildDescription("sql");
  }
コード例 #12
0
ファイル: main.cpp プロジェクト: Doodle3D/Doodle3D
    void keyPressed(int key) {
        switch (key) {
            case '/': case '\\': case '$': case '#': case '|': case '%': case '@': case '^': case '&': case '_': side.setShape(key); break;
            case '3': side.is3D=!side.is3D; break;
            case '<': twists-=.5; break;
            case '>': twists+=.5; break;
            case '\'': twists=0; break;
            case '?': showHelp(); break;
            case 'a': side.toggle(); break;
            case 'b': useSubpathColors=!useSubpathColors; break;
            case 'C': canvas.createCircle(); break;
            case 'c': canvas.clear(); files.unloadFile(); break;
            case 'd': debug=!debug; refreshDebugInfo(); break;
            case 'e': print(true); break;
            case 'f': ofToggleFullscreen(); break;
            case 'k': path.setFilled(!path.isFilled()); path.flagShapeChanged(); break;
            case 'h': objectHeight+=5; if (objectHeight>maxObjectHeight) objectHeight=maxObjectHeight; break;
            case 'H': objectHeight-=5; if (objectHeight<3) objectHeight=3; break;
            case 'G': ultimaker.sendCommand("G28 X0 Y0 Z0\nM84",2); break;
            case 'A': ultimaker.sendCommand("M84"); break;
            case 'T': ultimaker.sendCommand("M109 S230"); break;
            case 'l': files.loadNext(); break;
            case 'L': files.loadPrevious(); break;
            case 'o': files.load(); break;
            case 'p': case 'm': case OF_KEY_RETURN: print(); break;
            case 'q': stop(); break;
//            case 'r': ultimaker.setRelative(); break;
            case 'S': files.save(); break;
            case 's': files.saveAs(); break;
            case '`': showSubPathLines=!showSubPathLines;
            case 't': ultimaker.sendCommand("M105",1); break;
            case 'u': case 'z': canvas.undo(); break;
            case '~': files.deleteCurrentFile(); break;
            case ' ': files.listDir(); break;
            case 'x': files.saveSvg(resourceFolder+"template.svg",documentFolder+"output.svg"); break;
            case 27: if (ultimaker.isThreadRunning()) ultimaker.stopThread(); break;
            case 'n': cloneApp(); break; //run new instance of Doodle3D
            case 'i': cout << getNumInstances() << endl; break;
        }
    }
コード例 #13
0
  ParallelEnergyPlusSplitJob::ParallelEnergyPlusSplitJob(const UUID &t_uuid,
          const Tools &tools,
          const JobParams &params,
          const Files &files,
      const JobState &t_restoreData)
    : Job_Impl(t_uuid, JobType::ParallelEnergyPlusSplit, tools, params, files, t_restoreData),
      m_numSplits(boost::lexical_cast<int>(params.get("numsplits").children.at(0).value)),
      m_offset(boost::lexical_cast<int>(params.get("offset").children.at(0).value))
  {
    try {
      m_input = files.getLastByExtension("idf");
      resetFiles(m_files, m_input);
    } catch (const std::runtime_error &) {
    }

    m_description = buildDescription("idf");
  }
コード例 #14
0
ファイル: files_tests.cpp プロジェクト: Benguang/mesos
TEST_F(FilesTest, AttachTest)
{
  Files files;
  ASSERT_SOME(os::write("file", "body"));
  ASSERT_SOME(os::mkdir("dir"));

  AWAIT_EXPECT_READY(files.attach("file", "myname"));       // Valid file.
  AWAIT_EXPECT_READY(files.attach("dir", "mydir"));         // Valid dir.
  AWAIT_EXPECT_READY(files.attach("file", "myname"));       // Re-attach.
  AWAIT_EXPECT_FAILED(files.attach("missing", "somename")); // Missing file.

  ASSERT_SOME(os::write("file2", "body"));

  AWAIT_EXPECT_READY(files.attach("file2", "myname"));  // Overwrite.
  AWAIT_EXPECT_FAILED(files.attach("$@", "foo"));       // Bad path.
}
コード例 #15
0
  void ExpandObjectsJob::getFiles(const Files &t_files) const
  {
    if (!m_idf)
    {
      try {
        m_idf = t_files.getLastByExtension("idf");


        if (!m_idf->hasRequiredFile(toPath("Energy+.idd")))
        {
          m_idf->addRequiredFile( toPath("Energy+.idd"), toPath("Energy+.idd"));
        }

      } catch (const std::runtime_error &) {
        // no idf set
      }
    }
  }
コード例 #16
0
ファイル: hires1.cpp プロジェクト: 86400/scummvm
void HiRes1Engine::initGameState() {
	_state.vars.resize(IDI_HR1_NUM_VARS);

	StreamPtr stream(_files->createReadStream(IDS_HR1_EXE_1));

	// Load room data from executable
	_roomDesc.clear();
	stream->seek(IDI_HR1_OFS_ROOMS);
	for (uint i = 0; i < IDI_HR1_NUM_ROOMS; ++i) {
		Room room;
		stream->readByte();
		_roomDesc.push_back(stream->readByte());
		for (uint j = 0; j < 6; ++j)
			room.connections[j] = stream->readByte();
		room.picture = stream->readByte();
		room.curPicture = stream->readByte();
		_state.rooms.push_back(room);
	}

	// Load item data from executable
	stream->seek(IDI_HR1_OFS_ITEMS);
	byte id;
	while ((id = stream->readByte()) != 0xff) {
		Item item = Item();
		item.id = id;
		item.noun = stream->readByte();
		item.room = stream->readByte();
		item.picture = stream->readByte();
		item.isLineArt = stream->readByte();
		item.position.x = stream->readByte();
		item.position.y = stream->readByte();
		item.state = stream->readByte();
		item.description = stream->readByte();

		stream->readByte();

		byte size = stream->readByte();

		for (uint i = 0; i < size; ++i)
			item.roomPictures.push_back(stream->readByte());

		_state.items.push_back(item);
	}
}
コード例 #17
0
ファイル: main.cpp プロジェクト: rushs777/femus
int main(int argc,char **args) {

  bool Vanka=0, Gmres=0, Asm=0;
  if(argc >= 2) {
    if( !strcmp("vanka",args[1])) 	Vanka=1;
    else if( !strcmp("gmres",args[1])) 	Gmres=1;
    else if( !strcmp("asm",args[1])) 	Asm=1;
    
    if(Vanka+Gmres+Asm==0) {
      cout << "wrong input arguments!" << endl;
      exit(0);
    }
  }
  else {
    cout << "No input argument set default smoother = Gmres" << endl;
    Gmres=1;
  }
  
  /// Init Petsc-MPI communicator
  FemusInit mpinit(argc,args,MPI_COMM_WORLD);
  
  Files files; 
        files.CheckIODirectories();
        files.RedirectCout();

  /// INIT MESH =================================  
  
  unsigned short nm,nr;
  nm=2;
  std::cout<<"MULTIGRID levels: "<< nm << endl;

  nr=0;
  std::cout<<"MAX_REFINEMENT levels: " << nr << endl<< endl;
  
  int tmp=nm;  nm+=nr;  nr=tmp;
  
  char *infile = new char [50];
 
  sprintf(infile,"./input/nsbenc.neu");
  
  //Adimensional quantity (Lref,Uref)
  double Lref = 1.;
  double Uref = 1.;
  
  //Steadystate NonLinearMultiLevelProblem  
  //MultiLevelMesh ml_msh(nm,nr,infile,"seventh",Lref,SetRefinementFlag); 
  MultiLevelMesh ml_msh;
  ml_msh.ReadCoarseMesh(infile,"seventh",Lref);
  ml_msh.RefineMesh(nm,nr,NULL);
  
  // ml_msh.EraseCoarseLevels(2);
  
  MultiLevelSolution ml_sol(&ml_msh);
  
  // generate solution vector
  ml_sol.AddSolution("T",LAGRANGE,SECOND);
  ml_sol.AddSolution("U",LAGRANGE,SECOND);
  ml_sol.AddSolution("V",LAGRANGE,SECOND);
  // the pressure variable should be the last for the Schur decomposition
  ml_sol.AddSolution("P",DISCONTINOUS_POLYNOMIAL,FIRST);
  ml_sol.AssociatePropertyToSolution("P","Pressure");
 
  //Initialize (update Init(...) function)
  ml_sol.Initialize("U",InitVariableU);
  ml_sol.Initialize("V");
  ml_sol.Initialize("P");
  ml_sol.Initialize("T");
  
  //Set Boundary (update Dirichlet(...) function)
  ml_sol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
  ml_sol.GenerateBdc("U");
  ml_sol.GenerateBdc("V");
  ml_sol.GenerateBdc("P");
  ml_sol.GenerateBdc("T");
  
  MultiLevelProblem ml_prob(&ml_sol);
  
  // add fluid material
  Parameter parameter(Lref,Uref);
  
  // Generate fluid Object (Adimensional quantities,viscosity,density,fluid-model)
  Fluid fluid(parameter,0.001,1,"Newtonian",0.001,1.);
  cout << "Fluid properties: " << endl;
  cout << fluid << endl;
  
  ml_prob.parameters.set<Fluid>("Fluid") = fluid;
   
  
  //BEGIN Navier-Stokes Multilevel Problem
  std::cout << std::endl;
  std::cout << " *********** Navier-Stokes ************  " << std::endl;
    
  NonLinearImplicitSystem & system1 = ml_prob.add_system<NonLinearImplicitSystem> ("Navier-Stokes");
  system1.AddSolutionToSystemPDE("U");
  system1.AddSolutionToSystemPDE("V");
  system1.AddSolutionToSystemPDE("P");
  
  // Set MG Options
  system1.SetAssembleFunction(AssembleMatrixResNS);  
  system1.SetMaxNumberOfNonLinearIterations(3);
  system1.SetMaxNumberOfLinearIterations(2);
  system1.SetLinearConvergenceTolerance(1.e-10);
  system1.SetNonLinearConvergenceTolerance(1.e-04);
  system1.SetMgType(F_CYCLE);
  system1.SetNumberPreSmoothingStep(1);
  system1.SetNumberPostSmoothingStep(1);
      
  //Set Smoother Options
  if(Gmres) 		system1.SetMgSmoother(GMRES_SMOOTHER);
  else if(Asm) 		system1.SetMgSmoother(ASM_SMOOTHER);
  else if(Vanka)	system1.SetMgSmoother(VANKA_SMOOTHER);
  
  system1.init();
  
  std::string  AMR  = "yes";
  unsigned int maxAMRlevels 	= 6;
  std::string  AMRnorm="l2";
  double       AMRthreshold 	=0.001;
 
  system1.SetAMRSetOptions(AMR,maxAMRlevels,AMRnorm,AMRthreshold);
  
  //common smoother options
  system1.SetSolverFineGrids(GMRES);
  system1.SetPreconditionerFineGrids(ILU_PRECOND); 
  system1.SetTolerances(1.e-12,1.e-20,1.e+50,4);
  //for Vanka and ASM smoothers
  system1.ClearVariablesToBeSolved();
  system1.AddVariableToBeSolved("All");
  //system1.AddVariableToBeSolved("U");
  //system1.AddVariableToBeSolved("V");
  //system1.AddVariableToBeSolved("P");
  system1.SetNumberOfSchurVariables(1);
  //system1.SetElementBlockNumber(4);   
  system1.SetElementBlockNumber("All",1);     
  //for Gmres smoother
  system1.SetDirichletBCsHandling(PENALTY); 
   
  // Solve Navier-Stokes system
  ml_prob.get_system("Navier-Stokes").solve();
  //END Navier-Stokes Multilevel Problem
  
  
//   //BEGIN Temperature MultiLevel Problem
//   std::cout << std::endl;
//   std::cout << " *********** Temperature ************* " << std::endl;
//     
//   LinearImplicitSystem & system2 = ml_prob.add_system<LinearImplicitSystem> ("Temperature");
//   system2.AddSolutionToSystemPDE("T");
//   
//   
//   // Set MG Options
//   system2.SetAssembleFunction(AssembleMatrixResT);
//   system2.SetMaxNumberOfLinearIterations(6);
//   system2.SetLinearConvergenceTolerance(1.e-9);  
//   system2.SetMgType(V_CYCLE);
//   system2.SetNumberPreSmoothingStep(1);
//   system2.SetNumberPostSmoothingStep(1);
//    
//   //Set Smoother Options
//   if(Gmres) 		system2.SetMgSmoother(GMRES_SMOOTHER);
//   else if(Asm) 		system2.SetMgSmoother(ASM_SMOOTHER);
//   else if(Vanka)	system2.SetMgSmoother(VANKA_SMOOTHER);
//   
//   system2.init(); 
//   //common smoother option
//   system2.SetSolverFineGrids(GMRES); 
//   system2.SetTolerances(1.e-12,1.e-20,1.e+50,4);
//   system2.SetPreconditionerFineGrids(ILU_PRECOND);
//   //for Vanka and ASM smoothers
//   system2.ClearVariablesToBeSolved();
//   system2.AddVariableToBeSolved("All");
//   system2.SetNumberOfSchurVariables(0);
//   system2.SetElementBlockNumber(4);                
//   //for Gmres smoother
//   system2.SetDirichletBCsHandling(PENALTY); 
//   
//   // Solve Temperature system
//   ml_prob.get_system("Temperature").solve();
//   //END Temperature Multilevel Problem
//   
//   double l2normvarU = ml_sol.GetSolutionLevel(3)->GetSolutionName("U")->l2_norm(); 
//   
//   double l2normvarUStored = 16.313927822836003;
//   
//   std::cout << "Solution U l2norm: " << l2normvarU << std::endl; 
//   
//   if( fabs((l2normvarU - l2normvarUStored )/l2normvarUStored) > 1.e-6) 
//   {
//     exit(1);
//   }
//   
//   double l2normvarV = ml_sol.GetSolutionLevel(3)->GetSolutionName("V")->l2_norm(); 
//   
//   double l2normvarVStored = 6.0644257018060355;
//   
//   std::cout << "Solution V l2norm: " << l2normvarV << std::endl; 
//   
//   if( fabs((l2normvarV - l2normvarVStored )/l2normvarVStored )> 1.e-6) 
//   {
//     exit(1);
//   }
//   
//   double l2normvarP = ml_sol.GetSolutionLevel(3)->GetSolutionName("P")->l2_norm(); 
//   
//   double l2normvarPStored = 1.8202105018866834;
//   
//   std::cout << "Solution P l2norm: " << l2normvarP << std::endl; 
//   
//   if( fabs((l2normvarP - l2normvarPStored )/l2normvarPStored) > 1.e-6) 
//   {
//     exit(1);
//   }
//   
//   double l2normvarT = ml_sol.GetSolutionLevel(3)->GetSolutionName("T")->l2_norm(); 
//   
//   double l2normvarTStored = 219.68194612060503;
//   
//   std::cout << "Solution T l2norm: " << l2normvarT <<std::endl; 
//   
//   if( fabs((l2normvarT - l2normvarTStored )/l2normvarTStored) > 1.e-6) 
//   {
//     exit(1);
//   }
  
  std::vector<std::string> print_vars;
  print_vars.push_back("U");
  print_vars.push_back("V");
  print_vars.push_back("P");
  print_vars.push_back("T");
  
  GMVWriter gmvio(&ml_sol);
  gmvio.write(files.GetOutputPath(),"biquadratic",print_vars);
  
  
  
  //Destroy all the new systems
  ml_prob.clear();
    
  delete [] infile;
  return 0;
}
コード例 #18
0
ファイル: main.cpp プロジェクト: rushs777/femus
int main(int argc,char **args) {

  /// Init Petsc-MPI communicator
  FemusInit mpinit(argc,args,MPI_COMM_WORLD);
  
  Files files; 
        files.CheckIODirectories();
	//files.RedirectCout();
  
  bool Vanka=0, Gmres=0, Asm=0;
  if(argc >= 2) {
    if( !strcmp("vanka",args[1])) 	Vanka=1;
    else if( !strcmp("gmres",args[1])) 	Gmres=1;
    else if( !strcmp("asm",args[1])) 	Asm=1;
    
    if(Vanka+Gmres+Asm==0) {
      cout << "wrong input arguments!" << endl;
      exit(0);
    }
  }
  else {
    cout << "No input argument set default smoother = Gmres" << endl;
    Gmres=1;
  }
  
  /// INIT MESH =================================  
  
  unsigned short nm,nr;
  nm=4;
  std::cout<<"MULTIGRID levels: "<< nm << endl;

  nr=0;
  std::cout<<"MAX_REFINEMENT levels: " << nr << endl<< endl;
  
  int tmp=nm;  nm+=nr;  nr=tmp;
  
  char *infile = new char [50];
 
  sprintf(infile,"./input/box10x10.neu");
  
  //Adimensional quantity (Lref,Uref)
  double Lref = 1.;
  double Uref = 1.;
  
  //Steadystate NonLinearMultiLevelProblem  
  //MultiLevelMesh ml_msh(nm,nr,infile,"seventh",Lref,SetRefinementFlag); 
  MultiLevelMesh ml_msh;
  ml_msh.ReadCoarseMesh(infile,"seventh",Lref);
  ml_msh.RefineMesh(nm,nr,NULL);
  
  ml_msh.EraseCoarseLevels(nm-1);
  
  MultiLevelSolution ml_sol(&ml_msh);
  
  // generate solution vector
  
  FEOrder orderPre = FIRST;
  FEOrder orderVel = FIRST;
  FEOrder orderTemp = FIRST;
  
  ml_sol.AddSolution("U", LAGRANGE, orderVel);
  ml_sol.AddSolution("V", LAGRANGE, orderVel);
  ml_sol.AddSolution("lmbd", DISCONTINOUS_POLYNOMIAL, ZERO, 0, false);
  
  // the pressure variable should be the last for the Schur decomposition
  // ml_sol.AddSolution("P",DISCONTINOUS_POLYNOMIAL,FIRST);
  ml_sol.AddSolution("P",LAGRANGE, orderPre);
  ml_sol.AssociatePropertyToSolution("P","Pressure");
 
  ml_sol.AddSolution("T",LAGRANGE,orderTemp);
  
  //Initialize (update Init(...) function)
  ml_sol.Initialize("U");
  ml_sol.Initialize("V");
  ml_sol.Initialize("P");
  ml_sol.Initialize("T");
  ml_sol.Initialize("lmbd");
  //Set Boundary (update Dirichlet(...) function)
  ml_sol.AttachSetBoundaryConditionFunction(SetBoundaryConditionCavityFlow);
  ml_sol.GenerateBdc("U");
  ml_sol.GenerateBdc("V");
  ml_sol.GenerateBdc("P");
  ml_sol.GenerateBdc("T");
  
  SetLambda(ml_sol, 0, orderVel, ELASTICITY);
  //SetLambda(ml_sol, 0, 2,"diffusion");
  
  MultiLevelProblem ml_prob(&ml_sol);
  
  // add fluid material
  Parameter parameter(Lref,Uref);
  
  // Generate fluid Object (Adimensional quantities,viscosity,density,fluid-model)
  Fluid fluid(parameter,0.001,1,"Newtonian",0.001,1.);
  cout << "Fluid properties: " << endl;
  cout << fluid << endl;
  
  ml_prob.parameters.set<Fluid>("Fluid") = fluid;
   
  
  //BEGIN Navier-Stokes Multilevel Problem
  std::cout << std::endl;
  std::cout << " *********** Navier-Stokes ************  " << std::endl;
    
  NonLinearImplicitSystem & system1 = ml_prob.add_system<NonLinearImplicitSystem> ("Navier-Stokes");
  system1.AddSolutionToSystemPDE("U");
  system1.AddSolutionToSystemPDE("V");
  system1.AddSolutionToSystemPDE("P");
  
  // Set MG Options
  system1.SetAssembleFunction(AssembleMatrixResNS);  
  system1.SetMaxNumberOfNonLinearIterations(90);
  system1.SetMaxNumberOfLinearIterations(2);
  system1.SetLinearConvergenceTolerance(1.e-10);
  system1.SetNonLinearConvergenceTolerance(1.e-10);
  system1.SetMgType(F_CYCLE);
  system1.SetNumberPreSmoothingStep(1);
  system1.SetNumberPostSmoothingStep(1);
      
  //Set Smoother Options
  if(Gmres) 		system1.SetMgSmoother(GMRES_SMOOTHER);
  else if(Asm) 		system1.SetMgSmoother(ASM_SMOOTHER);
  else if(Vanka)	system1.SetMgSmoother(VANKA_SMOOTHER);
  
  system1.init();
  //common smoother options
//   system1.AddStabilization(true);
  system1.SetSolverFineGrids(GMRES);
  system1.SetPreconditionerFineGrids(ILU_PRECOND); 
  system1.SetTolerances(1.e-12,1.e-20,1.e+50,4);
 
  system1.ClearVariablesToBeSolved();
  //system1.AddVariableToBeSolved("All");
  system1.AddVariableToBeSolved("U");
  system1.AddVariableToBeSolved("V");
  system1.AddVariableToBeSolved("P");
  //for Vanka and ASM smoothers
  system1.SetNumberOfSchurVariables(0);
  system1.SetElementBlockNumber(4);   
  //system1.SetElementBlockNumber("All",1);     
  //for Gmres smoother
  system1.SetDirichletBCsHandling(PENALTY); 
  //system1.SetDirichletBCsHandling(ELIMINATION); 
   
  // Solve Navier-Stokes system
  ml_prob.get_system("Navier-Stokes").solve();
  //END Navier-Stokes Multilevel Problem
  
  
  //BEGIN Temperature MultiLevel Problem
  std::cout << std::endl;
  std::cout << " *********** Temperature ************* " << std::endl;
    
  LinearImplicitSystem & system2 = ml_prob.add_system<LinearImplicitSystem> ("Temperature");
  system2.AddSolutionToSystemPDE("T");
  
  
  // Set MG Options
  system2.SetAssembleFunction(AssembleMatrixResT);
  system2.SetMaxNumberOfLinearIterations(6);
  system2.SetLinearConvergenceTolerance(1.e-9);  
  system2.SetMgType(V_CYCLE);
  system2.SetNumberPreSmoothingStep(1);
  system2.SetNumberPostSmoothingStep(1);
   
  //Set Smoother Options
  if(Gmres) 		system2.SetMgSmoother(GMRES_SMOOTHER);
  else if(Asm) 		system2.SetMgSmoother(ASM_SMOOTHER);
  else if(Vanka)	system2.SetMgSmoother(VANKA_SMOOTHER);
  
  system2.init(); 
  //common smoother option
  system2.SetSolverFineGrids(GMRES); 
  system2.SetTolerances(1.e-12,1.e-20,1.e+50,4);
  system2.SetPreconditionerFineGrids(ILU_PRECOND);
  //for Vanka and ASM smoothers
  system2.ClearVariablesToBeSolved();
  system2.AddVariableToBeSolved("All");
  system2.SetNumberOfSchurVariables(0);
  system2.SetElementBlockNumber(4);                
  //for Gmres smoother
  system2.SetDirichletBCsHandling(PENALTY); 
  //system2.SetDirichletBCsHandling(ELIMINATION); 
  
  
  // Solve Temperature system
  ml_prob.get_system("Temperature").solve();
  //END Temperature Multilevel Problem
    
  /// Print all solutions
  std::vector<std::string> print_vars;
  print_vars.push_back("U");
  print_vars.push_back("V");
  print_vars.push_back("P");
  print_vars.push_back("T");
       
  VTKWriter vtkio(&ml_sol);
  vtkio.write(files.GetOutputPath(),"biquadratic",print_vars);
  //vtkio.write(DEFAULT_OUTPUTDIR,"biquadratic",print_vars);
  
  GMVWriter gmvio(&ml_sol);
  gmvio.write(DEFAULT_OUTPUTDIR,"biquadratic",print_vars);
  // gmvio.write(files.GetOutputPath(),"biquadratic",print_vars);
    
  //   XDMFWriter xdmfio(ml_sol);
  //   xdmfio.write(files.GetOutputPath(),"biquadratic",print_vars);
   
  //Destroy all the new systems
  ml_prob.clear();
  
  delete [] infile;
  return 0;
}
コード例 #19
0
ファイル: main.cpp プロジェクト: coyigg/femus
int main(int argc,char **args) {
  
  /// Init Petsc-MPI communicator
  FemusInit mpinit(argc,args,MPI_COMM_WORLD);
  
  Files files; 
        files.CheckIODirectories();
        files.RedirectCout();
	
  /// INIT MESH =================================  
  
  unsigned short nm,nr;
  nm=4;
  std::cout<<"MULTIGRID levels: "<< nm << endl;

  nr=0;
  std::cout<<"MAX_REFINEMENT levels: " << nr << endl<< endl;
  
  int tmp=nm;  nm+=nr;  nr=tmp;
  
  char *infile = new char [50];
 
  sprintf(infile,"./input/nsbenchreg.neu");
  
  //Adimensional quantity (Lref,Uref)
  double Lref = 1.;
  double Uref = 1.;
  
  MultiLevelMesh ml_msh(nm,nr,infile,"seventh",Lref,NULL);
   
  MultiLevelSolution ml_sol(&ml_msh);
   
  // generate solution vector
  ml_sol.AddSolution("U",LAGRANGE,SECOND,2);
  ml_sol.AddSolution("V",LAGRANGE,SECOND,2);
  // the pressure variable should be the last for the Schur decomposition
  ml_sol.AddSolution("P",DISCONTINOUS_POLYNOMIAL,FIRST,1);
  ml_sol.AssociatePropertyToSolution("P","Pressure");
  
  //Initialize (update Init(...) function)
  ml_sol.Initialize("All");
  
  //Set Boundary (update Dirichlet(...) function)
  ml_sol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
  ml_sol.GenerateBdc("U","Time_dependent");
  ml_sol.GenerateBdc("V");
  ml_sol.GenerateBdc("P");

  
  MultiLevelProblem ml_prob(&ml_sol);
  
  
  Parameter parameter(Lref,Uref);
  
  // Generate fluid Object (Adimensional quantities,viscosity,density,fluid-model)
  Fluid fluid(parameter,0.001,1.,"Newtonian");
  cout << "Fluid properties: " << endl;
  cout << fluid << endl;  

  // add fluid material
  ml_prob.parameters.set<Fluid>("Fluid") = fluid;
  
  
 
  //create systems
  // add the system Navier-Stokes to the MultiLevel problem
  TransientNonlinearImplicitSystem & system = ml_prob.add_system<TransientNonlinearImplicitSystem> ("Navier-Stokes");
  system.AddSolutionToSystemPDE("U");
  system.AddSolutionToSystemPDE("V");
  system.AddSolutionToSystemPDE("P");
  
  // init all the systems
  system.init();
 
  // System Navier-Stokes
  system.SetAssembleFunction(AssembleMatrixResNS);  
  system.SetMaxNumberOfLinearIterations(1);
  system.SetLinearConvergenceTolerance(1.e-8);  
  system.SetMgType(V_CYCLE);
  system.SetMaxNumberOfNonLinearIterations(15);

  // time loop parameter
  system.SetIntervalTime(0.1);
  const unsigned int n_timesteps = 20;
  const unsigned int write_interval = 1;
  
  for (unsigned time_step = 0; time_step < n_timesteps; time_step++) {
   
    // Solving Navier-Stokes system
    std::cout << std::endl;
    std::cout << " *********** Navier-Stokes ************  " << std::endl;
    ml_prob.get_system("Navier-Stokes").solve();
   
    //update Solution
    ml_prob.get_system<TransientNonlinearImplicitSystem>("Navier-Stokes").UpdateSolution();

    // print solution
    if ( !(time_step%write_interval) ) {
        
      //print solution 
      std::vector<std::string> print_vars;
      print_vars.push_back("U");
      print_vars.push_back("V");
      print_vars.push_back("P");
      
//       ml_prob.printsol_vtu_inline("biquadratic",print_vars,time_step);
      VTKWriter vtkio(&ml_sol);
      vtkio.write(files.GetOutputPath(),"biquadratic",print_vars,time_step);
    }
  
  } //end loop timestep
  

  // Destroy all the new systems
  ml_prob.clear();
   

  delete[] infile;
  return 0;
}
コード例 #20
0
ファイル: hires1.cpp プロジェクト: 86400/scummvm
void HiRes1Engine::init() {
	if (Common::File::exists("MYSTHOUS.DSK")) {
		_files = new Files_DOS33();
		if (!static_cast<Files_DOS33 *>(_files)->open("MYSTHOUS.DSK"))
			error("Failed to open MYSTHOUS.DSK");
	} else
		_files = new Files_Plain();

	_graphics = new Graphics_v1(*_display);

	StreamPtr stream(_files->createReadStream(IDS_HR1_EXE_1));

	// Some messages have overrides inside the executable
	_gameStrings.cantGoThere = readStringAt(*stream, IDI_HR1_OFS_STR_CANT_GO_THERE);
	_gameStrings.dontHaveIt = readStringAt(*stream, IDI_HR1_OFS_STR_DONT_HAVE_IT);
	_gameStrings.dontUnderstand = readStringAt(*stream, IDI_HR1_OFS_STR_DONT_UNDERSTAND);
	_gameStrings.gettingDark = readStringAt(*stream, IDI_HR1_OFS_STR_GETTING_DARK);

	// Load other strings from executable
	_strings.enterCommand = readStringAt(*stream, IDI_HR1_OFS_STR_ENTER_COMMAND);
	_strings.verbError = readStringAt(*stream, IDI_HR1_OFS_STR_VERB_ERROR);
	_strings.nounError = readStringAt(*stream, IDI_HR1_OFS_STR_NOUN_ERROR);
	_strings.playAgain = readStringAt(*stream, IDI_HR1_OFS_STR_PLAY_AGAIN);
	_strings.pressReturn = readStringAt(*stream, IDI_HR1_OFS_STR_PRESS_RETURN);
	_strings.lineFeeds = readStringAt(*stream, IDI_HR1_OFS_STR_LINE_FEEDS);

	// Set message IDs
	_messageIds.cantGoThere = IDI_HR1_MSG_CANT_GO_THERE;
	_messageIds.dontUnderstand = IDI_HR1_MSG_DONT_UNDERSTAND;
	_messageIds.itemDoesntMove = IDI_HR1_MSG_ITEM_DOESNT_MOVE;
	_messageIds.itemNotHere = IDI_HR1_MSG_ITEM_NOT_HERE;
	_messageIds.thanksForPlaying = IDI_HR1_MSG_THANKS_FOR_PLAYING;

	// Load message offsets
	stream->seek(IDI_HR1_OFS_MSGS);
	for (uint i = 0; i < IDI_HR1_NUM_MESSAGES; ++i)
		_messages.push_back(_files->getDataBlock(IDS_HR1_MESSAGES, stream->readUint16LE()));

	// Load picture data from executable
	stream->seek(IDI_HR1_OFS_PICS);
	for (uint i = 1; i <= IDI_HR1_NUM_PICS; ++i) {
		byte block = stream->readByte();
		Common::String name = Common::String::format("BLOCK%i", block);
		uint16 offset = stream->readUint16LE();
		_pictures[i] = _files->getDataBlock(name, offset);
	}

	// Load commands from executable
	stream->seek(IDI_HR1_OFS_CMDS_1);
	readCommands(*stream, _roomCommands);

	stream->seek(IDI_HR1_OFS_CMDS_0);
	readCommands(*stream, _globalCommands);

	// Load dropped item offsets
	stream->seek(IDI_HR1_OFS_ITEM_OFFSETS);
	loadDroppedItemOffsets(*stream, IDI_HR1_NUM_ITEM_OFFSETS);

	// Load right-angle line art
	stream->seek(IDI_HR1_OFS_CORNERS);
	uint16 cornersCount = stream->readUint16LE();
	for (uint i = 0; i < cornersCount; ++i)
		_corners.push_back(_files->getDataBlock(IDS_HR1_EXE_1, IDI_HR1_OFS_CORNERS + stream->readUint16LE()));

	if (stream->eos() || stream->err())
		error("Failed to read game data from '" IDS_HR1_EXE_1 "'");

	stream->seek(IDI_HR1_OFS_VERBS);
	loadWords(*stream, _verbs, _priVerbs);

	stream->seek(IDI_HR1_OFS_NOUNS);
	loadWords(*stream, _nouns, _priNouns);
}
コード例 #21
0
ファイル: main.cpp プロジェクト: Doodle3D/Doodle3D
 void dragEvent(ofDragInfo dragInfo) {
     if (dragInfo.files.size()==1) {
         files.loadFromImage(dragInfo.files[0]);
     }
 }
コード例 #22
0
  void ModelToRadJob::startImpl(const boost::shared_ptr<ProcessCreator> &)
  {
    openstudio::path outpath = outdir();
    QWriteLocker l(&m_mutex);
    JobErrors errors;
    errors.result = ruleset::OSResultValue::Success;
    
    try {
      if (!m_model)
      {
        m_model = modelFile();
      }
      if (!m_sql)
      {
        m_sql = sqlFile();
      }

      resetFiles(m_files, m_model);
    } catch (const std::runtime_error &e) {
      errors.result = ruleset::OSResultValue::Fail;
      errors.addError(ErrorType::Error, e.what());
    }

    if (!m_sql || !m_model)
    {
      errors.result = ruleset::OSResultValue::Fail;
      errors.addError(ErrorType::Error, "Unable to find required model or sql file");
    }

    LOG(Info, "ModelToRad starting, filename: " << toString(m_model->fullPath));
    LOG(Info, "ModelToRad starting, outdir: " << toString(outpath));

    l.unlock();

    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Starting));

    emitStarted();
    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Processing));

    if (errors.result == ruleset::OSResultValue::Fail)
    {
      setErrors(errors);
      return;
    }


    try {
      boost::filesystem::create_directories(outpath);

      //
      // setup
      //
      LOG(Debug, "Working Directory: " + openstudio::toString(outpath));

      // get model
      boost::optional<openstudio::IdfFile> idf = openstudio::IdfFile::load(m_model->fullPath);
      openstudio::model::Model model = openstudio::model::Model(idf.get());

      // load the sql file
      openstudio::SqlFile sqlFile(m_sql->fullPath);

      if (!sqlFile.connectionOpen())
      {
        LOG(Error, "SqlFile connection is not open");
        errors.result = ruleset::OSResultValue::Fail;
        errors.addError(ErrorType::Error, "SqlFile collection is not open");
        setErrors(errors);
        return;
      }

      // set the sql file
      model.setSqlFile(sqlFile);
      if (!model.sqlFile())
      {
        LOG(Error, "SqlFile is not set on model");
        errors.result = ruleset::OSResultValue::Fail;
        errors.addError(ErrorType::Error, "SqlFile is not set on model");
        setErrors(errors);
        return;
      }

      openstudio::radiance::ForwardTranslator ft;
      std::vector<openstudio::path> outfiles = ft.translateModel(outpath, model);
      
      // capture translator errors and warnings?
      //ft.errors();
      //ft.warnings();
      
      Files outfileinfos;

      for (std::vector<openstudio::path>::const_iterator itr = outfiles.begin();
          itr != outfiles.end();
          ++itr)
      {
        FileInfo fi = RunManager_Util::dirFile(*itr);
        LOG(Info, "Output file generated: " << openstudio::toString(fi.fullPath));
        emitOutputFileChanged(fi);
        outfileinfos.append(fi);
      }

      l.relock();

      m_outputfiles = outfileinfos;

      /// Do work here - and be sure to set output files too
    } catch (const std::runtime_error &e) {
      errors.addError(ErrorType::Error, "Error with conversion (runtime_error): " + std::string(e.what()));
      errors.result = ruleset::OSResultValue::Fail;
    }
    catch (const std::exception &e) {
      errors.addError(ErrorType::Error, "Error with conversion: " + std::string(e.what()));
      errors.result = ruleset::OSResultValue::Fail;
    }

    setErrors(errors);
  }
コード例 #23
0
ファイル: main.cpp プロジェクト: TakingItCasual/Snakes
//The Game
int main(int argc, char* args[]) {

	Food Food;
	GraphicFiles_Vars GF_Var;
	InternalRandom IRand;
	LoopControl Loop;
	OptionsRandom ORand;
	Map Map;
	MidVars MidVar;
	Snake Snake;
	Timer Timer;

	GMI_Vars GMI_Var;

	Files File;
	FoodSys FoodSys;
	GameOver GameOver;
	GraphicFiles_Main GF_Main;
	Initializers Init;
	Input Input;
	Menu Menu;
	NPC NPC;
	Tail Tail;

	//External variables initializers.
	Init.ExternalVariableInitializers(Food, GMI_Var, IRand, Loop, Map, ORand, Snake);
	//Gets saved options from a txt file.
	File.ReadOptionsFile(IRand, Map, MidVar, ORand, Snake);
	//Gets high scores from a txt file.
	File.ReadHighScoresFile(IRand, MidVar);
	//Initializes SDL
	GF_Main.init_SDL(GMI_Var, GF_Var);
	//Gets snake movement controls from a txt file.
	File.ReadInputASCII(GF_Var, MidVar);
	//The program (re)start point.
	while (Loop.getGameReset()) {
		//Menu, where the user can customize and start the game.
		Menu.MainMenu(GMI_Var, GF_Var, IRand, Loop, Map, MidVar, ORand);
		//Saves Options to a txt file.
		File.WriteOptionsFile(Map, ORand, Snake);
		//Saves snake movement controls to a txt file.
		File.WriteInputASCII(GF_Var);
		if (Loop.getGameReset()) {
			//Initializes SDL components for the game loop.
			GF_Main.init_SDL_GameLoop(GMI_Var, GF_Var, Map, ORand);
			//Reads saved game txt file if game is loaded.
			File.ReadSavedGame(Food, IRand, Map, MidVar, ORand, Snake);
			//Defaults variables for the game loop.
			Init.InternalVariableInitializers(Food, GMI_Var, GF_Var, IRand, Loop, Map, ORand, Snake);
			//Constructes the borders of the map.
			Init.MapBorderBuild(IRand, Map);
			//Initializers for the game loop.
			Init.FunctionInitializers(Food, IRand, Map, ORand, Snake, Timer);
			//The game loop.
			while (!Loop.getExitState()) {
				//SDL based input system.
				Input.GetInput(GMI_Var, GF_Var, IRand, Loop, Map, ORand, Snake, Timer);
				//Saves game on exit if user chooses to.
				File.WriteSavedGame(Food, IRand, Loop, Map, ORand, Snake);
				//NPC AI
				NPC.NPC_Move(Food, Map, ORand, Snake);
				//Checks user input.
				Tail.ProcessUserInput(IRand, Loop, Map, ORand, Snake);
				//Deletes the snake right after death.
				Tail.DeleteSnakeTail(IRand, Map, ORand, Snake);
				//Places the food onto the map and processes it.
				FoodSys.FoodProcess(Food, GF_Var, IRand, Loop, Map, ORand, Snake);
				//Keeps the tail of the Snake the same size (becomes larger as you eat).
				Tail.TailLengthMaintainer(IRand, Map, ORand, Snake);
				//Draws the SDL game loop screen.
				GF_Main.UpdateGameScreen(GMI_Var, GF_Var, Food, Loop, Map, ORand, Snake);
				//Exits the game loop if a right condition is met.
				GameOver.GameLoopExit(IRand, Loop, Map, ORand, Snake);
			}
			GF_Main.quit_SDL_GameLoop(GF_Var);
		}
		//Saves high scores to a txt file.
		File.WriteHighScoresFile(IRand, Loop, MidVar, ORand);
		//Tells you how you exited the game loop and shows final score(s).
		GameOver.GameOverMessage(GMI_Var, GF_Var, IRand, Loop, Map, ORand);
	}
	//Quits SDL
	GF_Main.quit_SDL(GF_Var, ORand);

	return 0;
}
コード例 #24
0
        virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            notice()<<"Reading DICOM file "<<file<<" using DCMTK"<<std::endl;

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
            
            std::string fileName = file;
            if (ext=="dicom")
            {
                fileName = osgDB::getNameLessExtension(file);
            }

            fileName = osgDB::findDataFile( fileName, options );
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            Files files;
            
            osgDB::FileType fileType = osgDB::fileType(fileName);
            if (fileType==osgDB::DIRECTORY)
            {
                getDicomFilesInDirectory(fileName, files);
            }
            else
            {
#if 1
                files.push_back(fileName);
#else                            
                if (!getDicomFilesInDirectory(osgDB::getFilePath(fileName), files))
                {
                    files.push_back(fileName);
                }
#endif            
            }

            if (files.empty())
            {
                return ReadResult::FILE_NOT_FOUND;
            }

            osg::ref_ptr<osg::RefMatrix> matrix = new osg::RefMatrix;
            osg::ref_ptr<osg::Image> image;
            unsigned int imageNum = 0;
            EP_Representation pixelRep = EPR_Uint8;
            int numPlanes = 0;
            GLenum pixelFormat = 0;
            GLenum dataType = 0;
            unsigned int pixelSize = 0;
            
            typedef std::list<FileInfo> FileInfoList;
            FileInfoList fileInfoList;

            typedef std::map<double, FileInfo> DistanceFileInfoMap;
            typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
            OrientationFileInfoMap orientationFileInfoMap;
            
            unsigned int totalNumSlices = 0;

            for(Files::iterator itr = files.begin();
                itr != files.end();
                ++itr)
            {
                DcmFileFormat fileformat;
                OFCondition status = fileformat.loadFile((*itr).c_str());
                if(!status.good()) return ReadResult::ERROR_IN_READING_FILE;
                
                FileInfo fileInfo;
                fileInfo.filename = *itr;

                double pixelSize_y = 1.0;
                double pixelSize_x = 1.0;
                double sliceThickness = 1.0;
                double imagePositionPatient[3] = {0, 0, 0};
                double imageOrientationPatient[6] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0 };
                Uint16 numOfSlices = 1;
                
                double value = 0.0;
                if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,0).good())
                {
                    pixelSize_y = value;
                    fileInfo.matrix(1,1) = pixelSize_y;
                }

                if (fileformat.getDataset()->findAndGetFloat64(DCM_PixelSpacing, value,1).good())
                {
                    pixelSize_x = value;
                    fileInfo.matrix(0,0) = pixelSize_x;
                }

                // Get slice thickness
                if (fileformat.getDataset()->findAndGetFloat64(DCM_SliceThickness, value).good())
                {
                    sliceThickness = value;
                    notice()<<"sliceThickness = "<<sliceThickness<<std::endl;
                    fileInfo.sliceThickness = sliceThickness;
                }
    
                notice()<<"tagExistsWithValue(DCM_NumberOfFrames)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfFrames)<<std::endl;
                notice()<<"tagExistsWithValue(DCM_NumberOfSlices)="<<fileformat.getDataset()->tagExistsWithValue(DCM_NumberOfSlices)<<std::endl;

                Uint32 numFrames;
                if (fileformat.getDataset()->findAndGetUint32(DCM_NumberOfFrames, numFrames).good())
                {
                    fileInfo.numSlices = numFrames;
                    notice()<<"Read number of frames = "<<numFrames<<std::endl;
                }

                
                OFString numFramesStr;
                if (fileformat.getDataset()->findAndGetOFString(DCM_NumberOfFrames, numFramesStr).good())
                {
                    fileInfo.numSlices = atoi(numFramesStr.c_str());
                    notice()<<"Read number of frames = "<<numFramesStr<<std::endl;
                }

                if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfFrames, numOfSlices).good())
                {
                    fileInfo.numSlices = numOfSlices;
                    notice()<<"Read number of frames = "<<numOfSlices<<std::endl;
                }
                
                if (fileformat.getDataset()->findAndGetUint16(DCM_NumberOfSlices, numOfSlices).good())
                {
                    fileInfo.numSlices = numOfSlices;
                    notice()<<"Read number of slices = "<<numOfSlices<<std::endl;
                }



                // patient position
                for(int i=0; i<3; ++i)
                {
                    if (fileformat.getDataset()->findAndGetFloat64(DCM_ImagePositionPatient, imagePositionPatient[i],i).good())
                    {
                        notice()<<"Read DCM_ImagePositionPatient["<<i<<"], "<<imagePositionPatient[i]<<std::endl;
                    }
                    else
                    {
                        notice()<<"Have not read DCM_ImagePositionPatient["<<i<<"]"<<std::endl;
                    }
                }
                //notice()<<"imagePositionPatient[2]="<<imagePositionPatient[2]<<std::endl;
                
                fileInfo.matrix.setTrans(imagePositionPatient[0],imagePositionPatient[1],imagePositionPatient[2]);

                for(int i=0; i<6; ++i)
                {
                    double value = 0.0;
                    if (fileformat.getDataset()->findAndGetFloat64(DCM_ImageOrientationPatient, value,i).good())
                    {
                        imageOrientationPatient[i] = value;
                        notice()<<"Read imageOrientationPatient["<<i<<"], "<<imageOrientationPatient[i]<<std::endl;
                    }
                    else
                    {
                        notice()<<"Have not read imageOrientationPatient["<<i<<"]"<<std::endl;
                    }
                }

                osg::Vec3d dirX(imageOrientationPatient[0],imageOrientationPatient[1],imageOrientationPatient[2]);
                osg::Vec3d dirY(imageOrientationPatient[3],imageOrientationPatient[4],imageOrientationPatient[5]);
                osg::Vec3d dirZ = dirX ^ dirY;
                dirZ.normalize();
                
                dirX *= pixelSize_x;
                dirY *= pixelSize_y;
                
                fileInfo.matrix(0,0) = dirX[0];
                fileInfo.matrix(1,0) = dirX[1];
                fileInfo.matrix(2,0) = dirX[2];
                
                fileInfo.matrix(0,1) = dirY[0];
                fileInfo.matrix(1,1) = dirY[1];
                fileInfo.matrix(2,1) = dirY[2];
                
                fileInfo.matrix(0,2) = dirZ[0];
                fileInfo.matrix(1,2) = dirZ[1];
                fileInfo.matrix(2,2) = dirZ[2];
                
                fileInfo.distance = dirZ * (osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix);

                notice()<<"dirX = "<<dirX<<std::endl;
                notice()<<"dirY = "<<dirY<<std::endl;
                notice()<<"dirZ = "<<dirZ<<std::endl;
                notice()<<"matrix = "<<fileInfo.matrix<<std::endl;
                notice()<<"pos = "<<osg::Vec3d(0.0,0.0,0.0)*fileInfo.matrix<<std::endl;
                notice()<<"dist = "<<fileInfo.distance<<std::endl;
                notice()<<std::endl;

                (orientationFileInfoMap[dirZ])[fileInfo.distance] = fileInfo;

                totalNumSlices += fileInfo.numSlices;

            }

            if (orientationFileInfoMap.empty()) return 0;
            
            typedef std::map<double, FileInfo> DistanceFileInfoMap;
            typedef std::map<osg::Vec3d, DistanceFileInfoMap> OrientationFileInfoMap;
            for(OrientationFileInfoMap::iterator itr = orientationFileInfoMap.begin();
                itr != orientationFileInfoMap.end();
                ++itr)
            {
                notice()<<"Orientation = "<<itr->first<<std::endl;
                DistanceFileInfoMap& dfim = itr->second;
                for(DistanceFileInfoMap::iterator ditr = dfim.begin();
                    ditr != dfim.end();
                    ++ditr)
                {
                    FileInfo& fileInfo = ditr->second;
                    notice()<<"   d = "<<fileInfo.distance<<" "<<fileInfo.filename<<std::endl;
                }
            }
            

            DistanceFileInfoMap& dfim = orientationFileInfoMap.begin()->second;
            if (dfim.empty()) return 0;

            double totalDistance = 0.0;
            if (dfim.size()>1)
            {
                totalDistance = fabs(dfim.rbegin()->first - dfim.begin()->first);
            }
            else
            {
                totalDistance = dfim.begin()->second.sliceThickness * double(dfim.begin()->second.numSlices);
            }
            
            notice()<<"Total Distance including ends "<<totalDistance<<std::endl;

            double averageThickness = totalNumSlices<=1 ? 1.0 : totalDistance / double(totalNumSlices-1);
            
            notice()<<"Average thickness "<<averageThickness<<std::endl;

            for(DistanceFileInfoMap::iterator ditr = dfim.begin();
                ditr != dfim.end();
                ++ditr)
            {
                FileInfo& fileInfo = ditr->second;
                
                std::auto_ptr<DicomImage> dcmImage(new DicomImage(fileInfo.filename.c_str()));
                if (dcmImage.get())
                {
                    if (dcmImage->getStatus()==EIS_Normal)
                    {

                        // get the pixel data
                        const DiPixel* pixelData = dcmImage->getInterData();
                        if(!pixelData) 
                        {
                            warning()<<"Error: no data in DicomImage object."<<std::endl;
                            return ReadResult::ERROR_IN_READING_FILE;
                        }
                        
                        osg::ref_ptr<osg::Image> imageAdapter = new osg::Image;
                        
                        EP_Representation curr_pixelRep;
                        int curr_numPlanes;
                        GLenum curr_pixelFormat;
                        GLenum curr_dataType;
                        unsigned int curr_pixelSize;

                        // create the new image
                        convertPixelTypes(pixelData,
                                          curr_pixelRep, curr_numPlanes, 
                                          curr_dataType, curr_pixelFormat, curr_pixelSize);

                        imageAdapter->setImage(dcmImage->getWidth(), dcmImage->getHeight(), dcmImage->getFrameCount(),
                                              curr_pixelFormat,
                                              curr_pixelFormat,
                                              curr_dataType,
                                              (unsigned char*)(pixelData->getData()),
                                              osg::Image::NO_DELETE);
                        if (!image)
                        {
                            pixelRep = curr_pixelRep;
                            numPlanes = curr_numPlanes;
                            dataType = curr_dataType;
                            pixelFormat = curr_pixelFormat;
                            pixelSize = curr_pixelSize;

                            (*matrix)(0,0) = fileInfo.matrix(0,0);
                            (*matrix)(1,0) = fileInfo.matrix(1,0);
                            (*matrix)(2,0) = fileInfo.matrix(2,0);
                            (*matrix)(0,1) = fileInfo.matrix(0,1);
                            (*matrix)(1,1) = fileInfo.matrix(1,1);
                            (*matrix)(2,1) = fileInfo.matrix(2,1);
                            (*matrix)(0,2) = fileInfo.matrix(0,2) * averageThickness;
                            (*matrix)(1,2) = fileInfo.matrix(1,2) * averageThickness;
                            (*matrix)(2,2) = fileInfo.matrix(2,2) * averageThickness;
                            

                            
                            image = new osg::Image;
                            image->setUserData(matrix.get());
                            image->setFileName(fileName.c_str());
                            image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, 
                                                 pixelFormat, dataType);
                                                 
                                                 
                            matrix->preMult(osg::Matrix::scale(double(image->s()), double(image->t()), double(image->r())));

                            notice()<<"Image dimensions = "<<image->s()<<", "<<image->t()<<", "<<image->r()<<" pixelFormat=0x"<<std::hex<<pixelFormat<<" dataType=0x"<<std::hex<<dataType<<std::dec<<std::endl;
                        }
                        else if (pixelData->getPlanes()>numPlanes ||
                                 pixelData->getRepresentation()>pixelRep)
                        {
                            notice()<<"Need to reallocated "<<image->s()<<", "<<image->t()<<", "<<image->r()<<std::endl;
                            
                            // record the previous image settings to use when we copy back the content.
                            osg::ref_ptr<osg::Image> previous_image = image;

                            // create the new image
                            convertPixelTypes(pixelData,
                                              pixelRep, numPlanes, 
                                              dataType, pixelFormat, pixelSize);
                                              
                            image = new osg::Image;
                            image->setUserData(previous_image->getUserData());
                            image->setFileName(fileName.c_str());
                            image->allocateImage(dcmImage->getWidth(), dcmImage->getHeight(), totalNumSlices, 
                                                 pixelFormat, dataType);
                                                 
                            osg::copyImage(previous_image.get(), 0,0,0, previous_image->s(), previous_image->t(), imageNum,
                                           image.get(), 0, 0, 0,                                                 
                                           false);
                            
                        }
                        
                        osg::copyImage(imageAdapter.get(), 0,0,0, imageAdapter->s(), imageAdapter->t(), imageAdapter->r(), 
                                       image.get(), 0, 0, imageNum,
                                       false);
                                             
                        imageNum += dcmImage->getFrameCount();
                    }
                    else
                    {
                        warning()<<"Error in reading dicom file "<<fileName.c_str()<<", error = "<<DicomImage::getString(dcmImage->getStatus())<<std::endl;
                    }
                }
            }
            
            if (!image)
            {
                return ReadResult::ERROR_IN_READING_FILE;
            }

            notice()<<"Spacing = "<<*matrix<<std::endl;
            
            return image.get();
        }
コード例 #25
0
ファイル: main.cpp プロジェクト: CasaNostra/femus
 int main(int argc, char** argv) {

#ifdef HAVE_LIBMESH
   libMesh::LibMeshInit init(argc,argv);
#else   
   FemusInit init(argc,argv);
#endif
   
 // ======= Files ========================
  Files files; 
        files.ConfigureRestart();
        files.CheckIODirectories();
        files.CopyInputFiles();
        files.RedirectCout();

  // ======= Physics Input Parser ========================
  FemusInputParser<double> physics_map("Physics",files.GetOutputPath());

  const double rhof   = physics_map.get("rho0");
  const double Uref   = physics_map.get("Uref");
  const double Lref   = physics_map.get("Lref");
  const double  muf   = physics_map.get("mu0");

  const double  _pref = rhof*Uref*Uref;           physics_map.set("pref",_pref);
  const double   _Re  = (rhof*Uref*Lref)/muf;     physics_map.set("Re",_Re);
  const double   _Fr  = (Uref*Uref)/(9.81*Lref);  physics_map.set("Fr",_Fr);
  const double   _Pr  = muf/rhof;                 physics_map.set("Pr",_Pr);

  // ======= Mesh =====
  const unsigned NoLevels = 3;
  const unsigned dim = 2;
  const GeomElType geomel_type = QUAD;
  GenCase mesh(NoLevels,dim,geomel_type,"inclQ2D2x2.gam");
          mesh.SetLref(1.);  
	  
  // ======= MyDomainShape  (optional, implemented as child of Domain) ====================
  FemusInputParser<double> box_map("Box",files.GetOutputPath());
  Box mybox(mesh.get_dim(),box_map);
      mybox.InitAndNondimensionalize(mesh.get_Lref());

          mesh.SetDomain(&mybox);    
	  
          mesh.GenerateCase(files.GetOutputPath());

          mesh.SetLref(Lref);
      mybox.InitAndNondimensionalize(mesh.get_Lref());
	  
          XDMFWriter::ReadMeshAndNondimensionalizeBiquadraticHDF5(files.GetOutputPath(),mesh); 
	  XDMFWriter::PrintMeshXDMF(files.GetOutputPath(),mesh,BIQUADR_FE);
          XDMFWriter::PrintMeshLinear(files.GetOutputPath(),mesh);
	  
  //gencase is dimensionalized, meshtwo is nondimensionalized
  //since the meshtwo is nondimensionalized, all the BC and IC are gonna be implemented on a nondimensionalized mesh
  //now, a mesh may or may not have an associated domain
  //moreover, a mesh may or may not be read from file
  //the generation is dimensional, the nondimensionalization occurs later
  //Both the Mesh and the optional domain must be nondimensionalized
  //first, we have to say if the mesh has a shape or not
  //that depends on the application, it must be put at the main level
  //then, after you know the shape, you may or may not generate the mesh with that shape 
  //the two things are totally independent, and related to the application, not to the library

  // ===== QuantityMap : this is like the MultilevelSolution =========================================
  QuantityMap  qty_map;
  qty_map.SetMeshTwo(&mesh);
  qty_map.SetInputParser(&physics_map);

  Pressure       pressure("Qty_Pressure",qty_map,1,LL);             qty_map.AddQuantity(&pressure);
  VelocityX     velocityX("Qty_Velocity0",qty_map,1,QQ);            qty_map.AddQuantity(&velocityX);
  VelocityY     velocityY("Qty_Velocity1",qty_map,1,QQ);            qty_map.AddQuantity(&velocityY);
  Temperature temperature("Qty_Temperature",qty_map,1,QQ);          qty_map.AddQuantity(&temperature);
  TempLift       templift("Qty_TempLift",qty_map,1,QQ);             qty_map.AddQuantity(&templift);  
  TempAdj         tempadj("Qty_TempAdj",qty_map,1,QQ);              qty_map.AddQuantity(&tempadj);  
  // ===== end QuantityMap =========================================
  
  // ====== Start new main =================================
  
  MultiLevelMesh ml_msh;
  ml_msh.GenerateCoarseBoxMesh(8,8,0,0,1,0,2,0,0,QUAD9,"fifth"); //   ml_msh.GenerateCoarseBoxMesh(numelemx,numelemy,numelemz,xa,xb,ya,yb,za,zb,elemtype,"fifth");
  ml_msh.RefineMesh(NoLevels,NoLevels,NULL);
  ml_msh.PrintInfo();
  
  ml_msh.SetWriter(XDMF);
  //ml_msh.GetWriter()->write(files.GetOutputPath(),"biquadratic");
  
  ml_msh.SetDomain(&mybox);    
	  
  MultiLevelSolution ml_sol(&ml_msh);
  ml_sol.AddSolution("Qty_Temperature",LAGRANGE,SECOND,0);
  ml_sol.AddSolution("Qty_TempLift",LAGRANGE,SECOND,0);
  ml_sol.AddSolution("Qty_TempAdj",LAGRANGE,SECOND,0);
  ml_sol.AddSolutionVector(ml_msh.GetDimension(),"Qty_Velocity",LAGRANGE,SECOND,0);
  ml_sol.AddSolution("Qty_Pressure",LAGRANGE,FIRST,0);
  ml_sol.AddSolution("Qty_TempDes",LAGRANGE,SECOND,0,false); //this is not going to be an Unknown! //moreover, this is not going to need any BC (i think they are excluded with "false") // I would like to have a Solution that is NOT EVEN related to the mesh at all... just like a function "on-the-fly"

  // ******* Set problem *******
  MultiLevelProblem ml_prob(&ml_sol);
  ml_prob.SetMeshTwo(&mesh);
  ml_prob.SetQruleAndElemType("fifth");
  ml_prob.SetInputParser(&physics_map);
  ml_prob.SetQtyMap(&qty_map); 
  
  // ******* Initial condition *******
  ml_sol.InitializeMLProb(&ml_prob,"Qty_Temperature",SetInitialCondition);  
  ml_sol.InitializeMLProb(&ml_prob,"Qty_TempLift",SetInitialCondition);  
  ml_sol.InitializeMLProb(&ml_prob,"Qty_TempAdj",SetInitialCondition);  
  ml_sol.InitializeMLProb(&ml_prob,"Qty_Velocity0",SetInitialCondition);  
  ml_sol.InitializeMLProb(&ml_prob,"Qty_Velocity1",SetInitialCondition);  
  ml_sol.InitializeMLProb(&ml_prob,"Qty_Pressure",SetInitialCondition); 
  ml_sol.InitializeMLProb(&ml_prob,"Qty_TempDes",SetInitialCondition); 

  /// @todo you have to call this before you can print 
  /// @todo I can also call it after instantiation MLProblem  
  /// @todo I cannot call it with "All" and with a FUNCTION, because I need the string for "All" as a variable
  /// @todo Have to say that you have to call this initialize BEFORE the generation of the boundary conditions;
  /// if you called this after, it would superimpose the BOUNDARY VALUES 
  /// @todo you have to initialize also those variables which are NOT unknowns!
  
  // ******* Set boundary function function *******
  ml_sol.AttachSetBoundaryConditionFunctionMLProb(SetBoundaryCondition);
  
  // ******* Generate boundary conditions *******
  ml_sol.GenerateBdc("Qty_Temperature","Steady",&ml_prob);
  ml_sol.GenerateBdc("Qty_TempLift","Steady",&ml_prob);
  ml_sol.GenerateBdc("Qty_TempAdj","Steady",&ml_prob);
  ml_sol.GenerateBdc("Qty_Velocity0","Steady",&ml_prob);
  ml_sol.GenerateBdc("Qty_Velocity1","Steady",&ml_prob);
  ml_sol.GenerateBdc("Qty_Pressure","Steady",&ml_prob);

  
  // ******* Debug *******
  ml_sol.SetWriter(VTK);
  std::vector<std::string> print_vars(1); print_vars[0] = "All"; // we should find a way to make this easier
  ml_sol.GetWriter()->write(files.GetOutputPath(),"biquadratic",print_vars);

  
//===============================================
//================== Add EQUATIONS AND ======================
//========= associate an EQUATION to QUANTITIES ========
//========================================================
// not all the Quantities need to be unknowns of an equation

  SystemTwo & eqnNS = ml_prob.add_system<SystemTwo>("Eqn_NS");
  
          eqnNS.AddSolutionToSystemPDEVector(ml_msh.GetDimension(),"Qty_Velocity");
          eqnNS.AddSolutionToSystemPDE("Qty_Pressure");
	  
          eqnNS.AddUnknownToSystemPDE(&velocityX); 
          eqnNS.AddUnknownToSystemPDE(&velocityY); 
          eqnNS.AddUnknownToSystemPDE(&pressure);
	  
	  eqnNS.SetAssembleFunction(GenMatRhsNS);
  

  SystemTwo & eqnT = ml_prob.add_system<SystemTwo>("Eqn_T");
  
         eqnT.AddSolutionToSystemPDE("Qty_Temperature");
         eqnT.AddSolutionToSystemPDE("Qty_TempLift");
         eqnT.AddSolutionToSystemPDE("Qty_TempAdj");
	 
         eqnT.AddUnknownToSystemPDE(&temperature);
         eqnT.AddUnknownToSystemPDE(&templift);
         eqnT.AddUnknownToSystemPDE(&tempadj); //the order in which you add defines the order in the matrix as well, so it is in tune with the assemble function
	 
	 eqnT.SetAssembleFunction(GenMatRhsT);
  
//================================ 
//========= End add EQUATIONS  and ========
//========= associate an EQUATION to QUANTITIES ========
//================================

//Ok now that the mesh file is there i want to COMPUTE the MG OPERATORS... but I want to compute them ONCE and FOR ALL,
//not for every equation... but the functions belong to the single equation... I need to make them EXTERNAL
// then I'll have A from the equation, PRL and REST from a MG object.
//So somehow i'll have to put these objects at a higher level... but so far let us see if we can COMPUTE and PRINT from HERE and not from the gencase
	 
 
//once you have the list of the equations, you loop over them to initialize everything

   for (MultiLevelProblem::const_system_iterator eqn = ml_prob.begin(); eqn != ml_prob.end(); eqn++) {
     
   SystemTwo* sys = static_cast<SystemTwo*>(eqn->second);
   
  // ******* set MG-Solver *******
  sys->SetMgType(F_CYCLE);
  sys->SetLinearConvergenceTolerance(1.e-10);
  sys->SetNonLinearConvergenceTolerance(1.e-10);//1.e-5
  sys->SetNumberPreSmoothingStep(1);
  sys->SetNumberPostSmoothingStep(1);
  sys->SetMaxNumberOfLinearIterations(8);     //2
  sys->SetMaxNumberOfNonLinearIterations(15); //10
  
  // ******* Set Preconditioner *******
  sys->SetMgSmoother(GMRES_SMOOTHER);//ASM_SMOOTHER,VANKA_SMOOTHER
   
  // ******* init *******
  sys->init();
  
  // ******* Set Smoother *******
  sys->SetSolverFineGrids(GMRES);
  sys->SetPreconditionerFineGrids(ILU_PRECOND); 
  sys->SetTolerances(1.e-12,1.e-20,1.e+50,20);   /// what the heck do these parameters mean?

    // ******* Add variables to be solved *******  /// do we always need this?
  sys->ClearVariablesToBeSolved();
  sys->AddVariableToBeSolved("All");
  
    
  // ******* For Gmres Preconditioner only *******
  sys->SetDirichletBCsHandling(ELIMINATION);
  
  // ******* For Gmres Preconditioner only *******
//   sys->solve();

//=====================
    sys -> init_two();     //the dof map is built here based on all the solutions associated with that system
    sys -> _LinSolver[0]->set_solver_type(GMRES);  //if I keep PREONLY it doesn't run

//=====================
    sys -> init_unknown_vars();
//=====================
    sys -> _dofmap.ComputeMeshToDof();
//=====================
    sys -> initVectors();
//=====================
    sys -> Initialize();
///=====================
    sys -> _bcond.GenerateBdc();
//=====================
    GenCase::ReadMGOps(files.GetOutputPath(),sys);
    
    } 
	 
  // ======== Loop ===================================
  FemusInputParser<double> loop_map("TimeLoop",files.GetOutputPath());
  OptLoop opt_loop(files, loop_map); 
   
  opt_loop.TransientSetup(ml_prob);  // reset the initial state (if restart) and print the Case

  opt_loop.optimization_loop(ml_prob);

// at this point, the run has been completed 
  files.PrintRunForRestart(DEFAULT_LAST_RUN);
  files.log_petsc();
  
// ============  clean ================================
  ml_prob.clear();
  mesh.clear();
  
  
  return 0;
}
コード例 #26
0
ファイル: elliptic_nonlin.cpp プロジェクト: FeMTTU/femus
int main(int argc, char** args) {

    // ======= Init ========================
  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);
  
    // ======= Files ========================
  Files files; 
        files.CheckIODirectories();
        files.RedirectCout();

    // ======= Quad Rule ========================
  std::string fe_quad_rule("seventh");
 /* "seventh" is the order of accuracy that is used in the gauss integration scheme
    In the future it is not going to be an argument of the mesh function   */
  
    // ======= Mesh ========================
  MultiLevelMesh ml_mesh;
  ml_mesh.GenerateCoarseBoxMesh(NSUB_X,NSUB_Y,0,0.,1.,0.,1.,0.,0.,QUAD9,fe_quad_rule.c_str());
  unsigned numberOfUniformLevels = 1;
  unsigned numberOfSelectiveLevels = 0;
  ml_mesh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL);
  ml_mesh.PrintInfo();

    // ======= Solution ========================
  MultiLevelSolution ml_sol(&ml_mesh);  // define the multilevel solution and attach the ml_mesh object to it

  // add variables to ml_sol
  ml_sol.AddSolution("state",   LAGRANGE, FIRST);
  ml_sol.AddSolution("control", LAGRANGE, FIRST);
  ml_sol.AddSolution("adjoint", LAGRANGE, FIRST);
  ml_sol.AddSolution("mu",      LAGRANGE, FIRST);  
  ml_sol.AddSolution("TargReg", DISCONTINUOUS_POLYNOMIAL, ZERO); //this variable is not solution of any eqn, it's just a given field
  ml_sol.AddSolution("ContReg", DISCONTINUOUS_POLYNOMIAL, ZERO); //this variable is not solution of any eqn, it's just a given field

  const unsigned int fake_time_dep_flag = 2;  //this is needed to be able to use _SolOld
  const std::string act_set_flag_name = "act_flag";
  ml_sol.AddSolution(act_set_flag_name.c_str(), LAGRANGE, FIRST,fake_time_dep_flag);               

    // ======= Problem ========================
  MultiLevelProblem ml_prob(&ml_sol);  // define the multilevel problem attach the ml_sol object to it

  ml_prob.SetQuadratureRuleAllGeomElems(fe_quad_rule);
  ml_prob.SetFilesHandler(&files);
  
    // ======= Initial values ========================
  ml_sol.Initialize("All");    // initialize all variables to zero

//   ml_sol.Initialize("All", SetInitialCondition, &ml_prob); //unfortunately if I do this it sets all to zero //I would like to do an attach function similar to the BC
  ml_sol.Initialize("state",   SetInitialCondition, &ml_prob);
  ml_sol.Initialize("control", SetInitialCondition, &ml_prob);
  ml_sol.Initialize("adjoint", SetInitialCondition, &ml_prob);
  ml_sol.Initialize("mu",      SetInitialCondition, &ml_prob);
  ml_sol.Initialize("TargReg", SetInitialCondition, &ml_prob);
  ml_sol.Initialize("ContReg", SetInitialCondition, &ml_prob);
  ml_sol.Initialize(act_set_flag_name.c_str(),  SetInitialCondition, &ml_prob);

    // ======= Boundary Conditions ========================
  ml_sol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);  // attach the boundary condition function and generate boundary data

//   ml_sol.GenerateBdc("All");  //this would do it also for the non-equation-related variables
  ml_sol.GenerateBdc("state");
  ml_sol.GenerateBdc("control");
  ml_sol.GenerateBdc("adjoint");
  ml_sol.GenerateBdc("mu");  //we need this for all Pde variables to make the matrix iterations work... but this should be related to the matrix and not to the sol... The same for the initial condition

    // ======= System ========================
  NonLinearImplicitSystemWithPrimalDualActiveSetMethod& system = ml_prob.add_system < NonLinearImplicitSystemWithPrimalDualActiveSetMethod > ("OptSys");

  system.SetActiveSetFlagName(act_set_flag_name);

  //here we decide the order in the matrix!
  const std::vector < std::string > sol_matrix_pos = {"state","control","adjoint","mu"};
  for (unsigned k = 0; k < sol_matrix_pos.size(); k++)  system.AddSolutionToSystemPDE(sol_matrix_pos[k].c_str());  
  
  // attach the assembling function to system
  system.SetAssembleFunction(AssembleProblem);
  
  ml_sol.SetWriter(VTK);   //need to move this here for the DebugNonlinear function
  ml_sol.GetWriter()->SetDebugOutput(true);
  
  system.SetDebugNonlinear(true);
  system.SetDebugFunction(ComputeIntegral);
  //   system.SetMaxNumberOfNonLinearIterations(2);

    // ======= Solve ========================
  system.init();    // initialize and solve the system
  system.MGsolve();
  
//   ComputeIntegral(ml_prob);
 
    // ======= Final Print ========================
  std::vector < std::string > variablesToBePrinted;
  variablesToBePrinted.push_back("all");
  ml_sol.GetWriter()->Write(files.GetOutputPath()/*DEFAULT_OUTPUTDIR*/, "biquadratic", variablesToBePrinted);    // print solutions


  return 0;
}
コード例 #27
0
ファイル: hires1.cpp プロジェクト: 86400/scummvm
void HiRes1Engine::runIntro() const {
	StreamPtr stream(_files->createReadStream(IDS_HR1_EXE_0));

	stream->seek(IDI_HR1_OFS_LOGO_0);
	_display->setMode(DISPLAY_MODE_HIRES);
	_display->loadFrameBuffer(*stream);
	_display->updateHiResScreen();
	delay(4000);

	if (shouldQuit())
		return;

	_display->setMode(DISPLAY_MODE_TEXT);

	StreamPtr basic(_files->createReadStream(IDS_HR1_LOADER));
	Common::String str;

	str = readStringAt(*basic, IDI_HR1_OFS_PD_TEXT_0, '"');
	_display->printAsciiString(str + '\r');

	str = readStringAt(*basic, IDI_HR1_OFS_PD_TEXT_1, '"');
	_display->printAsciiString(str + "\r\r");

	str = readStringAt(*basic, IDI_HR1_OFS_PD_TEXT_2, '"');
	_display->printAsciiString(str + "\r\r");

	str = readStringAt(*basic, IDI_HR1_OFS_PD_TEXT_3, '"');
	_display->printAsciiString(str + '\r');

	inputKey();
	if (g_engine->shouldQuit())
		return;

	_display->setMode(DISPLAY_MODE_MIXED);

	str = readStringAt(*stream, IDI_HR1_OFS_GAME_OR_HELP);

	bool instructions = false;

	while (1) {
		_display->printString(str);
		Common::String s = inputString();

		if (g_engine->shouldQuit())
			break;

		if (s.empty())
			continue;

		if (s[0] == APPLECHAR('I')) {
			instructions = true;
			break;
		} else if (s[0] == APPLECHAR('G')) {
			break;
		}
	};

	if (instructions) {
		_display->setMode(DISPLAY_MODE_TEXT);
		stream->seek(IDI_HR1_OFS_INTRO_TEXT);

		const uint pages[] = { 6, 6, 4, 5, 8, 7, 0 };

		uint page = 0;
		while (pages[page] != 0) {
			_display->home();

			uint count = pages[page++];
			for (uint i = 0; i < count; ++i) {
				str = readString(*stream);
				_display->printString(str);
				stream->seek(3, SEEK_CUR);
			}

			inputString();

			if (g_engine->shouldQuit())
				return;

			stream->seek(6, SEEK_CUR);
		}
	}

	_display->printAsciiString("\r");

	_display->setMode(DISPLAY_MODE_MIXED);

	// Title screen shown during loading
	stream.reset(_files->createReadStream(IDS_HR1_EXE_1));
	stream->seek(IDI_HR1_OFS_LOGO_1);
	_display->loadFrameBuffer(*stream);
	_display->updateHiResScreen();
	delay(2000);
}
コード例 #28
0
ファイル: files_tests.cpp プロジェクト: Benguang/mesos
TEST_F(FilesTest, ResolveTest)
{
  Files files;
  process::UPID upid("files", process::node());

  // Test the directory / file resolution.
  ASSERT_SOME(os::mkdir("1/2"));
  ASSERT_SOME(os::write("1/two", "two"));
  ASSERT_SOME(os::write("1/2/three", "three"));

  // Attach some paths.
  AWAIT_EXPECT_READY(files.attach("1", "one"));
  AWAIT_EXPECT_READY(files.attach("1", "/one/"));
  AWAIT_EXPECT_READY(files.attach("1/2", "two"));
  AWAIT_EXPECT_READY(files.attach("1/2", "one/two"));

  // Resolve 1/2/3 via each attached path.
  JSON::Object expected;
  expected.values["offset"] = 0;
  expected.values["data"] = "three";

  Future<Response> response =
    process::http::get(upid, "read.json", "path=one/2/three&offset=0");

  AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
  AWAIT_EXPECT_RESPONSE_BODY_EQ(stringify(expected), response);

  response =
    process::http::get(upid, "read.json", "path=/one/2/three&offset=0");

  AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
  AWAIT_EXPECT_RESPONSE_BODY_EQ(stringify(expected), response);

  response =
    process::http::get(upid, "read.json", "path=two/three&offset=0");

  AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
  AWAIT_EXPECT_RESPONSE_BODY_EQ(stringify(expected), response);

  response =
    process::http::get(upid, "read.json", "path=one/two/three&offset=0");

  AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
  AWAIT_EXPECT_RESPONSE_BODY_EQ(stringify(expected), response);

  // Percent encoded '/' urls.
  response =
    process::http::get(upid, "read.json", "path=%2Fone%2F2%2Fthree&offset=0");

  AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
  AWAIT_EXPECT_RESPONSE_BODY_EQ(stringify(expected), response);

  response =
    process::http::get(upid, "read.json", "path=one%2Ftwo%2Fthree&offset=0");

  AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
  AWAIT_EXPECT_RESPONSE_BODY_EQ(stringify(expected), response);

  // Reading dirs not allowed.
  AWAIT_EXPECT_RESPONSE_STATUS_EQ(
      BadRequest().status,
      process::http::get(upid, "read.json", "path=one/2"));
  AWAIT_EXPECT_RESPONSE_STATUS_EQ(
      BadRequest().status,
      process::http::get(upid, "read.json", "path=one"));
  AWAIT_EXPECT_RESPONSE_STATUS_EQ(
      BadRequest().status,
      process::http::get(upid, "read.json", "path=one/"));

  // Breaking out of sandbox.
  AWAIT_EXPECT_RESPONSE_STATUS_EQ(
      BadRequest().status,
      process::http::get(upid, "read.json", "path=two/../two"));
}
コード例 #29
0
ribi::foam::Mesh::Mesh(
  const Files& files,
  const std::vector<boost::shared_ptr<ribi::Coordinat3D>>& points
  )
  : m_boundaries{},
    m_cells{CreateEmptyCells(files)},
    m_faces{CreateFacesWithPoints(files,points)},
    m_points(points)
{
  #ifndef NDEBUG
  Test();
  #endif
  //Add Cell owner to Faces
  {
    assert(!m_cells.empty());
    const FaceIndex n_faces = files.GetFaces()->GetMaxFaceIndex();
    for (FaceIndex i = FaceIndex(0); i!=n_faces; ++i)
    {
      const CellIndex owner_cell_index { files.GetOwner()->GetItem(i).GetCellIndex() };
      #ifndef NDEBUG
      if (owner_cell_index.Get() >= static_cast<int>(m_cells.size()))
      {
        TRACE("ERROR");
        TRACE(owner_cell_index);
        TRACE(m_cells.size());
      }
      #endif
      assert(owner_cell_index.Get() >= 0);
      assert(owner_cell_index.Get() < static_cast<int>(m_cells.size()));
      assert(m_cells[ owner_cell_index.Get() ]);
      const boost::shared_ptr<Cell> owner { m_cells[ owner_cell_index.Get() ] };
      assert(owner);
      assert(!m_faces[i.Get()]->GetOwner() );
      m_faces[i.Get()]->AssignOwner(owner);
      assert( m_faces[i.Get()]->GetOwner() );
    }
  }
  #ifndef NDEBUG
  for (const boost::shared_ptr<Face> face: m_faces) { assert(face); assert(face->GetOwner()); }
  #endif

  //Add owned Faces to Cells
  {
    std::map<boost::shared_ptr<Cell>,std::vector<boost::shared_ptr<Face>>> m;
    for (const boost::shared_ptr<Face> face: m_faces)
    {
      assert(face);
      const boost::shared_ptr<Cell> owner { face->GetOwner() };
      assert(owner);
      //if (!owner) continue;
      if (m.find(owner) == m.end()) { m.insert(std::make_pair(owner, std::vector<boost::shared_ptr<Face>>() ) ); }
      assert(m.find(owner) != m.end());
      (*m.find(owner)).second.push_back(face);
    }
    for (auto p: m)
    {
      p.first->AssignOwnedFaces(p.second);
    }
  }
  //Add neighbours to Faces
  {
    const int n_faces = static_cast<int>(m_faces.size());
    for (int i=0; i!=n_faces; ++i)
    {
      const FaceIndex index(i);
      assert(files.GetNeighbour());
      //Not all Faces have a neighbour
      if (!files.GetNeighbour()->CanGetItem(index)) continue;
      assert(files.GetNeighbour()->CanGetItem(index));
      const CellIndex neighbour_index {
        files.GetNeighbour()->GetItem(index).GetCellIndex()
      };
      assert(i >= 0);
      assert(i < static_cast<int>(m_faces.size()));
      assert(neighbour_index.Get() < static_cast<int>(m_cells.size()));
      assert(!m_faces[i]->GetNeighbour());
      m_faces[i]->AssignNeighbour( m_cells[ neighbour_index.Get() ] );
      assert(m_faces[i]->GetNeighbour());
    }
  }

  //Assign boundaries
  m_boundaries = CreateBoundaries(files,m_faces);

  //Check
  #ifndef NDEBUG
  for (boost::shared_ptr<Cell> cell: m_cells)
  {
    assert(cell);
    //assert( (cell->GetNeighbour() || !cell->GetNeighbour())
    //  && "Not all cells have a neighbour, for example in a 1x1x1 mesh");
  }

  if (GetNumberOfBoundaries() != files.GetBoundary()->GetMaxBoundaryIndex().Get())
  {
    TRACE("ERROR");
    TRACE(GetNumberOfBoundaries());
    TRACE(files.GetBoundary()->GetMaxBoundaryIndex());
  }
  #endif
  assert(GetNumberOfBoundaries() == files.GetBoundary()->GetMaxBoundaryIndex().Get());

  assert(GetNumberOfFaces() == files.GetFaces()->GetMaxFaceIndex().Get());
}
コード例 #30
0
ファイル: main.cpp プロジェクト: rushs777/femus
int main(int argc,char **args) {
  
  /// Init Petsc-MPI communicator
  FemusInit mpinit(argc,args,MPI_COMM_WORLD);

  Files files; 
        files.CheckIODirectories();
        files.RedirectCout();
	
  unsigned short nm,nr;
  std::cout<<"#MULTIGRID levels? (>=1) \n";
  //std::cin>>nm;
  nm=4;

  std::cout<<"#MAX_REFINEMENT levels? (>=0) \n";
  //std::cin>>nr;
  nr=0;
  int tmp=nm;
  nm+=nr;
  nr=tmp;

  const std::string infile = "./input/fsifirst.neu";
  
  double Lref = 1.;
  double Uref = 1.;
  double rhof = 1000.;
  double muf = 1.;
  double rhos = 1000;
  double ni = 0.4;
  double E = 5600000;
  
  MultiLevelMesh ml_msh(nm,nr,infile.c_str(),"fifth",Lref,SetRefinementFlag);
  
  MultiLevelSolution ml_sol(&ml_msh);
  
  //Start System Variables
  ml_sol.AddSolution("DX",LAGRANGE,SECOND,2);
  ml_sol.AddSolution("DY",LAGRANGE,SECOND,2);
//   ml_sol.AssociatePropertyToSolution("DX","Displacement"); // Add this line
//   ml_sol.AssociatePropertyToSolution("DY","Displacement"); // Add this line 
  ml_sol.AddSolution("U",LAGRANGE,SECOND,2);
  ml_sol.AddSolution("V",LAGRANGE,SECOND,2);
  
  //   ml_sol.PairSolution("U","DX"); // Add this line
  //   ml_sol.PairSolution("V","DY"); // Add this line 
  
  ml_sol.AddSolution("AX",LAGRANGE,SECOND,1,0);
  ml_sol.AddSolution("AY",LAGRANGE,SECOND,1,0);
  // Since the Pressure is a Lagrange multiplier it is used as an implicit variable
  ml_sol.AddSolution("P",DISCONTINOUS_POLYNOMIAL,FIRST,1);
  ml_sol.AssociatePropertyToSolution("P","Pressure"); // Add this line

  //Initialize (update Init(...) function)
  ml_sol.Initialize("All");

  //Set Boundary (update Dirichlet(...) function)
  ml_sol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);
  ml_sol.GenerateBdc("DX","Steady");
  ml_sol.GenerateBdc("DY","Steady");
  ml_sol.GenerateBdc("U","Time_dependent");
  ml_sol.GenerateBdc("V","Steady");
  ml_sol.GenerateBdc("AX","Steady");
  ml_sol.GenerateBdc("AY","Steady");
  ml_sol.GenerateBdc("P","Steady");

  
  MultiLevelProblem ml_prob(&ml_sol);
  

  Parameter par(Lref,Uref);
  
  // Generate Solid Object
  Solid solid(par,E,ni,rhos,"Neo-Hookean");
  cout << "Solid properties: " << endl;
  cout << solid << endl;
  
  // Generate Fluid Object
  Fluid fluid(par,muf,rhof,"Newtonian");
  cout << "Fluid properties: " << endl;
  cout << fluid << endl;

  // Add fluid object
  ml_prob.parameters.set<Fluid>("Fluid") = fluid;
  
  // Add Solid Object
  ml_prob.parameters.set<Solid>("Solid") = solid;

  ml_msh.MarkStructureNode();
   
  //create systems
  // add the system FSI to the MultiLevel problem
  TransientMonolithicFSINonlinearImplicitSystem & system = ml_prob.add_system<TransientMonolithicFSINonlinearImplicitSystem> ("Fluid-Structure-Interaction");
  system.AddSolutionToSystemPDE("DX");
  system.AddSolutionToSystemPDE("DY");
  system.AddSolutionToSystemPDE("U");
  system.AddSolutionToSystemPDE("V");
  system.AddSolutionToSystemPDE("P");
  
  // init all the systems
  system.init();
   
  // System Fluid-Structure-Interaction
  system.SetAssembleFunction(AssembleMatrixResFSI);  
  system.SetMaxNumberOfLinearIterations(1);
  system.SetLinearConvergenceTolerance(1.e-8);  
  system.SetMgType(V_CYCLE);
  system.SetMaxNumberOfNonLinearIterations(4);
  system.SetNonLinearConvergenceTolerance(1.e-5);
  system.SetDirichletBCsHandling(PENALTY);
  
  //system.SetDirichletBCsHandling(ELIMINATION);
  
  // time loop parameter
  system.AttachGetTimeIntervalFunction(SetVariableTimeStep);
  const unsigned int n_timesteps = 5;
  const unsigned int write_interval = 1;
  
  std::vector<std::string> mov_vars;
  mov_vars.push_back("DX");
  mov_vars.push_back("DY");
  VTKWriter vtkio(&ml_sol);
  vtkio.SetMovingMesh(mov_vars);
  
  for (unsigned time_step = 0; time_step < n_timesteps; time_step++) {
   
    // Solving Fluid-Structure-Interaction system
    std::cout << std::endl;
    std::cout << " *********** Fluid-Structure-Interaction ************  " << std::endl;
    system.solve();
   
    //The update of the acceleration must be done before the update of the other variables
    system.NewmarkAccUpdate();
    
    //update Solution
    system.UpdateSolution();

    // print solution
    if ( !(time_step%write_interval) ) {
        
      //print solution 
      std::vector<std::string> print_vars;
      print_vars.push_back("DX");
      print_vars.push_back("DY");
      print_vars.push_back("U");
      print_vars.push_back("V");
      print_vars.push_back("P");
      
//       ml_prob.printsol_vtu_inline("biquadratic",print_vars,time_step);
      vtkio.write(files.GetOutputPath(),"biquadratic",print_vars,time_step);
    }
  
  } //end loop timestep
  

  // Destroy all the new systems
  ml_prob.clear();
   
  return 0;
}