bool FunctionTests::testAdaptiveIntegrate() { bool success = true; // we must create our own basisCache here because _basisCache // has had its ref cell points set, which basically means it's // opted out of having any help with integration. BasisCachePtr basisCache = Teuchos::rcp( new BasisCache( _elemType, _spectralConfusionMesh ) ); vector<GlobalIndexType> cellIDs; cellIDs.push_back(0); basisCache->setPhysicalCellNodes( _spectralConfusionMesh->physicalCellNodesForCell(0), cellIDs, true ); double eps = .1; // FunctionPtr boundaryLayerFunction = Teuchos::rcp( new BoundaryLayerFunction(eps) ); int numCells = basisCache->cellIDs().size(); FieldContainer<double> integrals(numCells); double quadtol = 1e-2; double computedIntegral = boundaryLayerFunction->integrate(_spectralConfusionMesh,quadtol); double trueIntegral = (eps*(exp(1/eps) - exp(-1/eps)))*2.0; double diff = trueIntegral-computedIntegral; double relativeError = abs(diff)/abs(trueIntegral); // relative error double tol = 1e-2; if (relativeError > tol) { success = false; cout << "failing testAdaptiveIntegrate() with computed integral " << computedIntegral << " and true integral " << trueIntegral << endl; } return success; }
void PerspCutGenerator::generateCut() { const double * x = s_->getPrimal(); UInt binindex; binindex = bp_->getIndex(); FunctionPtr f = cp_->getFunction(); UInt indexvar = 0; ConstVariablePtr cvp; double sb = x[binindex]; double vsol = 0.0; // Generate solution y=(x/z,1), x are continuous and z is binary variable double * y = new double[rnv_]; std::fill(y, y + rnv_, 0); for (VarSetConstIterator it=f->varsBegin(); it!=f->varsEnd(); ++it) { cvp = *it; indexvar = cvp->getIndex(); //std::cout << cvp->getName() << " " << x[indexvar] << std::endl; if (indexvar != binindex) { vsol = x[indexvar]; y[indexvar] = vsol/sb; //std::cout << "corresponding y " << y[indexvar] << std::endl; } } y[binindex] = 1; gPCut(f,y); delete [] y; return; }
bool ScratchPadTests::testConstantFunctionProduct() { bool success = true; // set up basisCache (even though it won't really be used here) BasisCachePtr basisCache = Teuchos::rcp( new BasisCache( _elemType, _spectralConfusionMesh ) ); vector<GlobalIndexType> cellIDs; int cellID = 0; cellIDs.push_back(cellID); basisCache->setPhysicalCellNodes( _spectralConfusionMesh->physicalCellNodesForCell(cellID), cellIDs, true ); int numCells = _basisCache->getPhysicalCubaturePoints().dimension(0); int numPoints = _testPoints.dimension(0); FunctionPtr three = Function::constant(3.0); FunctionPtr two = Function::constant(2.0); FieldContainer<double> values(numCells,numPoints); two->values(values,basisCache); three->scalarMultiplyBasisValues( values, basisCache ); FieldContainer<double> expectedValues(numCells,numPoints); expectedValues.initialize( 3.0 * 2.0 ); double tol = 1e-15; double maxDiff = 0.0; if ( ! fcsAgree(expectedValues, values, tol, maxDiff) ) { success = false; cout << "Expected product differs from actual; maxDiff: " << maxDiff << endl; } return success; }
void CompilerCore::register_function (VertexPtr root, DataStream &os) { if (root.is_null()) { return; } FunctionPtr function; if (root->type() == op_function || root->type() == op_func_decl) { function = create_function (root); } else if (root->type() == op_extern_func) { register_function_header (root, os); return; } else { kphp_fail(); } FunctionSetPtr function_set = get_function_set (fs_function, function->name, true); bool force_flag = function->type() == FunctionData::func_global; if (add_to_function_set ( function_set, function, force_flag)) { function->is_required = true; if (force_flag) { function->req_id = stage::get_file()->req_id; } else { function->req_id = function_set->req_id; } os << function; } };
bool FunctionTests::testIntegrate() { bool success = true; FunctionPtr x = Function::xn(1); double value = x->integrate(_spectralConfusionMesh); double expectedValue = 0.0; // odd function in x on (-1,1)^2 double tol = 1e-11; if (abs(value-expectedValue)>tol) { success = false; cout << "failed testIntegrate() on function x" << endl; } // now, let's try for the integral of the dot product of vector-valued functions FunctionPtr y = Function::yn(1); FunctionPtr f1 = 1 * Function::vectorize(x, y); // 1 * to trigger creation of a ProductFunction value = (f1 * f1)->integrate(_spectralConfusionMesh,1); // enrich cubature to handle quadratics expectedValue = 8.0 / 3.0; // integral of x^2 + y^2 on (-1,1)^2 if (abs(value-expectedValue)>tol) { success = false; cout << "failing testIntegrate() on function (x,y) dot (x,y)" << endl; } return success; }
/*static*/ Dictionary UDFUtils::Serialize(const FunctionPtr& f) { Dictionary dict = SerializeCommonFunctionAttributes(*f, s_serializationVersion, s_userDefinedFunctionTypeValue); bool native = f->IsNative(); dict[nativeUDFKey] = native; dict[userDefinedStateKey] = (native) ? f->SerializeNativeImpl() : f->Serialize(); return dict; }
double integralOverMesh(LinearTermPtr testTerm, VarPtr testVar, FunctionPtr fxnToSubstitute) { map<int, FunctionPtr > varAsFunction; varAsFunction[testVar->ID()] = fxnToSubstitute; FunctionPtr substituteOnBoundary = testTerm->evaluate(varAsFunction, true); FunctionPtr substituteOnInterior = testTerm->evaluate(varAsFunction, false); double integral = substituteOnBoundary->integrate(mesh); integral += substituteOnInterior->integrate(mesh); return integral; }
bool basisSumEqualsFunction(FieldContainer<double> &basisCoefficients, BasisPtr basis, FunctionPtr f) { // tests on [0,1] FunctionPtr sumFunction = Teuchos::rcp( new BasisSumFunction(basis, basisCoefficients) ); int cubatureDegree = basis->getDegree() * 2; BasisCachePtr basisCache = BasisCache::basisCache1D(0, 1, cubatureDegree); double tol = 1e-13; return sumFunction->equals(f, basisCache, tol); }
/// <summary> /// The example shows /// - how to load a pretrained model and evaluate several nodes by combining their outputs /// Note: The example uses the model trained by <CNTK>/Examples/Image/Classification/ResNet/Python/TrainResNet_CIFAR10.py /// Please see README.md in <CNTK>/Examples/Image/Classification/ResNet about how to train the model. /// The parameter 'modelFilePath' specifies the path to the model. /// </summary> void EvaluateCombinedOutputs(const wchar_t* modelFilePath, const DeviceDescriptor& device) { printf("\n===== Evaluate combined outputs =====\n"); // Load the model. FunctionPtr modelFunc = Function::Load(modelFilePath, device); // Get node of interest std::wstring intermediateLayerName = L"final_avg_pooling"; FunctionPtr interLayerPrimitiveFunc = modelFunc->FindByName(intermediateLayerName); Variable poolingOutput = interLayerPrimitiveFunc->Output(); // Create a function which combine outputs from the node "final_avg_polling" and the final layer of the model. FunctionPtr evalFunc = Combine( { modelFunc->Output(), poolingOutput }); Variable inputVar = evalFunc->Arguments()[0]; // Prepare input data. // For evaluating an image, you first need to perform some image preprocessing to make sure that the input image has the correct size and layout // that match the model inputs. // Please note that the model used by this example expects the CHW image layout. // inputVar.Shape[0] is image width, inputVar.Shape[1] is image height, and inputVar.Shape[2] is channels. // For simplicity and avoiding external dependencies, we skip the preprocessing step here, and just use some artificially created data as input. std::vector<float> inputData(inputVar.Shape().TotalSize()); for (size_t i = 0; i < inputData.size(); ++i) { inputData[i] = static_cast<float>(i % 255); } // Create input value and input data map ValuePtr inputVal = Value::CreateBatch(inputVar.Shape(), inputData, device); std::unordered_map<Variable, ValuePtr> inputDataMap = { { inputVar, inputVal } }; // Create output data map. Using null as Value to indicate using system allocated memory. // Alternatively, create a Value object and add it to the data map. Variable modelOutput = evalFunc->Outputs()[0]; Variable interLayerOutput = evalFunc->Outputs()[1]; std::unordered_map<Variable, ValuePtr> outputDataMap = { { modelOutput, nullptr }, { interLayerOutput, nullptr } }; // Start evaluation on the device evalFunc->Evaluate(inputDataMap, outputDataMap, device); // Get evaluate result as dense outputs for(auto & outputVariableValuePair : outputDataMap) { auto variable = outputVariableValuePair.first; auto value = outputVariableValuePair.second; std::vector<std::vector<float>> outputData; value->CopyVariableValueTo(variable, outputData); PrintOutput<float>(variable.Shape().TotalSize(), outputData); } }
void values(FieldContainer<double> &values, BasisCachePtr basisCache) { CHECK_VALUES_RANK(values); FunctionPtr fsq = _f*_f; int numCells = basisCache->cellIDs().size(); int numPoints = values.dimension(1); FieldContainer<double> cellIntegs(numCells); fsq->integrate(cellIntegs,basisCache); for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int ptIndex=0; ptIndex<numPoints; ptIndex++) { values(cellIndex,ptIndex) = cellIntegs(cellIndex); } } }
Expr visit(const Call *c) override { Expr expr = IRMutator2::visit(c); c = expr.as<Call>(); internal_assert(c); if (c->func.defined()) { FunctionPtr ptr = c->func; ptr.strengthen(); expr = Call::make(c->type, c->name, c->args, c->call_type, ptr, c->value_index, c->image, c->param); } return expr; }
void OutputFunctionInfo(FunctionPtr func) { auto inputVariables = func->Arguments(); fprintf(stderr, "Function '%S': Input Variables (count=%lu)\n", func->Name().c_str(), inputVariables.size()); for_each(inputVariables.begin(), inputVariables.end(), [](const Variable v) { fprintf(stderr, " name=%S, kind=%d\n", v.Name().c_str(), static_cast<int>(v.Kind())); }); auto outputVariables = func->Outputs(); fprintf(stderr, "Function '%S': Output Variables (count=%lu)\n", func->Name().c_str(), outputVariables.size()); for_each(outputVariables.begin(), outputVariables.end(), [](const Variable v) { fprintf(stderr, " name=%S, kind=%d\n", v.Name().c_str(), static_cast<int>(v.Kind())); }); }
/// <summary> /// The example shows /// - how to load model. /// - how to prepare input data for a batch of samples. /// - how to prepare input and output data map. /// - how to evaluate a model. /// - how to retrieve evaluation result and retrieve output data in dense format. /// Note: The example uses the model trained by <CNTK>/Examples/Image/Classification/ResNet/Python/TrainResNet_CIFAR10.py /// Please see README.md in <CNTK>/Examples/Image/Classification/ResNet about how to train the model. /// The parameter 'modelFile' specifies the path to the model. /// </summary> void EvaluationBatchUsingDense(const wchar_t* modelFile, const DeviceDescriptor& device) { printf("\n===== Evaluate batch of samples using dense format.\n"); // The number of samples in the batch. size_t sampleCount = 3; // Load the model. // The model is trained by <CNTK>/Examples/Image/Classification/ResNet/Python/TrainResNet_CIFAR10.py // Please see README.md in <CNTK>/Examples/Image/Classification/ResNet about how to train the model. FunctionPtr modelFunc = Function::Load(modelFile, device); // Get input variable. The model has only one single input. Variable inputVar = modelFunc->Arguments()[0]; // The model has only one output. // If the model has more than one output, use modelFunc->Outputs to get the list of output variables. Variable outputVar = modelFunc->Output(); // Prepare input data. // For evaluating an image, you first need to perform some image preprocessing to make sure that the input image has the correct size and layout // that match the model inputs. // Please note that the model used by this example expects the CHW image layout. // inputVar.Shape[0] is image width, inputVar.Shape[1] is image height, and inputVar.Shape[2] is channels. // For simplicity and avoiding external dependencies, we skip the preprocessing step here, and just use some artificially created data as input. std::vector<float> inputData(inputVar.Shape().TotalSize() * sampleCount); for (size_t i = 0; i < inputData.size(); ++i) { inputData[i] = static_cast<float>(i % 255); } // Create input value and input data map. ValuePtr inputVal = Value::CreateBatch(inputVar.Shape(), inputData, device); std::unordered_map<Variable, ValuePtr> inputDataMap = { { inputVar, inputVal } }; // Create output data map. Using null as Value to indicate using system allocated memory. // Alternatively, create a Value object and add it to the data map. std::unordered_map<Variable, ValuePtr> outputDataMap = { { outputVar, nullptr } }; // Start evaluation on the device modelFunc->Evaluate(inputDataMap, outputDataMap, device); // Get evaluate result as dense output ValuePtr outputVal = outputDataMap[outputVar]; std::vector<std::vector<float>> outputData; outputVal->CopyVariableValueTo(outputVar, outputData); PrintOutput<float>(outputVar.Shape().TotalSize(), outputData); }
TEST_F(FunctionTests, TestQuotientRule) { // take f = exp(x) / x^2. f' = f - 2 * x * exp(x) / x^4 FunctionPtr x2 = Teuchos::rcp( new Xn(2) ); FunctionPtr exp_x = Teuchos::rcp( new Exp_x ); FunctionPtr x = Teuchos::rcp( new Xn(1) ); FunctionPtr f = exp_x / x2; FunctionPtr f_prime = f->dx(); FunctionPtr f_prime_expected = f - 2 * x * exp_x / (x2 * x2); checkFunctionsAgree(f_prime, f_prime_expected, _basisCache); }
TEST_F(FunctionTests, TestProductRule) { // take f = x^2 * exp(x). f' = 2 x * exp(x) + f FunctionPtr x2 = Teuchos::rcp( new Xn(2) ); FunctionPtr exp_x = Teuchos::rcp( new Exp_x ); FunctionPtr x = Teuchos::rcp( new Xn(1) ); FunctionPtr f = x2 * exp_x; FunctionPtr f_prime = f->dx(); FunctionPtr f_prime_expected = 2.0 * x * exp_x + f; checkFunctionsAgree(f_prime, f_prime_expected, _basisCache); }
Trainer BuildTrainer(const FunctionPtr& function, const Variable& labels, LearningRateSchedule lr = 0.005, MomentumSchedule m = 0.0) { auto trainingLoss = CNTK::CrossEntropyWithSoftmax(function, labels, L"lossFunction"); auto prediction = CNTK::ClassificationError(function, labels, L"classificationError"); auto learner = MomentumSGDLearner(function->Parameters(), lr, m); return Trainer(function, trainingLoss, prediction, { learner }); }
void TestFunctionSaveAndLoad(const FunctionPtr& function, const DeviceDescriptor& device) { auto file = L"TestFunctionSaveAndLoad.out"; { Dictionary model = function->Serialize(); auto stream = GetFstream(file, false); // todo : as text. *stream << model; stream->flush(); } Dictionary model; { auto stream = GetFstream(file, true); *stream >> model; } auto reloadedFunction = Function::Deserialize(model, device); if (!AreEqual(function, reloadedFunction)) { throw std::runtime_error("TestFunctionSaveAndLoad: original and reloaded functions are not identical."); } }
virtual void values(FieldContainer<double> &values, BasisCachePtr basisCache) { // not the most efficient implementation _fxn->values(values,basisCache); vector<GlobalIndexType> contextCellIDs = basisCache->cellIDs(); int cellIndex=0; // keep track of index into values int entryCount = values.size(); int numCells = values.dimension(0); int numEntriesPerCell = entryCount / numCells; for (vector<GlobalIndexType>::iterator cellIt = contextCellIDs.begin(); cellIt != contextCellIDs.end(); cellIt++) { GlobalIndexType cellID = *cellIt; if (_cellIDs.find(cellID) == _cellIDs.end()) { // clear out the associated entries for (int j=0; j<numEntriesPerCell; j++) { values[cellIndex*numEntriesPerCell + j] = 0; } } cellIndex++; } }
void ParQGHandler::linearAt_(FunctionPtr f, double fval, const double *x, double *c, LinearFunctionPtr *lf, int *error) { int n = rel_->getNumVars(); double *a = new double[n]; VariableConstIterator vbeg = rel_->varsBegin(), vend = rel_->varsEnd(); const double linCoeffTol = env_->getOptions()->findDouble("conCoeff_tol")->getValue(); std::fill(a, a+n, 0.); f->evalGradient(x, a, error); if (*error==0) { *lf = (LinearFunctionPtr) new LinearFunction(a, vbeg, vend, linCoeffTol); *c = fval - InnerProduct(x, a, minlp_->getNumVars()); } else { logger_->msgStream(LogError) << me_ <<"gradient not defined at this point." << std::endl; #if SPEW logger_->msgStream(LogDebug) << me_ <<"gradient not defined at this point." << std::endl; #endif } delete [] a; return; }
// bool matchesPoint(double x, double y) { // return true; // } bool matchesPoints(FieldContainer<bool> &pointsMatch, BasisCachePtr basisCache) { const FieldContainer<double> *points = &(basisCache->getPhysicalCubaturePoints()); const FieldContainer<double> *normals = &(basisCache->getSideNormals()); int numCells = (*points).dimension(0); int numPoints = (*points).dimension(1); FieldContainer<double> beta_pts(numCells,numPoints,2); _beta->values(beta_pts,basisCache); double tol=1e-14; bool somePointMatches = false; for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int ptIndex=0; ptIndex<numPoints; ptIndex++) { double n1 = (*normals)(cellIndex,ptIndex,0); double n2 = (*normals)(cellIndex,ptIndex,1); double beta_n = beta_pts(cellIndex,ptIndex,0)*n1 + beta_pts(cellIndex,ptIndex,1)*n2 ; // cout << "beta = (" << beta_pts(cellIndex,ptIndex,0)<<", "<< // beta_pts(cellIndex,ptIndex,1)<<"), n = ("<<n1<<", "<<n2<<")"<<endl; pointsMatch(cellIndex,ptIndex) = false; if (beta_n < 0) { pointsMatch(cellIndex,ptIndex) = true; somePointMatches = true; } } } return somePointMatches; }
void values(FieldContainer<double> &values, BasisCachePtr sliceBasisCache) { vector<GlobalIndexType> sliceCellIDs = sliceBasisCache->cellIDs(); Teuchos::Array<int> dim; values.dimensions(dim); dim[0] = 1; // one cell Teuchos::Array<int> offset(dim.size()); for (int cellOrdinal = 0; cellOrdinal < sliceCellIDs.size(); cellOrdinal++) { offset[0] = cellOrdinal; int enumeration = values.getEnumeration(offset); FieldContainer<double>valuesForCell(dim,&values[enumeration]); GlobalIndexType sliceCellID = sliceCellIDs[cellOrdinal]; int numPoints = sliceBasisCache->getPhysicalCubaturePoints().dimension(1); int spaceDim = sliceBasisCache->getPhysicalCubaturePoints().dimension(2); FieldContainer<double> spaceTimePhysicalPoints(1,numPoints,spaceDim+1); for (int ptOrdinal=0; ptOrdinal<numPoints; ptOrdinal++) { for (int d=0; d<spaceDim; d++) { spaceTimePhysicalPoints(0,ptOrdinal,d) = sliceBasisCache->getPhysicalCubaturePoints()(cellOrdinal,ptOrdinal,d); } spaceTimePhysicalPoints(0,ptOrdinal,spaceDim) = _t; } GlobalIndexType cellID = _cellIDMap[sliceCellID]; BasisCachePtr spaceTimeBasisCache = BasisCache::basisCacheForCell(_spaceTimeMesh, cellID); FieldContainer<double> spaceTimeRefPoints(1,numPoints,spaceDim+1); CamelliaCellTools::mapToReferenceFrame(spaceTimeRefPoints, spaceTimePhysicalPoints, _spaceTimeMesh, cellID); spaceTimeRefPoints.resize(numPoints,spaceDim+1); spaceTimeBasisCache->setRefCellPoints(spaceTimeRefPoints); _spaceTimeFunction->values(valuesForCell, spaceTimeBasisCache); } }
void RunEvaluationOneHidden(FunctionPtr evalFunc, const DeviceDescriptor& device) { const std::wstring inputNodeName = L"features"; const std::wstring outputNodeName = L"out.z_output"; Variable inputVar; if (!GetInputVariableByName(evalFunc, inputNodeName, inputVar)) { fprintf(stderr, "Input variable %S is not available.\n", inputNodeName.c_str()); throw("Input variable not found error."); } Variable outputVar; if (!GetOutputVaraiableByName(evalFunc, outputNodeName, outputVar)) { fprintf(stderr, "Output variable %S is not available.\n", outputNodeName.c_str()); throw("Output variable not found error."); } // Evaluate the network in several runs size_t iterationCount = 4; size_t numSamples = 3; for (size_t t = 0; t < iterationCount; ++t) { std::vector<float> inputData(inputVar.Shape().TotalSize() * numSamples); for (size_t i = 0; i < inputData.size(); ++i) { inputData[i] = static_cast<float>(i % 255); } NDShape inputShape = inputVar.Shape().AppendShape({1, numSamples}); ValuePtr inputValue = MakeSharedObject<Value>(MakeSharedObject<NDArrayView>(inputShape, inputData, true)); ValuePtr outputValue; std::unordered_map<Variable, ValuePtr> outputs = {{outputVar, outputValue}}; evalFunc->Forward({{inputVar, inputValue}}, outputs, device); outputValue = outputs[outputVar]; NDShape outputShape = outputVar.Shape().AppendShape({1, numSamples}); std::vector<float> outputData(outputShape.TotalSize()); NDArrayViewPtr cpuArrayOutput = MakeSharedObject<NDArrayView>(outputShape, outputData, false); cpuArrayOutput->CopyFrom(*outputValue->Data()); assert(outputData.size() == outputVar.Shape()[0] * numSamples); fprintf(stderr, "Evaluation result:\n"); size_t dataIndex = 0; auto outputDim = outputVar.Shape()[0]; for (size_t i = 0; i < numSamples; i++) { fprintf(stderr, "Iteration:%lu, Sample %lu:\n", t, i); fprintf(stderr, "Ouput:"); for (size_t j = 0; j < outputDim; j++) { fprintf(stderr, "%f ", outputData[dataIndex++]); } fprintf(stderr, "\n"); } } }
bool SOS1Handler::isGUB(SOS *sos) { VariablePtr var; int nz = sos->getNz(); ConstConstraintPtr c; FunctionPtr f; LinearFunctionPtr lf; bool isgub = false; for (VariableConstIterator viter = sos->varsBegin(); viter!=sos->varsEnd(); ++viter) { var = *viter; if (Binary!=var->getType() || ImplBin!=var->getType()) { return false; } } // If we are here, then it means all variables are binary. Check if their sum // is <= 1. var = *(sos->varsBegin()); for (ConstrSet::iterator it=var->consBegin(); it!=var->consEnd() && false==isgub; ++it) { c = *it; f = c->getFunction(); isgub = true; if (Linear!=f->getType()) { isgub = false; } else if ((UInt) nz==f->getNumVars()) { isgub = false; } else if (fabs(c->getUb()-1.0)>zTol_) { isgub = false; } else { lf = f->getLinearFunction(); for (VariableConstIterator viter = sos->varsBegin(); viter!=sos->varsEnd(); ++viter) { if ((lf->getWeight(*viter)-1.0)>zTol_) { isgub = false; break; } } } } return isgub; }
void Context::AddFunction(FunctionPtr function) { StringView name = function->GetName(); if (IsNameUsed(name)) throw ILException("Cannot declare function, the name '" + static_cast<std::string>(name) + "' is already being used."); functions.emplace(name, function); }
void FunctionTests::checkFunctionsAgree(FunctionPtr f1, FunctionPtr f2, BasisCachePtr basisCache) { ASSERT_EQ(f1->rank(), f2->rank()) << "f1->rank() " << f1->rank() << " != f2->rank() " << f2->rank() << endl; int rank = f1->rank(); int numCells = basisCache->getPhysicalCubaturePoints().dimension(0); int numPoints = basisCache->getPhysicalCubaturePoints().dimension(1); int spaceDim = basisCache->getPhysicalCubaturePoints().dimension(2); Teuchos::Array<int> dim; dim.append(numCells); dim.append(numPoints); for (int i=0; i<rank; i++) { dim.append(spaceDim); } FieldContainer<double> f1Values(dim); FieldContainer<double> f2Values(dim); f1->values(f1Values,basisCache); f2->values(f2Values,basisCache); double tol = 1e-14; double maxDiff; EXPECT_TRUE(fcsAgree(f1Values,f2Values,tol,maxDiff)) << "Test failed: f1 and f2 disagree; maxDiff " << maxDiff << ".\n" << "f1Values: \n" << f1Values << "f2Values: \n" << f2Values; }
void Transformer::copyLinear_(ConstProblemPtr p, ProblemPtr newp) { FunctionPtr f; LinearFunctionPtr newlf; ConstConstraintPtr c; ConstraintPtr newc; ObjectivePtr obj; // copy linear constraints. for (ConstraintConstIterator it=p->consBegin(); it!=p->consEnd(); ++it) { c = *it; if (Linear==c->getFunction()->getType()) { // create a clone of this linear function. newlf = c->getLinearFunction()->cloneWithVars(newp->varsBegin()); f = (FunctionPtr) new Function(newlf); newc = newp->newConstraint(f, c->getLb(), c->getUb()); lHandler_->addConstraint(newc); } } // copy linear objective. obj = p->getObjective(); if (!obj) { f.reset(); newp_->newObjective(f, 0.0, Minimize); } else { switch (obj->getFunctionType()) { case (Constant): f = FunctionPtr(); // NULL newp->newObjective(f, obj->getConstant(), obj->getObjectiveType(), obj->getName()); break; case (Linear): newlf = obj->getFunction()->getLinearFunction()-> cloneWithVars(newp->varsBegin()); f = (FunctionPtr) new Function(newlf); newp->newObjective(f, obj->getConstant(), obj->getObjectiveType(), obj->getName()); break; default: break; } } }
void values(FieldContainer<double> &values, BasisCachePtr basisCache) { FieldContainer<double> points = basisCache->getPhysicalCubaturePoints(); FieldContainer<double> normals = basisCache->getSideNormals(); int numCells = points.dimension(0); int numPoints = points.dimension(1); FieldContainer<double> Tv(numCells,numPoints); FieldContainer<double> u1v(numCells,numPoints);; _u1->values(u1v,basisCache); _T->values(Tv,basisCache); bool isSubsonic = false; double min_y = YTOP; double max_y = 0.0; values.initialize(0.0); for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int ptIndex=0; ptIndex<numPoints; ptIndex++) { double x = points(cellIndex,ptIndex,0); double y = points(cellIndex,ptIndex,1); double T = Tv(cellIndex,ptIndex); double un = u1v(cellIndex,ptIndex); // WARNING: ASSUMES NORMAL AT OUTFLOW = (1,0) double c = sqrt(_gamma * (_gamma-1.0) * _cv * T); bool outflowMatch = ((abs(x-2.0) < _tol) && (y > 0.0) && (y < YTOP)); bool subsonicMatch = (un < c) && (un > 0.0); if (subsonicMatch && outflowMatch) { values(cellIndex,ptIndex) = 1.0; isSubsonic = true; min_y = min(y,min_y); max_y = max(y,max_y); // cout << "y = " << y << endl; } } } if (isSubsonic) { // cout << "subsonic in interval y =(" << min_y << "," << max_y << ")" << endl; } }
void Transformer::makeObjLin_() { ObjectivePtr obj; assert(p_); assert(newp_); obj = p_->getObjective(); if (!obj) { return; } if (obj->getFunctionType() != Linear && obj->getFunctionType() != Constant) { VariablePtr eta = newp_->newVariable(VarTran); FunctionPtr etaf; FunctionPtr f = obj->getFunction(); LinearFunctionPtr lz = LinearFunctionPtr(new LinearFunction()); LinearFunctionPtr lz2; ObjectiveType otype = obj->getObjectiveType(); ConstraintPtr objcon; lz->addTerm(eta, -1.0); f->add(lz); if (otype == Minimize) { //XXX Do you want to keep track of the objective constraint? objcon = newp_->newConstraint(f, -INFINITY, 0.0); if (lHandler_) { lHandler_->addConstraint(objcon); } } else { objcon = newp_->newConstraint(f, 0.0, INFINITY); if (lHandler_) { lHandler_->addConstraint(objcon); } } lz2 = (LinearFunctionPtr) new LinearFunction(); lz2->addTerm(eta, 1.0); etaf = (FunctionPtr) new Function(lz2); newp_->newObjective(etaf, obj->getConstant(), otype); } }
bool matchesPoints(FieldContainer<bool> &pointsMatch, BasisCachePtr basisCache) { const FieldContainer<double> *points = &(basisCache->getPhysicalCubaturePoints()); int numCells = (*points).dimension(0); int numPoints = (*points).dimension(1); FieldContainer<double> T(numCells,numPoints); FieldContainer<double> u1(numCells,numPoints);; _u1->values(u1,basisCache); _T->values(T,basisCache); double tol=1e-14; bool somePointMatches = false; for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int ptIndex=0; ptIndex<numPoints; ptIndex++) { double x = (*points)(cellIndex,ptIndex,0); double y = (*points)(cellIndex,ptIndex,1); double T_val = T(cellIndex,ptIndex); double c = sqrt(_gamma * (_gamma-1.0) * _cv * T_val); double un = u1(cellIndex,ptIndex); // WARNING: ASSUMES NORMAL AT OUTFLOW = (1,0) cout << "un = " << un << ", T = " << T_val << endl; double tol = 1e-14; bool outflowMatch = ((abs(x-2.0) < tol) && (y > 0.0) && (y < YTOP)); bool subsonicMatch = (un < c) && (un > 0.0); pointsMatch(cellIndex,ptIndex) = false; if (outflowMatch && subsonicMatch) { pointsMatch(cellIndex,ptIndex) = true; somePointMatches = true; } } } return somePointMatches; }
void values(FieldContainer<double> &values, BasisCachePtr basisCache) { CHECK_VALUES_RANK(values); _f->values(values,basisCache); int numCells = values.dimension(0); int numPoints = values.dimension(1); for (int cellIndex=0; cellIndex<numCells; cellIndex++) { for (int ptIndex=0; ptIndex<numPoints; ptIndex++) { double value = values(cellIndex,ptIndex); values(cellIndex,ptIndex) = log(value); } } }