Esempio n. 1
0
Maybe<Real> NewtonPolySolve::FindSmallestPositiveRoot(const RPolynomial& p, const Real /*lastSmallestPositive*/) {
	if (NumberOfSignChanges(p) == 0)
		return Maybe<Real>();

	const CPolynomial q(p);
	//{
	//	bool converged;
	//	RPolynomial t = RPolynomial::MakeT();
	//	Scalar x = NextRoot(q, Scalar(lastSmallestPositive), &converged);
	//	if (converged && IsReal(x) && x.real() > 0 && NumberOfSignChanges(p.EvaluateAt(t + x.real() + .1)) == 0)
	//		return x.real();

	//	/*if (converged && )
	//		return x;*/
	//}

	
	const ScalarList roots = FindRoots(q);
	Maybe<Real> result;
	for (int i = 0 ; i < (int)roots.size() ; i++) {
		if (IsReal(roots[i]) && roots[i].real() > 0) {
			if (result.IsValid()) {
				result = std::min(result.Get(), roots[i].real());
			} else {
				result = roots[i].real();
			}
		}
	}
	return result;
}
    //----------------------------------------------------------------------------
    void EvaluatorVisitor::visit( const AST::FunctionExpression* const node )
    {
        ScalarList evaluatedArgs;
        AST::NodeList params = node->getParameterList();

        for ( unsigned int i = 0; i < params.size(); ++i )
        {
            AST::INode* argNode = params[ i ];
            argNode->accept( this );
            evaluatedArgs.push_back( mBranchValue );
        }

        //process function
        mSymbolTable.evaluateFunction( mBranchValue, node->getName(), evaluatedArgs );
    }
Esempio n. 3
0
ScalarList NewtonPolySolve::FindRoots(const CPolynomial& poly, const ScalarList& guessListIn) {
	
	if (poly.Degree() == 0) {
		if (poly[0] == Scalar(0))
			return ScalarList(1,0);
		else 
			throw Exception("No solution");
	}
		
	Scalar x(0);
	
	ScalarList guessList = guessListIn;

	if (!guessList.empty()) {
		x = guessList.back();
		guessList.pop_back();
	}
	
	bool converged;
	x = NextRoot(poly, x, &converged);
	
	ScalarList answers;
	if (poly.Degree() > 1)
		ScalarList answers = FindRoots(poly.RemoveRoot(x), guessList);

	answers.push_back(x);
	return answers;
}
    //---------------------------------------------------------------------------------
    void SymbolTable::evaluateFunction( AST::ConstantExpression& result, const String& name, const ScalarList& evaluatedArgs )
    {
        String funcname = name;

        const FunctionInfo* fi = getFunction( funcname );

        if ( !fi )
        {
            // note: getFunction( funcname ); calls errorHandler
            return;
        }

        if ( fi->argc >= -1 )    // -1 means any parameter count
        {

            if ( fi->argc == 0 && evaluatedArgs.size() != 0 )
            {
                //@todo BadFunctionCallException
                if ( mErrorHandler )
                {
                    Error err( Error::ERR_INVALIDPARAMS, "Function " + funcname + "() does not take any parameter." );
                    mErrorHandler->handleError( &err );
                }
            }

            else if ( fi->argc == 1 && evaluatedArgs.size() != 1 )
            {
                //@todo BadFunctionCallException
                if ( mErrorHandler )
                {
                    Error err( Error::ERR_INVALIDPARAMS, "Function " + funcname + "() takes exactly one parameter." );
                    mErrorHandler->handleError( &err );
                }
            }

            else if ( fi->argc == -1 )
            {
                // ok
            }

            else if ( static_cast<unsigned int>( fi->argc ) != evaluatedArgs.size() )
            {
                std::ostringstream oss;
                oss << "Function " << funcname << "() takes exactly " << fi->argc << " parameters.";
                //@todo BadFunctionCallException
                if ( mErrorHandler )
                {
                    Error err( Error::ERR_INVALIDPARAMS, oss.str() );
                    mErrorHandler->handleError( &err );
                }
            }

            fi->func( result, evaluatedArgs, mErrorHandler );
            return ;
        }


        //@todo UnknownSymbolException(std::string("Unknown function ") + funcname + "()"));
        if ( mErrorHandler )
        {
            Error err( Error::ERR_INVALIDPARAMS, "Unknown function " + funcname + "()" );
            mErrorHandler->handleError( &err );
        }
    }
