const double& logP(uint32_t x1, uint16_t asg1, uint32_t x2, uint16_t asg2) const { // If the factor is not symmetric then we may have to match the // arguments if( _var1 != _var2 ) { assert((x1 == var1() && x2 == var2()) || (x2 == var1() && x1 == var2())); if(x1 == var2() && x2 == var1()) std::swap(asg1, asg2); } ASSERT_LT( asg1 , arity1() ); ASSERT_LT( asg2 , arity2() ); // return value return _data[asg1 + asg2 * arity1()]; } // end of logP for a binary factor
TEST_F(UnifiedVarRenamerTests, ParametersOfFunctionDeclarationGetCorrectlyRenamed) { // Set-up the module. // // void test(int a, int b); // ShPtr<Variable> varA(Variable::create("a", IntType::create(32))); testFunc->addParam(varA); ShPtr<Variable> varB(Variable::create("b", IntType::create(32))); testFunc->addParam(varB); // testFunc is by default a definition, so we have to make it a // declaration. testFunc->convertToDeclaration(); // Setup the renamer. INSTANTIATE_VAR_NAME_GEN_AND_VAR_RENAMER(UnifiedVarRenamer, true); // Do the renaming. varRenamer->renameVars(module); // We expect the following output: // // void test(int a1, int a2); // VarVector params(testFunc->getParams()); ASSERT_EQ(2, params.size()); ShPtr<Variable> var1(params.front()); EXPECT_EQ("a1", var1->getName()); ShPtr<Variable> var2(params.back()); EXPECT_EQ("a2", var2->getName()); }
void FunctionCMP_2P2C<T1, T2>::output(const NumLib::TimeStep &/*time*/) { // update data for output Ogs6FemData* femData = Ogs6FemData::getInstance(); this->_msh_id = this->_problem->getDiscreteSystem()->getMesh()->getID(); // set the new output // we have 2 primary variables OutputVariableInfo var1("MEAN_PRESSURE", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _P); femData->outController.setOutput(var1.name, var1); OutputVariableInfo var2("MOLAR_FRACTION", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _X); femData->outController.setOutput(var2.name, var2); // and 8 secondary variables // add all seconary variables as well. OutputVariableInfo var_Sec_1("Capillary Pressure", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _PC); femData->outController.setOutput(var_Sec_1.name, var_Sec_1); OutputVariableInfo var_Sec_2("Liquid_Phase_Pressure", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _PL); femData->outController.setOutput(var_Sec_2.name, var_Sec_2); OutputVariableInfo var_Sec_3("Gas_Phase_Pressure", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _PG); femData->outController.setOutput(var_Sec_3.name, var_Sec_3); OutputVariableInfo var_Sec_4("Molar_Fraction_Light_component_Liquid_Phase", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _X_m); femData->outController.setOutput(var_Sec_4.name, var_Sec_4); OutputVariableInfo var_Sec_5("Molar_Fraction_Light_component_Gas_Phase", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _X_M); femData->outController.setOutput(var_Sec_5.name, var_Sec_5); OutputVariableInfo var_Sec_6("Molar_Density_Gas_Phase", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _NG); femData->outController.setOutput(var_Sec_6.name, var_Sec_6); OutputVariableInfo var_Sec_7("Molar_Density_Liquid_Phase", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _NL); femData->outController.setOutput(var_Sec_7.name, var_Sec_7); OutputVariableInfo var_Sec_8("Saturation", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _S); femData->outController.setOutput(var_Sec_8.name, var_Sec_8); }
int test_main(int , char* []) { typedef boost::variant<int, std::string> var_t; std_log(LOG_FILENAME_LINE,"[Test Case for recursive_comparison_test]"); var_t var1(3); var_t var2(5); var_t var3("goodbye"); var_t var4("hello"); assert_equality_comparable(var1, var1, var1); assert_equality_comparable(var_t(var1), var_t(var1), var_t(var1)); assert_equality_comparable(var1, var2, var3); assert_less_than_comparable(var1, var2, var3); assert_less_than_comparable(var2, var3, var4); std::vector<var_t> vec; vec.push_back( var3 ); vec.push_back( var2 ); vec.push_back( var4 ); vec.push_back( var1 ); std::sort(vec.begin(), vec.end()); std::string sort_result( print_range(vec.begin(), vec.end()) ); BOOST_CHECK( sort_result == "3 5 goodbye hello " ); #ifdef __SYMBIAN32__ testResultXml("variant_comparison_test"); close_log_file(); #endif return boost::exit_success; }
void FunctionCMP_NonIso_LocalNCPForm<T1, T2>::output(const NumLib::TimeStep &/*time*/) { //update data for output Ogs6FemData* femData = Ogs6FemData::getInstance(); this->_msh_id = this->_problem->getDiscreteSystem()->getMesh()->getID(); // set the new output // we have 2 primary variables OutputVariableInfo var1("MEAN_PRESSURE", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _P); femData->outController.setOutput(var1.name, var1); OutputVariableInfo var2("TOTAL_MASS_DENSITY", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _X); femData->outController.setOutput(var2.name, var2); OutputVariableInfo var3("TEMPERATURE", _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _T); femData->outController.setOutput(var3.name, var3); // and 8 secondary variables // add all seconary variables as well. //we have several secondary variables the values of which are defined on each elements OutputVariableInfo var_Sec_1("Saturation", _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _S); femData->outController.setOutput(var_Sec_1.name, var_Sec_1); OutputVariableInfo var_Sec_3("Gas_Pressure", _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _PG); femData->outController.setOutput(var_Sec_3.name, var_Sec_3); OutputVariableInfo var_Sec_4("Capillary_Pressure", _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _PC); femData->outController.setOutput(var_Sec_4.name, var_Sec_4); OutputVariableInfo var_Sec_6("Mass_Density_G_H", _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _rho_G_h); femData->outController.setOutput(var_Sec_6.name, var_Sec_6); OutputVariableInfo var_Sec_7("Mass_Density_G_W", _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _rho_G_w); femData->outController.setOutput(var_Sec_7.name, var_Sec_7); }
//Build pyomo expression in MC++ void *createVar(double lb, double pt, double ub, int count, int index) { MC var1( I( lb, ub ), pt ); var1.sub(count, index); void *ans = new MC(var1); return ans; }
void AutoActor::LoadB( const std::string &sMetricsGroup, const std::string &sElement ) { ThemeManager::PathInfo pi; bool b = THEME->GetPathInfo( pi, EC_BGANIMATIONS, sMetricsGroup, sElement ); ASSERT( b ); LuaThreadVariable var1( "MatchingMetricsGroup", pi.sMatchingMetricsGroup ); LuaThreadVariable var2( "MatchingElement", pi.sMatchingElement ); Load( pi.sResolvedPath ); }
void test_zono_volume(int n, int m, NT tolerance = 0.15) { typedef Cartesian<NT> Kernel; typedef typename Kernel::Point Point; typedef boost::mt19937 RNGType; typedef Zonotope<Point> Zonotope; Zonotope ZP = gen_zonotope<Zonotope, RNGType>(n, m); // Setup the parameters int walk_len=1; int nexp=1, n_threads=1; NT e=0.1, err=0.0000000001; NT C=2.0,ratio,frac=0.1,delta=-1.0, round_value = 1.0; int rnum = std::pow(e,-2) * 400 * n * std::log(n); int N = 500 * ((int) C) + ((int) (n * n / 2)); int W = 4*n*n+500; ratio = 1.0-1.0/(NT(n)); unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); RNGType rng(seed); boost::normal_distribution<> rdist(0,1); boost::random::uniform_real_distribution<>(urdist); boost::random::uniform_real_distribution<> urdist1(-1,1); std::pair<NT,NT> res_round; vars<NT, RNGType> var(rnum,n,walk_len,n_threads,err,e,0,0,0,0,rng, urdist,urdist1,-1.0,false,false,false,false,false,false,true,false); //Compute chebychev ball// std::pair<Point,NT> CheBall; CheBall = ZP.ComputeInnerBall(); // Estimate the volume std::cout << "--- Testing volume of Zonotope in dimension: " << n <<" and number of generators: "<< m << std::endl; std::cout << "Number type: " << typeid(NT).name() << std::endl; NT vol_exact = exact_zonotope_vol<NT>(ZP); res_round = rounding_min_ellipsoid(ZP, CheBall, var); round_value = round_value * res_round.first; NT vol = 0; unsigned int const num_of_exp = 10; for (unsigned int i=0; i<num_of_exp; i++) { CheBall = ZP.ComputeInnerBall(); vars<NT, RNGType> var2(rnum,n,10 + n/10,n_threads,err,e,0,0,0,0,rng, urdist,urdist1,-1.0,false,false,false,false,false,false,true,false); vars_g<NT, RNGType> var1(n,walk_len,N,W,1,e,CheBall.second,rng,C,frac,ratio,delta,false, false,false,false,false,false,false,true,false); vol += round_value * volume_gaussian_annealing(ZP, var1, var2, CheBall); } NT error = std::abs(((vol/num_of_exp)-vol_exact))/vol_exact; std::cout << "Computed volume (average) = " << vol/num_of_exp << std::endl; std::cout << "Expected volume = " << vol_exact << std::endl; CHECK(error < tolerance); }
//! Print the factor description void printP(std::ostream& out) const { out << "Binary Factor(v_" << var1() << " in {1..." << arity1() << "}, " << ", v_ " << var2() << " in {1..." << arity2() << "})" << std::endl; for(uint16_t i = 0; i < arity1(); ++i) { for(uint16_t j = 0; j < arity2(); ++j) { out << std::exp(logP(i,j)) << " "; } out << std::endl; } }
void FunctionOPSConc<T1, T2>::output(const NumLib::TimeStep &/*time*/) { size_t i; // update data for output Ogs6FemData* femData = Ogs6FemData::getInstance(); this->_msh_id = this->_problem->getDiscreteSystem()->getMesh()->getID(); // set the new output for (i=0; i<_concentrations.size(); i++) { OutputVariableInfo var1(this->getOutputParameterName(i), _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _concentrations[i]); femData->outController.setOutput(var1.name, var1); } }
TEST_F(VarRenamerTests, ClashingNamesEndingWithNumberAreSuffixedWithUnderscores) { // Set-up the module. // // int a; // int b; // int c; // // void test() { // } // ShPtr<Variable> varA(Variable::create("a", IntType::create(32))); module->addGlobalVar(varA); ShPtr<Variable> varB(Variable::create("b", IntType::create(32))); module->addGlobalVar(varB); ShPtr<Variable> varC(Variable::create("c", IntType::create(32))); module->addGlobalVar(varC); // Setup the name generator so it always returns "g1". INSTANTIATE_VAR_NAME_GEN_AND_VAR_RENAMER(VarRenamerWithCreate, false); EXPECT_CALL(*varNameGenMock, getNextVarName()) .Times(3) .WillOnce(Return("g1")) .WillOnce(Return("g1")) .WillOnce(Return("g1")); // Do the renaming. varRenamer->renameVars(module); // We expect the following output: // // int g1; // int g1_; // int g1__; // // void test() { // } // VarSet globalVarsSet(module->getGlobalVars()); ASSERT_EQ(3, globalVarsSet.size()); // We have to sort the variables to ease the checking. VarVector globalVarsVector(globalVarsSet.begin(), globalVarsSet.end()); sortByName(globalVarsVector); ShPtr<Variable> var1(globalVarsVector[0]); EXPECT_EQ("g1", var1->getName()); ShPtr<Variable> var2(globalVarsVector[1]); EXPECT_EQ("g1_", var2->getName()); ShPtr<Variable> var3(globalVarsVector[2]); EXPECT_EQ("g1__", var3->getName()); }
void LyricDisplay::Update( float fDeltaTime ) { ActorFrame::Update( fDeltaTime ); if( GAMESTATE->m_pCurSong == NULL ) return; /* If the song has changed (in a course), reset. */ if( GAMESTATE->m_fMusicSeconds < m_fLastSecond ) Init(); m_fLastSecond = GAMESTATE->m_fMusicSeconds; if( m_iCurLyricNumber >= GAMESTATE->m_pCurSong->m_LyricSegments.size() ) return; const Song *pSong = GAMESTATE->m_pCurSong; const float fStartTime = (pSong->m_LyricSegments[m_iCurLyricNumber].m_fStartTime) - IN_LENGTH.GetValue(); if( GAMESTATE->m_fMusicSeconds < fStartTime ) return; /* Clamp this lyric to the beginning of the next or the end of the music. */ float fEndTime; if( m_iCurLyricNumber+1 < GAMESTATE->m_pCurSong->m_LyricSegments.size() ) fEndTime = pSong->m_LyricSegments[m_iCurLyricNumber+1].m_fStartTime; else fEndTime = pSong->GetElapsedTimeFromBeat( pSong->m_fLastBeat ); const float fDistance = fEndTime - pSong->m_LyricSegments[m_iCurLyricNumber].m_fStartTime; const float fTweenBufferTime = IN_LENGTH.GetValue() + OUT_LENGTH.GetValue(); /* If it's negative, two lyrics are so close together that there's no time * to tween properly. Lyrics should never be this brief, anyway, so just * skip it. */ float fShowLength = max( fDistance - fTweenBufferTime, 0.0f ); // Make lyrics show faster for faster song rates. fShowLength /= GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; const LyricSegment &seg = GAMESTATE->m_pCurSong->m_LyricSegments[m_iCurLyricNumber]; LuaThreadVariable var1( "LyricText", seg.m_sLyric ); LuaThreadVariable var2( "LyricDuration", LuaReference::Create(fShowLength) ); LuaThreadVariable var3( "LyricColor", LuaReference::Create(seg.m_Color) ); PlayCommand( "Changed" ); m_iCurLyricNumber++; }
TEST_F(UnifiedVarRenamerTests, GlobalVariablesGetCorrectlyRenamed) { // Set-up the module. // // int a; // int b; // int c; // // void test() { // } // ShPtr<Variable> varA(Variable::create("a", IntType::create(32))); module->addGlobalVar(varA); ShPtr<Variable> varB(Variable::create("b", IntType::create(32))); module->addGlobalVar(varB); ShPtr<Variable> varC(Variable::create("c", IntType::create(32))); module->addGlobalVar(varC); // Setup the renamer. INSTANTIATE_VAR_NAME_GEN_AND_VAR_RENAMER(UnifiedVarRenamer, true); // Do the renaming. varRenamer->renameVars(module); // We expect the following output: // // int g1; // int g2; // int g3; // // void test() { // } // VarSet globalVarsSet(module->getGlobalVars()); ASSERT_EQ(3, globalVarsSet.size()); // We have to sort the variables to ease the checking. VarVector globalVarsVector(globalVarsSet.begin(), globalVarsSet.end()); sortByName(globalVarsVector); ShPtr<Variable> var1(globalVarsVector[0]); EXPECT_EQ("g1", var1->getName()); ShPtr<Variable> var2(globalVarsVector[1]); EXPECT_EQ("g2", var2->getName()); ShPtr<Variable> var3(globalVarsVector[2]); EXPECT_EQ("g3", var3->getName()); }
void test_CV_volume(Polytope &HP, NT expected, NT tolerance=0.3) { typedef typename Polytope::PolytopePoint Point; // Setup the parameters int n = HP.dimension(); int walk_len=1; int nexp=1, n_threads=1; NT e=0.1, err=0.0000000001; NT C=2.0,ratio,frac=0.1,delta=-1.0; int rnum = std::pow(e,-2) * 400 * n * std::log(n); int N = 500 * ((int) C) + ((int) (n * n / 2)); int W = 4*n*n+500; ratio = 1.0-1.0/(NT(n)); unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); RNGType rng(seed); boost::normal_distribution<> rdist(0,1); boost::random::uniform_real_distribution<>(urdist); boost::random::uniform_real_distribution<> urdist1(-1,1); //compute the chebychev ball std::pair<Point,NT> CheBall; // Estimate the volume std::cout << "Number type: " << typeid(NT).name() << std::endl; NT vol = 0; unsigned int const num_of_exp = 15; for (unsigned int i=0; i<num_of_exp; i++) { CheBall = HP.ComputeInnerBall(); vars<NT, RNGType> var2(rnum,n,10 + n/10,n_threads,err,e,0,0,0,0,rng, urdist,urdist1,-1.0,false,false,false,false,false,false,true,false); vars_g<NT, RNGType> var1(n,walk_len,N,W,1,e,CheBall.second,rng,C,frac,ratio,delta,false, false,false,false,false,false,false,true,false); vol += volume_gaussian_annealing(HP, var1, var2, CheBall); } NT error = std::abs(((vol/num_of_exp)-expected))/expected; std::cout << "Computed volume (average) = " << vol/num_of_exp << std::endl; std::cout << "Expected volume = " << expected << std::endl; CHECK(error < tolerance); }
STDMETHODIMP CBasic::optional4(/*[in, out, optional]*/ VARIANT* val1, /*[in, out, optional]*/ VARIANT* val2) { HRESULT hr = S_OK; //return the previously set in values if (val1->vt != VT_ERROR) { CComVariant var1(*val1); if (FAILED(hr = VariantCopy(val1, & m_var1))) return hr; m_var1 = var1; } if (val2->vt != VT_ERROR) { CComVariant var2(*val2); if (FAILED(hr = VariantCopy(val2, & m_var2))) return hr; m_var2 = var2; } return hr; }
bool Test2D_EM() { int dimensionality = 2; // Generate some data Eigen::MatrixXd data = GenerateData(40, dimensionality); // Initialize the model std::vector<Model*> models(2); for(unsigned int i = 0; i < models.size(); i++) { Model* model = new GaussianModel(dimensionality); models[i] = model; } MixtureModel mixtureModel; mixtureModel.SetModels(models); ExpectationMaximization expectationMaximization; expectationMaximization.SetData(data); expectationMaximization.SetRandom(false); expectationMaximization.SetMixtureModel(mixtureModel); expectationMaximization.SetMaxIterations(3); expectationMaximization.SetInitializationTechniqueToKMeans(); expectationMaximization.Compute(); // This is where we got the test output MixtureModel finalModel = expectationMaximization.GetMixtureModel(); for(unsigned int i = 0; i < finalModel.GetNumberOfModels(); ++i) { std::cout << "Model " << i << ":" << std::endl; finalModel.GetModel(i)->Print(); } Eigen::VectorXd mean0(2); mean0 << 0.0631675, -0.147669; Eigen::VectorXd mean1(2); mean1 << 10.23, 10.069; Eigen::MatrixXd var0(2,2); var0 << 0.818243, -0.027182, -0.027182, 0.836947; Eigen::MatrixXd var1(2,2); var1 << 2.49997, 0.10499, 0.10499, 1.85563; double epsilon = 1e-4; // Check means if((finalModel.GetModel(0)->GetMean() - mean0).norm() > epsilon) { return false; } if((finalModel.GetModel(1)->GetMean() - mean1).norm() > epsilon) { return false; } // Check variances if((finalModel.GetModel(0)->GetVariance() - var0).norm() > epsilon) { return false; } if((finalModel.GetModel(1)->GetVariance() - var1).norm() > epsilon) { return false; } return true; }
//' Sample points from a convex Polytope (H-polytope, V-polytope or a zonotope) or use direct methods for uniform sampling from the unit or the canonical or an arbitrary \eqn{d}-dimensional simplex and the boundary or the interior of a \eqn{d}-dimensional hypersphere //' //' Sample N points with uniform or multidimensional spherical gaussian -centered in an internal point- target distribution. //' The \eqn{d}-dimensional unit simplex is the set of points \eqn{\vec{x}\in \R^d}, s.t.: \eqn{\sum_i x_i\leq 1}, \eqn{x_i\geq 0}. The \eqn{d}-dimensional canonical simplex is the set of points \eqn{\vec{x}\in \R^d}, s.t.: \eqn{\sum_i x_i = 1}, \eqn{x_i\geq 0}. //' //' @param P A convex polytope. It is an object from class (a) Hpolytope or (b) Vpolytope or (c) Zonotope. //' @param N The number of points that the function is going to sample from the convex polytope. The default value is \eqn{100}. //' @param distribution Optional. A string that declares the target distribution: a) \code{'uniform'} for the uniform distribution or b) \code{'gaussian'} for the multidimensional spherical distribution. The default target distribution is uniform. //' @param WalkType Optional. A string that declares the random walk method: a) \code{'CDHR'} for Coordinate Directions Hit-and-Run, b) \code{'RDHR'} for Random Directions Hit-and-Run or c) \code{'BW'} for Ball Walk. The default walk is \code{'CDHR'}. //' @param walk_step Optional. The number of the steps for the random walk. The default value is \eqn{\lfloor 10 + d/10\rfloor}, where \eqn{d} implies the dimension of the polytope. //' @param exact A boolean parameter. It should be used for the uniform sampling from the boundary or the interior of a hypersphere centered at the origin or from the unit or the canonical or an arbitrary simplex. The arbitrary simplex has to be given as a V-polytope. For the rest well known convex bodies the dimension has to be declared and the type of body as well as the radius of the hypersphere. //' @param body A string that declares the type of the body for the exact sampling: a) \code{'unit simplex'} for the unit simplex, b) \code{'canonical simplex'} for the canonical simplex, c) \code{'hypersphere'} for the boundary of a hypersphere centered at the origin, d) \code{'ball'} for the interior of a hypersphere centered at the origin. //' @param Parameters A list for the parameters of the methods: //' \itemize{ //' \item{\code{variance} }{ The variance of the multidimensional spherical gaussian. The default value is 1.} //' \item{\code{dimension} }{ An integer that declares the dimension when exact sampling is enabled for a simplex or a hypersphere.} //' \item{\code{radius} }{ The radius of the \eqn{d}-dimensional hypersphere. The default value is \eqn{1}.} //' \item{\code{BW_rad} }{ The radius for the ball walk.} //' } //' @param InnerPoint A \eqn{d}-dimensional numerical vector that defines a point in the interior of polytope P. //' //' @references \cite{R.Y. Rubinstein and B. Melamed, //' \dQuote{Modern simulation and modeling} \emph{ Wiley Series in Probability and Statistics,} 1998.} //' @references \cite{A Smith, Noah and W Tromble, Roy, //' \dQuote{Sampling Uniformly from the Unit Simplex,} \emph{ Center for Language and Speech Processing Johns Hopkins University,} 2004.} //' @references \cite{Art B. Owen, //' \dQuote{Monte Carlo theory, methods and examples,} \emph{ Copyright Art Owen,} 2009-2013.} //' //' @return A \eqn{d\times N} matrix that contains, column-wise, the sampled points from the convex polytope P. //' @examples //' # uniform distribution from the 3d unit cube in V-representation using ball walk //' P = GenCube(3, 'V') //' points = sample_points(P, WalkType = "BW", walk_step = 5) //' //' # gaussian distribution from the 2d unit simplex in H-representation with variance = 2 //' A = matrix(c(-1,0,0,-1,1,1), ncol=2, nrow=3, byrow=TRUE) //' b = c(0,0,1) //' P = Hpolytope$new(A,b) //' points = sample_points(P, distribution = "gaussian", Parameters = list("variance" = 2)) //' //' # uniform points from the boundary of a 10-dimensional hypersphere //' points = sample_points(exact = TRUE, body = "hypersphere", Parameters = list("dimension" = 10)) //' //' # 10000 uniform points from a 2-d arbitrary simplex //' V = matrix(c(2,3,-1,7,0,0),ncol = 2, nrow = 3, byrow = TRUE) //' P = Vpolytope$new(V) //' points = sample_points(P, N = 10000, exact = TRUE) //' @export // [[Rcpp::export]] Rcpp::NumericMatrix sample_points(Rcpp::Nullable<Rcpp::Reference> P = R_NilValue, Rcpp::Nullable<unsigned int> N = R_NilValue, Rcpp::Nullable<std::string> distribution = R_NilValue, Rcpp::Nullable<std::string> WalkType = R_NilValue, Rcpp::Nullable<unsigned int> walk_step = R_NilValue, Rcpp::Nullable<bool> exact = R_NilValue, Rcpp::Nullable<std::string> body = R_NilValue, Rcpp::Nullable<Rcpp::List> Parameters = R_NilValue, Rcpp::Nullable<Rcpp::NumericVector> InnerPoint = R_NilValue){ typedef double NT; typedef Cartesian<NT> Kernel; typedef typename Kernel::Point Point; typedef boost::mt19937 RNGType; typedef HPolytope <Point> Hpolytope; typedef VPolytope <Point, RNGType> Vpolytope; typedef Zonotope <Point> zonotope; typedef IntersectionOfVpoly<Vpolytope> InterVP; typedef Eigen::Matrix<NT,Eigen::Dynamic,1> VT; typedef Eigen::Matrix<NT,Eigen::Dynamic,Eigen::Dynamic> MT; Hpolytope HP; Vpolytope VP; zonotope ZP; InterVP VPcVP; int type, dim, numpoints; NT radius = 1.0, delta = -1.0; bool set_mean_point = false, cdhr = true, rdhr = false, ball_walk = false, gaussian = false; std::list<Point> randPoints; std::pair<Point, NT> InnerBall; if (!N.isNotNull()) { numpoints = 100; } else { numpoints = Rcpp::as<unsigned int>(N); } if (exact.isNotNull()) { if (P.isNotNull()) { type = Rcpp::as<Rcpp::Reference>(P).field("type"); dim = Rcpp::as<Rcpp::Reference>(P).field("dimension"); if (Rcpp::as<bool>(exact) && type==2) { if (Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V")).rows() == Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V")).cols()+1) { Vpolytope VP; VP.init(dim, Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V")), VT::Ones(Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V")).rows())); Sam_arb_simplex(VP, numpoints, randPoints); } else { throw Rcpp::exception("Not a simplex!"); } } else if (Rcpp::as<bool>(exact) && type!=2) { throw Rcpp::exception("Not a simplex in V-representation!"); } } else { if (!body.isNotNull()) { throw Rcpp::exception("Wrong input!"); } else if (!Rcpp::as<Rcpp::List>(Parameters).containsElementNamed("dimension")) { throw Rcpp::exception("Wrong input!"); } dim = Rcpp::as<NT>(Rcpp::as<Rcpp::List>(Parameters)["dimension"]); if (Rcpp::as<Rcpp::List>(Parameters).containsElementNamed("radius")) { radius = Rcpp::as<NT>(Rcpp::as<Rcpp::List>(Parameters)["radius"]); } if (Rcpp::as<std::string>(body).compare(std::string("hypersphere"))==0) { for (unsigned int k = 0; k < numpoints; ++k) { randPoints.push_back(get_point_on_Dsphere<RNGType , Point >(dim, radius)); } } else if (Rcpp::as<std::string>(body).compare(std::string("ball"))==0) { for (unsigned int k = 0; k < numpoints; ++k) { randPoints.push_back(get_point_in_Dsphere<RNGType , Point >(dim, radius)); } } else if (Rcpp::as<std::string>(body).compare(std::string("unit simplex"))==0) { Sam_Unit<NT, RNGType >(dim, numpoints, randPoints); } else if (Rcpp::as<std::string>(body).compare(std::string("canonical simplex"))==0) { Sam_Canon_Unit<NT, RNGType >(dim, numpoints, randPoints); } else { throw Rcpp::exception("Wrong input!"); } } } else if (P.isNotNull()) { type = Rcpp::as<Rcpp::Reference>(P).field("type"); dim = Rcpp::as<Rcpp::Reference>(P).field("dimension"); unsigned int walkL = 10+dim/10; Point MeanPoint; if (InnerPoint.isNotNull()) { if (Rcpp::as<Rcpp::NumericVector>(InnerPoint).size()!=dim) { Rcpp::warning("Internal Point has to lie in the same dimension as the polytope P"); } else { set_mean_point = true; MeanPoint = Point( dim , Rcpp::as<std::vector<NT> >(InnerPoint).begin(), Rcpp::as<std::vector<NT> >(InnerPoint).end() ); } } if(walk_step.isNotNull()) walkL = Rcpp::as<unsigned int>(walk_step); NT a = 0.5; if (Rcpp::as<Rcpp::List>(Parameters).containsElementNamed("variance")) a = 1.0 / (2.0 * Rcpp::as<NT>(Rcpp::as<Rcpp::List>(Parameters)["variance"])); if(!WalkType.isNotNull() || Rcpp::as<std::string>(WalkType).compare(std::string("CDHR"))==0){ cdhr = true; rdhr = false; ball_walk = false; } else if (Rcpp::as<std::string>(WalkType).compare(std::string("RDHR"))==0) { cdhr = false; rdhr = true; ball_walk = false; } else if (Rcpp::as<std::string>(WalkType).compare(std::string("BW"))==0) { if (Rcpp::as<Rcpp::List>(Parameters).containsElementNamed("BW_rad")) { delta = Rcpp::as<NT>(Rcpp::as<Rcpp::List>(Parameters)["BW_rad"]); } cdhr = false; rdhr = false; ball_walk = true; } else { throw Rcpp::exception("Unknown walk type!"); } if (distribution.isNotNull()) { if (Rcpp::as<std::string>(distribution).compare(std::string("gaussian"))==0) { gaussian = true; } else if(Rcpp::as<std::string>(distribution).compare(std::string("uniform"))!=0) { throw Rcpp::exception("Wrong distribution!"); } } bool rand_only=false, NN=false, birk=false, verbose=false; unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // the random engine with this seed RNGType rng(seed); boost::random::uniform_real_distribution<>(urdist); boost::random::uniform_real_distribution<> urdist1(-1,1); switch(type) { case 1: { // Hpolytope HP.init(dim, Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("A")), Rcpp::as<VT>(Rcpp::as<Rcpp::Reference>(P).field("b"))); if (!set_mean_point || ball_walk) { InnerBall = HP.ComputeInnerBall(); if (!set_mean_point) MeanPoint = InnerBall.first; } break; } case 2: { // Vpolytope VP.init(dim, Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V")), VT::Ones(Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V")).rows())); if (!set_mean_point || ball_walk) { InnerBall = VP.ComputeInnerBall(); if (!set_mean_point) MeanPoint = InnerBall.first; } break; } case 3: { // Zonotope ZP.init(dim, Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("G")), VT::Ones(Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("G")).rows())); if (!set_mean_point || ball_walk) { InnerBall = ZP.ComputeInnerBall(); if (!set_mean_point) MeanPoint = InnerBall.first; } break; } case 4: { // Intersection of two V-polytopes Vpolytope VP1; Vpolytope VP2; VP1.init(dim, Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V1")), VT::Ones(Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V1")).rows())); VP2.init(dim, Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V2")), VT::Ones(Rcpp::as<MT>(Rcpp::as<Rcpp::Reference>(P).field("V2")).rows())); VPcVP.init(VP1, VP2); if (!set_mean_point || ball_walk) { InnerBall = VP.ComputeInnerBall(); if (!set_mean_point) MeanPoint = InnerBall.first; } break; } } if (ball_walk) { if (gaussian) { delta = 4.0 * InnerBall.second / std::sqrt(std::max(NT(1.0), a) * NT(dim)); } else { delta = 4.0 * InnerBall.second / std::sqrt(NT(dim)); } } vars<NT, RNGType> var1(1,dim,walkL,1,0.0,0.0,0,0.0,0,InnerBall.second,rng,urdist,urdist1, delta,verbose,rand_only,false,NN,birk,ball_walk,cdhr,rdhr); vars_g<NT, RNGType> var2(dim, walkL, 0, 0, 1, 0, InnerBall.second, rng, 0, 0, 0, delta, false, verbose, rand_only, false, NN, birk, ball_walk, cdhr, rdhr); switch (type) { case 1: { sampling_only<Point>(randPoints, HP, walkL, numpoints, gaussian, a, MeanPoint, var1, var2); break; } case 2: { sampling_only<Point>(randPoints, VP, walkL, numpoints, gaussian, a, MeanPoint, var1, var2); break; } case 3: { sampling_only<Point>(randPoints, ZP, walkL, numpoints, gaussian, a, MeanPoint, var1, var2); break; } case 4: { sampling_only<Point>(randPoints, VPcVP, walkL, numpoints, gaussian, a, MeanPoint, var1, var2); break; } } } else { throw Rcpp::exception("Wrong input!"); } Rcpp::NumericMatrix PointSet(dim,numpoints); typename std::list<Point>::iterator rpit=randPoints.begin(); typename std::vector<NT>::iterator qit; unsigned int j = 0, i; for ( ; rpit!=randPoints.end(); rpit++, j++) { qit = (*rpit).iter_begin(); i=0; for ( ; qit!=(*rpit).iter_end(); qit++, i++){ PointSet(i,j)=*qit; } } return PointSet; }
bool FunctionOPSConc<T1,T2>::initialize(const BaseLib::Options &option) { size_t i; // index Ogs6FemData* femData = Ogs6FemData::getInstance(); _msh_id = option.getOptionAsNum<size_t>("MeshID"); size_t time_id = option.getOptionAsNum<size_t>("TimeGroupID"); NumLib::ITimeStepFunction* tim = femData->list_tim[time_id]; //mesh and FE objects MeshLib::IMesh* msh = femData->list_mesh[_msh_id]; MyDiscreteSystem* dis = 0; dis = DiscreteLib::DiscreteSystemContainerPerMesh::getInstance()->createObject<MyDiscreteSystem>(msh); _feObjects = new FemLib::LagrangeFeObjectContainer(msh); // initialize the equilibrium reaction system _local_eq_react_sys = femData->m_EqReactSys; _local_kin_react_sys = femData->m_KinReactSys; // make sure the reduction scheme is already initialized. if (!(this->_local_eq_react_sys->IsInitialized()) && !(this->_local_kin_react_sys->IsInitialized())) { // error msg ERR("While initialize the OPS Reactive Transport Process, the chemEqReactSysActivity class has not been correctly initialized! "); // then stop the program exit(1); } // getting the number of components if (this->_local_eq_react_sys->get_n_Eq_React() > 0 && this->_local_eq_react_sys->get_n_Eq_React() > 0) { _n_Comp = std::max(this->_local_eq_react_sys->get_n_Comp(), this->_local_kin_react_sys->get_n_Comp()); _n_Comp_mob = std::max(this->_local_eq_react_sys->get_n_Comp_mob(), this->_local_kin_react_sys->get_n_Comp_mob()); } else if (this->_local_eq_react_sys->get_n_Eq_React() > 0) { _n_Comp = this->_local_eq_react_sys->get_n_Comp(); _n_Comp_mob = this->_local_eq_react_sys->get_n_Comp_mob(); } else if (this->_local_kin_react_sys->get_n_Kin_React() > 0) { _n_Comp = this->_local_kin_react_sys->get_n_Comp(); _n_Comp_mob = this->_local_kin_react_sys->get_n_Comp_mob(); } // set concentrations of all components as output for ( i=0; i < _n_Comp; i++ ) this->setOutputParameterName( i, femData->map_ChemComp[i]->second->get_name() ); // reactive transport problem with OPS _problem = new MyReactOPSProblemType( dis, _local_eq_react_sys ); _problem->setTimeSteppingFunction(*tim); // applying the same time stepping function for all linear problems // creating concentrations vector MyNodalFunctionScalar* tmp_conc; // first basis component for ( i=0; i < _n_Comp; i++ ) { if (femData->map_ChemComp[i]->second->getCompType() == ogsChem::BASIS_COMP) { MyVariableConc* comp = _problem->addVariable(femData->map_ChemComp[i]->second->get_name()); FemVariableBuilder var_builder; var_builder.doit(femData->map_ChemComp[i]->second->get_name(), option, msh, femData->geo, femData->geo_unique_name, _feObjects, comp); SolutionLib::FemIC* femIC = _problem->getVariable(i)->getIC(); tmp_conc = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); femIC->setup(*tmp_conc); } else { // FemIC vector is empty // initialize the vector with zeros tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); } _concentrations.push_back(tmp_conc); } } // then secondary mobile for (i = 0; i < _n_Comp; i++) { if (femData->map_ChemComp[i]->second->getCompType() == ogsChem::AQ_PHASE_COMP) { MyVariableConc* comp = _problem->addVariable(femData->map_ChemComp[i]->second->get_name()); FemVariableBuilder var_builder; var_builder.doit(femData->map_ChemComp[i]->second->get_name(), option, msh, femData->geo, femData->geo_unique_name, _feObjects, comp); SolutionLib::FemIC* femIC = _problem->getVariable(i)->getIC(); tmp_conc = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); femIC->setup(*tmp_conc); } else { // FemIC vector is empty // initialize the vector with zeros tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); } _concentrations.push_back(tmp_conc); } } // then secondary sorption for (i = 0; i < _n_Comp; i++) { if (femData->map_ChemComp[i]->second->getCompType() == ogsChem::SORPTION_COMP) { MyVariableConc* comp = _problem->addVariable(femData->map_ChemComp[i]->second->get_name()); FemVariableBuilder var_builder; var_builder.doit(femData->map_ChemComp[i]->second->get_name(), option, msh, femData->geo, femData->geo_unique_name, _feObjects, comp); SolutionLib::FemIC* femIC = _problem->getVariable(i)->getIC(); tmp_conc = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); femIC->setup(*tmp_conc); } else { // FemIC vector is empty // initialize the vector with zeros tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); } _concentrations.push_back(tmp_conc); } } // then secondary mineral for (i = 0; i < _n_Comp; i++) { if (femData->map_ChemComp[i]->second->getCompType() == ogsChem::MIN_PHASE_COMP) { MyVariableConc* comp = _problem->addVariable(femData->map_ChemComp[i]->second->get_name()); FemVariableBuilder var_builder; var_builder.doit(femData->map_ChemComp[i]->second->get_name(), option, msh, femData->geo, femData->geo_unique_name, _feObjects, comp); SolutionLib::FemIC* femIC = _problem->getVariable(i)->getIC(); tmp_conc = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); femIC->setup(*tmp_conc); } else { // FemIC vector is empty // initialize the vector with zeros tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); } _concentrations.push_back(tmp_conc); } } // then kinetic immob for (i = 0; i < _n_Comp; i++) { if (femData->map_ChemComp[i]->second->getCompType() == ogsChem::KIN_COMP) { MyVariableConc* comp = _problem->addVariable(femData->map_ChemComp[i]->second->get_name()); FemVariableBuilder var_builder; var_builder.doit(femData->map_ChemComp[i]->second->get_name(), option, msh, femData->geo, femData->geo_unique_name, _feObjects, comp); SolutionLib::FemIC* femIC = _problem->getVariable(i)->getIC(); tmp_conc = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); femIC->setup(*tmp_conc); } else { // FemIC vector is empty // initialize the vector with zeros tmp_conc->initialize(*dis, _problem->getVariable(i)->getCurrentOrder(), 1.0e-30); } _concentrations.push_back(tmp_conc); } } // adding variables into the linear problem // for the linear transport problem, variables are c_mobha for (i = 0; i < _n_Comp_mob; i++) { // set up problem MyLinearTransportProblemType* linear_problem = new MyLinearTransportProblemType(dis); // linear assemblers MyLinearAssemblerType* linear_assembler = new MyLinearAssemblerType(_feObjects); MyLinearResidualAssemblerType* linear_r_assembler = new MyLinearResidualAssemblerType(_feObjects); MyLinearJacobianAssemblerType* linear_j_eqs = new MyLinearJacobianAssemblerType(_feObjects); MyLinearEquationType* linear_eqs = linear_problem->createEquation(); linear_eqs->initialize(linear_assembler, linear_r_assembler, linear_j_eqs); linear_problem->setTimeSteppingFunction(*tim); // set up variables // in this case, the variables are concentrations of all mobile chemical components MyVariableConc* comp_conc = linear_problem->addVariable(femData->map_ChemComp[i]->second->get_name()); _linear_problems.push_back(linear_problem); } // set IC for linear transport components for (i = 0; i < _n_Comp_mob; i++) { SolutionLib::FemIC* linear_femIC = new SolutionLib::FemIC(msh); linear_femIC->addDistribution(femData->geo->getDomainObj(), new NumLib::TXFunctionDirect<double>(_concentrations[i]->getDiscreteData())); _linear_problems[i]->getVariable(0)->setIC(linear_femIC); } // set up linear solutions for (i = 0; i < _n_Comp_mob; i++) { MyLinearSolutionType* linear_solution = new MyLinearSolutionType(dis, this->_linear_problems[i]); MyLinearSolver* linear_solver = linear_solution->getLinearEquationSolver(); const BaseLib::Options* optNum = option.getSubGroup("Numerics"); linear_solver->setOption(*optNum); this->_linear_solutions.push_back(linear_solution); } // set up solution _solution = new MyReactOPSSolution(dis, _problem, this, _linear_problems, _linear_solutions); // run equilibrium reactions on each node that is not on boundary this->calc_nodal_react_sys(0.0); // set initial output parameter for (i = 0; i<_concentrations.size(); i++) { OutputVariableInfo var1(this->getOutputParameterName(i), _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _concentrations[i]); femData->outController.setOutput(var1.name, var1); } return true; }
int main (int argc, char *argv[]) { ifstream infile; infile.open("Proj3_op.txt"); if(!infile){ cerr << "Unable to open the file\n"; exit(1); } cout << "Before Everything!!!" << "\n"; IloEnv env; IloInt i,j,varCount1,varCount2,varCount3,conCount; //same as “int i;” IloInt k,w,K,W,E,l,P,N,L; IloInt tab, newline, val; //from file char line[2048]; try { N = 9; K = 3; L = 36; W = (IloInt)atoi(argv[1]); IloModel model(env); //set up a model object IloNumVarArray var1(env);// C - primary cout << "Here\n"; IloNumVarArray var2(env);// B - backup cout << "here1\n"; IloNumVarArray var3(env);// = IloNumVarArray(env,W); //declare an array of variable objects, for unknowns IloNumVar W_max(env, 0, W, ILOINT); //var1: c_ijk_w IloRangeArray con(env);// = IloRangeArray(env,N*N + 3*w); //declare an array of constraint objects IloNumArray2 t = IloNumArray2(env,N); //Traffic Demand IloNumArray2 e = IloNumArray2(env,N); //edge matrix //IloObjective obj; //Define the Xijk matrix cout << "Before init xijkl\n"; Xijkl xijkl_m(env, L); for(l=0;l<L;l++){ xijkl_m[l] = Xijk(env, N); for(i=0;i<N;i++){ xijkl_m[l][i] = Xjk(env, N); for(j=0;j<N;j++){ xijkl_m[l][i][j] = IloNumArray(env, K); } } } //reset everything to zero here for(l=0;l<L;l++) for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) xijkl_m[l][i][j][k] = 0; input_Xijkl(xijkl_m); cout<<"bahre\n"; for(i=0;i<N;i++){ t[i] = IloNumArray(env,N); for(j=0;j<N;j++){ if(i == j) t[i][j] = IloNum(0); else if(i != j) t[i][j] = IloNum((i+j+2)%5); } } printf("ikde\n"); //Minimize W_max IloObjective obj=IloMinimize(env); obj.setLinearCoef(W_max, 1.0); cout << "here khali\n"; //Setting var1[] for Demands Constraints for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++) var1.add(IloNumVar(env, 0, 1, ILOINT)); //c_ijk_w variables set. //Setting var2[] for Demands Constraints for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++) var2.add(IloNumVar(env, 0, 1, ILOINT)); //b_ijk_w variables set. for(w = 0;w < W;w++) var3.add(IloNumVar(env, 0, 1, ILOINT)); //Variables for u_w cout<<"variables ready\n"; conCount = 0; for(i=0;i<N;i++) for(j=0;j<N;j++){ con.add(IloRange(env, 2 * t[i][j], 2 * t[i][j])); //varCount1 = 0; for(k=0;k<K;k++) for(w=0;w<W;w++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],1.0); } conCount++; }//Adding Demands Constraints to con cout<<"1st\n"; IloInt z= 0; for(w=0;w<W;w++){ for(l=0;l<L;l++){ con.add(IloRange(env, -IloInfinity, 1)); for(i=0;i<N;i++){ for(j=0;j<N;j++){ for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]); con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]); } } } conCount++; } } cout<<"2nd\n"; //Adding Wavelength Constraints_1 to con P = N * (N-1) * K; for(w=0;w<W;w++){ con.add(IloRange(env, -IloInfinity, 0)); varCount1 = 0; for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); con[conCount].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w],1.0); } con[conCount].setLinearCoef(var3[w],-P); conCount++; } cout<<"3rd\n"; for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++){ con.add(IloRange(env, -IloInfinity, 1)); con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w], 1.0); con[conCount++].setLinearCoef(var2[i*N*W*K+j*W*K+k*W+w], 1.0); } varCount3 = 0; for(w=0;w<W;w++){ con.add(IloRange(env, 0, IloInfinity)); con[conCount].setLinearCoef(W_max, 1.0); con[conCount++].setLinearCoef(var3[w], -1.0 * (w+1)); } cout<<"after constraints\n"; //model.add(obj); //add objective function into model model.add(IloMinimize(env,obj)); model.add(con); //add constraints into model IloCplex cplex(model); //create a cplex object and extract the //model to this cplex object // Optimize the problem and obtain solution. if ( !cplex.solve() ) { env.error() << "Failed to optimize LP" << endl; throw(-1); } IloNumArray vals(env); //declare an array to store the outputs //if 2 dimensional: IloNumArray2 vals(env); env.out() << "Solution status = " << cplex.getStatus() << endl; //return the status: Feasible/Optimal/Infeasible/Unbounded/Error/… env.out() << "Solution value = " << cplex.getObjValue() << endl; //return the optimal value for objective function cplex.getValues(vals, var1); //get the variable outputs env.out() << "Values Var1 = " << vals << endl; //env.out() : output stream cplex.getValues(vals, var3); env.out() << "Values Val3 = " << vals << endl; } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught" << endl; } env.end(); //close the CPLEX environment return 0; } // END main
int main (int argc, char *argv[]) { ifstream infile; clock_t start_time, end_time; infile.open("Proj3_op.txt"); if(!infile){ cerr << "Unable to open the file\n"; exit(1); } cout << "Before Everything!!!" << "\n"; IloEnv env; IloInt i,j,varCount1,varCount2,varCount3,conCount; //same as “int i;” IloInt k,w,K,W,E,l,P,N,L; IloInt tab, newline, val; //from file char line[2048]; try { N = 9; K = 2; L = 36; W = (IloInt)atoi(argv[1]); IloModel model(env); //set up a model object IloNumVarArray var1(env);// = IloNumVarArray(env,K*W*N*N); IloNumVarArray var3(env);// = IloNumVarArray(env,W); //declare an array of variable objects, for unknowns IloNumVar W_max(env, 0, W, ILOINT); IloRangeArray con(env);// = IloRangeArray(env,N*N + 3*w); //declare an array of constraint objects IloNumArray2 t = IloNumArray2(env,N); //Traffic Demand IloNumArray2 e = IloNumArray2(env,N); //edge matrix //IloObjective obj; //Define the Xijk matrix Xijkl xijkl_m(env, L); for(l=0;l<L;l++){ xijkl_m[l] = Xijk(env, N); for(i=0;i<N;i++){ xijkl_m[l][i] = Xjk(env, N); for(j=0;j<N;j++){ xijkl_m[l][i][j] = IloNumArray(env, K); } } } //reset everything to zero here for(l=0;l<L;l++) for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) xijkl_m[l][i][j][k] = 0; input_Xijkl(xijkl_m); cout<<"bahre\n"; FILE *file; file = fopen(argv[2],"r"); int tj[10]; for(i=0;i<N;i++){ t[i] = IloNumArray(env,N); fscanf(file,"%d %d %d %d %d %d %d %d %d \n",&tj[0],&tj[1],&tj[2],&tj[3],&tj[4],&tj[5],&tj[6],&tj[7],&tj[8]); for(j=0;j<N;j++){ t[i][j] = IloNum(tj[j]); } } printf("ikde\n"); //Minimize W_max IloObjective obj=IloMinimize(env); obj.setLinearCoef(W_max, 1.0); cout << "here khali\n"; //Setting var1[] for Demands Constraints for(i=0;i<N;i++) for(j=0;j<N;j++) for(k=0;k<K;k++) for(w=0;w<W;w++) var1.add(IloNumVar(env, 0, 1, ILOINT)); for(w = 0;w < W;w++) var3.add(IloNumVar(env, 0, 1, ILOINT)); //Variables for u_w cout<<"variables ready\n"; conCount = 0; for(i=0;i<N;i++) for(j=0;j<N;j++){ con.add(IloRange(env, t[i][j], t[i][j])); //varCount1 = 0; for(k=0;k<K;k++) for(w=0;w<W;w++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); //cout << "Before Adding Constraint\n"; //con[1].setLinearCoef(IloNumVar(env, 0, 1, ILOINT), 1.0); //cout<<"coef set "<<varCount1; } conCount++; }//Adding Demands Constraints to con cout<<"1st\n"; IloInt z= 0; for(w=0;w<W;w++){ for(l=0;l<L;l++){ con.add(IloRange(env, -IloInfinity, 1)); for(i=0;i<N;i++){ for(j=0;j<N;j++){ for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],xijkl_m[l][i][j][k]); } } } conCount++; } } cout<<"2nd\n"; //Adding Wavelength Constraints_1 to con P = N * (N-1) * K; for(w=0;w<W;w++){ con.add(IloRange(env, -IloInfinity, 0)); varCount1 = 0; for(i=0;i<9;i++) for(j=0;j<9;j++) for(k=0;k<K;k++){ con[conCount].setLinearCoef(var1[i*N*W*K+j*W*K+k*W+w],1.0); } con[conCount].setLinearCoef(var3[w],-P); conCount++; } cout<<"3rd\n"; varCount3 = 0; for(w=0;w<W;w++){ con.add(IloRange(env, 0, IloInfinity)); con[conCount].setLinearCoef(W_max, 1.0); con[conCount++].setLinearCoef(var3[w], -1.0 * (w+1)); } cout<<"after constraints\n"; //model.add(obj); //add objective function into model model.add(IloMinimize(env,obj)); model.add(con); //add constraints into model IloCplex cplex(model); //create a cplex object and extract the //model to this cplex object // Optimize the problem and obtain solution. start_time = clock(); if ( !cplex.solve() ) { env.error() << "Failed to optimize LP" << endl; throw(-1); } end_time = clock(); IloNumArray vals(env); //declare an array to store the outputs IloNumVarArray opvars(env); //if 2 dimensional: IloNumArray2 vals(env); //env.out() << "Solution status = " << cplex.getStatus() << endl; //return the status: Feasible/Optimal/Infeasible/Unbounded/Error/… env.out() << "W_max value = " << cplex.getObjValue() << endl; //return the optimal value for objective function cplex.getValues(vals, var1); //get the variable outputs //env.out() << "Values Var1 = " << vals << endl; //env.out() : output stream cplex.getValues(vals, var3); //env.out() << "Values Val3 = " << vals << endl; } catch (IloException& e) { cerr << "Concert exception caught: " << e << endl; } catch (...) { cerr << "Unknown exception caught" << endl; } env.end(); //close the CPLEX environment float running_time (((float)end_time - (float)start_time)/CLOCKS_PER_SEC); cout << "*******RUNNING TIME: " << running_time << endl; return 0; } // END main
bool FunctionCMP_2P2C<T1, T2>::initialize(const BaseLib::Options &option) { Ogs6FemData* femData = Ogs6FemData::getInstance(); _msh_id = option.getOptionAsNum<size_t>("MeshID"); size_t time_id = option.getOptionAsNum<size_t>("TimeGroupID"); NumLib::ITimeStepFunction* tim = femData->list_tim[time_id]; //mesh and FE objects MeshLib::IMesh* msh = femData->list_mesh[_msh_id]; // get the number of elements size_t n_ele = msh->getNumberOfElements(); MyDiscreteSystem* dis = 0; dis = DiscreteLib::DiscreteSystemContainerPerMesh::getInstance()->createObject<MyDiscreteSystem>(msh); _feObjects = new FemLib::LagrangeFeObjectContainer(msh); // set names of the output parameters this->setOutputParameterName(0, "MEAN_PRESSURE"); this->setOutputParameterName(1, "MOLAR_FRACTION"); // also secondary variables // TODO: set seconary variable names also as output parameters // create the MyCompMultiPhase problem _problem = new MyCompMultiPhaseProblemType(dis); _problem->setTimeSteppingFunction(*tim); // applying the time stepping function // creating mean pressure vector MyVariableCompMultiPhase* mean_pressure = _problem->addVariable("MEAN_PRESSURE"); FemVariableBuilder var_builder; var_builder.doit("MEAN_PRESSURE", option, msh, femData->geo, femData->geo_unique_name, _feObjects, mean_pressure); SolutionLib::FemIC* femIC = _problem->getVariable(0)->getIC(); _P = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty _P->initialize(*dis, _problem->getVariable(0)->getCurrentOrder(), 0.0); femIC->setup(*_P); } else { // FemIC vector is empty // initialize the vector with zeros _P->initialize(*dis, _problem->getVariable(0)->getCurrentOrder(), 0.0); } // creating molar fraction MyVariableCompMultiPhase* molar_fraction = _problem->addVariable("MOLAR_FRACTION"); var_builder.doit("MOLAR_FRACTION", option, msh, femData->geo, femData->geo_unique_name, _feObjects, molar_fraction); femIC = _problem->getVariable(1)->getIC(); _X = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty _X->initialize(*dis, _problem->getVariable(1)->getCurrentOrder(), 0.0); femIC->setup(*_X); } else { // FemIC vector is empty // initialize the vector with zeros _X->initialize(*dis, _problem->getVariable(1)->getCurrentOrder(), 0.0); } // initialize the local EOS problem _LP_EOS = new LocalProblem_EOS(); //ogsChem::LocalVector _output1; //_output1 = ogsChem::LocalVector::Zero(_LP_EOS->N); _PC = new MyNodalFunctionScalar(); _PC->initialize(*dis, FemLib::PolynomialOrder::Linear, 0.0); //_PC->setValue(0, 0.0); //PC_ini _PL = new MyNodalFunctionScalar(); _PL->initialize(*dis, FemLib::PolynomialOrder::Linear, 100.0);//PL_ini _PG = new MyNodalFunctionScalar(); _PG->initialize(*dis, FemLib::PolynomialOrder::Linear, 100.0); _X_m = new MyNodalFunctionScalar(); _X_m->initialize(*dis, FemLib::PolynomialOrder::Linear, 0.0); _X_M = new MyNodalFunctionScalar(); _X_M->initialize(*dis, FemLib::PolynomialOrder::Linear,0.0); _NG = new MyNodalFunctionScalar(); _NG->initialize(*dis, FemLib::PolynomialOrder::Linear, 0.0); _NL = new MyNodalFunctionScalar(); _NL->initialize(*dis, FemLib::PolynomialOrder::Linear, 0.0); _S = new MyNodalFunctionScalar(); _S->initialize(*dis, FemLib::PolynomialOrder::Linear, 0.0); _mat_secDer = new MyNodalFunctionMatrix(); MathLib::LocalMatrix tmp_mat = MathLib::LocalMatrix::Zero(8, 2); _mat_secDer->initialize(*dis, FemLib::PolynomialOrder::Linear, tmp_mat); //initialize the local M matrix and K matrix for (size_t index = 0; index < n_ele; index++) { MathLib::LocalMatrix test1 = MathLib::LocalMatrix::Zero(6, 6); _elem_M_matrix.push_back(test1); MathLib::LocalMatrix test2 = MathLib::LocalMatrix::Zero(6, 6); _elem_K_matrix.push_back(test2); } // linear assemblers MyNonLinearAssemblerType* nonlin_assembler = new MyNonLinearAssemblerType(_feObjects, this); MyNonLinearResidualAssemblerType* non_linear_r_assembler = new MyNonLinearResidualAssemblerType(_feObjects, this); MyNonLinearJacobianAssemblerType* non_linear_j_assembler = new MyNonLinearJacobianAssemblerType(_feObjects, this); // define nonlinear problem _non_linear_problem = new MyNonLinearCompMultiPhaseProblemType(dis); _non_linear_eqs = _non_linear_problem->createEquation(); _non_linear_eqs->initialize(nonlin_assembler, non_linear_r_assembler, non_linear_j_assembler); _non_linear_problem->setTimeSteppingFunction(*tim); _non_linear_problem->addVariable("MEAN_PRESSURE"); _non_linear_problem->addVariable("MOLAR_FRACTION"); SolutionLib::FemIC* P_ic = new SolutionLib::FemIC(msh); P_ic->addDistribution(femData->geo->getDomainObj(), new NumLib::TXFunctionDirect<double>(_P->getDiscreteData())); var_builder.doit("MEAN_PRESSURE", option, msh, femData->geo, femData->geo_unique_name, _feObjects, _non_linear_problem->getVariable(0)); _non_linear_problem->getVariable(0)->setIC(P_ic); SolutionLib::FemIC* X_ic = new SolutionLib::FemIC(msh); X_ic->addDistribution(femData->geo->getDomainObj(), new NumLib::TXFunctionDirect<double>(_X->getDiscreteData())); var_builder.doit("MOLAR_FRACTION", option, msh, femData->geo, femData->geo_unique_name, _feObjects, _non_linear_problem->getVariable(1)); _non_linear_problem->getVariable(1)->setIC(X_ic); // set up non-linear solution myNRIterator = new MyNRIterationStepInitializer(non_linear_r_assembler, non_linear_j_assembler); myNSolverFactory = new MyDiscreteNonlinearSolverFactory(myNRIterator); this->_non_linear_solution = new MyNonLinearSolutionType(dis, this->_non_linear_problem, myNSolverFactory); this->_non_linear_solution->getDofEquationIdTable()->setNumberingType(DiscreteLib::DofNumberingType::BY_POINT); // global order this->_non_linear_solution->getDofEquationIdTable()->setLocalNumberingType(DiscreteLib::DofNumberingType::BY_VARIABLE); // local order const BaseLib::Options* optNum = option.getSubGroup("Numerics"); // linear solver MyLinearSolver* linear_solver = this->_non_linear_solution->getLinearEquationSolver(); linear_solver->setOption(*optNum); // set nonlinear solver options this->_non_linear_solution->getNonlinearSolver()->setOption(*optNum); // set theta if (!optNum->hasOption("TimeTheta")) { ERR("Time theta setting not found!!!"); exit(1); } else { double tmp_theta(optNum->getOptionAsNum<double>("TimeTheta")); non_linear_j_assembler->setTheta(tmp_theta); non_linear_r_assembler->setTheta(tmp_theta); _non_linear_eqs->getLinearAssembler()->setTheta(tmp_theta); } // get the nonlinear solution dof manager this->_nl_sol_dofManager = this->_non_linear_solution->getDofEquationIdTable(); // set up solution _solution = new MyCompMultiPhaseSolution(dis, _problem, _non_linear_solution, this); /** *Calculate the secondary variables on each node */ this->calc_nodal_eos_sys(0.0); // set initial output parameter OutputVariableInfo var1(this->getOutputParameterName(0), _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _P); femData->outController.setOutput(var1.name, var1); OutputVariableInfo var2(this->getOutputParameterName(1), _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _X); femData->outController.setOutput(var2.name, var2); return true; }
TEST_F(UnifiedVarRenamerTests, WhenUseDebugNamesIsFalseDoNotUseDebugNames) { // Set-up the module. // // int g; // from debug info // int h; // // void test(int p, int m) { // p has name from debug info // int a; // int b; // from debug info // } // ShPtr<Variable> varG(Variable::create("g", IntType::create(32))); module->addGlobalVar(varG); module->addDebugNameForVar(varG, varG->getName()); ShPtr<Variable> varH(Variable::create("h", IntType::create(32))); module->addGlobalVar(varH); ShPtr<Variable> varP(Variable::create("p", IntType::create(32))); testFunc->addParam(varP); module->addDebugNameForVar(varP, varP->getName()); ShPtr<Variable> varM(Variable::create("m", IntType::create(32))); testFunc->addParam(varM); ShPtr<Variable> varA(Variable::create("a", IntType::create(32))); testFunc->addLocalVar(varA); ShPtr<Variable> varB(Variable::create("b", IntType::create(32))); testFunc->addLocalVar(varB); module->addDebugNameForVar(varB, varB->getName()); ShPtr<VarDefStmt> varDefB(VarDefStmt::create(varB)); ShPtr<VarDefStmt> varDefA(VarDefStmt::create(varA, ShPtr<Expression>(), varDefB)); testFunc->setBody(varDefA); // Setup the renamer (do not use debug names). INSTANTIATE_VAR_NAME_GEN_AND_VAR_RENAMER(UnifiedVarRenamer, false); // Do the renaming. varRenamer->renameVars(module); // We expect the following output: // // int g1; // int g2; // // void test(int a1, int a2) { // int v1; // int v2; // } // // Globals: VarSet globalVarsSet(module->getGlobalVars()); ASSERT_EQ(2, globalVarsSet.size()); // We have to sort the variables to ease the checking. VarVector globalVarsVector(globalVarsSet.begin(), globalVarsSet.end()); sortByName(globalVarsVector); ShPtr<Variable> var1(globalVarsVector[0]); EXPECT_EQ("g1", var1->getName()); ShPtr<Variable> var2(globalVarsVector[1]); EXPECT_EQ("g2", var2->getName()); // Parameters: VarVector params(testFunc->getParams()); ASSERT_EQ(2, params.size()); ShPtr<Variable> par1(params.front()); EXPECT_EQ("a1", par1->getName()); ShPtr<Variable> par2(params.back()); EXPECT_EQ("a2", par2->getName()); // Locals: EXPECT_EQ("v1", varDefA->getVar()->getName()); EXPECT_EQ("v2", varDefB->getVar()->getName()); }
bool FunctionCMP_NonIsoTotalMassEXPForm<T1, T2>::initialize(const BaseLib::Options &option) { Ogs6FemData* femData = Ogs6FemData::getInstance(); _msh_id = option.getOptionAsNum<size_t>("MeshID"); size_t time_id = option.getOptionAsNum<int>("TimeGroupID"); NumLib::ITimeStepFunction* tim = femData->list_tim[time_id]; //mesh and FE objects MeshLib::IMesh* msh = femData->list_mesh[_msh_id]; // get the number of elements size_t n_ele = msh->getNumberOfElements(); size_t n_nodes = msh->getNumberOfNodes(); MyDiscreteSystem* dis = 0; dis = DiscreteLib::DiscreteSystemContainerPerMesh::getInstance()->createObject<MyDiscreteSystem>(msh); _feObjects = new FemLib::LagrangeFeObjectContainer(msh); // set names of the output parameters this->setOutputParameterName(0, "MEAN_PRESSURE"); this->setOutputParameterName(1, "TOTAL_MASS_DENSITY"); this->setOutputParameterName(2, "TEMPERATURE"); this->setOutputParameterName(3, "Saturation"); this->setOutputParameterName(4, "Liquid_Pressure"); this->setOutputParameterName(5, "Gas_Pressure"); this->setOutputParameterName(6, "Capillary_Pressure"); this->setOutputParameterName(7, "Mass_Density_L_H"); this->setOutputParameterName(8, "Mass_Density_G_H"); this->setOutputParameterName(9, "Mass_Density_G_W"); // also secondary variables // TODO: set seconary variable names also as output parameters // create the MyCMPPressureForm problem _problem = new MyCMPNonIsoTotalMassEXPFormProblemType(dis); _problem->setTimeSteppingFunction(*tim); // applying the time stepping function // creating mean pressure vector MyVariableCMPNonIsoTotalMassEXPForm* mean_pressure = _problem->addVariable("MEAN_PRESSURE"); FemVariableBuilder var_builder; var_builder.doit("MEAN_PRESSURE", option, msh, femData->geo, femData->geo_unique_name, _feObjects, mean_pressure); SolutionLib::FemIC* femIC = _problem->getVariable(0)->getIC(); _P = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty _P->initialize(*dis, _problem->getVariable(0)->getCurrentOrder(), 0.0); femIC->setup(*_P); } else { // FemIC vector is empty // initialize the vector with zeros _P->initialize(*dis, _problem->getVariable(0)->getCurrentOrder(), 0.0); } // creating molar fraction MyVariableCMPNonIsoTotalMassEXPForm* total_mass_density = _problem->addVariable("TOTAL_MASS_DENSITY"); var_builder.doit("TOTAL_MASS_DENSITY", option, msh, femData->geo, femData->geo_unique_name, _feObjects, total_mass_density); femIC = _problem->getVariable(1)->getIC(); _X = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty _X->initialize(*dis, _problem->getVariable(1)->getCurrentOrder(), 0.0); femIC->setup(*_X); } else { // FemIC vector is empty // initialize the vector with zeros _X->initialize(*dis, _problem->getVariable(1)->getCurrentOrder(), 0.0); } MyVariableCMPNonIsoTotalMassEXPForm* temperature = _problem->addVariable("TEMPERATURE"); var_builder.doit("TEMPERATURE", option, msh, femData->geo, femData->geo_unique_name, _feObjects, temperature); femIC = _problem->getVariable(2)->getIC(); _T = new MyNodalFunctionScalar(); if (femIC) { // FemIC vector is not empty _T->initialize(*dis, _problem->getVariable(2)->getCurrentOrder(), 0.0); femIC->setup(*_T); } else { // FemIC vector is empty // initialize the vector with zeros _T->initialize(*dis, _problem->getVariable(2)->getCurrentOrder(), 0.0); } // initialize the local EOS problem //_LP_EOS = new LocalProblem_EOS_TotalMassEXPForm(); //ogsChem::LocalVector _output1; //_output1 = ogsChem::LocalVector::Zero(_LP_EOS->N); _S = new MyIntegrationPointFunctionVector(); _S->initialize(dis); _PL = new MyIntegrationPointFunctionVector(); _PL->initialize(dis); _PG = new MyIntegrationPointFunctionVector(); _PG->initialize(dis); _PC = new MyIntegrationPointFunctionVector(); _PC->initialize(dis); _rho_L_h = new MyIntegrationPointFunctionVector(); _rho_L_h->initialize(dis); _rho_G_h = new MyIntegrationPointFunctionVector(); _rho_G_h->initialize(dis); _rho_G_w = new MyIntegrationPointFunctionVector(); _rho_G_w->initialize(dis); MathLib::LocalVector tmp = MathLib::LocalVector::Zero(1); for (size_t ele_id = 0; ele_id < n_ele; ele_id++) { MeshLib::IElement *e = msh->getElement(ele_id); const std::size_t node_ele = e->getNumberOfNodes();// _S->setNumberOfIntegationPoints(ele_id, node_ele); _PL->setNumberOfIntegationPoints(ele_id, node_ele); _PC->setNumberOfIntegationPoints(ele_id, node_ele); _rho_G_h->setNumberOfIntegationPoints(ele_id, node_ele); _rho_G_w->setNumberOfIntegationPoints(ele_id, node_ele); for (size_t jj = 0; jj < node_ele; jj++) { _S->setIntegrationPointValue(ele_id, jj, tmp); _PL->setIntegrationPointValue(ele_id, jj, tmp); _PC->setIntegrationPointValue(ele_id, jj, tmp); _rho_G_h->setIntegrationPointValue(ele_id, jj, tmp); _rho_G_w->setIntegrationPointValue(ele_id, jj, tmp); } } _mat_secDer = new MyNodalFunctionMatrix();// define a matrix to store all the derivatives of the secondary variables MathLib::LocalMatrix tmp_mat = MathLib::LocalMatrix::Zero(3, 2); //the size I will modify later _mat_secDer->initialize(*dis, FemLib::PolynomialOrder::Linear, tmp_mat); /** * initialize the vector of tempVar */ _vec_tempVar = new MyNodalFunctionVector(); MathLib::LocalVector tmp_vec = MathLib::LocalVector::Zero(2); _vec_tempVar->initialize(*dis, FemLib::PolynomialOrder::Linear, tmp_vec); //initialize the local M matrix and K matrix for (size_t index = 0; index < n_ele; index++) { MathLib::LocalMatrix test1 = MathLib::LocalMatrix::Zero(6, 6); _elem_M_matrix.push_back(test1); MathLib::LocalMatrix test2 = MathLib::LocalMatrix::Zero(6, 6); _elem_K_matrix.push_back(test2); } // linear assemblers MyNonLinearAssemblerType* nonlin_assembler = new MyNonLinearAssemblerType(_feObjects, this, msh->getGeometricProperty()->getCoordinateSystem()); MyNonLinearResidualAssemblerType* non_linear_r_assembler = new MyNonLinearResidualAssemblerType(_feObjects, this, msh->getGeometricProperty()->getCoordinateSystem()); MyNonLinearJacobianAssemblerType* non_linear_j_assembler = new MyNonLinearJacobianAssemblerType(_feObjects, this, msh->getGeometricProperty()->getCoordinateSystem()); // define nonlinear problem _non_linear_problem = new MyNonLinearCMPNonIsoTotalMassEXPFormProblemType(dis); _non_linear_eqs = _non_linear_problem->createEquation(); _non_linear_eqs->initialize(nonlin_assembler, non_linear_r_assembler, non_linear_j_assembler); _non_linear_problem->setTimeSteppingFunction(*tim); _non_linear_problem->addVariable("MEAN_PRESSURE"); _non_linear_problem->addVariable("TOTAL_MASS_DENSITY"); _non_linear_problem->addVariable("TEMPERATURE"); SolutionLib::FemIC* P_ic = new SolutionLib::FemIC(msh); P_ic->addDistribution(femData->geo->getDomainObj(), new NumLib::TXFunctionDirect<double>(_P->getDiscreteData())); var_builder.doit("MEAN_PRESSURE", option, msh, femData->geo, femData->geo_unique_name, _feObjects, _non_linear_problem->getVariable(0)); _non_linear_problem->getVariable(0)->setIC(P_ic); SolutionLib::FemIC* X_ic = new SolutionLib::FemIC(msh); X_ic->addDistribution(femData->geo->getDomainObj(), new NumLib::TXFunctionDirect<double>(_X->getDiscreteData())); var_builder.doit("TOTAL_MASS_DENSITY", option, msh, femData->geo, femData->geo_unique_name, _feObjects, _non_linear_problem->getVariable(1)); _non_linear_problem->getVariable(1)->setIC(X_ic); SolutionLib::FemIC* T_ic = new SolutionLib::FemIC(msh); T_ic->addDistribution(femData->geo->getDomainObj(), new NumLib::TXFunctionDirect<double>(_T->getDiscreteData())); var_builder.doit("TEMPERATURE", option, msh, femData->geo, femData->geo_unique_name, _feObjects, _non_linear_problem->getVariable(2)); _non_linear_problem->getVariable(2)->setIC(T_ic); // set up non-linear solution myNRIterator = new MyNRIterationStepInitializer(non_linear_r_assembler, non_linear_j_assembler); myNSolverFactory = new MyDiscreteNonlinearSolverFactory(myNRIterator); this->_non_linear_solution = new MyNonLinearSolutionType(dis, this->_non_linear_problem, myNSolverFactory); this->_non_linear_solution->getDofEquationIdTable()->setNumberingType(DiscreteLib::DofNumberingType::BY_POINT); // global order this->_non_linear_solution->getDofEquationIdTable()->setLocalNumberingType(DiscreteLib::DofNumberingType::BY_VARIABLE); // local order const BaseLib::Options* optNum = option.getSubGroup("Numerics"); // linear solver MyLinearSolver* linear_solver = this->_non_linear_solution->getLinearEquationSolver(); linear_solver->setOption(*optNum); // set nonlinear solver options this->_non_linear_solution->getNonlinearSolver()->setOption(*optNum); // set theta if (!optNum->hasOption("TimeTheta")) { ERR("Time theta setting not found!!!"); exit(1); } else { double tmp_theta(optNum->getOptionAsNum<double>("TimeTheta")); non_linear_j_assembler->setTheta(tmp_theta); non_linear_r_assembler->setTheta(tmp_theta); _non_linear_eqs->getLinearAssembler()->setTheta(tmp_theta); } // get the nonlinear solution dof manager this->_nl_sol_dofManager = this->_non_linear_solution->getDofEquationIdTable(); // set up solution _solution = new MyCMPNonIsoTotalMassEXPFormSolution(dis, _problem, _non_linear_solution, this); /** *Calculate the secondary variables on each node */ this->calc_nodal_eos_sys(0.0); // set initial output parameter OutputVariableInfo var1(this->getOutputParameterName(0), _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _P); femData->outController.setOutput(var1.name, var1); OutputVariableInfo var2(this->getOutputParameterName(1), _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _X); femData->outController.setOutput(var2.name, var2); OutputVariableInfo var3(this->getOutputParameterName(2), _msh_id, OutputVariableInfo::Node, OutputVariableInfo::Real, 1, _T); femData->outController.setOutput(var3.name, var3); // OutputVariableInfo var_Sec_1(this->getOutputParameterName(3), _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _S); femData->outController.setOutput(var_Sec_1.name, var_Sec_1); OutputVariableInfo var_Sec_2(this->getOutputParameterName(4), _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _PL); femData->outController.setOutput(var_Sec_2.name, var_Sec_2); OutputVariableInfo var_Sec_3(this->getOutputParameterName(5), _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _PG); femData->outController.setOutput(var_Sec_3.name, var_Sec_3); OutputVariableInfo var_Sec_4(this->getOutputParameterName(6), _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _PC); femData->outController.setOutput(var_Sec_4.name, var_Sec_4); OutputVariableInfo var_Sec_5(this->getOutputParameterName(7), _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _rho_L_h); femData->outController.setOutput(var_Sec_5.name, var_Sec_5); OutputVariableInfo var_Sec_6(this->getOutputParameterName(8), _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _rho_G_h); femData->outController.setOutput(var_Sec_6.name, var_Sec_6); OutputVariableInfo var_Sec_7(this->getOutputParameterName(9), _msh_id, OutputVariableInfo::Element, OutputVariableInfo::Real, 1, _rho_G_w); femData->outController.setOutput(var_Sec_7.name, var_Sec_7); return true; }
void test_recursive_variant() { typedef boost::make_recursive_variant< int , std::vector<boost::recursive_variant_> >::type var1_t; std::vector<var1_t> vec1; vec1.push_back(3); vec1.push_back(5); vec1.push_back(vec1); vec1.push_back(7); var1_t var1(vec1); std::string result1( boost::apply_visitor( vector_printer(), var1 ) ); std::cout << "result1: " << result1 << '\n'; BOOST_CHECK(result1 == "( 3 5 ( 3 5 ) 7 ) "); typedef boost::make_recursive_variant< boost::variant<int, double> , std::vector<boost::recursive_variant_> >::type var2_t; std::vector<var2_t> vec2; vec2.push_back(boost::variant<int, double>(3)); vec2.push_back(boost::variant<int, double>(3.5)); vec2.push_back(vec2); vec2.push_back(boost::variant<int, double>(7)); var2_t var2(vec2); std::string result2( boost::apply_visitor( vector_printer(), var2 ) ); std::cout << "result2: " << result2 << '\n'; BOOST_CHECK(result2 == "( 3 3.5 ( 3 3.5 ) 7 ) "); typedef boost::make_recursive_variant< int , std::vector< boost::variant< double , std::vector<boost::recursive_variant_> > > >::type var3_t; typedef boost::variant<double, std::vector<var3_t> > var4_t; std::vector<var3_t> vec3; vec3.push_back(3); vec3.push_back(5); std::vector<var4_t> vec4; vec4.push_back(3.5); vec4.push_back(vec3); vec3.push_back(vec4); vec3.push_back(7); var4_t var4(vec3); std::string result3( boost::apply_visitor( vector_printer(), var4 ) ); std::cout << "result2: " << result3 << '\n'; BOOST_CHECK(result3 == "( 3 5 ( 3.5 ( 3 5 ) ) 7 ) "); typedef boost::make_recursive_variant< double, std::vector<var1_t> >::type var5_t; std::vector<var5_t> vec5; vec5.push_back(3.5); vec5.push_back(vec1); vec5.push_back(17.25); std::string result5( vector_printer()(vec5) ); std::cout << "result5: " << result5 << '\n'; BOOST_CHECK(result5 == "( 3.5 ( 3 5 ( 3 5 ) 7 ) 17.25 ) "); typedef boost::make_recursive_variant< int, std::map<int, boost::recursive_variant_> >::type var6_t; var6_t var6; }