Esempio n. 5
0
//----------------------------------------------------------------------------
int main(int argc, char **argv)
{
  std::cout << "Usage : ASCII2H5Part "  
    << "-c full/path/to/.cfg "
    << "-a full/path/to/IdFile for optional point Id flagging "
    << "-t full/path/to/timefile.txt " 
    << "-f full/path/to/input/file " << std::endl;
  vtkSmartPointer<vtkTesting> test = vtkSmartPointer<vtkTesting>::New();
  for (int c=1; c<argc; c++ ) {
    test->AddArgument(argv[c]);
  }

  std::string asciipath, asciiname, errormsg, asciifile, hdf5file, ascii2h5config, ascii2h5IdFile;

  // config file
  char *cfg_name = vtkTestUtilities::GetArgOrEnvOrDefault("-c", argc, argv, "DUMMY_ENV_VAR", "");
  if (vtksys::SystemTools::GetFilenamePath(cfg_name).size()==0) {
    std::string cfg_path = vtksys::SystemTools::GetCurrentWorkingDirectory();
    ascii2h5config = cfg_path + "/" + cfg_name;
  }
  else {
    ascii2h5config = cfg_name;
  }
  delete []cfg_name;
  //
  if (!vtksys::SystemTools::FileExists(ascii2h5config.c_str()) ||
       vtksys::SystemTools::FileIsDirectory(ascii2h5config.c_str())) 
  {
    std::cout << "Can't find config file " << ascii2h5config.c_str() << "\n";
    return 0;
  }
  std::cout << "Config file found    : "  << ascii2h5config.c_str() << "\n";;

  // input file
  char *filename = vtkTestUtilities::GetArgOrEnvOrDefault("-f", argc, argv, "DUMMY_ENV_VAR", "");
  asciipath = vtksys::SystemTools::GetFilenamePath(filename);
  asciiname = vtksys::SystemTools::GetFilenameName(filename);
  asciifile = asciipath + "/" + asciiname;
  delete []filename;
  if (!vtksys::SystemTools::FileExists(asciifile.c_str()))
  {
    std::cout << "Can't find input file " << asciifile.c_str() << "\n";
    return 0;
  }
  std::cout << "Input file found     : "  << asciifile.c_str() << "\n";;

  // Point Id file
  char *idf_name = vtkTestUtilities::GetArgOrEnvOrDefault("-a", argc, argv, "DUMMY_ENV_VAR", "");
  std::map<long int, double> idMap;
  if (vtksys::SystemTools::FileExists(idf_name)) {
    ascii2h5IdFile = idf_name;
    std::cout << "Using Id file        : "  << ascii2h5IdFile.c_str() << "\n";
    std::ifstream idfile(idf_name);
    long int low, high;
    double flag;
    while (idfile.good()) {
      idfile >> low >> high >> flag;
      idMap.insert( std::pair<long int,double>(high, flag));
    }
  }
  delete []idf_name;

  // time override 
  bool   OverrideTime = false;
  double OverrideTimeStep = 0.0;
  char *time_steps = vtkTestUtilities::GetArgOrEnvOrDefault("-t", argc, argv, "DUMMY_ENV_VAR", "");
  std::string timeoverride = time_steps;
  if (timeoverride.size()>0) {
    OverrideTime = true;
    OverrideTimeStep = atof(timeoverride.c_str());
    std::cout << "Time override set to : " << OverrideTimeStep << " per step \n";;
  }
  delete []time_steps;

  //
  // generate new h5part file name
  //
  hdf5file  = vtksys::SystemTools::GetFilenameWithoutExtension(asciifile);
  hdf5file  = asciipath + "/" + hdf5file + ".h5part";
  std::cout << "Output HDF5 filename : "  << hdf5file.c_str() << "\n";;
  //
  // Now scan the file names to build up our pattern
  //
  std::string FieldNames;
  std::string FieldIndices;
  std::string TimeExpr;
  std::string IgnoreExp;
  //
  std::string FileNamePattern;
  std::string PrefixRegEx, BlockRegEx, VarRegEx, ExtRegEx, TimeRegEx, Text0RegEx;
  //
  int headerlines=0;
  int DFormat=0;
  // open config file
  std::ifstream cfg(ascii2h5config.c_str());
  char buf[512];
  while (cfg.good()) {
    cfg.getline(buf,512);
    if (strstr(buf, "FieldNames" )!=0)  { cfg.getline(buf,512); FieldNames = buf; }
    if (strstr(buf, "FieldIndices")!=0) { cfg.getline(buf,512); FieldIndices = buf; }
    if (strstr(buf, "TimeExpr")!=0)     { cfg.getline(buf,512); TimeExpr = buf; }
    if (strstr(buf, "IgnoreExp")!=0)    { cfg.getline(buf,512); IgnoreExp = buf; }
    if (strstr(buf, "HeaderLines")!=0)  { cfg.getline(buf,512); sscanf(buf,"%i", &headerlines);}
    if (strstr(buf, "DFormat")!=0)      { cfg.getline(buf,512); sscanf(buf,"%i", &DFormat); }    
    //
    if (strstr(buf, "FileNamePattern")!=0)  { cfg.getline(buf,512); FileNamePattern = buf; }
    if (strstr(buf, "PREFIX_RegEx")!=0)     { cfg.getline(buf,512); PrefixRegEx = buf; }
    if (strstr(buf, "BLOCK_RegEx")!=0)      { cfg.getline(buf,512); BlockRegEx = buf; }
    if (strstr(buf, "VAR_RegEx")!=0)        { cfg.getline(buf,512); VarRegEx = buf; }
    if (strstr(buf, "EXT_RegEx")!=0)        { cfg.getline(buf,512); ExtRegEx = buf; }
    if (strstr(buf, "TIME_RegEx")!=0)       { cfg.getline(buf,512); TimeRegEx = buf; }
    if (strstr(buf, "TEXT0_RegEx")!=0)      { cfg.getline(buf,512); Text0RegEx = buf; }
  }
  //
  FileSeriesFinder *Finder = new FileSeriesFinder(FileNamePattern);
  Finder->SetPrefixRegEx(PrefixRegEx.c_str());
  Finder->SetTimeRegEx(TimeRegEx.c_str());
  Finder->SetBlockRegEx(BlockRegEx.c_str());
  Finder->SetVarRegEx(VarRegEx.c_str());
  Finder->SetExtRegEx(ExtRegEx.c_str());
  Finder->SetText0RegEx(Text0RegEx.c_str());
  Finder->Scan(asciifile.c_str());

  bool multiblock = (Finder->GetNumberOfBlocks()>0);
  bool multivar   = (Finder->GetNumberOfVars()>0);
  bool multitime  = (Finder->GetNumberOfTimeSteps()>0);

  std::vector<double> time_values;
  typedef std::vector< vtkSmartPointer<vtkASCIIParticleReader> > varReader;
  typedef std::vector< varReader > blockReader;
  blockReader readers;
  //
  if (multitime) {
    Tnum = Finder->GetNumberOfTimeSteps();
    Finder->GetTimeValues(time_values);
  }
  int t=0;
  int b=0;
  do {
    int v=0;
    varReader varreaders;
    do {
      vtkSmartPointer<vtkASCIIParticleReader> reader = vtkSmartPointer<vtkASCIIParticleReader>::New();
      varreaders.push_back(reader);     
      std::string filename = Finder->GenerateFileName(t, b, v);
      reader->SetFileName(filename.c_str());
      reader->SetFieldNames(FieldNames.c_str());
      reader->SetFieldIndices(FieldIndices.c_str());
      reader->SetTimeExpression(TimeExpr.c_str());
      reader->SetIgnoreExpression(IgnoreExp.c_str());
      reader->SetHeaderLines(headerlines);
      reader->SetDFormat(DFormat);
      reader->SetTimeStep(0);
      reader->SetMultiFileScalarMode(multivar);
      reader->SetMultiFileCollectNode(multivar && v==0);
      if (b==0 && v==0) {
        if (!multitime) {
          std::cout << "Scanning for Time Steps " << asciifile.c_str() << std::endl;
          reader->UpdateInformation();
          reader->GetTimeStepValues(time_values);
          Tnum = (int)time_values.size();
          std::cout << "Found " << Tnum << " Time steps in file " << std::endl;
        }
      }
    } while (++v<Vnum);
    //
    readers.push_back(varreaders);
  } while (++b<Bnum);
  //

  vtkSmartPointer<vtkH5PartWriter> writer = vtkSmartPointer<vtkH5PartWriter>::New();
  writer->SetFileName((char*)hdf5file.c_str());
  vtkSmartPointer<vtkASCIIParticleReader> reader;
  vtkSmartPointer<vtkPolyData> polys;

  t=0;
  do { // Time
    b=0;
    std::cout << "Reading TimeStep " << t << std::endl;
    //
    vtkSmartPointer<vtkAppendPolyData> append = vtkSmartPointer<vtkAppendPolyData>::New();
    do { // Block    
      int v=0;
      ScalarList scalars;
      std::cout << "Reading Block " << b << std::endl;

      do { // Var
        std::cout << "Reading Var " << v << std::endl;
        reader = readers[b][v];
        std::string filename = Finder->GenerateFileName(t,b,v);
	      reader->SetFileName(filename.c_str());
        if (!multitime) {
          reader->SetTimeStep(t);
        }
        reader->Update();
        std::vector<double> values;
	      reader->GetTimeStepValues(values);
        if (values.size()>0) time_values[t] = values[values.size()>t ? t : 0];

        if (multivar) {
          vtkPolyData *p = vtkPolyData::SafeDownCast(reader->GetOutput());
          vtkFloatArray *floats = vtkFloatArray::SafeDownCast(p->GetPoints()->GetData());
          scalars.push_back(floats);
        }
        //
      } while (++v<Vnum);

      if (multivar) {
        readers[b][0]->CollectMultiFileScalars(scalars);
      }
      polys = vtkPolyData::SafeDownCast(readers[b][0]->GetOutput());
      //
      if (multiblock && polys) append->AddInput(polys);
    } while (++b<Bnum);
    //
    vtkPolyData *realData = polys;
    if (multiblock) {
      append->Update();
      realData = append->GetOutput();
    }
    if (idMap.size()) {
      vtkSmartPointer<vtkFloatArray> IdScalars = vtkSmartPointer<vtkFloatArray>::New(); 
      IdScalars->SetName("PointIdFlags");
      double scalar = 0.0;
      for (int i=0; i<realData->GetNumberOfPoints(); i++) {
        for (std::map<long int, double>::iterator it=idMap.begin(); it!=idMap.end(); ++it) {
          if (i<=it->first) {
            scalar = it->second;
            IdScalars->InsertNextTuple1(scalar);
            break;
          }
        }
      }
      if (IdScalars->GetNumberOfTuples()==realData->GetNumberOfPoints()) {
        realData->GetPointData()->AddArray(IdScalars);
      }
    }
    writer->SetInputData(realData);
    writer->SetTimeStep(t);
    if (time_values.size()>t) {
      writer->SetTimeValue(time_values[t]);
    }
    else {
      writer->SetTimeValue(t);
    }
    if (OverrideTime) {
      double val = OverrideTimeStep*(double)t;
      writer->SetTimeValue(val);
    }
    writer->Write();

    // to make sure reference counting deletes stuff
    reader = NULL;
    polys = NULL;
  } while (++t<Tnum);

  std::cout << "Closing hdf file " << std::endl;
  std::cout << "Written (hopefully) : " << hdf5file.c_str() << std::endl;
  writer->CloseFile();
  std::cout << "Done" << std::endl;
}