hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
9abe1f37b9f1402c88a3e15eb37137bdbd0c66e5
35,427
hpp
C++
external/swak/libraries/swakParsers/CommonValueExpressionDriverI.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/swak/libraries/swakParsers/CommonValueExpressionDriverI.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
external/swak/libraries/swakParsers/CommonValueExpressionDriverI.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright: ICE Stroemungsfoschungs GmbH Copyright (C) 1991-2008 OpenCFD Ltd. ------------------------------------------------------------------------------- License This file is based on CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Contributors/Copyright: 2010-2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at> \*---------------------------------------------------------------------------*/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "surfaceMesh.hpp" #include "fvsPatchField.hpp" #include "pointPatchField.hpp" #include "primitivePatchInterpolation.hpp" #include <cassert> namespace CML { inline const pointMesh &CommonValueExpressionDriver::pMesh() { if(!pMesh_.valid()) { pMesh_.set( new pointMesh(mesh()) ); } return pMesh_(); } template<class Type> tmp<Field<Type> > CommonValueExpressionDriver::evaluate( const exprString &expr, bool qPoint ) { parse(expr); return getResult<Type>(qPoint); } template<class Type> Type CommonValueExpressionDriver::evaluateUniform( const exprString &expr, bool qPoint ) { parse(expr); ExpressionResult result=this->getUniform(1,true); Type val=result.getResult<Type>()()[0]; return val; } template<class Type> tmp<Field<Type> > CommonValueExpressionDriver::makeField(Type val,bool isPoint) { label size=this->size(); if(isPoint) { size=this->pointSize(); } return tmp<Field<Type> >( new Field<Type>(size,val) ); } template<class Type> void CommonValueExpressionDriver::setResult(Field<Type> *val,bool isPoint) { result_.setResult<Type>(val,isPoint); } template<class Type> tmp<Field<Type> > CommonValueExpressionDriver::getResult(bool qPoint) { if(qPoint!=result_.isPoint()) { FatalErrorInFunction << "A " << (qPoint ? "point" : "face" ) << "-field was wanted" << " but we got a " << (!qPoint ? "point" : "face" ) << endl << exit(FatalError); } return result_.getResult<Type>(); } template<template<class> class BinOp,class Type> inline Type CommonValueExpressionDriver::getReduced( BinOp<Type> op, Type initial ) { return result_.getReduced(op,initial); } template<class Type> bool CommonValueExpressionDriver::isVariable( const word &name, bool isPoint, label expectedSize ) const { if(debug) { Pout << "CommonValueExpressionDriver::isVariable " << " looking for " << name << " isPoint: " << isPoint << " of type " << pTraits<Type>::typeName << " Expected size: " << expectedSize; } if(hasVariable(name)) { if(debug) { Pout << " - name found"; } const ExpressionResult &var=variable(name); if( var.valueType()==pTraits<Type>::typeName && var.isPoint()==isPoint ) { bool sizeOK=true; if(expectedSize>=0) { sizeOK=(var.size()==expectedSize); reduce(sizeOK,andOp<bool>()); } if(sizeOK) { if(debug) { Pout << " - OK" << endl; } return true; } } if(debug) { Pout << "(" << var.valueType() << " " << var.isPoint() << ")"; } } if(debug) { Pout << " - not OK -> trying global" << endl; } return isGlobal<Type>(name,isPoint,expectedSize); } template<class Type> bool CommonValueExpressionDriver::isGlobal( const word &name, bool isPoint, label expectedSize ) const { if(debug) { Pout << "CommonValueExpressionDriver::isGlobal " << " looking for " << name << " isPoint: " << isPoint << flush; } const ExpressionResult &aGlobal=lookupGlobal(name); if (debug) { Pout << " - found type " << aGlobal.valueType() << " isPoint " << isPoint; } if( aGlobal.valueType()==pTraits<Type>::typeName && aGlobal.isPoint()==isPoint ) { bool sizeOK=true; if(expectedSize>=0) { sizeOK=(aGlobal.size()==expectedSize); reduce(sizeOK,andOp<bool>()); } if(sizeOK) { if(debug) { Pout << " - OK" << endl; } return true; } else { if(debug) { Pout << " - Found but wrong size" << endl; } return false; } } else { if(debug) { Pout << " - not OK" << endl; } return false; } } template<class Type> bool CommonValueExpressionDriver::is(const word &name,bool isPoint) const { if(isVariable<Type>(name,isPoint)) { return true; } else { return isField<Type>(name,isPoint); } } template<class Type> bool CommonValueExpressionDriver::isField( const word &inName, bool isPoint ) const { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::isField. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } typedef GeometricField<Type,fvPatchField,volMesh> localVolField; typedef GeometricField<Type,fvsPatchField,surfaceMesh> localSurfaceField; typedef GeometricField<Type,pointPatchField,pointMesh> localPointField; if(isPoint) { if( isThere<localPointField>(name) ) { return true; } else { return false; } } else { if( isThere<localVolField>(name) ) { return true; } else if( isThere<localSurfaceField>(name) ) { return true; } else{ return false; } } } template<class T> inline bool CommonValueExpressionDriver::updateSet( autoPtr<T> &theSet, const word &inName, SetOrigin origin ) const { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::updateSet. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } label oldSize=theSet->size(); bool updated=false; const polyMesh &mesh=dynamic_cast<const polyMesh &>(theSet->db()); if(debug) { Pout << "UpdateSet: " << theSet->name() << " Id: " << name << " Origin: " << int(origin) << endl; } switch(origin) { case FILE: { // Scope to make sure header is not present in the other cases IOobject header ( name, mesh.time().timeName(), polyMesh::meshSubDir/"sets", mesh, IOobject::MUST_READ, IOobject::NO_WRITE ); if( header.headerOk() && header.headerClassName()==T::typeName ) { if(debug) { Pout << "Rereading from " << header.filePath() << endl; } theSet.reset( new T( header ) ); updated=true; } } break; case NEW: WarningInFunction << "State NEW shouldn't exist" << endl; [[fallthrough]]; case MEMORY: [[fallthrough]]; case CACHE: { word sName=name; if(mesh.thisDb().foundObject<T>(name)) { if(debug) { Pout << "Found " << name << " and rereading it" << endl; } theSet.reset( new T( mesh, name, mesh.thisDb().lookupObject<T>(name) ) ); } else { FatalErrorInFunction << name << " Not found" << endl << "In db: " << mesh.thisDb().names() << endl << exit(FatalError); } updated=true; } break; case INVALID: FatalErrorInFunction << T::typeName << " " << name << " is invalid" << endl << exit(FatalError); break; default: if(debug) { Pout << "Origin " << int(origin) << " not implemented" << endl; } [[fallthrough]]; } if(debug) { Pout << name << " old size " << oldSize << " new: " << theSet->size() << endl; } return updated; } template<class T> inline autoPtr<T> CommonValueExpressionDriver::getSet( const fvMesh &mesh, const word &inName, SetOrigin &origin ) const { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::getSet. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } // avoid the possibility of name-clashes const word regName=name+"RegisteredNameFor"+T::typeName; if(debug) { Pout << "Looking for " << T::typeName << " named " << name << " or registered as " << regName << " with mesh "; Pout << "Caching: " << cacheSets() << " Found: " << mesh.foundObject<T>(name) << " Found registered: " << mesh.foundObject<T>(regName) << endl; } if( !cacheSets() || ( !mesh.thisDb().foundObject<T>(regName) && !mesh.thisDb().foundObject<T>(name) ) ) { if(debug) { Pout << "Constructing a new " << T::typeName << " " << name << endl; if(debug>1) { Pout << mesh.thisDb().names(); } } origin=FILE; autoPtr<T> s( new T( mesh, name, IOobject::MUST_READ ) ); if(cacheSets()) { if(debug) { Pout << "Registering a copy of " << name << " with mesh" << endl; } autoPtr<T> toCache(new T(mesh,regName,s())); toCache->store(toCache); } return s; } else { if(mesh.thisDb().foundObject<T>(name)) { if(debug) { Pout << "Getting existing " << name << endl; } origin=MEMORY; return autoPtr<T>( new T( mesh, name, mesh.lookupObject<T>(name) ) ); } else { if(debug) { Pout << "Getting existing " << regName << endl; } origin=CACHE; return autoPtr<T>( new T( mesh, name, mesh.lookupObject<T>(regName) ) ); } } } template<> inline void CommonValueExpressionDriver::correctField( volScalarField &f ) const { f.correctBoundaryConditions(); } template<> inline void CommonValueExpressionDriver::correctField( volVectorField &f ) const { f.correctBoundaryConditions(); } template<> inline void CommonValueExpressionDriver::correctField( volTensorField &f ) const { f.correctBoundaryConditions(); } template<> inline void CommonValueExpressionDriver::correctField( volSymmTensorField &f ) const { f.correctBoundaryConditions(); } template<> inline void CommonValueExpressionDriver::correctField( volSphericalTensorField &f ) const { f.correctBoundaryConditions(); } template<class T> inline void CommonValueExpressionDriver::correctField(T &f) const { } template<class T> autoPtr<T> CommonValueExpressionDriver::getOrReadField( const word &name, bool failIfNoneFound, bool getOldTime ) { return this->getOrReadFieldInternal<T>( name, this->mesh(), failIfNoneFound, getOldTime ); } template<class T> autoPtr<T> CommonValueExpressionDriver::getOrReadPointField( const word &name, bool failIfNoneFound, bool getOldTime ) { return this->getOrReadFieldInternal<T>( name, this->pMesh(), failIfNoneFound, getOldTime ); } template<class T,class Mesh> autoPtr<T> CommonValueExpressionDriver::getOrReadFieldInternal( const word &inName, const Mesh &actualMesh, bool failIfNoneFound, bool getOldTime ) { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::getOrReadFieldInternal. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } if(debug) { Pout << "CommonValueExpressionDriver::getOrReadField. Name: " << name << " Type: " << T::typeName << endl; } dimensionSet nullDim(0,0,0,0,0); autoPtr<T> f; typedef typename T::value_type Type; if( ( hasVariable(name) && variable(name).valueType()==pTraits<Type>::typeName ) || isGlobal<Type>(name,false) ) { if(debug) { Pout << "Getting " << name << " from variables" << endl; } word patchType("calculated"); if(T::PatchFieldType::typeName=="fvPatchField") { patchType="zeroGradient"; } if(debug) { Info << "Creating field " << name << " of type " << T::typeName << " with patch type " << patchType << "(" << T::PatchFieldType::typeName << ")" << endl; } f.set( new T( IOobject ( name, this->mesh().time().timeName(), this->mesh(), IOobject::NO_READ, IOobject::NO_WRITE, false // don't register ), actualMesh, dimensioned<Type>(name,nullDim,pTraits<Type>::zero), patchType ) ); if(debug) { Pout <<"New field: " << name << " ownedByRegistry" << f->ownedByRegistry() << endl; } Field<Type> vals; if( hasVariable(name) && variable(name).valueType()==pTraits<Type>::typeName ) { vals=variable(name).getResult<Type>(true); } else { vals=const_cast<ExpressionResult &>( lookupGlobal(name) ).getResult<Type>(true); } if(debug) { Pout << "sizes: " << vals.size() << " " << f->size() << endl; } bool sameSize=vals.size()==f->size(); reduce(sameSize,andOp<bool>()); if(sameSize) { f->internalField()=vals; } else { Type avg=gAverage(vals); bool noWarn=false; if(!noWarn) { Type minVal=gMin(vals); Type maxVal=gMax(vals); if(mag(minVal-maxVal)>SMALL) { WarningInFunction << "The minimum value " << minVal << " and the maximum " << maxVal << " differ. I will use the average " << avg << endl; } } f->internalField()=avg; } correctField(f()); return f; } if( searchInMemory() && this->mesh().foundObject<T>(name) ) { if(debug) { Pout << "Getting " << name << " from memory" << endl; } f.set( new T( name+"_copyBySwak", // make sure that the original object is not shadowed this->mesh().lookupObject<T>(name) ) ); if(getOldTime) { if(debug) { Info << "Getting oldTime of " << name << " has " << this->mesh().lookupObject<T>(name).nOldTimes() << endl; } if( this->mesh().lookupObject<T>(name).nOldTimes()==0 && this->prevIterIsOldTime() ) { if(debug) { Info << "Using the previous iteration, because there is no oldTime" << endl; } f->oldTime()=this->mesh().lookupObject<T>(name).prevIter(); } } } else if( searchOnDisc() && getTypeOfField(name)==T::typeName ) { if(debug) { Pout << "Reading " << name << " from disc" << endl; } f.set( this->readAndRegister<T>(name,actualMesh).ptr() ); // oldTime automatically read } if(debug) { Info << "autoPtr: valid()=" << f.valid() << " empty()=" << f.empty() << endl; } if( !f.valid() && failIfNoneFound ) { FatalErrorInFunction << "Could not find the field " << name << " (" << inName << ")" << " in memory or on disc" << endl << exit(FatalError); } if(f.valid()) { if(debug) { Info << "Valid " << name << " found. Removing dimensions" << endl; } f->dimensions().reset(nullDim); if(f->nOldTimes()>0) { if(debug) { Info << "Removing dimensions of oldTime of " << name << " has " << f->nOldTimes() << endl; } // go through ALL old times T *fp=f.operator->(); while(fp->nOldTimes()>0) { fp=&(fp->oldTime()); // 1.6-ext seems to have a problem here fp->dimensions().reset(nullDim); } } } return f; } template<class Type> tmp<Field<Type> > CommonValueExpressionDriver::getVariable( const word &inName, const label expectedSize ) { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::getVariable. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } autoPtr<Field<Type> >vals; bool isSingleValue=false; if( hasVariable(name) && variable(name).valueType()==pTraits<Type>::typeName ) { isSingleValue=variable(name).isSingleValue(); vals.set( variable(name).getResult<Type>(true).ptr() ); } else if(isGlobal<Type>(name,false)) { ExpressionResult &var=const_cast<ExpressionResult &>( lookupGlobal(name) ); isSingleValue=var.isSingleValue(); vals.set( var.getResult<Type>(true).ptr() ); } if(vals.valid()) { bool qSize=vals->size()==expectedSize; reduce(qSize,andOp<bool>()); if( qSize ) { return tmp<Field<Type> >( vals.ptr() ); } else { if(!isSingleValue) { WarningInFunction << "Variable " << name << " is not a single value but does not " << "fit the size " << expectedSize << ". Using average and " << "hoping for the best" << endl; } return tmp<Field<Type> >( new Field<Type>( expectedSize,gAverage(vals()) ) ); } } else { FatalErrorInFunction << "Variable " << inName << " (aliased to " << name << ") not found." << endl << exit(FatalError); return tmp<Field<Type> >( new Field<Type>( expectedSize,pTraits<Type>::zero ) ); } } template<class T,class Mesh> inline tmp<T> CommonValueExpressionDriver::readAndRegister( const word &inName, const Mesh &actualMesh ) { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::readAndRegister. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } tmp<T>f( new T( IOobject ( name, this->time(), this->mesh(), IOobject::MUST_READ, IOobject::NO_WRITE ), actualMesh ) ); if(cacheReadFields()) { if(debug) { Pout << "Registering a copy of " << name << " with mesh" << endl; } autoPtr<T> toCache(new T(f())); toCache->store(toCache); } return f; } template<class T> tmp<T> CommonValueExpressionDriver::interpolateForeignField( const word &inMeshName, const word &inFieldName, meshToMeshOrder theOrder ) const { word meshName(inMeshName); if(this->hasAlias(meshName)) { if(debug) { Pout << "CommonValueExpressionDriver::interpolateForeignField. MeshName: " << meshName << " is an alias for " << this->getAlias(meshName) << endl; } meshName=this->getAlias(meshName); } word fieldName(inFieldName); if(this->hasAlias(fieldName)) { if(debug) { Pout << "CommonValueExpressionDriver::interpolateForeignField. fieldName: " << fieldName << " is an alias for " << this->getAlias(fieldName) << endl; } fieldName=this->getAlias(fieldName); } const fvMesh &theMesh=MeshesRepository::getRepository().getMesh( meshName ); const meshToMesh &interpolation=MeshesRepository::getRepository(). getMeshToMesh( meshName, this->mesh() ); if(!theMesh.foundObject<T>(fieldName)) { if(debug) { Pout << "Not Found " << fieldName << " in memory I have" << endl; } autoPtr<T> f( new T( IOobject ( fieldName, theMesh.time().timeName(), theMesh, IOobject::MUST_READ, IOobject::NO_WRITE ), theMesh ) ); if(debug) { Pout << "Field " << fieldName << " in memory store I will" << endl; } dimensionSet nullDim(0,0,0,0,0); f->dimensions().reset(nullDim); f->store(f); } if(debug) { Info << "Objects in mesh: " << theMesh.names() << endl; } return interpolation.mapSrcToTgt( theMesh.lookupObject<T>(fieldName), eqOp<typename T::value_type>() ); } template<class T> bool CommonValueExpressionDriver::CommonValueExpressionDriver::isForeignField( const word &meshName, const word &inName ) const { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::isForeignField. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } if(!isForeignMesh(meshName)) { return false; } const fvMesh &theMesh=MeshesRepository::getRepository().getMesh( meshName ); if(debug) { Pout << "CommonValueExpressionDriver::ForeignField. Name: " << name << " Type: " << T::typeName << endl; } if(theMesh.foundObject<T>(name)) { if(debug) { Pout << "Found " << name << " in memory" << endl; } return true; } if( getTypeOfFieldInternal(theMesh,name)==T::typeName ) { if(debug) { Pout << "Found " << name << " on disc" << endl; } return true; } else { if(debug) { Pout << name << " not found" << endl; } return false; } } template<class T> bool CommonValueExpressionDriver::CommonValueExpressionDriver::isThere( const word &inName ) const { word name(inName); if(this->hasAlias(name)) { if(debug) { Pout << "CommonValueExpressionDriver::isThere. Name: " << name << " is an alias for " << this->getAlias(name) << endl; } name=this->getAlias(name); } if(debug) { Pout << "CommonValueExpressionDriver::isThere. Name: " << name << " Type: " << T::typeName << " searchInMemory: " << searchInMemory() << " searchOnDisc_: " << searchOnDisc() << endl; } if(searchInMemory()) { if(this->mesh().foundObject<T>(name)) { if(debug) { Pout << "Found " << name << " in memory" << endl; } return true; } else if(debug) { Info << "No " << name << " of type " << T::typeName << " found in memory"; if(this->mesh().foundObject<IOobject>(name)) { Info<< " but of type " << this->mesh().lookupObject<IOobject>(name).headerClassName(); if( this->mesh().lookupObject<IOobject>(name).headerClassName() == T::typeName ) { // Info. This actually happens with clang 3.3 Info << " - strange. Type names are the same"; Info<< " Type fits: " << isA<T>( this->mesh().lookupObject<IOobject>(name) ); // this should fail const T &f=this->mesh().lookupObject<T>(name); Info << "for " <<f.name() << endl; } } Info << endl; } } if( searchOnDisc() && getTypeOfField(name)==T::typeName ) { if(debug) { Pout << "Found " << name << " on disc" << endl; } return true; } else { if(debug) { Pout << name << " not found" << endl; } return false; } } inline bool CommonValueExpressionDriver::isLine(const word &name) const { return lines_.found(name); } inline bool CommonValueExpressionDriver::isLookup(const word &name) const { return lookup_.found(name); } template <class Op,class Type> tmp<Field<bool> > CommonValueExpressionDriver::doCompare( const Field<Type> &a, Op op, const Field<Type> &b ) { assert(a.size()==b.size()); tmp<Field<bool> > res( new Field<bool>(a.size(),false) ); forAll(res(),i) { res()[i]=op(a[i],b[i]); } return res; } template <class Op> tmp<Field<bool> > CommonValueExpressionDriver::doLogicalOp( const Field<bool> &a, Op op, const Field<bool> &b ) { assert(a.size()==b.size()); tmp<Field<bool> > res( new Field<bool>(a.size(),false) ); forAll(res(),i) { res()[i]=op(a[i],b[i]); } return res; } template<class Type> tmp<Field<Type> > CommonValueExpressionDriver::doConditional( const Field<bool> &d, const Field<Type> &yes, const Field<Type> &no ) { assert(yes.size()==no.size() && d.size()==yes.size()); tmp<Field<Type> > res( new Field<Type>(yes.size()) ); forAll(res(),i) { res()[i] = d[i] ? yes[i] : no[i]; } return res; } tmp<Field<bool> > CommonValueExpressionDriver::doLogicalNot( const Field<bool> &a ) { tmp<Field<bool> > res( new Field<bool>(a.size()) );; forAll(res(),i) { res()[i] = a[i]; } return res; } template<class Location> void CommonValueExpressionDriver::error ( const Location& l, const std::string& m ) { std::ostringstream buff; buff << l; std::string place=" "; std::string place2="-"; for(unsigned int i=0;i<l.begin.column;i++) { place+=" "; place2+="-"; } bool firstArrow=true; for(unsigned int i=l.begin.column;i<l.end.column;i++) { place+="^"; if(firstArrow) { place2+="|"; firstArrow=false; } else { place2+=" "; } } for(unsigned int i=l.end.column;i<content_.size();i++) { // place+=" "; } FatalErrorInFunction // << CML::args.executable() << " Parser Error for driver " << type() << " at " << buff.str() << " :" << m << CML::endl << content_ << CML::endl << place.c_str() << CML::endl << place2.c_str() << CML::endl << getContextString().c_str() << CML::exit(CML::FatalError); // CML::Pout << buff.str() << ": " << m << CML::endl; } template<class Type> Type CommonValueExpressionDriver::calcWeightedAverage( const Field<Type> &result ) const { const scalarField weights( this->weights( result.size(), this->result().isPoint() ) ); const scalar wSum=gSum(weights); const Type tSum=gSum(weights*result); return tSum/wSum; } template<class T> void CommonValueExpressionDriver::addUniformVariable( const word &name, const T &val ) { ExpressionResult e; e.setSingleValue(val); variables_.set(name,e); } } // ************************************************************************* //
29.230198
102
0.423519
[ "mesh", "object" ]
9ac7135eef1ce53a0cbd9a438aa07cf54e98975b
757
cc
C++
actions/mine.cc
matis11/po-robot-wars
619cfc68d568da9bbf55926281771ee2927fa6a8
[ "Apache-2.0" ]
1
2016-01-11T16:49:08.000Z
2016-01-11T16:49:08.000Z
actions/mine.cc
matis11/po-robot-wars
619cfc68d568da9bbf55926281771ee2927fa6a8
[ "Apache-2.0" ]
null
null
null
actions/mine.cc
matis11/po-robot-wars
619cfc68d568da9bbf55926281771ee2927fa6a8
[ "Apache-2.0" ]
null
null
null
#include "actions/mine.h" #include "robots/robot.h" #include "fields/field.h" #include "robots/warehouse.h" #include "resources/oil.h" #include "logic/game.h" #include "logic/resourceset.h" using namespace robots; using namespace actions; using namespace resources; using namespace logic; using namespace fields; void mine::executeaction() { if (!verifyparameters()) { return; } resourceset fuelneeds; fuelneeds.set<oil>(1); object->loadedresources -= fuelneeds; resourceset product = object->myposition->produce(+object->loadedresources, object->getmaxcapacity()); object->loadedresources += product; } bool mine::verifyparameters() { return action::verifyparameters() && (object->myposition->canmine(object)); }
26.103448
106
0.721268
[ "object" ]
9ac9b9784de1ddecd433f6b9358f1f82ff702b1d
6,116
cpp
C++
deps/twlib/tw_task.cpp
armPelionEdge/grease-log-client
61deb80c37730ba53bf036c32ff1455ee102f781
[ "MIT" ]
1
2016-12-13T10:14:23.000Z
2016-12-13T10:14:23.000Z
deps/twlib/tw_task.cpp
armPelionEdge/grease-log-client
61deb80c37730ba53bf036c32ff1455ee102f781
[ "MIT" ]
1
2021-05-26T21:26:24.000Z
2021-05-27T14:44:42.000Z
deps/twlib/tw_task.cpp
armPelionEdge/grease-log-client
61deb80c37730ba53bf036c32ff1455ee102f781
[ "MIT" ]
2
2019-04-09T16:18:21.000Z
2019-07-02T20:20:29.000Z
/* * tw_task.cpp * * Created on: Nov 23, 2011 * Author: ed * (c) 2011, WigWag LLC */ #include <TW/tw_task.h> #include <TW/tw_sema.h> using namespace TWlib; BaseTask::BaseTask() : _running( false ), _completed( false ), _thrd_retval( NULL ), _lwp_num( 0 ), _thread_mutex() { _workdat._name = NULL; } /* BaseTask::BaseTask(TaskManager *tmgr) : _running( false ), _completed( false ), _thrd_retval( NULL ), _lwp_num( 0 ) { tmgr->addTask(this); } */ /** @return returns the thread's return value if its complete. NULL otherwise. */ long BaseTask::getLWP() { long ret = false; _thread_mutex.acquire(); ret = _lwp_num; _thread_mutex.release(); return ret; } /** * Starts the task's thread. * @param val * @return returns 0 on success. Returns value is the same as that of pthread_create() */ int BaseTask::startTask(void *val) { int ret = -1; bool start = false; _thread_mutex.acquire(); if(!_running) start = true; _thread_mutex.release(); if (start) { _workdat._param = val; _workdat._task = this; ret = pthread_create(&_pthread_dat, NULL, do_work, &_workdat); if (ret == 0) { _thread_mutex.acquire(); _running = true; _thread_mutex.release(); } } return ret; } /// @param s a NULL terminated string. A copy will be made, and will become the Thread's 'name' void BaseTask::nameTask( const char *s ) { _thread_mutex.acquire(); if(_workdat._name) TWTaskAllocator::free(_workdat._name); _workdat._name = (char *) TWTaskAllocator::malloc(strlen(s) + 1); ::strcpy(_workdat._name,s); _thread_mutex.release(); } /// @return a pointer to the given name of the string. If no name was given, this will be NULL. char *BaseTask::name() { char *ret = NULL; _thread_mutex.acquire(); ret = _workdat._name; _thread_mutex.release(); return ret; } /// @param s A std::string to append the Task's 'name' to. The string is assumed to be valid, /// and will not be erased - only appended to. /// If the Task does not have an assigned 'name' one will be created using the LWP number. /// @return reference to same string. std::string &BaseTask::appendName(std::string &s) { char *n = NULL; _thread_mutex.acquire(); n = _workdat._name; _thread_mutex.release(); if(n) { s.append(n); } else { char b[20]; string s2("Task LWP: "); s2.append(TWlib::convInt(b,(int) getLWP(),20)); s.append(s2); } return s; } /** * this is the function handed to pthread_create. taskdat points to a Task<T>::workdata_t struct * which has both a parameter for the work() function, plus a pointer to the task object * @param taskdat */ void *BaseTask::do_work( void *workdat ) { struct workdata_t *dat = (struct workdata_t *) workdat; dat->_task->_lwp_num = ::_TW_getLWPnum(); // get the LWP number and assign it void *ret = dat->_task->work( dat->_param ); // pthread_mutex_lock(&dat->_task->_pthread_mutex); dat->_task->_thread_mutex.acquire(); dat->_task->_completed = true; // pthread_mutex_unlock(&dat->_task->_pthread_mutex); dat->_task->_thread_mutex.release(); return ret; } /** @return returns true if the thread has been started. Returns false if threads is not started, or has ended. */ bool BaseTask::isRunning() { bool ret = false; // pthread_mutex_lock(&_pthread_mutex); _thread_mutex.acquire(); ret = _running; _thread_mutex.release(); // pthread_mutex_unlock(&_pthread_mutex); return ret; } /** @return returns true if the thread has executed & finished. */ bool BaseTask::isCompleted() { bool ret = false; // pthread_mutex_lock(&_pthread_mutex); _thread_mutex.acquire(); ret = _completed; _thread_mutex.release(); // pthread_mutex_unlock(&_pthread_mutex); return ret; } void *BaseTask::waitForTask(void) { int ret = pthread_join( _pthread_dat, &_thrd_retval ); return _thrd_retval; } void *BaseTask::waitForTask(TimeVal &t) { // NOTABLE Not portable - Linux only // http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_tryjoin_np.3.html int ret = pthread_timedjoin_np( _pthread_dat, &_thrd_retval, t.timespec() ); return _thrd_retval; } void TaskManager::addTask( BaseTask *t ) { _list.add(t); #ifdef _TW_TASK_DEBUG_THREADS_ TW_DEBUG_LT("Adding thread LWP %d to TaskManager %x\n",t->getLWP(), this); #endif } void TaskManager::joinAll() { tw_safeFIFO<BaseTask *,Allocator<Alloc_Std> >::iter _iter; _list.startIter(_iter); BaseTask *task; #ifdef _TW_TASK_DEBUG_THREADS_ TW_DEBUG_LT("Manager %x @ joinAll()\n",this); #endif while(_iter.getNext(task)) { #ifdef _TW_TASK_DEBUG_THREADS_ TW_DEBUG_LT("Waiting for thread LWP %d ...\n",task->getLWP()); #endif task->waitForTask(); #ifdef _TW_TASK_DEBUG_THREADS_ TW_DEBUG_LT("Thread LWP %d done.\n",task->getLWP()); #endif } _list.releaseIter(_iter); } void TaskManager::joinAll(TimeVal &v) { tw_safeFIFO<BaseTask *,Allocator<Alloc_Std> >::iter _iter; _list.startIter(_iter); BaseTask *task; while(_iter.getNext(task)) { #ifdef _TW_TASK_DEBUG_THREADS_ TW_DEBUG_LT("Waiting for thread LWP %d or timeout.\n",task->getLWP()); #endif task->waitForTask(v); #ifdef _TW_TASK_DEBUG_THREADS_ TW_DEBUG_LT("Thread LWP %d done.\n",task->getLWP()); #endif } _list.releaseIter(_iter); } string &TaskManager::dumpThreadInfo(string &s) { char buf[20]; s.clear(); // TW_DEBUG("dumpthreadinfo\n",NULL); s.append("TaskManager dump:\n"); tw_safeFIFO<BaseTask *,Allocator<Alloc_Std> >::iter _iter; _list.startIter(_iter); BaseTask *task; int c = 0; while(_iter.getNext(task)) { // TW_DEBUG("dumpthreadinfo.getNext\n",NULL); s.append(" "); s.append(TWlib::convInt(buf,(int) c,20)); s.append(": "); task->appendName(s); // TW_DEBUG("dumpthreadinfo.afterappendname\n",NULL); s.append(" (LWP:"); s.append(TWlib::convInt(buf,(int) task->getLWP(),20)); // TW_DEBUG("dumpthreadinfo.afterconvint\n",NULL); s.append(")\n"); } _list.releaseIter(_iter); // TW_DEBUG("dumpthreadinfo.return\n",NULL); return s; } void TaskManager::shutdownAll() { tw_safeFIFO<BaseTask *,Allocator<Alloc_Std> >::iter _iter; _list.startIter(_iter); BaseTask *task; while(!_iter.getNext(task)) { task->shutdown(); } _list.releaseIter(_iter); }
25.377593
111
0.69915
[ "object" ]
9acef037dff0741262992c5b6d3cc7a93b638841
7,176
hpp
C++
EncDec.hpp
mdejong/AdaptiveLosslessPrediction
8bd84290c1db10192c2102ddbeb5cca24dcef993
[ "BSD-3-Clause" ]
3
2017-01-25T18:13:59.000Z
2019-05-06T09:13:34.000Z
EncDec.hpp
mdejong/AdaptiveLosslessPrediction
8bd84290c1db10192c2102ddbeb5cca24dcef993
[ "BSD-3-Clause" ]
null
null
null
EncDec.hpp
mdejong/AdaptiveLosslessPrediction
8bd84290c1db10192c2102ddbeb5cca24dcef993
[ "BSD-3-Clause" ]
null
null
null
// // EncDec.hpp // // Copyright 2016 Mo DeJong. // // See LICENSE for terms. // // C++ templates for encoding and decoding numbers as bytes. #include "assert.h" #include <vector> #include <unordered_map> using namespace std; // Encode a signed delta +-N as a positive number starting at zero where // +1 is 1 and -1 is 2 and so on. static inline uint32_t convertSignedZeroDeltaToUnsigned(int delta) { if (delta == 0) { return 0; } else if (delta > 0) { // Positive value // 1 -> 1 // 2 -> 3 // 3 -> 5 return (delta * 2) - 1; } else { // Negative value // -1 -> 2 // -2 -> 4 // -3 -> 6 return (delta * -2); } } static inline int convertUnsignedZeroDeltaToSigned(uint32_t delta) { if (delta == 0) { return 0; } else if ((delta & 0x1) == 1) { // Odd value means positive delta // 1 -> 1 // 3 -> 2 // 5 -> 3 return (int) ((delta >> 1) + 1); } else { // Even value means negative delta // 2 -> -1 // 4 -> -2 // 6 -> -3 int s = (delta >> 1); return (s * -1); } } // Convert a signed delta to an unsigned delta that takes // care to treat the special case of the largest possible // value as a negative number. static inline uint32_t convertSignedZeroDeltaToUnsignedNbits(int delta, const int numBitsMax) { const unsigned int unsignedMaxValue = ~((~((unsigned int)0)) << numBitsMax); const unsigned int absMaxValue = (~((~((unsigned int)0)) << (numBitsMax - 1))) + 1; const int signedMaxValue = -1 * absMaxValue; if (delta == signedMaxValue) { // For example, at 4 bits the maximum value is -8 -> 0xFF return unsignedMaxValue; } else { return convertSignedZeroDeltaToUnsigned(delta); } } static inline int convertUnsignedZeroDeltaToSignedNbits(uint32_t delta, const int numBitsMax) { const unsigned int unsignedMaxValue = ~((~((unsigned int)0)) << numBitsMax); const unsigned int absMaxValue = (~((~((unsigned int)0)) << (numBitsMax - 1))) + 1; const int signedMaxValue = -1 * absMaxValue; if (delta == unsignedMaxValue) { // For example, at 4 bits the maximum value is 0xFF -> -8 return (int)signedMaxValue; } else { return convertUnsignedZeroDeltaToSigned(delta); } } // When dealing with a table of N values, a general purpose "wraparound" // delta from one element to another can be encoded to take the size of // table into account. For example, for a table of 3 values (0 10 30) // a delta from (30 to 0) can be represented by -2 but a smaller rep // would be +1 where adding one to the offset wraps around to the start. #define WRAPPED_ALLOW_N_1 1 static inline int convertToWrappedTableDelta(unsigned int off1, unsigned int off2, const unsigned int N) { const bool debug = false; if (debug) { printf("convertToWrappedTableDelta %d %d and N = %d\n", off1, off2, N); } #if defined(DEBUG) # if defined(WRAPPED_ALLOW_N_1) # else assert(N > 1); # endif // WRAPPED_ALLOW_N_1 assert(off1 < N); assert(off2 < N); #endif // DEBUG // delta indicates move needed to adjust off1 to match off2 int delta = off2 - off1; if (debug) { printf("delta %d\n", (int)delta); } #if defined(DEBUG) if (abs(delta) >= N) { // For example, 4 bit range is (-15, 15) assert(0); } #endif // DEBUG // For (-15, 15) mid = 7, negMid = -8 // For (-3, 3) mid = 1, negMid = -2 const int mid = N >> 1; // N / 2 int negMid = mid * -1; if ((N & 0x1) == 0) { negMid += 1; if (debug) { printf("even wrap range adjust upward %d\n", (int)negMid); } } if (debug) { printf("wrap range (%d,0,%d)\n", (int)negMid, (int)mid); } int wrappedDelta = delta; if (delta > mid) { wrappedDelta = ((int)N - delta) * -1; if (debug) { printf("wrappedDelta : %d - %d = %d\n", (int)N, (int)delta, wrappedDelta); } } else if (delta < negMid) { // Note that a positive delta that reaches the same offset is preferred // as compare to a negative delta. wrappedDelta = (int)N + delta; if (debug) { printf("wrappedDelta : %d + %d = %d\n", (int)N, (int)delta, wrappedDelta); } } return wrappedDelta; } // A wrapped table delta should be added to the previous offset // to regenerate a table offset. The returned value is the table // offset after the delta has been applied. static inline uint32_t convertFromWrappedTableDelta(uint32_t offset, int wrappedDelta, const unsigned int N) { const bool debug = false; #if defined(DEBUG) # if defined(WRAPPED_ALLOW_N_1) # else assert(N > 1); # endif // WRAPPED_ALLOW_N_1 assert(offset < N); if (abs(wrappedDelta) > N) { // For example, 4 bit range is (-15, 15) assert(0); } #endif // DEBUG // For (-15, 15) mid = 7, negMid = -8 // For (-3, 3) mid = 1, negMid = -2 //const int mid = N >> 1; // N / 2 //const int negMid = (mid + 1) * -1; int signedOffset = (int)offset + wrappedDelta; if (debug) { printf("offset + delta : %d + %d = %d\n", (int)offset, (int)wrappedDelta, signedOffset); } if (signedOffset < 0) { // Wrapped around from zero to the end signedOffset += N; } else if (signedOffset >= N) { // Wrapped around from end to zero signedOffset -= N; } if (debug) { printf("adjusted to (0,N): %d\n", (int)signedOffset); } #if defined(DEBUG) assert(signedOffset >= 0); assert(signedOffset < N); #endif // DEBUG return (uint32_t) signedOffset; } // Convert table offsets to signed offsets that are then represented // by unsigned 32 bit values. template <typename T> vector<uint32_t> convertToWrappedUnsignedTableDeltaVector(const vector<T> & inVec, const unsigned int N) { int prev; vector<uint32_t> deltas; deltas.reserve(inVec.size()); // The first value is always a delta from zero, so handle it before // the loop logic. { int val = inVec[0]; deltas.push_back(val); prev = val; } int maxi = (int) inVec.size(); for (int i = 1; i < maxi; i++) { int cur = inVec[i]; int wrappedDelta = convertToWrappedTableDelta(prev, cur, N); uint32_t unsignedDelta = convertSignedZeroDeltaToUnsigned(wrappedDelta); deltas.push_back(unsignedDelta); prev = cur; } return std::move(deltas); } // FIXME: need to supply table N values for each block // Read unsigned value, convert to signed, then unwrap based on table N static inline vector<int> convertFromWrappedUnsignedTableDeltaVector(const vector<uint32_t> & inVec, const unsigned int N) { int prev; vector<int> offsets; offsets.reserve(inVec.size()); // The first value is always a delta from zero, so handle it before // the loop logic. { int val = inVec[0]; offsets.push_back(val); prev = val; } const int maxi = (int) inVec.size(); for (int i = 1; i < maxi; i++) { int unsignedDelta = inVec[i]; int wrappedDelta = convertUnsignedZeroDeltaToSigned(unsignedDelta); uint32_t offset = convertFromWrappedTableDelta(prev, wrappedDelta, N); offsets.push_back(offset); prev = offset; } return std::move(offsets); }
23.683168
96
0.626672
[ "vector" ]
9ae146c34da1d932083bc788138a6ed22467a4c6
21,252
cpp
C++
Source/MaliOC/Private/MaliOCReportWidgetGenerator.cpp
ARM-software/malioc-ue4
9bb9ec11739d5960d1d7dbd5dce2e68bcfcd5add
[ "Apache-2.0" ]
14
2019-02-19T09:36:29.000Z
2021-12-13T03:24:29.000Z
Source/MaliOC/Private/MaliOCReportWidgetGenerator.cpp
QPC-database/malioc-ue4
9bb9ec11739d5960d1d7dbd5dce2e68bcfcd5add
[ "Apache-2.0" ]
2
2020-06-28T09:16:10.000Z
2022-03-09T10:20:49.000Z
Source/MaliOC/Private/MaliOCReportWidgetGenerator.cpp
QPC-database/malioc-ue4
9bb9ec11739d5960d1d7dbd5dce2e68bcfcd5add
[ "Apache-2.0" ]
9
2019-09-13T11:22:45.000Z
2021-07-04T00:31:52.000Z
/* * Copyright 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MaliOCPrivatePCH.h" #include "MaliOCReportWidgetGenerator.h" #include "MaliOCAsyncReportGenerator.h" #include "SExpandableArea.h" #include "MaliOCStyle.h" /* Standard widget padding */ static const FMargin WidgetPadding(3.0f, 2.0f, 3.0f, 2.0f); bool FReportWidgetGenerator::IsCompilationComplete() const { return Generator->GetProgress() == FAsyncReportGenerator::EProgress::COMPILATION_COMPLETE; } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION; FReportWidgetGenerator::FReportWidgetGenerator(TSharedRef<FAsyncReportGenerator> ReportGenerator) : Generator(ReportGenerator) { // Construct the throbber widget ThrobberWidget = SNew(SVerticalBox) + SVerticalBox::Slot() .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(SVerticalBox) + SVerticalBox::Slot() .Padding(WidgetPadding) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .AutoHeight() [ SNew(SThrobber) .NumPieces(7) ] + SVerticalBox::Slot() .Padding(WidgetPadding) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .AutoHeight() [ SAssignNew(ThrobberTextLine1, SRichTextBlock) .TextStyle(FMaliOCStyle::Get(), "Text.Normal") .Justification(ETextJustify::Type::Center) ] + SVerticalBox::Slot() .Padding(WidgetPadding) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .AutoHeight() [ SAssignNew(ThrobberTextLine2, SRichTextBlock) .TextStyle(FMaliOCStyle::Get(), "Text.Normal") .Justification(ETextJustify::Type::Center) ] ]; } /* Convert a string array into a list of strings widget */ TSharedRef<SWidget> GenerateFStringListView(const TArray<TSharedRef<FString>>& StringArray) { TSharedRef<SVerticalBox> verticalBox = SNew(SVerticalBox); for (const auto& string : StringArray) { verticalBox->AddSlot() .AutoHeight() [ SNew(SRichTextBlock) .Text(FText::FromString(*string)) .TextStyle(FMaliOCStyle::Get(), "Text.Normal") .DecoratorStyleSet(FMaliOCStyle::Get().Get()) .AutoWrapText(true) ]; } return verticalBox; } /* Add the source code box to any vertical box*/ void AddSourceCodeToVerticalBox(TSharedPtr<SVerticalBox>& VerticalBox, const FString& SourceCode) { if (SourceCode.Len() > 0) { // Replace tabs with two spaces for display in the widget, as the rich text block doesn't support tabs FString spacedSource = SourceCode.Replace(TEXT("\t"), TEXT(" ")); VerticalBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; VerticalBox->AddSlot() .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Source Code"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(true) .Padding(WidgetPadding) .BodyContent() [ SNew(SRichTextBlock) .Text(FText::FromString(spacedSource)) .TextStyle(FMaliOCStyle::Get(), "Text.Normal") .AutoWrapText(true) ] ]; } } /* Construct the error widget from an array of errors*/ TSharedRef<SWidget> ConstructErrorWidget(const TArray<TSharedRef<FMaliOCReport::FErrorReport>>& Errors) { TSharedRef<SVerticalBox> errorBox = SNew(SVerticalBox); for (const auto& error : Errors) { TSharedPtr<SVerticalBox> errorWarningBox = nullptr; errorBox->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(error->TitleName)) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ SAssignNew(errorWarningBox, SVerticalBox) ] ]; // Print the details of the shader (such as frequency) errorWarningBox->AddSlot() .AutoHeight() [ GenerateFStringListView(error->Details) ]; if (error->Errors.Num() > 0) { errorWarningBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; errorWarningBox->AddSlot() .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Errors"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ GenerateFStringListView(error->Errors) ] ]; } if (error->Warnings.Num() > 0) { errorWarningBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; errorWarningBox->AddSlot() .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Warnings"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ GenerateFStringListView(error->Warnings) ] ]; } AddSourceCodeToVerticalBox(errorWarningBox, error->SourceCode); } return errorBox; } /* Generate a Midgard stats table */ TSharedRef<SVerticalBox> GenerateMidgardStatsTable(const TSharedRef<FMaliOCReport::FMidgardReport::FRenderTarget>& RenderTarget) { TSharedRef<SVerticalBox> rtBox = SNew(SVerticalBox); int index = 0; // Four rows, 5 columns for (int i = 0; i < 4; i++) { TSharedPtr<SHorizontalBox> curRow = nullptr; rtBox->AddSlot() .AutoHeight() [ SAssignNew(curRow, SHorizontalBox) ]; const float columnWidths[] = { 2.5f, 1.0f, 1.0f, 1.0f, 2.0f }; const float widthScaleFactor = 50.0f; for (int j = 0; j < 5; j++) { curRow->AddSlot() .FillWidth(columnWidths[j]) .MaxWidth(columnWidths[j] * widthScaleFactor) [ SNew(STextBlock) .Text(*RenderTarget->StatsTable[index]) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ]; index++; } } rtBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; rtBox->AddSlot() .AutoHeight() [ GenerateFStringListView(RenderTarget->ExtraDetails) ]; return rtBox; }; /* Make the Midgard dump widget (where we dump the statistics for Midgard compilation) */ TSharedRef<SWidget> ConstructMidgardDumpWidget(const TArray<TSharedRef<FMaliOCReport::FMidgardReport>>& Reports, bool DumpSourceCode) { TSharedRef<SVerticalBox> midgardBox = SNew(SVerticalBox); for (const auto& report : Reports) { TSharedPtr<SVerticalBox> reportWarningBox = nullptr; midgardBox->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(report->TitleName)) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .ToolTipText(FText::FromString(report->TitleName)) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ SAssignNew(reportWarningBox, SVerticalBox) ] ]; // Print the details of the shader (such as frequency) reportWarningBox->AddSlot() .AutoHeight() [ GenerateFStringListView(report->Details) ]; // If there's only one render target, don't make an expandable area if (report->RenderTargets.Num() == 1) { reportWarningBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; reportWarningBox->AddSlot() .AutoHeight() [ GenerateMidgardStatsTable(report->RenderTargets[0]) ]; } else { for (const auto& rt : report->RenderTargets) { reportWarningBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; reportWarningBox->AddSlot() .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(FString::Printf(TEXT("Render Target %u"), rt->Index))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ GenerateMidgardStatsTable(rt) ] ]; } } // Dump the warnings if (report->Warnings.Num() > 0) { reportWarningBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; reportWarningBox->AddSlot() .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Warnings"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ GenerateFStringListView(report->Warnings) ] ]; } if (DumpSourceCode) { AddSourceCodeToVerticalBox(reportWarningBox, report->SourceCode); } } return midgardBox; } /* Make the Utgard dump widget (where we dump the statistics for Utgard compilation) */ TSharedRef<SWidget> ConstructUtgardDumpWidget(const TArray<TSharedRef<FMaliOCReport::FUtgardReport>>& Reports, bool DumpSourceCode) { TSharedRef<SVerticalBox> utgardBox = SNew(SVerticalBox); for (const auto& report : Reports) { TSharedPtr<SVerticalBox> reportWarningBox = nullptr; utgardBox->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(report->TitleName)) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .ToolTipText(FText::FromString(report->TitleName)) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ SAssignNew(reportWarningBox, SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ GenerateFStringListView(report->Details) ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SSeparator) ] + SVerticalBox::Slot() .AutoHeight() [ GenerateFStringListView(report->ExtraDetails) ] ] ]; // Dump the warnings if (report->Warnings.Num() > 0) { reportWarningBox->AddSlot() .AutoHeight() [ SNew(SSeparator) ]; reportWarningBox->AddSlot() .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Warnings"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .Padding(WidgetPadding) .BodyContent() [ GenerateFStringListView(report->Warnings) ] ]; } if (DumpSourceCode) { AddSourceCodeToVerticalBox(reportWarningBox, report->SourceCode); } } return utgardBox; } /* Create the top level report widget */ TSharedPtr<SWidget> ConstructReportWidget(const FAsyncReportGenerator& Generator) { TSharedPtr<SVerticalBox> Widget = nullptr; TSharedPtr<SWidget> ReportWidget = SNew(SScrollBox) + SScrollBox::Slot() [ SAssignNew(Widget, SVerticalBox) ]; auto Report = Generator.GetReport(); // First show any errors, if there are any if (Report->ErrorList.Num() > 0) { Widget->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Error Summary"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .BorderBackgroundColor(FLinearColor(0.5f, 0.5f, 0.5f, 1.0f)) .Padding(WidgetPadding) .BodyContent() [ ConstructErrorWidget(Report->ErrorList) ] ]; } // Next show Midgard reports if there are any if (Report->MidgardReports.Num() > 0) { Widget->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Statistics Summary"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .BorderBackgroundColor(FLinearColor(0.5f, 0.5f, 0.5f, 1.0f)) .Padding(WidgetPadding) .BodyContent() [ SNew(SVerticalBox) + SVerticalBox::Slot() .Padding(WidgetPadding) .AutoHeight() [ GenerateFStringListView(Report->ShaderSummaryStrings) ] + SVerticalBox::Slot() .AutoHeight() [ ConstructMidgardDumpWidget(Report->MidgardSummaryReports, false) ] ] ]; // Dump the rest of the shaders by vertex factory name TMap<FString, TArray<TSharedRef<FMaliOCReport::FMidgardReport>>> VertexFactoryNames; for (auto& report : Report->MidgardReports) { VertexFactoryNames.FindOrAdd(report->VertexFactoryName).Add(report); } for (const auto& name : VertexFactoryNames) { Widget->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(FString::Printf(TEXT("All %s"), *name.Key))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(true) .BorderBackgroundColor(FLinearColor(0.5f, 0.5f, 0.5f, 1.0f)) .Padding(WidgetPadding) .BodyContent() [ ConstructMidgardDumpWidget(name.Value, true) ] ]; } } // Next show Utgard reports, if there are any. These should be mutually exclusive with Midgard reports if (Report->UtgardReports.Num() > 0) { Widget->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(TEXT("Statistics Summary"))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(false) .BorderBackgroundColor(FLinearColor(0.5f, 0.5f, 0.5f, 1.0f)) .Padding(WidgetPadding) .BodyContent() [ SNew(SVerticalBox) + SVerticalBox::Slot() .Padding(WidgetPadding) .AutoHeight() [ GenerateFStringListView(Report->ShaderSummaryStrings) ] + SVerticalBox::Slot() .AutoHeight() [ ConstructUtgardDumpWidget(Report->UtgardSummaryReports, false) ] ] ]; // Dump the rest of the shaders by vertex factory name TMap<FString, TArray<TSharedRef<FMaliOCReport::FUtgardReport>>> VertexFactoryNames; for (auto& report : Report->UtgardReports) { VertexFactoryNames.FindOrAdd(report->VertexFactoryName).Add(report); } for (const auto& name : VertexFactoryNames) { Widget->AddSlot() .Padding(WidgetPadding) .AutoHeight() [ SNew(SExpandableArea) .AreaTitle(FText::FromString(FString::Printf(TEXT("All %s"), *name.Key))) .AreaTitleFont(FEditorStyle::GetFontStyle(TEXT("DetailsView.CategoryFontStyle"))) .InitiallyCollapsed(true) .BorderBackgroundColor(FLinearColor(0.5f, 0.5f, 0.5f, 1.0f)) .Padding(WidgetPadding) .BodyContent() [ ConstructUtgardDumpWidget(name.Value, true) ] ]; } } return ReportWidget; } END_SLATE_FUNCTION_BUILD_OPTIMIZATION; TSharedRef<SWidget> FReportWidgetGenerator::GetWidget() { auto progress = Generator->GetProgress(); if (progress == FAsyncReportGenerator::EProgress::COMPILATION_COMPLETE) { if (!CachedReportWidget.IsValid()) { // Make the widget once then cache it CachedReportWidget = ConstructReportWidget(Generator.Get()); } return CachedReportWidget.ToSharedRef(); } else { // Set the throbber text depending on how far through compilation we are if (progress == FAsyncReportGenerator::EProgress::CROSS_COMPILATION_IN_PROGRESS) { ThrobberTextLine1->SetText(FText::FromString(TEXT("Compiling HLSL to GLSL"))); ThrobberTextLine2->SetText(FText()); } else { check(progress == FAsyncReportGenerator::EProgress::MALIOC_COMPILATION_IN_PROGRESS); const auto oscProgress = Generator->GetMaliOCCompilationProgress(); ThrobberTextLine1->SetText(FText::FromString(TEXT("Compiling Shaders"))); ThrobberTextLine2->SetText(FText::FromString(FString::Printf(TEXT("%u / %u"), oscProgress.NumCompiledShaders, oscProgress.NumTotalShaders))); } return ThrobberWidget.ToSharedRef(); } }
34.332795
153
0.522633
[ "render" ]
9af0dadaea4ee71bfe4fa8a434260bd9fbe12ba8
6,912
cpp
C++
functions.cpp
ariaman5/snake_and_ladder
38b7b56b18251b4acaace288030d449cdaf7e74d
[ "MIT" ]
1
2018-01-26T02:58:48.000Z
2018-01-26T02:58:48.000Z
functions.cpp
ariaman5/snake_and_ladder
38b7b56b18251b4acaace288030d449cdaf7e74d
[ "MIT" ]
null
null
null
functions.cpp
ariaman5/snake_and_ladder
38b7b56b18251b4acaace288030d449cdaf7e74d
[ "MIT" ]
null
null
null
#include "header.h" #include <sstream> using namespace std; bool load_game( data::player &player , data::board &board , std::map <int , string> &graphical , std::vector <int> &dist , int &num_player , int &nrows , int &snake_count , int &ladder_count) { QString str = QDir::currentPath() ; if(!QDir(str + "/sound").exists() || !QDir(str + "/save").exists()) { return false; } if(!QDir(str + "/save/graphic").exists()) { return false; } if(!QDir(str + "/save/player").exists() || !QDir(str + "/save/board").exists()) { return false; } std::string self_path = str.toUtf8().constData(); try { char * buff = new char(1); ifstream input; string playerPath = self_path + "/save/player/pname" ; string boardPath = self_path + "/save/board/bholder"; string graphicPath = self_path + "/save/graphic/graphical"; string distPath = self_path + "/save/dist/distination"; input.open(boardPath.c_str() , ios_base::in); if(input.is_open()) { input>>nrows; input>>snake_count; input>>ladder_count; for(int i = 0 ; i< nrows*nrows ; i++) { input>>board.holder[i]; } input.close(); } else{ return false; } for(int i = 0 ; i<nrows * nrows ; i++) { dist.push_back(0); } input.open(distPath.c_str() , ios_base::in); if(input.is_open()) { for(int i = 0 ; i< nrows*nrows ; i++) { input>>dist[i]; } input.close(); } else{ return false; } input.open(graphicPath.c_str() , ios_base::in); if(input.is_open()) { string inp; int index; while(input>>inp) { index = stoi(inp); input>>inp; graphical[index]=inp; } input.close(); } else{ return false; } input.open(playerPath.c_str() , ios_base::in); if(input.is_open()) { input>>num_player; for(int i = 0 ; i<num_player ; i++) { input>>player.name[i]; } input.close(); } else{ return false; } playerPath = self_path + "/save/player/pcell" ; input.open(playerPath.c_str() , ios_base::in); if(input.is_open()) { for(int i = 0 ; i<num_player ; i++) { input>>player.cell[i]; } input.close(); } else{ return false; } playerPath = self_path + "/save/player/ppermit" ; input.open(playerPath.c_str() , ios_base::in); if(input.is_open()) { for(int i = 0 ; i<num_player ; i++) { input>>player.Play_Permit[i]; } input.close(); } else{ return false; } delete buff; } catch (const std::exception& e) { std::cout << e.what(); } return true; } bool save_game( data::player &player , data::board &board, std::map< int , std::string> &graphical , std::vector <int> &dist , int &num_player , int &nrows , int &snake_count , int &ladder_count) { QString str = QDir::currentPath() ; if(!QDir(str + "/sound").exists()) { QDir().mkdir(str + "/sound"); } if(!QDir(str + "/save").exists()) { QDir().mkdir(str + "/save"); } if(!QDir(str + "/save/player").exists()) { QDir().mkdir(str + "/save/player"); } if(!QDir(str + "/save/graphic").exists()) { QDir().mkdir(str + "/save/graphic"); } if(!QDir(str + "/save/dist").exists()) { QDir().mkdir(str + "/save/dist"); } if(!QDir(str + "/save/board").exists()) { QDir().mkdir(str + "/save/board"); } std::string self_path = str.toUtf8().constData(); try { char * buff = new char(1); fstream output; string playerPath = self_path + "/save/player/pname" ; string boardPath = self_path + "/save/board/bholder"; string graphicPath = self_path + "/save/graphic/graphical"; string distPath = self_path + "/save/dist/distination"; output.open(boardPath.c_str() , ios_base::out); if(output.is_open()) { output<<nrows<<endl; output<<snake_count<<endl; output<<ladder_count<<endl; for(int i = 0 ; i< nrows*nrows ; i++) { output<<board.holder[i]<<endl; } output.close(); } else{ return false; } output.open(distPath.c_str() , ios_base::out); if(output.is_open()) { for(int i = 0 ; i< nrows*nrows ; i++) { output<<dist[i]<<endl; } output.close(); } else{ return false; } output.open(graphicPath.c_str() , ios_base::out); if(output.is_open()) { for(auto iter = graphical.begin(); iter != graphical.end(); ++iter) { output<<iter->first<<" "<<iter->second<<endl; } output.close(); } else{ return false; } playerPath = self_path + "/save/player/pname" ; output.open(playerPath.c_str() , ios_base::out); if(output.is_open()) { output<<num_player<<endl; for(int i = 0 ; i<num_player ; i++) { output<<player.name[i]<<endl; } output.close(); } else{ return false; } playerPath = self_path + "/save/player/pcell" ; output.open(playerPath.c_str() , ios_base::out); if(output.is_open()) { for(int i = 0 ; i<num_player ; i++) { output<<player.cell[i]<<endl; } output.close(); } else{ return false; } playerPath = self_path + "/save/player/ppermit" ; output.open(playerPath.c_str() , ios_base::out); if(output.is_open()) { for(int i = 0 ; i<num_player ; i++) { output<<player.Play_Permit[i]<<endl; } output.close(); } else{ return false; } delete buff; } catch (const std::exception& e) { std::cout << e.what(); } return true; } void nsleep(int n) { struct timespec req ; req.tv_sec = 0; req.tv_nsec = n * 1000000L; nanosleep(&req, (struct timespec *)NULL); }
26.181818
196
0.463686
[ "vector" ]
b106300307ed65342d6bd1f15ef7cb66556f464b
9,816
cpp
C++
src/Rasterizer.cpp
williamsandst/theia-software-rasterizer
75cfff3ca1e822e3cef25a86a846f4994c53ab17
[ "MIT" ]
null
null
null
src/Rasterizer.cpp
williamsandst/theia-software-rasterizer
75cfff3ca1e822e3cef25a86a846f4994c53ab17
[ "MIT" ]
null
null
null
src/Rasterizer.cpp
williamsandst/theia-software-rasterizer
75cfff3ca1e822e3cef25a86a846f4994c53ab17
[ "MIT" ]
null
null
null
#include "Rasterizer.h" void Rasterizer::createPolyFragments(vector<Fragment>* fragments, Vertex v1, Vertex v2, Vertex v3, int viewWidth, int viewHeight) { //Generates a fragment polygon using homogenous coordinates. //In the future this will use recursive polygon clipping and bresenhams line algorithm //Should I be doing culling in here? I'm not sure? What if I want to move around the fragments like some crazy person? Vector4i bBox = findBoundingBox(Vector2i(ceil(v1.point[0]), ceil(v1.point[1])), Vector2i(ceil(v2.point[0]), ceil(v2.point[1])), Vector2i(ceil(v3.point[0]), ceil(v3.point[1])), viewWidth, viewHeight); if (bBox[2] == 0 || bBox[3] == 0) return; //No polygon visible/ nothing to draw float z, w; Vector3f wInverse = Vector3f(1 / v1.point[3], 1 / v2.point[3], 1 / v3.point[3]); vector<Vector2f> uvDivided = vector<Vector2f>{ v1.UVCoord / v1.point[3], v2.UVCoord / v2.point[3], v3.UVCoord / v3.point[3] }; vector<Vector4f> colorDivided = vector<Vector4f>{ v1.color / v1.point[3], v2.color / v2.point[3], v3.color / v3.point[3] }; vector<Vector4f> normalDivided = vector<Vector4f>{ v1.normal / v1.point[3], v2.normal / v2.point[3], v3.normal / v3.point[3] }; Vector4f oldNormal; Vector3f bc, point, normal; Vector4f color; Vector2f UVCoord; for (int y = bBox[1]; y < bBox[3]; y++) { for (int x = bBox[0]; x < bBox[2]; x++) { //Calculate barycentric coordinates bc = barycentric(v1.point, v2.point, v3.point, x, y); if (bc[0]<0 || bc[1]<0 || bc[2]<0) continue; //Point is not inside triangle //Depth z = v1.point[2] * bc[0] + v2.point[2] * bc[1] + v3.point[2] * bc[2]; point = Vector3f(x, y, z); //Perspective correct interpolation w = 1 / (bc[0] * wInverse[0] + bc[1] * wInverse[1] + bc[2] * wInverse[2]); UVCoord = (bc[0] * uvDivided[0] + bc[1] * uvDivided[1] + bc[2] * uvDivided[2]) * w; color = (bc[0] * colorDivided[0] + bc[1] * colorDivided[1] + bc[2] * colorDivided[2]) * w; oldNormal = (bc[0] * normalDivided[0] + bc[1] * normalDivided[1] + bc[2] * normalDivided[2]) * w; normal = Vector3f(oldNormal[0], oldNormal[1], oldNormal[2]); fragments->push_back(Fragment(point, normal, UVCoord, color)); } } } float Rasterizer::cross2D(float x0, float y0, float x1, float y1) { return (x0 * y1 - x1 * y0); } float Rasterizer::lineSide2D(Vector2f p, Vector2f lineFrom, Vector2f lineTo) { return cross2D(p[0] - lineFrom[0], p[1] - lineFrom[1], lineTo[0] - lineFrom[0], lineTo[1] - lineFrom[1]); } Vector2f Rasterizer::interpolateBCVec2(Vector3f &bc, float& w, vector<Vector2f>& value) { return (bc[0] * value[0] + bc[1] * value[1] + bc[2] * value[2]) * w; } Vector3f Rasterizer::interpolateBCVec3(Vector3f &bc, float& w, vector<Vector3f>& value) { return (bc[0] * value[0] + bc[1] * value[1] + bc[2] * value[2]) * w; } Vector4f Rasterizer::interpolateBCVec4(Vector3f &bc, float& w, vector<Vector4f>& value) { return (bc[0] * value[0] + bc[1] * value[1] + bc[2] * value[2]) * w; } void Rasterizer::scanLine(vector<Fragment>* fragments, int y, Vector2f pa, Vector2f pb, Vector2f pc, Vector2f pd, Vertex v1, Vertex v2, Vertex v3, VertexScanAttrib *vDiv, int maxWidth, Framebuffer& depthBuffer, bool earlyDepthTest) { // Thanks to current Y, we can compute the gradient to compute others values like // the starting X (sx) and ending X (ex) to draw between // if pa.Y == pb.Y or pc.Y == pd.Y, gradient is forced to 1 float gradient1 = pa[1] != pb[1] ? (y - pa[1]) / (pb[1] - pa[1]) : 1; float gradient2 = pc[1] != pd[1] ? (y - pc[1]) / (pd[1] - pc[1]) : 1; int sx = max(0, (int)interpolate(pa[0], pb[0], gradient1)); int ex = min(maxWidth, (int)interpolate(pc[0], pd[0], gradient2) + 1); Vector3f bc; Fragment frag; float z, w; // drawing a line from left (sx) to right (ex) for (int x = sx; x < ex; x++) { bc = barycentric(v1.point, v2.point, v3.point, x, y); if (bc[0] < 0 || bc[1] < 0 || bc[2] < 0) continue; //Point is not inside triangle. Why does this trigger? z = v1.point[2] * bc[0] + v2.point[2] * bc[1] + v3.point[2] * bc[2]; //Early depth test if (earlyDepthTest) { if (depthBuffer.getDepthValue(x, y) <= z) continue; } //Perspective correct interpolation w = 1 / (bc[0] * vDiv->wInverse[0] + bc[1] * vDiv->wInverse[1] + bc[2] * vDiv->wInverse[2]); //UVCoord = (bc[0] * vDiv->uvDivided[0] + bc[1] * vDiv->uvDivided[1] + bc[2] * vDiv->uvDivided[2]) * w; //color = (bc[0] * vDiv->colorDivided[0] + bc[1] * vDiv->colorDivided[1] + bc[2] * vDiv->colorDivided[2]) * w; //oldNormal = (bc[0] * vDiv->normalDivided[0] + bc[1] * vDiv->normalDivided[1] + bc[2] * vDiv->normalDivided[2]) * w; //normal = Vector3f(oldNormal[0], oldNormal[1], oldNormal[2]); //Set early depth depthBuffer.setDepthValue(x, y, z); frag = Fragment(Vector3f(x, y, z), interpolateBCVec3(bc, w, vDiv->normalDivided), interpolateBCVec2(bc, w, vDiv->uvDivided), interpolateBCVec4(bc, w, vDiv->colorDivided)); fragments->push_back(frag); } } float Rasterizer::interpolate(float min, float max, float gradient) { return min + (max - min) * clamp(gradient, 0, 1); } void Rasterizer::createPolyFragments2(vector<Fragment>* fragments, Vertex v1, Vertex v2, Vertex v3, int viewWidth, int viewHeight, Framebuffer& depthBuffer, bool earlyDepthTest) { Vector2f p1(v1.point[0], v1.point[1]); Vector2f p2(v2.point[0], v2.point[1]); Vector2f p3(v3.point[0], v3.point[1]); if (round(p1[1]) == round(p2[1]) && round(p1[1]) == p3[1]) return; if (p1[1] > p2[1]) std::swap(p1, p2); //Bubblesort in-place if (p1[1] > p3[1]) std::swap(p1, p3); if (p2[1] > p3[1]) std::swap(p2, p3); VertexScanAttrib vAttrib = VertexScanAttrib(v1, v2, v3); int maxY = min(viewHeight, (int)p3[1]); int minY = max(0, (int)p1[1]); if ((lineSide2D(p2, p1, p3) > 0)) { for (int y = minY; y <=maxY; y++) { if (y < p2[1]) { scanLine(fragments, y, p1, p3, p1, p2, v1, v2, v3, &vAttrib, viewWidth, depthBuffer, earlyDepthTest); } else { scanLine(fragments, y, p1, p3, p2, p3, v1, v2, v3, &vAttrib, viewWidth, depthBuffer, earlyDepthTest); } } } else { for (int y = minY; y <= maxY; y++) { if (y < p2[1]) { scanLine(fragments, y, p1, p2, p1, p3, v1, v2, v3, &vAttrib, viewWidth, depthBuffer, earlyDepthTest); } else { scanLine(fragments, y, p2, p3, p1, p3, v1, v2, v3, &vAttrib, viewWidth, depthBuffer, earlyDepthTest); } } } } void Rasterizer::createLineFragments(vector<Fragment>* fragments, Vertex v1, Vertex v2, Vertex v3, int viewWidth, int viewHeight) { bresenham(fragments, v1.point[0], v1.point[1], v2.point[0], v2.point[1]); bresenham(fragments, v1.point[0], v1.point[1], v3.point[0], v3.point[1]); bresenham(fragments, v2.point[0], v2.point[1], v3.point[0], v3.point[1]); } void Rasterizer::createDebugFragments(vector<Fragment>* fragments, Vertex v1, Vertex v2, Vertex v3, int viewWidth, int viewHeight) { //Draws normals in Wireframe mode bresenham(fragments, v1.point[0], v1.point[1], v2.point[0], v2.point[1]); bresenham(fragments, v1.point[0], v1.point[1], v3.point[0], v3.point[1]); bresenham(fragments, v2.point[0], v2.point[1], v3.point[0], v3.point[1]); bresenham(fragments, v1.point[0], v1.point[1], v1.point[0]+ v1.normal[0]*50, v1.point[1] + v1.normal[1] * 50); bresenham(fragments, v2.point[0], v2.point[1], v2.point[0] + v2.normal[0] * 50, v2.point[1] + v2.normal[1] * 50); bresenham(fragments, v3.point[0], v3.point[1], v3.point[0] + v3.normal[0] * 50, v3.point[1] + v3.normal[1] * 50); } Vector4i Rasterizer::findBoundingBox(Vector2i a, Vector2i b, Vector2i c, int width, int height) { int xMin, yMin, xMax, yMax; xMin = min(a[0], b[0]); xMin = max(0, min(xMin, c[0])); yMin = min(a[1], b[1]); yMin = max(0, min(yMin, c[1])); xMax = max(a[0], b[0]); xMax = min(width, max(xMax, c[0])); yMax = max(a[1], b[1]); yMax = min(height, max(yMax, c[1])); return Vector4i(xMin, yMin, xMax, yMax); } Vector3f Rasterizer::barycentric(Vector4f a, Vector4f b, Vector4f c, int x, int y) { Vector3f crossA(c[0] - a[0], b[0] - a[0], a[0] - x); Vector3f crossB(c[1] - a[1], b[1] - a[1], a[1] - y); Vector3f u = crossA.cross(crossB); if (abs(u[2])<1) return Vector3f(-1, 1, 1); //Degenerate triangle, return something bad return Vector3f(1.f - (u[0] + u[1]) / u[2], u[1] / u[2], u[0] / u[2]); } void Rasterizer::bresenham(vector<Fragment>* fragments, int x1, int y1, int x2, int y2) { //cout << "Line from (" << to_string(x1) << "," << to_string(y1) << " to (" << to_string(x2) << "," << to_string(y2) << ")" << endl; int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i; dx = x2 - x1; dy = y2 - y1; dx1 = fabs(dx); dy1 = fabs(dy); px = 2 * dy1 - dx1; py = 2 * dx1 - dy1; if (dy1 <= dx1) { if (dx >= 0) { x = x1; y = y1; xe = x2; } else { x = x2; y = y2; xe = x1; } fragments->push_back(Fragment(Vector3f(x, y, 0), Vector4f(1, 1, 1, 1))); for (i = 0; x<xe; i++) { x = x + 1; if (px<0) { px = px + 2 * dy1; } else { if ((dx<0 && dy<0) || (dx>0 && dy>0)) { y = y + 1; } else { y = y - 1; } px = px + 2 * (dy1 - dx1); } fragments->push_back(Fragment(Vector3f(x, y, 0), Vector4f(1, 1, 1, 1))); } } else { if (dy >= 0) { x = x1; y = y1; ye = y2; } else { x = x2; y = y2; ye = y1; } fragments->push_back(Fragment(Vector3f(x, y, 0), Vector4f(1, 1, 1, 1))); for (i = 0; y<ye; i++) { y = y + 1; if (py <= 0) { py = py + 2 * dx1; } else { if ((dx<0 && dy<0) || (dx>0 && dy>0)) { x = x + 1; } else { x = x - 1; } py = py + 2 * (dx1 - dy1); } fragments->push_back(Fragment(Vector3f(x, y, 0), Vector4f(1, 1, 1, 1))); } } } Rasterizer::Rasterizer() { } Rasterizer::~Rasterizer() { }
30.77116
231
0.605848
[ "vector" ]
b107e6be2366b825a966fc0bb9f766099975bee4
7,611
cpp
C++
Code/Tools/Standalone/Source/Driller/Annotations/AnnotationsDataView_Events.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2021-08-08T19:54:51.000Z
2021-08-08T19:54:51.000Z
Code/Tools/Standalone/Source/Driller/Annotations/AnnotationsDataView_Events.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
2
2022-01-13T04:29:38.000Z
2022-03-12T01:05:31.000Z
Code/Tools/Standalone/Source/Driller/Annotations/AnnotationsDataView_Events.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "AnnotationsDataView_Events.hxx" #include "AnnotationsHeaderView_Events.hxx" #include "Annotations.hxx" #include <Source/Driller/Axis.hxx> #include <QPainter> #include <QPainterPath> #include <QPen> #include <QMouseEvent> namespace Driller { static const float adv_events_arrow_width = 8.0f; AnnotationsDataView_Events::AnnotationsDataView_Events(AnnotationHeaderView_Events* header, AnnotationsProvider* annotations) : QWidget(header) , m_ptrHeaderView(header) , m_ptrAnnotations(annotations) , m_ptrAxis(NULL) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setFixedHeight(18); setAutoFillBackground(false); setAttribute(Qt::WA_OpaquePaintEvent, true); setMouseTracking(true); m_CurrentFrameNumber = 0; } void AnnotationsDataView_Events::AttachToAxis(Charts::Axis* pAxis) { if (m_ptrAxis) { disconnect(m_ptrAxis, SIGNAL(destroyed(QObject*)), this, SLOT(OnAxisDestroyed())); disconnect(m_ptrAxis, SIGNAL(Invalidated()), this, SLOT(OnAxisInvalidated())); } m_ptrAxis = pAxis; if (pAxis) { connect(m_ptrAxis, SIGNAL(destroyed(QObject*)), this, SLOT(OnAxisDestroyed())); connect(m_ptrAxis, SIGNAL(Invalidated()), this, SLOT(OnAxisInvalidated())); } } void AnnotationsDataView_Events::OnAxisDestroyed() { m_ptrAxis = NULL; update(); } void AnnotationsDataView_Events::OnAxisInvalidated() { update(); } AnnotationsDataView_Events::~AnnotationsDataView_Events() { } void AnnotationsDataView_Events::paintEvent(QPaintEvent* event) { (void)event; m_ClickableAreas.clear(); // scan for annotations // fill with black QPainter painter(this); painter.fillRect(rect(), Qt::black); if (!m_ptrAxis) { return; } if (!m_ptrAxis->GetValid()) { return; } QRectF drawRange = rect(); // adjust for inset: drawRange.adjust(2.0f, 0.0f, -4.0f, 0.0f); float leftEdge = (float)drawRange.left(); float drawRangeWidth = (float)drawRange.width(); AZ::s64 eventIndexStart = (AZ::s64)m_ptrAxis->GetWindowMin(); AZ::s64 eventIndexEnd = (AZ::s64)m_ptrAxis->GetWindowMax() + 1; float eventIndexRange = ((float)m_ptrAxis->GetWindowMax() - (float)m_ptrAxis->GetWindowMin()); // this is the domain range if (eventIndexRange <= 0.0f) { return; } float oneEventWidthInPixels = drawRangeWidth / eventIndexRange; float halfEventWidth = oneEventWidthInPixels * 0.5f; // find the first event within that range: QPen fatPen(QColor(255, 255, 255, 255)); fatPen.setWidth(2); fatPen.setCapStyle(Qt::FlatCap); AnnotationsProvider::ConstAnnotationIterator it = m_ptrAnnotations->GetFirstAnnotationForFrame(m_CurrentFrameNumber); AnnotationsProvider::ConstAnnotationIterator endIt = m_ptrAnnotations->GetEnd(); // now keep going until we hit the end of the range: while (it != endIt) { if (it->GetEventIndex() >= eventIndexEnd) { break; } if (it->GetEventIndex() < eventIndexStart) { ++it; continue; // we're within the zoom } // transform that event ID into the window domain: float eventRatio = ((float)it->GetEventIndex() - m_ptrAxis->GetWindowMin()) / eventIndexRange; float center = floorf(leftEdge + (drawRangeWidth * eventRatio)); center += (float)drawRange.left(); center += halfEventWidth; QPainterPath newPath; QPolygonF newPolygon; newPolygon << QPointF(center - adv_events_arrow_width, 1.0f) << QPointF(center, drawRange.height() - 1.0f) << QPointF(center + adv_events_arrow_width, 1.0f); newPath.addPolygon(newPolygon); newPath.closeSubpath(); if (m_eventsToHighlight.find(it->GetEventIndex()) != m_eventsToHighlight.end()) { painter.setPen(fatPen); painter.setBrush(m_ptrAnnotations->GetColorForChannel(it->GetChannelCRC())); } else { painter.setPen(QColor(0, 0, 0, 0)); painter.setBrush(m_ptrAnnotations->GetColorForChannel(it->GetChannelCRC())); } painter.drawPath(newPath); m_ClickableAreas[it->GetEventIndex()] = newPath; ++it; } } void AnnotationsDataView_Events::mouseMoveEvent(QMouseEvent* event) { AZStd::unordered_set<AZ::s64> newEventsToHighlight; for (auto it = m_ClickableAreas.begin(); it != m_ClickableAreas.end(); ++it) { if (it->second.contains(event->pos())) { auto annot = m_ptrAnnotations->GetAnnotationForEvent(it->first); if (annot != m_ptrAnnotations->GetEnd()) { newEventsToHighlight.insert(annot->GetEventIndex()); emit InformOfMouseOverAnnotation(*annot); } } } bool doUpdate = false; // did our highlight change? for (auto it = newEventsToHighlight.begin(); it != newEventsToHighlight.end(); ++it) { if (m_eventsToHighlight.find(*it) == m_eventsToHighlight.end()) { doUpdate = true; break; } } // did our highlight change? if (!doUpdate) { for (auto it = m_eventsToHighlight.begin(); it != m_eventsToHighlight.end(); ++it) { if (newEventsToHighlight.find(*it) == newEventsToHighlight.end()) { doUpdate = true; break; } } } if (doUpdate) { newEventsToHighlight.swap(m_eventsToHighlight); update(); } // find the first annotation within a margin: event->ignore(); } void AnnotationsDataView_Events::mousePressEvent(QMouseEvent* event) { for (auto it = m_ClickableAreas.begin(); it != m_ClickableAreas.end(); ++it) { if (it->second.contains(event->pos())) { auto annot = m_ptrAnnotations->GetAnnotationForEvent(it->first); if (annot != m_ptrAnnotations->GetEnd()) { emit InformOfClickAnnotation(*annot); } } } event->ignore(); } void AnnotationsDataView_Events::mouseReleaseEvent(QMouseEvent* event) { event->ignore(); } void AnnotationsDataView_Events::OnScrubberFrameUpdate(FrameNumberType newFramenumber) { if (newFramenumber != m_CurrentFrameNumber) { m_CurrentFrameNumber = newFramenumber; // we don't update here because we wait for the new range to be set //update(); } } } #include <Source/Driller/Annotations/moc_AnnotationsDataView_Events.cpp>
30.322709
169
0.578899
[ "transform", "3d" ]
6253858ab6b82879b0af97d7363325f7877b655a
8,597
cpp
C++
CM2005 Object Oriented Programming/Midterm/Merkelrex-TradingBot/MerkelMain.cpp
LevDoesCode/UoL
312b2d1096af4925c94b81d656e5d326dbad939e
[ "MIT" ]
null
null
null
CM2005 Object Oriented Programming/Midterm/Merkelrex-TradingBot/MerkelMain.cpp
LevDoesCode/UoL
312b2d1096af4925c94b81d656e5d326dbad939e
[ "MIT" ]
null
null
null
CM2005 Object Oriented Programming/Midterm/Merkelrex-TradingBot/MerkelMain.cpp
LevDoesCode/UoL
312b2d1096af4925c94b81d656e5d326dbad939e
[ "MIT" ]
null
null
null
#include "MerkelMain.h" #include <iostream> #include <vector> #include "OrderBookEntry.h" #include "CSVReader.h" MerkelMain::MerkelMain() { currentTime = orderBook.getEarliestTime(); wallet.insertCurrency("BTC", 10); wallet.insertCurrency("ETC", 10); wallet.insertCurrency("DOGE", 10); wallet.insertCurrency("USDT", 10); } std::string MerkelMain::getCurrentTime() { return currentTime; } std::vector<std::string> MerkelMain::getKnownProducts() { return orderBook.getKnownProducts(); } void MerkelMain::init() { int input; currentTime = orderBook.getEarliestTime(); wallet.insertCurrency("BTC", 10); while (true) { printMenu(); input = getUserOption(); processUserOption(input); } } void MerkelMain::printMenu() { // 1 print help std::cout << "1: Print help " << std::endl; // 2 print exchange stats std::cout << "2: Print exchange stats" << std::endl; // 3 make an offer std::cout << "3: Make an offer " << std::endl; // 4 make a bid std::cout << "4: Make a bid " << std::endl; // 5 print wallet std::cout << "5: Print wallet " << std::endl; // 6 continue std::cout << "6: Continue " << std::endl; std::cout << "============== " << std::endl; std::cout << "Current time is: " << currentTime << std::endl; } void MerkelMain::printHelp() { std::cout << "Help - your aim is to make money. Analyse the market and make bids and offers. " << std::endl; } void MerkelMain::printMarketStats() { for (std::string const &p : orderBook.getKnownProducts()) { std::cout << "Product: " << p << std::endl; std::vector<OrderBookEntry> entries = orderBook.getOrders(OrderBookType::ask, p, currentTime); std::cout << "Asks seen: " << entries.size() << std::endl; std::cout << "Max ask: " << OrderBook::getHighPrice(entries) << std::endl; std::cout << "Min ask: " << OrderBook::getLowPrice(entries) << std::endl; } // std::cout << "OrderBook contains : " << orders.size() << " entries" << std::endl; // unsigned int bids = 0; // unsigned int asks = 0; // for (OrderBookEntry& e : orders) // { // if (e.orderType == OrderBookType::ask) // { // asks ++; // } // if (e.orderType == OrderBookType::bid) // { // bids ++; // } // } // std::cout << "OrderBook asks: " << asks << " bids:" << bids << std::endl; } // Enter a new ask void MerkelMain::enterAsk() { std::cout << "Make an ask - enter the amount: product,price, amount, eg ETH/BTC,200,0.5" << std::endl; std::string input; std::getline(std::cin, input); std::vector<std::string> tokens = CSVReader::tokenise(input, ','); if (tokens.size() != 3) { std::cout << "MerkelMain::enterAsk Bad input! " << input << std::endl; } else { try { OrderBookEntry obe = CSVReader::stringsToOBE( tokens[1], tokens[2], currentTime, tokens[0], OrderBookType::ask); obe.username = "simuser"; if (wallet.canFulfillOrder(obe)) { std::cout << "Wallet looks good. " << std::endl; orderBook.insertOrder(obe); } else { std::cout << "Wallet has insufficient funds . " << std::endl; } } catch (const std::exception &e) { std::cout << " MerkelMain::enterAsk Bad input " << std::endl; } } } // Enter a new bid void MerkelMain::enterBid() { std::cout << "Make an bid - enter the amount: product,price, amount, eg ETH/BTC,200,0.5" << std::endl; std::string input; std::getline(std::cin, input); std::vector<std::string> tokens = CSVReader::tokenise(input, ','); if (tokens.size() != 3) { std::cout << "MerkelMain::enterBid Bad input! " << input << std::endl; } else { try { OrderBookEntry obe = CSVReader::stringsToOBE( tokens[1], tokens[2], currentTime, tokens[0], OrderBookType::bid); obe.username = "simuser"; if (wallet.canFulfillOrder(obe)) { std::cout << "Wallet looks good. " << std::endl; orderBook.insertOrder(obe); } else { std::cout << "Wallet has insufficient funds . " << std::endl; } } catch (const std::exception &e) { std::cout << " MerkelMain::enterBid Bad input " << std::endl; } } } // Withdraw an order void MerkelMain::withdrawOrder(OrderBookEntry order) { orderBook.removeOrder(order); } void MerkelMain::printWallet() { std::cout << wallet.toString() << std::endl; } std::vector<OrderBookEntry> MerkelMain::gotoNextTimeframe(bool silent) { // Sales vector to return std::vector<OrderBookEntry> sales; if (!silent) std::cout << "Going to next time frame. " << std::endl; // Match ask to bids product by product for (std::string p : orderBook.getKnownProducts()) { std::cout << "Matching.. " << p << std::endl; std::vector<OrderBookEntry> productSales = orderBook.matchAsksToBids(p, currentTime); std::cout << "Number of sales for " << p << ": " << productSales.size() << std::endl; for (OrderBookEntry &sale : sales) { if (!silent) std::cout << "Sale price: " << sale.price << " amount " << sale.amount << std::endl; if (sale.username == "simuser") { // update the wallet wallet.processSale(sale); } } // Add this product sales to the complete sales list sales.insert(sales.end(), productSales.begin(), productSales.end()); } currentTime = orderBook.getNextTime(currentTime); return sales; } // Enter an ask at the current time void MerkelMain::enterAsk(double price, double amount, std::string product) { OrderBookEntry order = {price, amount, currentTime, product, OrderBookType::ask, "simuser"}; // check if the wallet can afford it if (wallet.canFulfillOrder(order)) { orderBook.insertOrder(order); } } // Enter a bid at the current time void MerkelMain::enterBid(double price, double amount, std::string product) { OrderBookEntry order = {price, amount, currentTime, product, OrderBookType::bid, "simuser"}; // check if the wallet can afford it if (wallet.canFulfillOrder(order)) { orderBook.insertOrder(order); } } int MerkelMain::getUserOption() { int userOption = 0; std::string line; std::cout << "Type in 1-6" << std::endl; std::getline(std::cin, line); try { userOption = std::stoi(line); } catch (const std::exception &e) { // } std::cout << "You chose: " << userOption << std::endl; return userOption; } void MerkelMain::processUserOption(int userOption) { if (userOption == 0) // bad input { std::cout << "Invalid choice. Choose 1-6" << std::endl; } if (userOption == 1) { printHelp(); } if (userOption == 2) { printMarketStats(); } if (userOption == 3) { enterAsk(); } if (userOption == 4) { enterBid(); } if (userOption == 5) { printWallet(); } if (userOption == 6) { gotoNextTimeframe(false); } } std::vector<OrderBookEntry> MerkelMain::getCurrentAsks() { std::vector<OrderBookEntry> currentAsks; for (const std::string &prod : orderBook.getKnownProducts()) { std::vector<OrderBookEntry> thisProductAsks = orderBook.getOrders(OrderBookType::ask, prod, currentTime); currentAsks.insert(currentAsks.end(), thisProductAsks.begin(), thisProductAsks.end()); } return currentAsks; } std::vector<OrderBookEntry> MerkelMain::getCurrentBids() { std::vector<OrderBookEntry> currentBids; for (const std::string &prod : orderBook.getKnownProducts()) { std::vector<OrderBookEntry> thisProductBids = orderBook.getOrders(OrderBookType::bid, prod, currentTime); currentBids.insert(currentBids.end(), thisProductBids.begin(), thisProductBids.end()); } return currentBids; } std::string MerkelMain::returnWallet() { return wallet.toString(); }
27.554487
113
0.562754
[ "vector" ]
6259e2d2544df99b24d7cfde74cf9c01f5c3a76b
5,176
cc
C++
src/cpp/examples/minimal.cc
SanggunLee/edgetpu
d3cf166783265f475c1ddba5883e150ee84f7bfe
[ "Apache-2.0" ]
320
2019-09-19T07:10:48.000Z
2022-03-12T01:48:56.000Z
src/cpp/examples/minimal.cc
Machine-Learning-Practice/edgetpu
6d699665efdc5d84944b5233223c55fe5d3bd1a6
[ "Apache-2.0" ]
563
2019-09-27T06:40:40.000Z
2022-03-31T23:12:15.000Z
src/cpp/examples/minimal.cc
Machine-Learning-Practice/edgetpu
6d699665efdc5d84944b5233223c55fe5d3bd1a6
[ "Apache-2.0" ]
119
2019-09-25T02:51:10.000Z
2022-03-03T08:11:12.000Z
// Example to run a model using one Edge TPU. // It depends only on tflite and edgetpu.h #include <algorithm> #include <chrono> // NOLINT #include <iostream> #include <memory> #include <ostream> #include <string> #include "edgetpu.h" #include "src/cpp/examples/model_utils.h" #include "src/cpp/test_utils.h" #include "tensorflow/lite/interpreter.h" #include "tensorflow/lite/model.h" std::vector<uint8_t> decode_bmp(const uint8_t* input, int row_size, int width, int height, int channels, bool top_down) { std::vector<uint8_t> output(height * width * channels); for (int i = 0; i < height; i++) { int src_pos; int dst_pos; for (int j = 0; j < width; j++) { if (!top_down) { src_pos = ((height - 1 - i) * row_size) + j * channels; } else { src_pos = i * row_size + j * channels; } dst_pos = (i * width + j) * channels; switch (channels) { case 1: output[dst_pos] = input[src_pos]; break; case 3: // BGR -> RGB output[dst_pos] = input[src_pos + 2]; output[dst_pos + 1] = input[src_pos + 1]; output[dst_pos + 2] = input[src_pos]; break; case 4: // BGRA -> RGBA output[dst_pos] = input[src_pos + 2]; output[dst_pos + 1] = input[src_pos + 1]; output[dst_pos + 2] = input[src_pos]; output[dst_pos + 3] = input[src_pos + 3]; break; default: std::cerr << "Unexpected number of channels: " << channels << std::endl; std::abort(); break; } } } return output; } std::vector<uint8_t> read_bmp(const std::string& input_bmp_name, int* width, int* height, int* channels) { int begin, end; std::ifstream file(input_bmp_name, std::ios::in | std::ios::binary); if (!file) { std::cerr << "input file " << input_bmp_name << " not found\n"; std::abort(); } begin = file.tellg(); file.seekg(0, std::ios::end); end = file.tellg(); size_t len = end - begin; std::vector<uint8_t> img_bytes(len); file.seekg(0, std::ios::beg); file.read(reinterpret_cast<char*>(img_bytes.data()), len); const int32_t header_size = *(reinterpret_cast<const int32_t*>(img_bytes.data() + 10)); *width = *(reinterpret_cast<const int32_t*>(img_bytes.data() + 18)); *height = *(reinterpret_cast<const int32_t*>(img_bytes.data() + 22)); const int32_t bpp = *(reinterpret_cast<const int32_t*>(img_bytes.data() + 28)); *channels = bpp / 8; // there may be padding bytes when the width is not a multiple of 4 bytes // 8 * channels == bits per pixel const int row_size = (8 * *channels * *width + 31) / 32 * 4; // if height is negative, data layout is top down // otherwise, it's bottom up bool top_down = (*height < 0); // Decode image, allocating tensor once the image size is known const uint8_t* bmp_pixels = &img_bytes[header_size]; return decode_bmp(bmp_pixels, row_size, *width, abs(*height), *channels, top_down); } int main(int argc, char* argv[]) { if (argc != 1 && argc != 3) { std::cout << " minimal <edgetpu model> <input resized image>" << std::endl; return 1; } // Modify the following accordingly to try different models and images. const std::string model_path = argc == 3 ? argv[1] : coral::GetTempPrefix() + "/mobilenet_v1_1.0_224_quant_edgetpu.tflite"; const std::string resized_image_path = argc == 3 ? argv[2] : coral::GetTempPrefix() + "/resized_cat.bmp"; // Read model. std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile(model_path.c_str()); if (model == nullptr) { std::cerr << "Fail to build FlatBufferModel from file: " << model_path << std::endl; std::abort(); } // Build interpreter. std::shared_ptr<edgetpu::EdgeTpuContext> edgetpu_context = edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(); std::unique_ptr<tflite::Interpreter> interpreter = coral::BuildEdgeTpuInterpreter(*model, edgetpu_context.get()); // Read the resized image file. int width, height, channels; const std::vector<uint8_t>& input = read_bmp(resized_image_path, &width, &height, &channels); const auto& required_shape = coral::GetInputShape(*interpreter, 0); if (height != required_shape[0] || width != required_shape[1] || channels != required_shape[2]) { std::cerr << "Input size mismatches: " << "width: " << width << " vs " << required_shape[0] << ", height: " << height << " vs " << required_shape[1] << ", channels: " << channels << " vs " << required_shape[2] << std::endl; std::abort(); } // Print inference result. const auto& result = coral::RunInference(input, interpreter.get()); auto it = std::max_element(result.begin(), result.end()); std::cout << "[Image analysis] max value index: " << std::distance(result.begin(), it) << " value: " << *it << std::endl; return 0; }
33.830065
79
0.59544
[ "vector", "model" ]
626957ef50a3f6e1abb5ed9f30217b55d4c13f9f
3,106
cpp
C++
codeforces/1512C.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1512C.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1512C.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// C. A-B Palindrome #include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; int main() { int t; cin >> t; while (t--) { int a, b; cin >> a >> b; string s; getline(cin >> ws, s); int n = s.size(); bool ans = true; vector<char> v(n); int pairs = 0; vector<int> pair_idxs; for (int i = 0; i < n / 2; ++i) { if (s[i] == '?' && s[n-i-1] == '?') { ++pairs; pair_idxs.push_back(i); continue; } else if (s[i] != '?' && s[n-i-1] != '?') { if (s[i] != s[n-i-1]) { ans = false; break; } else { v[i] = s[i]; v[n-i-1] = s[i]; } } // s[i] != '?' || s[n-i-1] != '?' else { if (s[i] != '?') { v[i] = s[i]; v[n-i-1] = s[i]; } else { v[i] = s[n-i-1]; v[n-i-1] = s[n-i-1]; } } if (v[i] == '0') { a -= 2; } else if (v[i] == '1') { b -= 2; } } if (n % 2 != 0) { if (s[n/2] == '0') { v[n/2] = '0'; --a; } else if (s[n/2] == '1') { v[n/2] = '1'; --b; } // Editorial - https://codeforces.com/blog/entry/89535 else { if (a % 2 != 0) { v[n/2] = '0'; --a; } else if (b % 2 != 0) { v[n/2] = '1'; --b; } else { ans = false; } } } if (ans != false && !(a == 0 && b == 0 && pairs == 0)) { if (a % 2 != 0 || b % 2 != 0) { ans = false; } else if (pairs * 2 != a + b) { ans = false; } else { int idx = 0, i; for (; a > 1 && idx < pair_idxs.size(); ++idx) { a -= 2; i = pair_idxs[idx]; v[i] = '0'; v[n-i-1] = '0'; } for (; idx < pair_idxs.size(); ++idx) { b -= 2; i = pair_idxs[idx]; v[i] = '1'; v[n-i-1] = '1'; } } } if (a != 0 || b != 0) { ans = false; } if (ans) { for (auto el: v) { cout << el; } cout << endl; } else { cout << "-1" << endl; } } return 0; }
22.507246
66
0.223117
[ "vector" ]
626fedb2ac3ae4a154847d537ee26d58a89d106a
36,863
cpp
C++
src/mpm.cpp
edemaine/taichi_mpm
3bb90fbe4c901aafc048dbb2d8d8aa388226d011
[ "MIT" ]
2,137
2018-08-11T08:15:55.000Z
2022-03-31T12:35:56.000Z
src/mpm.cpp
LucasCampos/taichi_mpm
cd866e0546fb0c6383144ee0dac7d6e3884e00d3
[ "MIT" ]
52
2018-08-18T02:29:07.000Z
2022-02-23T03:03:24.000Z
src/mpm.cpp
LucasCampos/taichi_mpm
cd866e0546fb0c6383144ee0dac7d6e3884e00d3
[ "MIT" ]
321
2018-08-16T05:43:45.000Z
2022-03-25T09:34:53.000Z
/******************************************************************************* Copyright (c) The Taichi MPM Authors (2018- ). All Rights Reserved. The use of this software is governed by the LICENSE file. *******************************************************************************/ #ifdef TC_USE_MPI #include <mpi.h> #endif #include <taichi/system/threading.h> #include <taichi/visual/texture.h> #include <taichi/math/svd.h> #include <taichi/math.h> #include <taichi/common/asset_manager.h> #include <taichi/common/testing.h> #include <taichi/system/profiler.h> #include "articulation.h" #include "mpm.h" #include "poisson_disk_sampler.h" #include "particle_allocator.h" #include "boundary_particle.h" TC_NAMESPACE_BEGIN template <int dim> void MPM<dim>::initialize(const Config &config) { TC_P(grid_block_size()); TC_TRACE("BaseParticle size: {} B", sizeof(Particle)); Simulation<dim>::initialize(config); config_backup = config; res = config.get<Vectori>("res"); apic_damping = config.get("apic_damping", 0.0f); rpic_damping = config.get("rpic_damping", 0.0f); penalty = config.get("penalty", 0.0f); delta_x = config.get("delta_x", delta_x); inv_delta_x = 1.0f / delta_x; gravity = config.get("gravity", Vector::axis(1) * (-10.0_f)); apic = config.get("apic", true); pushing_force = config.get("pushing_force", 20000.0_f); TC_ASSERT_INFO(!config.has_key("delta_t"), "Please use 'base_delta_t' instead of 'delta_t'"); base_delta_t = config.get("base_delta_t", 1e-4_f); base_delta_t *= config.get("dt_multiplier", 1.0_f); reorder_interval = config.get<int>("reorder_interval", 1000); cfl = config.get("cfl", 1.0f); particle_gravity = config.get<bool>("particle_gravity", true); TC_LOAD_CONFIG(affine_damping, 0.0f); spgrid_size = 4096; while (spgrid_size / 2 > (res.max() + 1)) { spgrid_size /= 2; } TC_INFO("Created SPGrid of size {}", spgrid_size); TC_STATIC_IF(dim == 2) { grid = std::make_unique<SparseGrid>(spgrid_size, spgrid_size); } TC_STATIC_ELSE { grid = std::make_unique<SparseGrid>(spgrid_size, spgrid_size, spgrid_size); } TC_STATIC_END_IF page_map = std::make_unique<SPGrid_Page_Map<log2_size>>(*grid); rigid_page_map = std::make_unique<SPGrid_Page_Map<log2_size>>(*grid); fat_page_map = std::make_unique<SPGrid_Page_Map<log2_size>>(*grid); grid_region = Region(Vectori(0), res + VectorI(1), Vector(0)); if (config.get("energy_experiment", false)) { TC_ASSERT(config.get("optimized", true) == false); } // Add a background rigid body rigids.emplace_back(std::make_unique<RigidBody<dim>>()); rigids.back()->set_as_background(); } template <int dim> std::string MPM<dim>::add_particles(const Config &config) { auto region = RegionND<dim>(Vectori(0), res); if (config.get_string("type") == "rigid") { add_rigid_particle(config); return std::to_string((int)rigids.size() - 1); } else { auto detect_particles_inside_levelset = [&](const Vector &pos) { if (this->levelset.levelset0 == nullptr) return; real phi = this->levelset.sample(pos * inv_delta_x, this->current_t); if (phi < 0) { TC_WARN("Particles inside levelset generate.\n"); } }; auto create_particle = [&](const Vector &coord, real maximum, const Config &config) { ParticlePtr p_i; Particle *p; std::string type = config.get<std::string>("type"); std::tie(p_i, p) = allocator.allocate_particle(type); Config config_new = config; std::string param_string[3] = {"cohesion_tex", "theta_c_tex", "theta_s_tex"}; for (auto &p : param_string) if (config.has_key(p)) { std::shared_ptr<Texture> texture = AssetManager::get_asset<Texture>(config.get<int>(p)); real value = texture->sample(coord).x; config_new.set(p.substr(0, p.length() - 4), value); } p->initialize(config_new); p->pos = coord; if (config_backup.get("sand_climb", false)) { std::shared_ptr<Texture> texture = AssetManager::get_asset<Texture>( config_backup.get<int>("sand_texture")); real speed = config_backup.get("sand_speed", 0.0_f); real radius = 15.0_f / 180 * (real)M_PI; real x = p->pos[0] + this->current_t * speed * cos(radius); real y = p->pos[1] + this->current_t * speed * sin(radius); real z = p->pos[2]; y -= 0.1 / cos(radius); y -= x * tan(radius); Vector coord(0.5_f); coord.x = x; coord.y = z; if (texture->sample(coord).x < y) return; } if (this->near_boundary(*p)) { TC_WARN("particle out of box or near boundary. Ignored."); return; } detect_particles_inside_levelset(coord); p->vol = pow<dim>(delta_x) / maximum; p->set_mass(p->vol * config.get("density", 400.0f)); p->set_velocity(config.get("initial_velocity", Vector(0.0f))); if (config.get("stork_nod", 0.0_f) > 0.0_f) { real x = coord[0]; real y = coord[1]; real d = std::max(-0.5_f * x + y - 0.25_f, 0_f); real linear = config.get("stork_nod", 0.0_f); Vector v(0.0_f); v[0] = -d * linear; v[1] = -0.5_f * d * linear; p->set_velocity(v); } particles.push_back(p_i); }; int benchmark = config.get("benchmark", 0); if (benchmark) { TC_INFO("Generating particles for benchmarking"); TC_STATIC_IF(dim == 3) { // Make sure it is a cube TC_ASSERT(res == Vectori(res[0])); real s; if (benchmark == 125) { s = 0.1; } else if (benchmark == 8000) { s = 0.4; } else { s = 0; TC_ERROR("s must be 125 or 8000"); } int lower = (int)std::round(res[0] * (0.5_f - s)); int higher = lower + (int)std::round(res[0] * 2 * s); TC_P(lower); TC_P(higher); Vector offset(0.25_f * this->delta_x); for (auto ind : Region(Vectori(lower), Vectori(higher))) { for (int i = 0; i < 8; i++) { Vector sign(1); if (i % 2 == 0) sign[0] = -1; if (i / 2 % 2 == 0) sign[1] = -1; if (i / 4 % 2 == 0) sign[2] = -1; create_particle(ind.get_pos() * delta_x + offset * sign, 1, config); } } } TC_STATIC_END_IF; TC_ASSERT(dim == 3); TC_P(particles.size()); return ""; } if (config.get("point_cloud", false)) { TC_STATIC_IF(dim == 3) { TC_INFO("Reading point cloud, fn={}", config.get<std::string>("mesh_fn")); std::string mesh_fn = config.get<std::string>("mesh_fn"); std::string full_fn = absolute_path(mesh_fn); std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>(); Config mesh_config; mesh_config.set("filename", full_fn); mesh->initialize(mesh_config); Vector scale = config.get("scale", Vector(1.0f)); Vector translate = config.get("translate", Vector(0.0f)); for (auto &coord : mesh->vertices) { create_particle(coord * scale + translate, 8, config); } } TC_STATIC_ELSE{TC_NOT_IMPLEMENTED} TC_STATIC_END_IF } else { std::shared_ptr<Texture> density_texture = AssetManager::get_asset<Texture>(config.get<int>("density_tex")); real maximum = 0.0f; for (auto &ind : region) { Vector coord = (ind.get_ipos().template cast<real>() + Vector(0.5f)) * this->delta_x; real sample = density_texture->sample(coord).x; maximum = std::max(sample, maximum); } if (config.get("pd", true)) { PoissonDiskSampler<dim> sampler; std::vector<Vector> samples; if (config.get("pd_write_periodic_data", false)) { sampler.write_periodic_data(); } if (config.get("pd_periodic", true)) { if (config.get("pd_source", false)) { Vector sample_offset = config.get("initial_velocity", Vector(0.0f)) * this->current_t; real delta_t = config.get("delta_t", 1e-3f); Vector sample_advection = config.get("initial_velocity", Vector(0.0f)) * delta_t + 0.5_f * gravity * (delta_t + base_delta_t) * delta_t; sampler.sample_from_source(density_texture, region, this->delta_x, sample_offset, sample_advection, samples); } else if (config.get("pd_packed", false)) { std::shared_ptr<Texture> local_texture = AssetManager::get_asset<Texture>(config.get<int>("local_tex")); real radius = config.get("packed_radius", 0.01_f); real gap = config.get("packed_gap", 0.002_f); sampler.sample_packed(density_texture, local_texture, region, this->delta_x, radius, gap, samples); } else { sampler.sample_from_periodic_data(density_texture, region, this->delta_x, samples); } } else { sampler.sample(density_texture, region, this->delta_x, samples); } for (auto &coord : samples) { create_particle(coord, maximum, config); if (config.get<bool>("only_one", false)) { break; } } } else { TC_P(maximum); for (auto &ind : region) { for (int l = 0; l < maximum; l++) { Vector coord = (ind.get_ipos().template cast<real>() + Vector::rand()) * this->delta_x; if (rand() > density_texture->sample(coord).x / maximum) { continue; } create_particle(coord, maximum, config); } } } } } TC_P(particles.size()); return ""; } template <int dim> std::vector<RenderParticle> MPM<dim>::get_render_particles() const { return std::vector<RenderParticle>(); } template <int dim> void MPM<dim>::normalize_grid_and_apply_external_force( Vector velocity_increment_) { VectorP velocity_increment(velocity_increment_, 0); parallel_for_each_active_grid([&](GridState<dim> &g) { real mass = g.velocity_and_mass[dim]; if (mass > 0) { real inv_mass = 1.0_f / mass; VectorP alpha(Vector(inv_mass), 1); // Original: // g.velocity_and_mass *= alpha; g.velocity_and_mass += // velocity_increment; g.velocity_and_mass = fused_mul_add(g.velocity_and_mass, alpha, velocity_increment); } }); } template <int dim> void MPM<dim>::apply_grid_boundary_conditions( const DynamicLevelSet<dim> &levelset, real t) { int expr_leaky_levelset = config_backup.get<int>("expr_leaky_levelset", 0); real hack_velocity = config_backup.get<real>("hack_velocity", 0.0_f); int grid_block_size_max = grid_block_size().max(); auto block_op = [&](uint32 b, uint64 block_offset, GridState<dim> *g) { Vectori block_base_coord(SparseMask::LinearToCoord(block_offset)); Vector center = Vector(block_base_coord + grid_block_size() / Vectori(2)); if (!expr_leaky_levelset && levelset.inside(center) && std::abs(levelset.sample(center, t)) >= (real)grid_block_size_max) { return; } Region region(Vectori(0), grid_block_size()); for (auto &ind_ : region) { Vectori ind = block_base_coord + ind_.get_ipos(); if (grid_mass(ind) == 0.0f) { continue; } Vector pos = Vector(ind); real phi; Vector n; Vector boundary_velocity; real mu; if (expr_leaky_levelset == 0) { phi = levelset.sample(pos, t); if (phi < -3 || 0 < phi) continue; n = levelset.get_spatial_gradient(pos, t); if (hack_velocity != 0.0_f) { // if (length(offset) < 0.27_f) { if (0.5_f < pos.y * delta_x && pos.y * delta_x < 0.7_f && t <= config_backup.get("hack_time", 0.0_f)) { boundary_velocity = hack_velocity * Vector::axis(0); } else { boundary_velocity = Vector(0); } } else { boundary_velocity = -levelset.get_temporal_derivative(pos, t) * n * delta_x; } if (config_backup.get("sand_speed", 0.0_f) > 0) { real speed = config_backup.get("sand_speed", 0.0_f); real radius = 15.0_f / 180 * (real)M_PI; boundary_velocity = Vector(0); boundary_velocity.x = speed * (-cos(radius)); boundary_velocity.y = speed * (-sin(radius)); } mu = levelset.levelset0->friction; if (config_backup.get("gravity_cutting", false)) { if (real(ind.y) > 0.7_f * res[1]) mu = -1; } if (config_backup.get("sand_crawler", false)) { if (real(ind.y) < 0.535_f * res[1]) mu = -1; } } else { int y = ind.y; if (res[1] / 2 - expr_leaky_levelset <= y && y < res[1] / 2) { n = Vector::axis(1); } else { continue; } boundary_velocity = Vector(0); mu = -1; } Vector v = friction_project(grid_velocity(ind), boundary_velocity, n, mu); VectorP &v_and_m = get_grid(ind).velocity_and_mass; v_and_m = VectorP(v, v_and_m[dim]); } }; parallel_for_each_block_with_index(block_op, true); } template <> void MPM<2>::apply_dirichlet_boundary_conditions() { real distance = config_backup.get("dirichlet_boundary_radius", 0.0_f); real distance_l = config_backup.get("dirichlet_distance_left", distance); real distance_r = config_backup.get("dirichlet_distance_right", distance); real velocity = config_backup.get("dirichlet_boundary_velocity", 0.0_f); real velocity_l = config_backup.get("dirichlet_boundary_left", velocity); real velocity_r = config_backup.get("dirichlet_boundary_right", velocity); Vector vl(0.0_f), vr(0.0_f); vl[0] = velocity_l; vr[0] = velocity_r; for (auto &ind_ : grid_region) { Vectori ind = ind_.get_ipos(); Vector pos = Vector(ind) * delta_x; if (pos[0] < distance_l) { get_grid(ind).velocity_and_mass = VectorP(vl, get_grid(ind).velocity_and_mass[3]); } else if (pos[0] > 1.0_f - distance_r) { get_grid(ind).velocity_and_mass = VectorP(vr, get_grid(ind).velocity_and_mass[3]); } } } template <> void MPM<3>::apply_dirichlet_boundary_conditions() { for (auto &ind_ : grid_region) { Vectori ind = ind_.get_ipos(); Vector pos = Vector(ind) * delta_x; Vector v(0); if (pos.y > 0.525_f) { get_grid(ind).velocity_and_mass = VectorP(v, get_grid(ind).velocity_and_mass[3]); } } } template <int dim> void MPM<dim>::particle_collision_resolution(real t) { parallel_for_each_particle([&](Particle &p) { Vector pos = p.pos * inv_delta_x; real phi = this->levelset.sample(pos, t); if (phi < 0) { Vector gradient = this->levelset.get_spatial_gradient(pos, t); p.pos -= gradient * phi * delta_x; p.set_velocity(p.get_velocity() - dot(gradient, p.get_velocity()) * gradient); } }); } template <int dim> void MPM<dim>::step(real dt) { if (dt < 0) { substep(); request_t = this->current_t; } else { request_t += dt; while (this->current_t + base_delta_t < request_t) { update_counter += this->particles.size(); substep(); } } TC_TRACE("#Particles {}", particles.size()); auto average = std::accumulate(rigid_block_fractions.begin(), rigid_block_fractions.end(), 0.0) / rigid_block_fractions.size(); TC_TRACE("Average rigid block fraction: {:.2f}%", 100 * average); step_counter += 1; if (config_backup.get("print_energy", false)) { TC_P(calculate_energy()); } TC_WARN("Times of particle updating : {}", update_counter); } template <int dim> void MPM<dim>::substep() { Profiler _p("mpm_substep"); cutting_counter = 0; plasticity_counter = 0; const real delta_t = base_delta_t; if (particles.empty()) { // TC_DEBUG("dt = {}, No particles", base_delta_t); } else { // TC_DEBUG("dt = {}, Do substep for {} particles, ", base_delta_t, // particles.size()); } TC_PROFILE("sort_particles_and_populate_grid", sort_particles_and_populate_grid()); if (has_rigid_body()) { for (int i = 0; i < config_backup.get("coupling_iterations", 1); i++) { TC_PROFILE("rigidify", rigidify(delta_t)); TC_PROFILE("articulate", articulate(delta_t)); TC_PROFILE("rasterize_rigid_boundary", rasterize_rigid_boundary()); } } if (config_backup.get("visualize_cdf", false)) { int counter = 0; for (auto &ind : grid_region) { Particle *p = allocator[counter]; GridState<dim> &g = get_grid(ind); p->pos = ind.get_pos() * delta_x; p->boundary_distance = g.distance; p->states = g.states; counter++; } TC_PROFILE("advect_rigid_bodies", advect_rigid_bodies(delta_t)); this->current_t += delta_t; substep_counter += 1; return; } if (config_backup.get("visualize_particle_cdf", false)) { int counter = 0; for (auto &ind : grid_region) { Region region(Vectori(0), Vectori(4)); for (auto &sub_ind : region) { Particle *p = allocator[counter]; TC_ASSERT((std::size_t)counter < allocator.pool.size()); p->states = 0; p->pos = (ind.get_pos() + sub_ind.get_pos() * 0.25_f) * delta_x; counter++; } } TC_PROFILE("gather_cdf", gather_cdf()); TC_PROFILE("advect_rigid_bodies", advect_rigid_bodies(delta_t)); this->current_t += delta_t; substep_counter += 1; return; } if (has_rigid_body()) { TC_PROFILE("gather_cdf", gather_cdf()); } if (!config_backup.get("benchmark_rasterize", false)) { if (config_backup.get("optimized", true)) { TC_PROFILE_TPE("P2G optimized", rasterize_optimized(delta_t), particles.size()); } else { TC_PROFILE_TPE("P2G", rasterize(delta_t), particles.size()); } } else { while (true) { Time::Timer _("Rasterize x 20"); base_delta_t = 0; for (int i = 0; i < 20; i++) { rasterize_optimized(delta_t); } } } Vector gravity_velocity_increment = gravity * delta_t; if (particle_gravity) { // Add gravity to particles instead of grid gravity_velocity_increment = Vector(0); } TC_PROFILE( "normalize_grid_and_apply_external_force", normalize_grid_and_apply_external_force(gravity_velocity_increment)); if (config_backup.get("rigid_body_levelset_collision", false)) { TC_PROFILE("rigid_body_levelset_collision", rigid_body_levelset_collision(this->current_t, delta_t)); } TC_PROFILE("boundary_condition", apply_grid_boundary_conditions(this->levelset, this->current_t)); if (config_backup.get("dirichlet_boundary_radius", 0.0_f) > 0.0_f) { TC_PROFILE("apply_dirichlet_boundary_conditions", apply_dirichlet_boundary_conditions()); } if (!config_backup.get("benchmark_resample", false)) { if (config_backup.get("optimized", true)) { TC_PROFILE_TPE("G2P optimized", resample_optimized(), particles.size()); } else { TC_PROFILE_TPE("G2P", resample(), particles.size()); } } else { // NOTE: debugging here while (true) { Time::Timer _("Resample x 20"); base_delta_t = 0; for (int i = 0; i < 20; i++) { resample_optimized(); } } } if (config_backup.get("clean_boundary", true)) { TC_PROFILE("clean boundary", clear_boundary_particles()); } if (config_backup.get("particle_collision", false)) { TC_PROFILE("particle_collision", particle_collision_resolution(this->current_t)); } if (has_rigid_body()) { TC_PROFILE("advect_rigid_bodies", advect_rigid_bodies(delta_t)); } this->current_t += delta_t; substep_counter += 1; } template <int dim> bool MPM<dim>::test() const { return true; } template <int dim> void MPM<dim>::clear_boundary_particles() { std::vector<ParticlePtr> particles_new; static bool has_deleted = false; int remove_particles = config_backup.get("remove_particles", 0); real remove_height = config_backup.get("remove_height", 0.02_f); // Do not use bool here for concurrency std::vector<uint8> particle_remaining(particles.size(), 0); tbb::parallel_for(0, (int)particles.size(), [&](int i) { auto p_i = particles[i]; auto p = allocator[p_i]; if (near_boundary(*p) || p->pos.abnormal() || p->get_velocity().abnormal()) { return; } if (remove_particles) { int kind = remove_particles; real h = remove_height; if (!has_deleted && this->current_t >= 0.1) { if (p->pos.x >= 0.45 && p->pos.y >= 0.6 - 0.5 * h && p->pos.y <= 0.6 + 0.5 * h) { if (kind == 1) { return; } else if (kind == 2) { p->set_mu_to_zero(); } else if (kind == 3) { p->set_lambda_and_mu_to_zero(); } } } } particle_remaining[i] = 1; }); particles_new.reserve(particles.size()); for (int i = 0; i < (int)particles.size(); i++) { if (particle_remaining[i]) particles_new.push_back(particles[i]); } if (!has_deleted && this->current_t >= 0.1) has_deleted = true; int deleted = (int)particles.size() - (int)particles_new.size(); if (deleted != 0 && config_backup.get("warn_particle_deletion", false)) { TC_WARN( "{} boundary (or abnormal) particles deleted.\n{} Particles remained\n", deleted, particles_new.size()); } particles = particles_new; } template <int dim> std::string MPM<dim>::get_debug_information() { // return std::to_string(rigids[1].velocity.x); return ""; } template <int dim> MPM<dim>::~MPM() { } template <typename T> Array2D<T> horizontal_stack(const Array2D<T> &a, const Array2D<T> &b) { TC_ASSERT(a.get_res()[1] == b.get_res()[1]); Array2D<T> merged(Vector2i(a.get_res()[0] + b.get_res()[0], a.get_res()[1])); for (auto &ind : a.get_region()) { merged[ind] = a[ind]; } for (auto &ind : b.get_region()) { merged[ind + Vector2i(a.get_res()[0], 0)] = b[ind]; } return merged; } template <typename T> Array2D<T> vertical_stack(const Array2D<T> &a, const Array2D<T> &b) { TC_ASSERT(a.get_res()[0] == b.get_res()[0]); Array2D<T> merged(Vector2i(a.get_res()[0], a.get_res()[1] + b.get_res()[1])); for (auto &ind : a.get_region()) { merged[ind] = a[ind]; } for (auto &ind : b.get_region()) { merged[ind + Vector2i(0, a.get_res()[1])] = b[ind]; } return merged; } template <> void MPM<2>::draw_cdf(const Config &config) { // Step 1: sample particles int scale = 5; for (int i = 7; i < (res[0] - 7) * scale; i++) { for (int j = 7; j < (res[1] - 7) * scale; j++) { auto alloc = allocator.allocate_particle("snow"); Particle &p = *alloc.second; p.pos = Vector(delta_x * (i + 0.5_f) / scale, delta_x * (j + 0.5_f) / scale); p.vol = pow<dim>(delta_x); p.set_mass(p.vol * 400); p.set_velocity(config.get("initial_velocity", Vector(0.0f))); particles.push_back(alloc.first); } } base_delta_t = 0.001; TC_P("seeded"); for (int i = 0; i < 5; i++) { substep(); } TC_P("stepped"); Array2D<Vector3> img_dist, img_affinity, img_normal; img_dist.initialize(res * scale); img_affinity.initialize(res * scale); img_normal.initialize(res * scale); // Step 2: compute sample color and gather from grid for (auto &p_i : particles) { auto &p = *allocator[p_i]; if (p.near_boundary()) { Vectori ipos = (p.pos * real(scale) * inv_delta_x).template cast<int>(); TC_ASSERT(img_affinity.inside(ipos)); // img[ipos] = Vector3(p->near_boundary); img_dist[ipos] = Vector3(p.boundary_distance * inv_delta_x * 0.2f); Vector3 affinity_color; affinity_color.x = p.states % 4 * 0.33_f; affinity_color.y = p.states / 4 % 4 * 0.33_f; affinity_color.z = p.states / 16 % 4 * 0.33_f; img_affinity[ipos] = Vector3(affinity_color); img_normal[ipos] = Vector3(p.boundary_normal * 0.5_f + Vector(0.5_f)); } } auto merged_lower = horizontal_stack(horizontal_stack(img_dist, img_affinity), img_normal); // Step 3: Grid CDF Region region(Vectori(0), res * scale); for (auto &ind : region) { Vectori ipos = ind.get_ipos() / Vectori(scale); img_dist[ind] = Vector3(get_grid(ipos).get_distance() * inv_delta_x * 0.2f); Vector3 affinity_color; auto states = get_grid(ipos).get_states(); affinity_color.x = states % 4 * 0.33_f; affinity_color.y = states / 4 % 4 * 0.33_f; affinity_color.z = states / 16 % 4 * 0.33_f; img_affinity[ind] = Vector3(affinity_color); } auto merged_upper = horizontal_stack(horizontal_stack(img_dist, img_affinity), img_normal); auto merged = vertical_stack(merged_lower, merged_upper); merged.write_as_image("/tmp/cdf.png"); } template <> void MPM<3>::draw_cdf(const Config &config) { TC_NOT_IMPLEMENTED } template <int dim> void MPM<dim>::sort_allocator() { TC_TRACE("Reording particles"); Time::Timer _("reorder"); std::swap(allocator.pool_, allocator.pool); if (allocator.pool.size() < allocator.pool_.size()) { allocator.pool.resize(allocator.pool_.size()); } for (uint32 i = 0; i < particles.size(); i++) { int j = particles[i]; allocator.pool[i] = allocator.pool_[j]; particles[i] = i; } allocator.gc(particles.size()); } template <int dim> void MPM<dim>::sort_particles_and_populate_grid() { // Profiler::disable(); constexpr int index_bits = (32 - SparseMask::block_bits); TC_ASSERT(particles.size() < (1 << index_bits)); if (particles.size() > particle_sorter.size()) { particle_sorter.resize(particles.size()); } auto grid_array = grid->Get_Array(); { Profiler _("prepare array to sort"); tbb::parallel_for(0, (int)particles.size(), [&](int i) { uint64 offset = SparseMask::Linear_Offset(to_std_array( get_grid_base_pos(allocator[particles[i]]->pos * inv_delta_x))); particle_sorter[i] = ((offset >> SparseMask::data_bits) << index_bits) + i; }); } TC_PROFILE("parallel_sort", tbb::parallel_sort(particle_sorter.begin(), particle_sorter.begin() + particles.size())); { Profiler _("reorder particle pointers"); // Reorder particles std::swap(particles, particles_); // if (particles.size() < particles_.size()) { // TODO: make it more efficient particles.resize(particles_.size()); //} for (int i = 0; i < (int)particles.size(); i++) { particles[i] = particles_[particle_sorter[i] & ((1ll << index_bits) - 1)]; } } // Reorder particles if (reorder_interval > 0 && substep_counter % reorder_interval == 0) { sort_allocator(); } // Reset page_map { Profiler _("reset page map"); page_map->Clear(); for (int i = 0; i < (int)particles.size(); i++) { uint64 offset = (particle_sorter[i] >> index_bits) << SparseMask::data_bits; page_map->Set_Page(offset); } page_map->Update_Block_Offsets(); } // Update particle offset auto blocks = page_map->Get_Blocks(); { Profiler _("fat page map"); // Reset fat_page_map fat_page_map->Clear(); for (int b = 0; b < (int)blocks.second; b++) { auto base_offset = blocks.first[b]; TC_STATIC_IF(dim == 2) { auto x = 1 << SparseMask::block_xbits; auto y = 1 << SparseMask::block_ybits; auto c = SparseMask::LinearToCoord(base_offset); for (int i = -1 + (c[0] == 0); i < 2; i++) { for (int j = -1 + (c[1] == 0); j < 2; j++) { fat_page_map->Set_Page(SparseMask::Packed_Add( base_offset, SparseMask::Linear_Offset(x * i, y * j))); } } } TC_STATIC_ELSE { auto x = 1 << SparseMask::block_xbits; auto y = 1 << SparseMask::block_ybits; auto z = 1 << SparseMask::block_zbits; auto c = SparseMask::LinearToCoord(base_offset); for (int i = -1 + (c[0] == 0); i < 2; i++) { for (int j = -1 + (c[1] == 0); j < 2; j++) { for (int k = -1 + (c[2] == 0); k < 2; k++) { fat_page_map->Set_Page(SparseMask::Packed_Add( base_offset, SparseMask::Linear_Offset(x * i, y * j, z * k))); } } } } TC_STATIC_END_IF } fat_page_map->Update_Block_Offsets(); } auto fat_blocks = fat_page_map->Get_Blocks(); { Profiler _("reset grid"); for (int i = 0; i < (int)fat_blocks.second; i++) { auto offset = fat_blocks.first[i]; std::memset(&grid_array(offset), 0, 1 << log2_size); } } { Profiler _("block particle offset"); block_meta.clear(); uint64 last_offset = -1; for (uint32 i = 0; i < particles.size(); i++) { if (last_offset != (particle_sorter[i] >> 32)) { block_meta.push_back({i, 0}); } last_offset = particle_sorter[i] >> 32; } block_meta.push_back({(uint32)particles.size(), 0}); TC_ASSERT(block_meta.size() == blocks.second + 1); } { Profiler _("grid particle offset"); parallel_for_each_block_with_index( [&](uint32 b, uint64 base_offset, GridState<dim> *g) { auto particle_begin = block_meta[b].particle_offset; auto particle_end = block_meta[b + 1].particle_offset; int count = 0; for (uint32 i = particle_begin; i < particle_end; i++) { auto base_pos = get_grid_base_pos(allocator[particles[i]]->pos * inv_delta_x); uint64 offset = SparseMask::Linear_Offset(to_std_array(base_pos)); auto index = (offset >> SparseMask::data_bits) & ((1 << SparseMask::block_bits) - 1); g[index].particle_count += 1; count++; } // TC_ASSERT(count == particle_end - particle_begin); }, false); } // Profiler::enable(); TC_STATIC_IF(dim == 3) { Profiler _("update rigid page map"); this->update_rigid_page_map(); } TC_STATIC_END_IF } template <int dim> std::string MPM<dim>::general_action(const Config &config) { std::string action = config.get<std::string>("action"); if (action == "add_articulation") { Config new_config = config; new_config.set("obj0", rigids[config.get<int>("obj0")].get()); if (config.has_key("obj1")) { new_config.set("obj1", rigids[config.get<int>("obj1")].get()); } else { new_config.set("obj1", rigids[0].get()); } auto art = create_instance_unique<Articulation<dim>>( config.get<std::string>("type"), new_config); articulations.push_back(std::move(art)); } else if (action == "cdf") { draw_cdf(config); } else if (action == "save") { TC_P(this->get_name()); write_to_binary_file_dynamic(this, config.get<std::string>("file_name")); } else if (action == "calculate_energy") { return fmt::format("{}", calculate_energy()); } else if (action == "load") { read_from_binary_file_dynamic(this, config.get<std::string>("file_name")); for (auto &r : rigids) { if (r->pos_func_id != -1) { typename RigidBody<dim>::PositionFunctionType *f = (typename RigidBody<dim>::PositionFunctionType *)config.get<uint64>( fmt::format("script{:05d}", r->pos_func_id)); r->pos_func = *f; TC_INFO("scripted position loaded"); } if (r->rot_func_id != -1) { typename RigidBody<dim>::RotationFunctionType *f = (typename RigidBody<dim>::RotationFunctionType *)config.get<uint64>( fmt::format("script{:05d}", r->rot_func_id)); r->rot_func = *f; TC_INFO("scripted rotation loaded"); } } } else if (action == "delete_particles_inside_level_set") { std::vector<ParticlePtr> particles_new; int deleted = 0; for (auto p_i : particles) { auto p = allocator[p_i]; if (this->levelset.sample(p->pos * inv_delta_x, this->current_t) < 0) { deleted += 1; continue; } particles_new.push_back(p_i); } TC_INFO( "{} boundary (or abnormal) particles deleted.\n{} Particles remained\n", deleted, particles_new.size()); particles = particles_new; } else { TC_ERROR("Unknown action: {}", action); } return ""; } template std::string MPM<2>::general_action(const Config &config); template std::string MPM<3>::general_action(const Config &config); using MPM2D = MPM<2>; using MPM3D = MPM<3>; TC_IMPLEMENTATION(Simulation2D, MPM2D, "mpm"); TC_IMPLEMENTATION(Simulation3D, MPM3D, "mpm"); TC_TEST("mpm_serialization") { std::string fn = "/tmp/snapshot.tcb", fn2; MPM<3> mpm, mpm_loaded; mpm.penalty = 2013011374; mpm.res = Vector3i(42, 95, 63); mpm.delta_x = 1024; mpm.inv_delta_x = 1025; write_to_binary_file(mpm, fn); read_from_binary_file(mpm_loaded, fn); if (remove(fn.c_str()) != 0) { TC_WARN("Error occur when deleting binary file."); } #define CHECK_LOADED(x) CHECK(mpm_loaded.x == mpm.x) CHECK_LOADED(res); CHECK_LOADED(penalty); CHECK_LOADED(delta_x); CHECK_LOADED(inv_delta_x); // CHECK_LOADED(grid_region); std::vector<Element<2>> elems, elems2; elems.resize(1000); write_to_binary_file(elems, fn); read_from_binary_file(elems2, fn); if (remove(fn.c_str()) != 0) { TC_WARN("Error occur when deleting binary file."); } } template <> void MPM<2>::update_rigid_page_map() { TC_NOT_IMPLEMENTED } template <> void MPM<3>::update_rigid_page_map() { constexpr int dim = 3; auto block_size = grid_block_size(); rigid_page_map->Clear(); std::vector<int> block_has_rigid(page_map->Get_Blocks().second, 0); auto block_op = [&](uint32 b, uint64 block_offset, GridState<dim> *g) { int particle_begin; int particle_end = block_meta[b].particle_offset; bool has_rigid = false; for (uint32 t = 0; t < SparseMask::elements_per_block; t++) { particle_begin = particle_end; particle_end += g[t].particle_count; for (int k = particle_begin; k < particle_end; k++) { Particle &p = *allocator[particles[k]]; has_rigid = has_rigid || p.is_rigid(); } } if (has_rigid) { block_has_rigid[b] = true; } }; parallel_for_each_block_with_index(block_op, false, false); auto blocks = page_map->Get_Blocks(); // We do not have thread-safe Set_Page... for (uint i = 0; i < blocks.second; i++) { auto offset = blocks.first[i]; if (!block_has_rigid[i]) { continue; } Vectori base_pos(SparseMask::LinearToCoord(offset)); for (auto &ind : Region(Vectori(-1), Vectori(2))) { if (VectorI(0) <= VectorI(ind) && VectorI(ind) < VectorI(spgrid_size)) { auto nei_offset = SparseMask::Linear_Offset(base_pos + ind.get_ipos() * block_size); TC_ASSERT(fat_page_map->Test_Page(offset)); rigid_page_map->Set_Page(nei_offset); } } } rigid_page_map->Update_Block_Offsets(); rigid_block_fractions.push_back(1.0_f * rigid_page_map->Get_Blocks().second / fat_page_map->Get_Blocks().second); } template <int dim> real MPM<dim>::calculate_energy() { sort_particles_and_populate_grid(); rasterize(0, false); float64 kinetic = 0; float64 potential = 0; auto blocks = fat_page_map->Get_Blocks(); auto grid_array = grid->Get_Array(); for (int b = 0; b < (int)blocks.second; b++) { GridState<dim> *g = reinterpret_cast<GridState<dim> *>(&grid_array(blocks.first[b])); for (int i = 0; i < (int)SparseMask::elements_per_block; i++) { real mass = g[i].velocity_and_mass[dim]; if (mass == 0) continue; Vector velocity(g[i].velocity_and_mass / mass); kinetic += mass * velocity.length2() * 0.5_f; } } std::mutex mut; parallel_for_each_particle([&](Particle &p) { // We do not care about performance here. mut.lock(); potential += p.potential_energy(); mut.unlock(); }); TC_WARN("t={} Energy: kinetic={}, potential={}", this->current_t, kinetic, potential); auto mechanical_energy = kinetic + potential; TC_INFO("Visualize energy: t={}, energy={}", this->current_t, mechanical_energy); return mechanical_energy; } TC_NAMESPACE_END
33.15018
80
0.601742
[ "mesh", "vector" ]
627e4c8ea71ea5eb56ae1dd17cbf1393dca3603b
5,322
cpp
C++
src/nexus/backend/sleep_model.cpp
dengwxn/nexuslb
4b19116f09fad414bd40538de0105eb728fc4b51
[ "BSD-3-Clause" ]
null
null
null
src/nexus/backend/sleep_model.cpp
dengwxn/nexuslb
4b19116f09fad414bd40538de0105eb728fc4b51
[ "BSD-3-Clause" ]
null
null
null
src/nexus/backend/sleep_model.cpp
dengwxn/nexuslb
4b19116f09fad414bd40538de0105eb728fc4b51
[ "BSD-3-Clause" ]
null
null
null
#include "nexus/backend/sleep_model.h" #include <glog/logging.h> #include <immintrin.h> #include <chrono> #include <stdexcept> #include <thread> #include "nexus/backend/model_ins.h" #include "nexus/common/time_util.h" namespace nexus { namespace backend { namespace { template <class Rep, class Period> inline void BlockSleepFor(const std::chrono::duration<Rep, Period>& duration) { std::this_thread::sleep_for(duration); } template <class Rep, class Period> inline void SpinSleepFor(const std::chrono::duration<Rep, Period>& duration) { auto until = Clock::now() + duration; while (Clock::now() < until) { _mm_pause(); } } template <class Rep, class Period> inline void SleepFor(const std::chrono::duration<Rep, Period>& duration) { BlockSleepFor(duration); } } // namespace SleepModel::SleepModel(SleepProfile profile, const ModelInstanceConfig& config, ModelIndex model_index) : ModelInstance(-1, config, model_index), profile_(std::move(profile)) { LOG(INFO) << "Construct SleepModel." << "slope_us=" << profile.slope_us() << ", intercept_us=" << profile.intercept_us() << ", preprocess_us=" << profile.preprocess_us() << ", postprocess_us=" << profile.postprocess_us(); if (model_session_.image_height() > 0) { image_height_ = model_session_.image_height(); image_width_ = model_session_.image_width(); } else { image_height_ = model_info_["image_height"].as<int>(); image_width_ = model_info_["image_width"].as<int>(); } max_batch_ = 500; input_shape_.set_dims( {static_cast<int>(max_batch_), image_height_, image_width_, 3}); input_size_ = input_shape_.NumElements(1); input_layer_ = model_info_["input_layer"].as<std::string>(); input_data_type_ = DT_FLOAT; if (model_info_["output_layer"].IsSequence()) { for (size_t i = 0; i < model_info_["output_layer"].size(); ++i) { output_layers_.push_back( model_info_["output_layer"][i].as<std::string>()); } } else { output_layers_.push_back(model_info_["output_layer"].as<std::string>()); } for (const auto& name : output_layers_) { // Dummy values int n = 10; output_sizes_[name] = n; output_shapes_[name] = Shape{1, n}; } } Shape SleepModel::InputShape() { return input_shape_; } std::unordered_map<std::string, Shape> SleepModel::OutputShapes() { return output_shapes_; } ArrayPtr SleepModel::CreateInputGpuArray() { auto num_elements = max_batch_ * image_height_ * image_width_ * 3; auto nbytes = num_elements * type_size(input_data_type_); auto buf = std::make_shared<Buffer>(nbytes, cpu_device_); auto arr = std::make_shared<Array>(input_data_type_, num_elements, cpu_device_); return arr; } void SleepModel::WarmupInputArray(std::shared_ptr<Array> input_array) { char* data = input_array->Data<char>(); size_t size = type_size(input_array->data_type()) * input_array->num_elements(); for (size_t i = 0; i < size; ++i) { data[i] = i & 0xFF; } } std::unordered_map<std::string, ArrayPtr> SleepModel::GetOutputGpuArrays() { return {}; } void SleepModel::Preprocess(std::shared_ptr<Task> task) { auto prepare_image = [&, this] { auto in_arr = std::make_shared<Array>(DT_FLOAT, input_size_, cpu_device_); task->AppendInput(in_arr); }; const auto& query = task->query; const auto& input_data = query.input(); switch (input_data.data_type()) { case DT_IMAGE: { task->attrs["im_height"] = image_height_; task->attrs["im_width"] = image_width_; if (query.window_size() > 0) { for (int i = 0; i < query.window_size(); ++i) { const auto& rect = query.window(i); prepare_image(); } } else { prepare_image(); } break; } default: task->result.set_status(INPUT_TYPE_INCORRECT); task->result.set_error_message("Input type incorrect: " + DataType_Name(input_data.data_type())); break; } SleepFor(std::chrono::microseconds(profile_.preprocess_us())); } void SleepModel::Forward(std::shared_ptr<BatchTask> batch_task) { size_t batch_size = batch_task->batch_size(); SleepFor(std::chrono::microseconds(profile_.forward_us(batch_size))); std::unordered_map<std::string, Slice> slices; for (uint i = 0; i < output_layers_.size(); ++i) { const auto& name = output_layers_[i]; slices.emplace(name, Slice(batch_size, output_sizes_.at(name))); } batch_task->SliceOutputBatch(slices); } void SleepModel::Postprocess(std::shared_ptr<Task> task) { const QueryProto& query = task->query; QueryResultProto* result = &task->result; result->set_status(CTRL_OK); for (auto output : task->outputs) { auto out_arr = output->arrays.at(output_layers_[0]); size_t count = out_arr->num_elements(); size_t output_size = output_sizes_.at(output_layers_[0]); auto* record = result->add_output(); } SleepFor(std::chrono::microseconds(profile_.postprocess_us())); } uint64_t SleepModel::GetPeakBytesInUse() { throw std::runtime_error("SleepModel::GetPeakBytesInUse NotSupported"); } uint64_t SleepModel::GetBytesInUse() { throw std::runtime_error("SleepModel::GetBytesInUse NotSupported"); } } // namespace backend } // namespace nexus
30.763006
79
0.676813
[ "shape" ]
6282ff4c5261fdc68b7eded3ad6bc1a3b7b94570
2,823
cpp
C++
content/code/cpp/yahtzee.cpp
transferorbit/coderefinery_testing
b1011345cd6ed614e702b372bd2d987521bba130
[ "CC-BY-4.0" ]
8
2019-03-11T12:36:25.000Z
2021-09-30T00:32:11.000Z
content/code/cpp/yahtzee.cpp
transferorbit/coderefinery_testing
b1011345cd6ed614e702b372bd2d987521bba130
[ "CC-BY-4.0" ]
126
2016-12-13T11:12:23.000Z
2022-03-30T20:17:17.000Z
content/code/cpp/yahtzee.cpp
transferorbit/coderefinery_testing
b1011345cd6ed614e702b372bd2d987521bba130
[ "CC-BY-4.0" ]
37
2016-12-13T11:00:28.000Z
2022-01-18T13:53:07.000Z
#include <cstdlib> #include <iostream> #include <random> #include <tuple> #include <vector> /* Roll a fair die n_dice times. The faces of the die can be set (default is 1 to 6). * The PRNG engine is moved in the function such that changes in its state are propagated back to the caller. */ template <typename PRNGEngine = decltype(std::default_random_engine())> std::vector<unsigned int> roll_dice( unsigned int n_dice = 5, std::vector<unsigned int> faces = {1, 2, 3, 4, 5, 6}, PRNGEngine&& gen = std::default_random_engine(std::random_device()())) { // create a fair die auto weights = std::vector<double>(faces.size(), 1.0); auto fair_dice = std::discrete_distribution<unsigned int>(weights.begin(), weights.end()); auto rolls = std::vector<unsigned int>(n_dice, 0); for (auto i = 0u; i < n_dice; ++i) { rolls[i] = faces[fair_dice(gen)]; } return rolls; } /* count how many times each face comes up */ std::vector<unsigned int> count(const std::vector<unsigned int>& toss, const std::vector<unsigned int>& faces = { 1, 2, 3, 4, 5, 6}) { auto face_counts = std::vector<unsigned int>(faces.size(), 0); for (auto i = 0; i < faces.size(); ++i) { face_counts[i] = std::count(toss.cbegin(), toss.cend(), faces[i]); } return face_counts; } std::tuple<unsigned int, unsigned int> yahtzee() { auto n_dice = 5; auto faces = std::vector<unsigned int>{1, 2, 3, 4, 5, 6}; auto toss = [faces](unsigned int n_dice) { return roll_dice(n_dice, faces); }; // throw all dice auto first_toss = toss(n_dice); auto face_counts = count(first_toss); auto it_max = std::max_element(face_counts.cbegin(), face_counts.cend()); // number of faces that showed the most auto n_collected = *it_max; // corresponding index in the array, will be used to get which face showed up // the most auto idx_max = std::distance(face_counts.cbegin(), it_max); // all 5 dice showed the same face! YAHTZEE! if (n_collected == 5) return std::make_tuple(faces[idx_max], n_collected); // no yahtzee :( // we throw (n_dice - n_collected) dice auto second_toss = toss(n_dice - n_collected); n_collected += count(second_toss, {faces[idx_max]})[0]; // YAHTZEE! if (n_collected == 5) return std::make_tuple(faces[idx_max], n_collected); // final chance auto third_toss = toss(n_dice - n_collected); n_collected += count(third_toss, {faces[idx_max]})[0]; return std::make_tuple(faces[idx_max], n_collected); } int main() { for (auto i = 0; i < 100; ++i) { unsigned int value = 0, times = 0; std::tie(value, times) = yahtzee(); std::cout << "We got " << value << " " << times << " times in round " << i << std::endl; if (times == 5) { std::cout << "YAHTZEE in round " << i << std::endl; } } return EXIT_SUCCESS; }
33.607143
109
0.65108
[ "vector" ]
6285bf6b5fea788012a1a357d47867f2ce37e4a6
5,031
cpp
C++
ww-example/ExampleObjects.cpp
koalefant/yasli
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
[ "MIT" ]
8
2021-07-08T18:06:33.000Z
2022-01-17T18:29:57.000Z
ww-example/ExampleObjects.cpp
koalefant/yasli
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
[ "MIT" ]
null
null
null
ww-example/ExampleObjects.cpp
koalefant/yasli
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
[ "MIT" ]
1
2021-12-31T15:52:56.000Z
2021-12-31T15:52:56.000Z
#include <string> #include <vector> using std::vector; namespace yasli { class Archive; template<class T> class SharedPtr; }; using yasli::Archive; using yasli::SharedPtr; struct ObjectNode; bool serialize(Archive& ar, SharedPtr<ObjectNode>& node, const char* name, const char* label); #include "ww/PropertyTree.h" #include "ww/Serialization.h" #include "ww/HSplitter.h" #include "ww/VBox.h" #include "ww/Button.h" #include "ww/Color.h" #include "ww/Icon.h" using yasli::RefCounter; using namespace ww; enum Filter { FILTER_OUTLINE = 0x1, FILTER_PROPERTIES = 0x2 }; struct Geometry : RefCounter { virtual ~Geometry() {} virtual void serialize(Archive& ar) { } }; struct GeometryBox : Geometry { virtual void serialize(Archive& ar) { } }; struct GeometrySphere : Geometry { virtual void serialize(Archive& ar) { } }; YASLI_CLASS_NULL(Geometry, "None") YASLI_CLASS(Geometry, GeometryBox, "Box") YASLI_CLASS(Geometry, GeometrySphere, "Sphere") #include "Icons/favourites.xpm" #include "Icons/favouritesDisabled.xpm" struct ObjectNode : RefCounter { std::string name_; bool enabled_; bool favourite_; Color color_; float weight_; bool isRoot_; int counter_; vector<SharedPtr<ObjectNode> > children_; SharedPtr<Geometry> geometry_; ObjectNode() : enabled_(false) , favourite_(false) , isRoot_(false) , weight_(1.0f) , counter_(0) { } void serialize(Archive& ar) { if (ar.filter(FILTER_OUTLINE)) { if (isRoot_) { #include "Icons/package.xpm" static Icon packageIcon(package_xpm); ar(packageIcon, "typeIcon", "^^"); } else if (children_.empty()) { #include "Icons/page.xpm" static Icon pageIcon(page_xpm); ar(pageIcon, "typeIcon", "^^"); } else { #include "Icons/folder.xpm" static Icon folderIcon(folder_xpm); ar(folderIcon, "typeIcon", "^^"); } ar(name_, "name", "^!!<"); ar(geometry_, "geometry", "^>40>"); ar(children_, "children", "^>0>"); ar(IconToggle(favourite_, favourites_xpm, favouritesDisabled_xpm), "favourite", "^"); if (ar.isOutput()) { ++counter_; ar(counter_, "counter", "^>40>"); } } if (ar.filter(FILTER_PROPERTIES)) { if (!ar.filter(FILTER_OUTLINE)) { // prevent duplication when both filters enabled ar(name_, "name", "^"); } ar(color_, "color", "Color"); ar(enabled_, "enabled", "Enabled"); ar(weight_, "weight", "Weight"); ar(geometry_, "geometry", "Geometry"); ar(IconToggle(favourite_, favourites_xpm, favouritesDisabled_xpm), "favourite", "Favourite"); } } }; bool serialize(Archive& ar, SharedPtr<ObjectNode>& node, const char* name, const char* label) { if (!node) node = new ObjectNode(); return ar(yasli::asObject(node), name, label); } struct ObjectsData { SharedPtr<ObjectNode> root_; ww::signal0 signalChanged_; void serialize(Archive& ar) { ar(root_, "root", "<Tree"); } ObjectsData() { root_ = new ObjectNode; generate(); root_->isRoot_ = true; } void generate() { root_->name_ = "Root"; root_->children_.clear(); static int index = 0; for (int i = 0; i < 55; ++i) { char name[32]; sprintf_s(name, sizeof(name), "Node %d", index); ObjectNode node; node.name_ = name; node.color_.setHSV((index % 10) / 9.0f * 360.0f, 1.0f, 1.0f); root_->children_.push_back(new ObjectNode(node)); ++index; } signalChanged_.emit(); } } objectsData; class ObjectsWidget : public ww::HSplitter { public: ww::PropertyTree* outlineTree_; void onGenerate() { objectsData.generate(); } ObjectsWidget() { outlineTree_ = new ww::PropertyTree(); ww::VBox* vbox = new ww::VBox(); { outlineTree_->setFilter(FILTER_OUTLINE); outlineTree_->setCompact(true); outlineTree_->setUndoEnabled(true, false); outlineTree_->setShowContainerIndices(false); outlineTree_->setExpandLevels(2); objectsData.signalChanged_.connect(this, &ObjectsWidget::onDataChanged); vbox->add(outlineTree_, PACK_FILL); ww::Button* button = new ww::Button("Generate New Tree", 2); button->signalPressed().connect(this, &ObjectsWidget::onGenerate); vbox->add(button, PACK_COMPACT); } add(vbox, 0.3f); ww::PropertyTree* propertyTree = new ww::PropertyTree(); propertyTree->setFilter(FILTER_PROPERTIES); propertyTree->signalObjectChanged().connect(this, &ObjectsWidget::onPropertyChanged); propertyTree->setUndoEnabled(true, false); propertyTree->setExpandLevels(2); add(propertyTree); outlineTree_->attachPropertyTree(propertyTree); outlineTree_->attach(yasli::Serializer(objectsData)); } void onDataChanged() { outlineTree_->revert(); } void onPropertyChanged(const yasli::Object& object) { //outlineTree_->revertObject(object.address()); } }; ww::Widget* createObjectsSample() { return new ObjectsWidget(); }
21.779221
97
0.651163
[ "geometry", "object", "vector" ]
629ae048344523d58ac692958f1aa51815192f45
15,407
cpp
C++
Samples/Win7Samples/dataaccess/oledb/sampprov/rowset.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/dataaccess/oledb/sampprov/rowset.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/dataaccess/oledb/sampprov/rowset.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
//-------------------------------------------------------------------- // Microsoft OLE DB Sample Provider // (C) Copyright 1991 - 1999 Microsoft Corporation. All Rights Reserved. // // @doc // // @module ROWSET.CPP | CRowset object implementation // // // Includes ------------------------------------------------------------------ #include "headers.h" static const int MAX_BITS = 1008; static const int TYPE_CHAR = 1; static const int TYPE_SLONG = 3; // Code ---------------------------------------------------------------------- // CRowset::CRowset ---------------------------------------------------------- // // @mfunc Constructor for this class // // @rdesc NONE // CRowset::CRowset ( LPUNKNOWN pUnkOuter //@parm IN | Outer Unkown Pointer ) // invoke ctor for base class : CBaseObj( BOT_ROWSET ) { // Initialize simple member vars m_cRef = 0L; m_pUnkOuter = pUnkOuter ? pUnkOuter : this; // Intialize buffered row count + pointers to allocated memory m_pFileio = NULL; m_cRows = 0; m_irowFilePos = 0; m_irowLastFilePos = 0; m_cbTotalRowSize = 0; m_cbRowSize = 0; m_irowMin = 0; m_ulRowRefCount = 0; m_pextbufferAccessor= NULL; m_pIBuffer = NULL; m_prowbitsIBuffer = NULL; m_pLastBindBase = NULL; m_rgbRowData = NULL; m_dwStatus = 0; m_pUtilProp = NULL; m_pCreator = NULL; m_wszFilePath[0] = L'\0'; m_wszDataSourcePath[0] = L'\0'; // Initially, NULL all contained interfaces m_pIAccessor = NULL; m_pIColumnsInfo = NULL; m_pIConvertType = NULL; m_pIRowset = NULL; m_pIRowsetChange = NULL; m_pIRowsetIdentity = NULL; m_pIRowsetInfo = NULL; m_pIGetRow = NULL; // Increment global object count. OBJECT_CONSTRUCTED(); return; } // CRowset::~CRowset --------------------------------------------------------- // // @mfunc Destructor for this class // // @rdesc NONE // CRowset:: ~CRowset ( void ) { // Free pointers. // (Note delete is safe for NULL ptr.) SAFE_DELETE( m_prowbitsIBuffer ); SAFE_DELETE( m_pUtilProp ); if (m_pIBuffer) ReleaseSlotList( m_pIBuffer ); // Free accessors. // Each accessor is allocated via new/delete. // We store an array of ptrs to each accessor (m_pextbufferAccessor). if (m_pextbufferAccessor) { HACCESSOR hAccessor, hAccessorLast; PACCESSOR pAccessor; m_pextbufferAccessor->GetFirstLastItemH(hAccessor, hAccessorLast); for (; hAccessor <= hAccessorLast; hAccessor++) { m_pextbufferAccessor->GetItemOfExtBuffer(hAccessor, &pAccessor); SAFE_DELETE( pAccessor ); } SAFE_DELETE( m_pextbufferAccessor ); } // Free contained interfaces SAFE_DELETE( m_pIAccessor ); SAFE_DELETE( m_pIColumnsInfo ); SAFE_DELETE( m_pIConvertType ); SAFE_DELETE( m_pIRowset ); SAFE_DELETE( m_pIRowsetChange ); SAFE_DELETE( m_pIRowsetIdentity ); SAFE_DELETE( m_pIRowsetInfo ); SAFE_DELETE( m_pIGetRow ); // free CFileio object if (m_pFileio) SAFE_DELETE( m_pFileio ); if( m_pCreator ) m_pCreator->GetOuterUnknown()->Release(); if( m_pParentObj ) m_pParentObj->GetOuterUnknown()->Release(); // Decrement global object count. OBJECT_DESTRUCTED(); return; } // CRowset::FInit ------------------------------------------------------------ // // @mfunc Initialize the rowset Object // // @rdesc Did the Initialization Succeed // @flag TRUE | Initialization succeeded // @flag FALSE | Initialization failed // BOOL CRowset::FInit ( CFileIO * pCFileio, //@parm IN | pointer to Fileio object CBaseObj * pParentBaseObj, //@parm IN | pointer to Base Object creating the rowset WCHAR * pwszFilePath, //@parm IN | The File Path of the csv file WCHAR * pwszDataSource //@parm IN | The datasource path ) { // Asserts assert(pCFileio); assert(pParentBaseObj); assert(m_pUnkOuter); assert(pParentBaseObj); LPUNKNOWN pIUnknown = m_pUnkOuter; m_pFileio = pCFileio; m_pParentObj = pParentBaseObj; m_pParentObj->GetOuterUnknown()->AddRef(); //-------------------- // Get FileInfo //-------------------- // Find # of columns in the result set. m_cCols = m_pFileio->GetColumnCnt(); if( m_cCols <= 0 ) return FALSE; m_cbRowSize = m_pFileio->GetRowSize(); if (FAILED( CreateHelperFunctions())) return FALSE; m_cbTotalRowSize = m_pIBuffer->cbSlot; //-------------------- // Perform binding //-------------------- // Bind result set columns to the first row of the internal buffer. // For each column bind it's data as well as length. Leave space for // derived status info. // Note that we could defer binding, but this way we can check for // bad errors before we begin. // We may need to bind again if going back and forth // with GetNextRows. assert(m_rgbRowData); if (FAILED( Rebind((BYTE *) GetRowBuff( m_irowMin, TRUE )))) return FALSE; // allocate utility object that manages our properties m_pUtilProp = new CUtilProp(); if (!m_pUtilProp) return FALSE; // Allocate contained interface objects // Note that our approach is simple - we always create *all* of the Rowset interfaces // If our properties were read\write (i.e., could be set), we would need to // consult properties to known which interfaces to create. // Also, none of our interfaces conflict. If any did conflict, then we could // not just blindly create them all. m_pIColumnsInfo = new CImpIColumnsInfo( this, pIUnknown ); m_pIConvertType = new CImpIConvertType(this, pIUnknown); m_pIRowset = new CImpIRowset( this, pIUnknown ); m_pIRowsetIdentity = new CImpIRowsetIdentity( this, pIUnknown ); m_pIRowsetInfo = new CImpIRowsetInfo( this, pIUnknown ); m_pIAccessor = new CImpIAccessor( this, pIUnknown ); m_pIGetRow = new CImpIGetRow( this, pIUnknown ); if (!m_pFileio->IsReadOnly()) m_pIRowsetChange = new CImpIRowsetChange( this, pIUnknown ); if (m_pIAccessor && FAILED(m_pIAccessor->FInit(TRUE))) return FALSE; StringCchCopyW(m_wszFilePath, sizeof(m_wszFilePath)/sizeof(WCHAR), pwszFilePath); StringCchCopyW(m_wszDataSourcePath, sizeof(m_wszDataSourcePath)/sizeof(WCHAR), pwszDataSource); // if all interfaces were created, return success return (BOOL) (m_pIAccessor && m_pIColumnsInfo && m_pIConvertType && m_pIRowset && m_pIRowsetIdentity && m_pIRowsetInfo && ((m_pFileio->IsReadOnly() && !m_pIRowsetChange) || (!m_pFileio->IsReadOnly() && m_pIRowsetChange)) && m_pIGetRow); } // CRowset::QueryInterface --------------------------------------------------- // // @mfunc Returns a pointer to a specified interface. Callers use // QueryInterface to determine which interfaces the called object // supports. // // @rdesc HRESULT indicating the status of the method // @flag S_OK | Interface is supported and ppvObject is set. // @flag E_NOINTERFACE | Interface is not supported by the object // @flag E_INVALIDARG | One or more arguments are invalid. // STDMETHODIMP CRowset::QueryInterface ( REFIID riid, LPVOID * ppv ) { if (NULL == ppv) return ResultFromScode( E_INVALIDARG ); // Place NULL in *ppv in case of failure *ppv = NULL; // This is the non-delegating IUnknown implementation if (riid == IID_IUnknown) *ppv = (LPVOID) this; else if (riid == IID_IAccessor) *ppv = (LPVOID) m_pIAccessor; else if (riid == IID_IColumnsInfo) *ppv = (LPVOID) m_pIColumnsInfo; else if (riid == IID_IConvertType) *ppv = (LPVOID) m_pIConvertType; else if (riid == IID_IRowset) *ppv = (LPVOID) m_pIRowset; else if (riid == IID_IRowsetChange && SupportIRowsetChange() ) *ppv = (LPVOID) m_pIRowsetChange; else if (riid == IID_IRowsetIdentity) *ppv = (LPVOID) m_pIRowsetIdentity; else if (riid == IID_IRowsetInfo) *ppv = (LPVOID) m_pIRowsetInfo; else if (riid == IID_IGetRow) *ppv = (LPVOID) m_pIGetRow; // If we're going to return an interface, AddRef it first if (*ppv) { ((LPUNKNOWN) *ppv)->AddRef(); return ResultFromScode( S_OK ); } else return ResultFromScode( E_NOINTERFACE ); } // CRowset::AddRef ----------------------------------------------------------- // // @mfunc Increments a persistence count for the object // // @rdesc Current reference count // STDMETHODIMP_( DBREFCOUNT ) CRowset::AddRef ( void ) { return ++m_cRef; } // CRowset::Release ---------------------------------------------------------- // // @mfunc Decrements a persistence count for the object and if // persistence count is 0, the object destroys itself. // // @rdesc Current reference count // STDMETHODIMP_( DBREFCOUNT ) CRowset::Release ( void ) { if (!--m_cRef) { this->m_pCreator->DecrementOpenRowsets(); delete this; return 0; } return m_cRef; } // CRowset::CreateHelperFunctions -------------------------------------------- // // @mfunc Creates Helper classes that are needed to manage the Rowset Object // // @rdesc HRESULT // @flag S_OK | Helper classes created // @flag E_FAIL | Helper classes were not created // HRESULT CRowset::CreateHelperFunctions ( void ) { //---------------------- // Create helper objects //---------------------- // Bit array to track presence/absense of rows. m_prowbitsIBuffer = new CBitArray; if( !m_prowbitsIBuffer || FAILED(m_prowbitsIBuffer->FInit(MAX_BITS, g_dwPageSize))) return ResultFromScode( E_FAIL ); // List of free slots. // This manages the allocation of sets of contiguous rows. if (FAILED( InitializeSlotList( MAX_TOTAL_ROWBUFF_SIZE / (ULONG)m_cbRowSize, (ULONG) m_cbRowSize, g_dwPageSize, m_prowbitsIBuffer, &m_pIBuffer, &m_rgbRowData ))) return ResultFromScode( E_FAIL ); // Locate some free slots. // Should be at very beginning. // This tells us which row we will bind to: m_irowMin. if (FAILED( GetNextSlots( m_pIBuffer, 1, &m_irowMin ))) return ResultFromScode( E_FAIL ); ReleaseSlots( m_pIBuffer, m_irowMin, 1 ); return ResultFromScode( S_OK ); } // CRowset::Rebind -------------------------------------------- // // @mfunc Establishes data offsets and type for the file // routines to place the data // // @rdesc HRESULT // @flag S_OK | Bindings set fine // @flag E_FAIL | Bindings could not be set // HRESULT CRowset::Rebind ( BYTE *pBase //@parm IN | Base pointer for Data Area ) { COLUMNDATA *pColumn; // Bind result set columns. // Use established types and sizes and offsets. // Bind to internal row buffer, area beginning with 'pRowBuff'. // // For each column, bind it's data as well as length. // Offsets point to start of COLUMNDATA structure. assert( pBase ); // Optimize by not doing it over again. if( pBase != m_pLastBindBase ) { m_pLastBindBase = 0; for (DBORDINAL cCols=1; cCols <= m_cCols; cCols++) { pColumn = m_pFileio->GetColumnData(cCols, (ROWBUFF *)pBase); if( FAILED( m_pFileio->SetColumnBind(cCols, pColumn)) ) return( E_FAIL ); } // Remember in case we bind to same place again. m_pLastBindBase = pBase; } return( S_OK ); } // CRowset::GetRowBuff-------------------------------------------- // // @mfunc Shorthand way to get the address of a row buffer. // Later we may extend this so that it can span several // non-contiguous blocks of memory. // // @rdesc Pointer to the buffer. // ROWBUFF* CRowset::GetRowBuff ( DBCOUNTITEM iRow, //@parm IN | Row to get address of. BOOL fDataLocation //@parm IN | Get the Data offset. ) { // This assumes iRow is valid... // How can we calculate maximum row? // Should we return NULL if it's out of range? assert( m_rgbRowData ); assert( m_cbRowSize ); assert( iRow > 0 ); // Get the LSTSlot address or the Data offset (We need to make sure this structure is properly aligned) if ( fDataLocation ) return (ROWBUFF *) ROUND_UP ((m_rgbRowData + m_cbTotalRowSize*iRow), COLUMN_ALIGNVAL); else return (ROWBUFF *) ROUND_UP ((m_rgbRowData + m_cbRowSize + (m_cbTotalRowSize*(iRow-1))), COLUMN_ALIGNVAL); } ////////////////////////////////////////////////////////////////////////////// // Helper functions Helper functions Helper functions ////////////////////////////////////////////////////////////////////////////// // GetInternalTypeFromCSVType ------------------------------------------------ // // @func This function returns the default OLE DB representation // for a data type // HRESULT GetInternalTypeFromCSVType ( SWORD swDataType, //@parm IN | Data Type BOOL fIsSigned, //@parm IN | Signed or Unsigned DWORD *pdwdbType //@parm OUT | OLE DB type for DBColumnInfo ) { static struct { SWORD swCSVType; BOOL fIsSigned; // 1=signed, 0=unsigned BOOL fSignedDistinction; // 1=signed matters DWORD dwdbType; } TypeTable[] = { {TYPE_CHAR, 0, 0, DBTYPE_STR }, {TYPE_SLONG, 1, 1, DBTYPE_I4 }, }; for (int j=0; j < NUMELEM( TypeTable ); j++) { if (swDataType == TypeTable[j].swCSVType // type match && (!TypeTable[j].fSignedDistinction // care about sign? || fIsSigned == TypeTable[j].fIsSigned)) // sign match { assert( pdwdbType ); *pdwdbType = TypeTable[j].dwdbType; return ResultFromScode( S_OK ); } } // Should never get here, since we supposedly have // a table of all possible CSV types. assert( !"Unmatched CSV Type." ); return ResultFromScode( E_FAIL ); } // SupportIRowsetChange ------------------------------------------------ // // @func This function returns if IrowsetChange is supported // BOOL CRowset::SupportIRowsetChange() { BOOL fIRowsetChange = FALSE; ULONG cPropSets = 0; DBPROPSET * rgPropSets = NULL; DBPROPID rgPropId[1]; DBPROPIDSET rgPropertySets[1]; // Get the value of the DBPROP_CANHOLDROWS property rgPropertySets[0].guidPropertySet = DBPROPSET_ROWSET; rgPropertySets[0].rgPropertyIDs = rgPropId; rgPropertySets[0].cPropertyIDs = 1; rgPropId[0] = DBPROP_IRowsetChange; // Get the IRowsetChange Property from m_pUtilProp GetCUtilProp()->GetProperties(PROPSET_ROWSET, 1, rgPropertySets, &cPropSets, &rgPropSets); // Get the Prompt value if( V_BOOL(&rgPropSets->rgProperties->vValue) == VARIANT_TRUE ) fIRowsetChange = TRUE; // release properties FreeProperties(&cPropSets, &rgPropSets); return fIRowsetChange; }
29.628846
108
0.593951
[ "object" ]
629e29b9a8196e48a444ebe7eb3b936b82a67d3b
3,657
cpp
C++
050_recursive_dir_scan/RecursiveDirScanLib/RecursiveDirScan.cpp
xenogenics/spl-for-beginners
a8e569fb40596b19bf784116de3914ef0f3d8ef3
[ "0BSD" ]
40
2015-10-17T17:35:01.000Z
2022-02-20T22:14:09.000Z
Examples-for-beginners/050_recursive_dir_scan/RecursiveDirScanLib/RecursiveDirScan.cpp
HelenaAH30/samples
e3b17d63339f7098b8d7f33bbf0b6002c1c602cf
[ "Apache-2.0" ]
65
2015-02-18T14:11:24.000Z
2021-03-08T16:49:42.000Z
Examples-for-beginners/050_recursive_dir_scan/RecursiveDirScanLib/RecursiveDirScan.cpp
HelenaAH30/samples
e3b17d63339f7098b8d7f33bbf0b6002c1c602cf
[ "Apache-2.0" ]
81
2015-03-13T13:36:31.000Z
2021-04-22T03:47:22.000Z
/* * RecursiveDirScan.cpp * * Created on: May 13, 2013 * Author: sen */ #include "RecursiveDirScan.h" namespace recursive_dir_scan { RecursiveDirScan::RecursiveDirScan() { // TODO Auto-generated constructor stub } // End of constructor RecursiveDirScan::~RecursiveDirScan() { // TODO Auto-generated destructor stub } // End of destructor // Define a method that creates and returns a singleton access to // our global RecursiveDirScan object. RecursiveDirScan & RecursiveDirScan::getRecursiveDirScanObject() { // A static variable that will get initialized only once per process. static RecursiveDirScan rds; // Return our singleton global RecursiveDirScan object. return rds; } // End of method getRecursiveDirScanObject // This method will get all the names of the files present in the given directory. // While collecting the file names, it will ignore any files that even partially match any // of the names in the ignore files list supplied by the caller. (See 2nd method // argument below.) // PLEASE NOTE THAT THIS METHOD IS RECURSIVE AND NO SPECIAL CHECK IS DONE FOR RECUSRION DEPTH. // SO, DON'T TRY TO RECURSIVELY ITERATE THROUGH TOO MANY SUB-DIRECTORIES. boolean RecursiveDirScan::getFileNamesInDirectory(rstring dirName, SPL::list<rstring> listOfFileNamesToBeIgnored, SPL::list<rstring> & listOfFileNamesFound, int32 & recursionLevel) { DIR *dp; struct dirent *dirp; // Increment the recursion level. recursionLevel++; if((dp = opendir(dirName.c_str())) == NULL) { return(false); } // Clear the list passed to us only during the very first entry into this recursive method. if (recursionLevel == 1) { SPL::Functions::Collections::clearM(listOfFileNamesFound); } while ((dirp = readdir(dp)) != NULL) { string tempStr = string(dirp->d_name); // Check and filter if this file is . or .. if (tempStr.compare(".") == 0) { continue; } if (tempStr.compare("..") == 0) { continue; } rstring fullPathName = dirName + "/" + tempStr; // If it is a sub-directory, recurse into it and look for more files. if (dirp->d_type == DT_DIR) { // Do recursive search now. getFileNamesInDirectory(fullPathName, listOfFileNamesToBeIgnored, listOfFileNamesFound, recursionLevel); } else { boolean ignoreThisFile = false; int32 sizeOfIgnoreFilesList = SPL::Functions::Collections::size(listOfFileNamesToBeIgnored); // We will ignore this file, if it even partially matches with // any of the user-specified file names in the ignoreFiles list. for (int32 cnt=0; cnt<sizeOfIgnoreFilesList; cnt++) { if (tempStr.find(listOfFileNamesToBeIgnored[cnt]) != string::npos) { // There is a partial match between the current filename found inside // the directory and one of the filenames in the ignoreFiles list. ignoreThisFile = true; break; } } // End of for loop. if (ignoreThisFile == true) { // Continue the while loop to get the next file that is present. continue; } // Append the filename to the list. SPL::Functions::Collections::appendM(listOfFileNamesFound, fullPathName); } // End of if(dirp->d_type == DT_DIR) } // End of while ((dirp = readdir(dp)) != NULL) closedir(dp); int32 sizeOfFileNamesFoundList = SPL::Functions::Collections::size(listOfFileNamesFound); // If there are no files found in the directory, return false. if (sizeOfFileNamesFoundList > 0) { return(true); } else { return(false); } } // End of method getFileNamesInDirectory } /* namespace recursive_dir_scan */
34.5
183
0.696199
[ "object" ]
62a00168deff45cac507e404695f63b99da25f64
7,267
cpp
C++
Core/Obfuscation.cpp
HikariObfuscatorSuite/hikari-modules
9159ceb22accb97cfe8cf4e2c7925b56ea347241
[ "Apache-2.0" ]
1
2022-01-05T03:39:42.000Z
2022-01-05T03:39:42.000Z
Core/Obfuscation.cpp
HikariObfuscatorSuite/hikari-modules
9159ceb22accb97cfe8cf4e2c7925b56ea347241
[ "Apache-2.0" ]
null
null
null
Core/Obfuscation.cpp
HikariObfuscatorSuite/hikari-modules
9159ceb22accb97cfe8cf4e2c7925b56ea347241
[ "Apache-2.0" ]
null
null
null
// For open-source license, please refer to [License](https://github.com/HikariObfuscator/Hikari/wiki/License). //===----------------------------------------------------------------------===// /* Hikari 's own "Pass Scheduler". Because currently there is no way to add dependency to transform passes Ref : http://lists.llvm.org/pipermail/llvm-dev/2011-February/038109.html */ #include "llvm/Transforms/Obfuscation/Obfuscation.h" #include <iostream> using namespace llvm; using namespace std; // Begin Obfuscator Options static cl::opt<uint64_t> AesSeed("aesSeed", cl::init(0x1337), cl::desc("seed for the PRNG")); static cl::opt<bool> EnableAntiClassDump("enable-acdobf", cl::init(false), cl::NotHidden, cl::desc("Enable AntiClassDump.")); static cl::opt<bool> EnableBogusControlFlow("enable-bcfobf", cl::init(false), cl::NotHidden, cl::desc("Enable BogusControlFlow.")); static cl::opt<bool> EnableFlattening("enable-cffobf", cl::init(false), cl::NotHidden, cl::desc("Enable Flattening.")); static cl::opt<bool> EnableBasicBlockSplit("enable-splitobf", cl::init(false), cl::NotHidden, cl::desc("Enable BasicBlockSpliting.")); static cl::opt<bool> EnableSubstitution("enable-subobf", cl::init(false), cl::NotHidden, cl::desc("Enable Instruction Substitution.")); static cl::opt<bool> EnableAllObfuscation("enable-allobf", cl::init(false), cl::NotHidden, cl::desc("Enable All Obfuscation.")); static cl::opt<bool> EnableFunctionCallObfuscate( "enable-fco", cl::init(false), cl::NotHidden, cl::desc("Enable Function CallSite Obfuscation.")); static cl::opt<bool> EnableStringEncryption("enable-strcry", cl::init(false), cl::NotHidden, cl::desc("Enable Function CallSite Obfuscation.")); static cl::opt<bool> EnableIndirectBranching("enable-indibran", cl::init(false), cl::NotHidden, cl::desc("Enable Indirect Branching.")); static cl::opt<bool> EnableFunctionWrapper("enable-funcwra", cl::init(false), cl::NotHidden, cl::desc("Enable Function Wrapper.")); // End Obfuscator Options static void LoadEnv() { if (getenv("SPLITOBF")) { EnableBasicBlockSplit = true; } if (getenv("SUBOBF")) { EnableSubstitution = true; } if (getenv("ALLOBF")) { EnableAllObfuscation = true; } if (getenv("FCO")) { EnableFunctionCallObfuscate = true; } if (getenv("STRCRY")) { EnableStringEncryption = true; } if (getenv("INDIBRAN")) { EnableIndirectBranching = true; } if (getenv("FUNCWRA")) { EnableFunctionWrapper = true;//Broken } if (getenv("BCFOBF")) { EnableBogusControlFlow = true; } if (getenv("ACDOBF")) { EnableAntiClassDump = true; } if (getenv("CFFOBF")) { EnableFlattening = true; } } namespace llvm { struct Obfuscation : public ModulePass { static char ID; Obfuscation() : ModulePass(ID) {} StringRef getPassName() const override { return StringRef("HikariObfuscationScheduler"); } bool runOnModule(Module &M) override { // Initial ACD Pass if (EnableAllObfuscation || EnableAntiClassDump) { ModulePass *P = createAntiClassDumpPass(); P->doInitialization(M); P->runOnModule(M); delete P; } // Now do FCO FunctionPass *FP = createFunctionCallObfuscatePass(EnableAllObfuscation || EnableFunctionCallObfuscate); FP->doInitialization(M); for (Module::iterator iter = M.begin(); iter != M.end(); iter++) { Function &F = *iter; if (!F.isDeclaration()) { FP->runOnFunction(F); } } delete FP; // Now Encrypt Strings ModulePass *MP = createStringEncryptionPass(EnableAllObfuscation || EnableStringEncryption); MP->runOnModule(M); delete MP; /* // Placing FW here does provide the most obfuscation however the compile time // and product size would be literally unbearable for any large project // Move it to post run if (EnableAllObfuscation || EnableFunctionWrapper) { ModulePass *P = createFunctionWrapperPass(); P->runOnModule(M); delete P; }*/ // Now perform Function-Level Obfuscation for (Module::iterator iter = M.begin(); iter != M.end(); iter++) { Function &F = *iter; if (!F.isDeclaration()) { FunctionPass *P = NULL; P = createSplitBasicBlockPass(EnableAllObfuscation || EnableBasicBlockSplit); P->runOnFunction(F); delete P; P = createBogusControlFlowPass(EnableAllObfuscation || EnableBogusControlFlow); P->runOnFunction(F); delete P; P = createFlatteningPass(EnableAllObfuscation || EnableFlattening); P->runOnFunction(F); delete P; P = createSubstitutionPass(EnableAllObfuscation || EnableSubstitution); P->runOnFunction(F); delete P; } } errs() << "Doing Post-Run Cleanup\n"; FunctionPass *P = createIndirectBranchPass(EnableAllObfuscation || EnableIndirectBranching); vector<Function *> funcs; for (Module::iterator iter = M.begin(); iter != M.end(); iter++) { funcs.push_back(&*iter); } for (Function *F : funcs) { P->runOnFunction(*F); } delete P; MP = createFunctionWrapperPass(EnableAllObfuscation || EnableFunctionWrapper); MP->runOnModule(M); delete MP; // Cleanup Flags vector<Function *> toDelete; for (Module::iterator iter = M.begin(); iter != M.end(); iter++) { Function &F = *iter; if (F.isDeclaration() && F.hasName() && F.getName().contains("hikari_")) { for (User *U : F.users()) { if (Instruction *Inst = dyn_cast<Instruction>(U)) { Inst->eraseFromParent(); } } toDelete.push_back(&F); } } for (Function *F : toDelete) { F->eraseFromParent(); } errs() << "Hikari Out\n"; return true; } // End runOnModule }; ModulePass *createObfuscationPass() { LoadEnv(); if (AesSeed!=0x1337) { cryptoutils->prng_seed(AesSeed); } else{ cryptoutils->prng_seed(); } cout<<"Initializing Hikari Core with Revision ID:"<<GIT_COMMIT_HASH<<endl; return new Obfuscation(); } } // namespace llvm char Obfuscation::ID = 0; INITIALIZE_PASS_BEGIN(Obfuscation, "obfus", "Enable Obfuscation", true, true) INITIALIZE_PASS_DEPENDENCY(AntiClassDump); INITIALIZE_PASS_DEPENDENCY(BogusControlFlow); INITIALIZE_PASS_DEPENDENCY(Flattening); INITIALIZE_PASS_DEPENDENCY(FunctionCallObfuscate); INITIALIZE_PASS_DEPENDENCY(IndirectBranch); INITIALIZE_PASS_DEPENDENCY(SplitBasicBlock); INITIALIZE_PASS_DEPENDENCY(StringEncryption); INITIALIZE_PASS_DEPENDENCY(Substitution); INITIALIZE_PASS_END(Obfuscation, "obfus", "Enable Obfuscation", true, true)
33.031818
111
0.611807
[ "vector", "transform" ]
62a3e400a48e5c46b676c8a120763c5320110985
8,189
hpp
C++
examples/mantevo/miniFE-1.1/optional/stk_mesh/base/Transaction.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
1
2019-11-26T22:24:12.000Z
2019-11-26T22:24:12.000Z
examples/mantevo/miniFE-1.1/optional/stk_mesh/base/Transaction.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
examples/mantevo/miniFE-1.1/optional/stk_mesh/base/Transaction.hpp
sdressler/objekt
30ee938f5cb06193871f802be0bbdae6ecd26a33
[ "BSD-3-Clause" ]
null
null
null
/*------------------------------------------------------------------------*/ /* Copyright 2010 Sandia Corporation. */ /* Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive */ /* license for use of this work by or on behalf of the U.S. Government. */ /* Export of this program may require a license from the */ /* United States Government. */ /*------------------------------------------------------------------------*/ #ifndef stk_mesh_Transaction_hpp #define stk_mesh_Transaction_hpp #include <set> #include <vector> #include <iosfwd> namespace stk{ namespace mesh { class Bucket; class BulkData; class Entity; class Part; /** \brief Bucket containers used to sort mesh entities by state * so that they can be accessed after modification_end() */ typedef std::vector<Bucket *> BucketList; /** \addtogroup stk_mesh_module * \{ */ //---------------------------------------------------------------------- /** \brief Transaction journal of modifications to the bulk data * during a transaction. Since the modification transaction * guarantees a path independent result of mesh entities when * modification_end() is called, the transaction just notes * the state of altered mesh entities when the transaction * was started. */ class Transaction { public: /* \brief The following are the variable type and valid values for * defining the type of transaction bucket. */ typedef unsigned char State; enum { NOT_IN_TRANSACTION = 0 , MODIFIED = 1, INSERTED = 2, DELETED = 3 }; /* \brief There are two different types of transactions: * incremental and bulk. This can be set when reseting a * transaction. */ enum TransactionType { INCREMENTAL = 1 , BULK = 2 }; public: /** \brief Bucket containers used to sort mesh entities by state * so that they can be accessed after modification_end() */ typedef std::vector<BucketList> BucketListByType; /** \brief Part list for tracking bulk transactions */ typedef std::set<Part *> PartSet; /** \brief Pretty print the transaction */ std::ostream & print_stream ( std::ostream &os ) const; /** \brief Retrieve buckets of a particular type that contain * modified entities. */ const BucketList & get_modified_buckets ( unsigned type ) const { return m_modified[type]; } /** \brief Retrieve buckets of a particular type that contain * deleted entities. */ const BucketList & get_deleted_buckets ( unsigned type ) const { return m_deleted[type]; } /** \brief Retrieve buckets of a particular type that contain * inserted entities. */ const BucketList & get_inserted_buckets ( unsigned type ) const { return m_inserted[type]; } /** \brief Retrieve a part vector of parts whose entities were * modified. */ void get_parts_with_modified_entities ( PartVector &pv ) const { translate_partset_to_partvector ( m_modified_parts , pv ); } /** \brief Retrieve a part vector of parts from which entities * were deleted. */ void get_parts_with_deleted_entities ( PartVector &pv ) const { translate_partset_to_partvector ( m_deleted_parts , pv ); } /** \brief Retrieve a part vector of parts into which entities * were inserted. */ void get_parts_with_inserted_entities ( PartVector &pv ) const { translate_partset_to_partvector ( m_inserted_parts , pv ); } private: /** \brief Pretty print helper */ void print_proc_transaction ( unsigned , std::ostream & ) const; /** \brief Pretty print helper */ void print_transaction ( unsigned , std::ostream & ) const; Transaction (); Transaction ( BulkData & , TransactionType ); Transaction & operator = ( const Transaction & ); ~Transaction (); /** \brief Unlike other parts of \ref stk::mesh , Transactions * manage their own memory. This method is called * during purge() to ensure the bucket containers are * in an appropriate state. Upon destruction, this * function is not called. */ void allocate_bucket_lists (); TransactionType m_transaction_type; BulkData &m_bulk_data; BucketListByType m_modified; BucketListByType m_deleted; BucketListByType m_inserted; PartSet m_modified_parts; PartSet m_deleted_parts; PartSet m_inserted_parts; std::set<Entity *> m_to_delete; void flush_deletes (); /** \brief At modification_begin(), the transaction log is purged. * This method will empty the m_modified and m_inserted lists and * delete the entities in m_deleted. */ void reset ( TransactionType type = BULK ); void flush (); /** \brief Let the transaction log know this entity has been * modified in some way. No relations are followed. */ void modify_sole_entity ( Entity &e ); /** \brief Let the transaction log know this entity has been * modified in some way. All entities for which e is in the * closure will also be marked modified. */ void modify_entity ( Entity & e ); /** \brief Let the transaction log know this entity has been added * to the local mesh */ void insert_entity ( Entity & e ); /** \brief Let the transaction log know this entity has been * removed from the local mesh */ void delete_entity ( Entity & e ); /** \brief Helper method to empty m_modified and m_inserted */ void purge_map ( BucketListByType & ); /** \brief Helper method to delete entities in m_deleted */ void purge_and_erase_map ( BucketListByType & ); /** \brief This method will use the declase bucket method in \ref * stk::mesh::Bucket . This returns the appropriate bucket to * store entity information in. */ Bucket *get_unfilled_transaction_bucket ( const unsigned *const , EntityRank , BucketList & , State ); /** \brief This method will use the declase bucket method in \ref * stk::mesh::Bucket . This returns the appropriate bucket to * store entity information in. The function is templated to avoid * confusing header inclusions. */ template <class ENTITY> Bucket *get_unfilled_transaction_bucket ( const ENTITY &e , BucketList &bm , State s ) { return get_unfilled_transaction_bucket ( e.bucket().key() , e.entity_rank() , bm , s ); } /** \brief This method will add an entity to a transaction bucket */ void add_entity_to_transaction_bucket ( Entity & , Bucket * ); /** \brief This method will remove an entity from its current * transaction bucket and place it in a new bucket. */ void swap_entity_between_transaction_buckets ( Entity & , BucketList & , BucketList & , State ); /** \brief This method will remove an entity from a transaction * bucket. */ void remove_entity_from_bucket ( Entity & , BucketList & ); /** \brief When a part contains an entity that needs logging, this * function will add that part to the particular part set, be it * modified, deleted, or inserted */ void add_parts_to_partset ( Entity & , PartSet & ); /** \brief This functions creates a PartVector from a PartSet */ void translate_partset_to_partvector ( const PartSet & , PartVector & ) const; // BulkData needs access to modify_entity, insert_entity, and // delete_entity. friend class BulkData; friend std::ostream & operator<< ( std::ostream &os , const Transaction &rhs ); }; inline std::ostream &operator<< ( std::ostream &os , const Transaction &rhs ) { return rhs.print_stream ( os ); } /** \brief Pretty print helper */ void print_bucket_list ( const BucketList & , std::ostream & ); /* * \} */ } } #endif
31.496154
106
0.627061
[ "mesh", "vector" ]
62a4115c79edc649720b101eb275632a01977104
3,725
hpp
C++
src/layer/common/dropout_layer-inl.hpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
114
2017-06-14T07:05:31.000Z
2021-06-13T05:30:49.000Z
src/layer/common/dropout_layer-inl.hpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
7
2017-11-17T08:16:55.000Z
2019-10-05T00:09:20.000Z
src/layer/common/dropout_layer-inl.hpp
pl8787/textnet-release
c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f
[ "Apache-2.0" ]
40
2017-06-15T03:21:10.000Z
2021-10-31T15:03:30.000Z
#ifndef TEXTNET_LAYER_DROPOUT_LAYER_INL_HPP_ #define TEXTNET_LAYER_DROPOUT_LAYER_INL_HPP_ #include <iostream> #include <fstream> #include <sstream> #include <set> #include <mshadow/tensor.h> #include "../layer.h" #include "../op.h" namespace textnet { namespace layer { template<typename xpu> class DropoutLayer : public Layer<xpu>{ public: DropoutLayer(LayerType type) { this->layer_type = type; } virtual ~DropoutLayer(void) {} virtual int BottomNodeNum() { return 1; } virtual int TopNodeNum() { return 1; } virtual int ParamNodeNum() { return 0; } virtual void Require() { // default value, just set the value you want this->defaults["rate"] = SettingV(0.5f); // require value, set to SettingV(), // it will force custom to set in config Layer<xpu>::Require(); } virtual void SetupLayer(std::map<std::string, SettingV> &setting, const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top, mshadow::Random<xpu> *prnd) { Layer<xpu>::SetupLayer(setting, bottom, top, prnd); utils::Check(bottom.size() == BottomNodeNum(), "DropoutLayer:bottom size problem."); utils::Check(top.size() == TopNodeNum(), "DropoutLayer:top size problem."); rate = setting["rate"].fVal(); utils::Check(rate >= 0.0 && rate <= 1.0, "Dropout rate must between 0.0 and 1.0."); } virtual void Reshape(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top, bool show_info = false) { utils::Check(bottom.size() == BottomNodeNum(), "DropoutLayer:bottom size problem."); utils::Check(top.size() == TopNodeNum(), "DropoutLayer:top size problem."); top[0]->Resize(bottom[0]->data.shape_, bottom[0]->length.shape_, true); mask.Resize(bottom[0]->data.shape_, true); if (show_info) { bottom[0]->PrintShape("bottom0"); top[0]->PrintShape("top0"); } } virtual void CheckReshape(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { // Check for reshape bool need_reshape = false; if (! (bottom[0]->data.shape_ == top[0]->data.shape_)) { need_reshape = true; } // Do reshape if (need_reshape) { this->Reshape(bottom, top); } } virtual void Forward(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { using namespace mshadow::expr; mshadow::Tensor<xpu, 4> bottom_data = bottom[0]->data; mshadow::Tensor<xpu, 4> top_data = top[0]->data; top[0]->length = F<op::identity>(bottom[0]->length); const float pkeep = 1.0f - rate; if (this->phrase_type == kTrain) { mask = F<op::threshold>(this->prnd_->uniform(mask.shape_), pkeep); top_data = bottom_data * mask; } else { top_data = bottom_data * pkeep; } } virtual void Backprop(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { using namespace mshadow::expr; mshadow::Tensor<xpu, 4> bottom_diff = bottom[0]->diff; mshadow::Tensor<xpu, 4> top_diff = top[0]->diff; if (this->prop_error[0]) { bottom_diff += top_diff * mask; } } protected: float rate; mshadow::TensorContainer<xpu, 4> mask; }; } // namespace layer } // namespace textnet #endif // LAYER_DROPOUT_LAYER_INL_HPP_
31.837607
76
0.56698
[ "vector" ]
62a80fe923710a6907a386df585dbe980dcbb25f
1,732
cc
C++
chrome/services/machine_learning/decision_tree_predictor.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/services/machine_learning/decision_tree_predictor.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/services/machine_learning/decision_tree_predictor.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <utility> #include "base/metrics/histogram_macros.h" #include "base/optional.h" #include "base/values.h" #include "chrome/services/machine_learning/decision_tree_predictor.h" #include "chrome/services/machine_learning/metrics.h" #include "chrome/services/machine_learning/public/cpp/decision_tree_model.h" namespace machine_learning { DecisionTreePredictor::DecisionTreePredictor( std::unique_ptr<DecisionTreeModel> model) : model_(std::move(model)) {} // static std::unique_ptr<DecisionTreePredictor> DecisionTreePredictor::FromModelSpec( mojom::DecisionTreeModelSpecPtr spec) { metrics::ScopedLatencyRecorder recorder( metrics::kDecisionTreeModelValidationLatency); return std::make_unique<DecisionTreePredictor>( DecisionTreeModel::FromModelSpec(std::move(spec))); } DecisionTreePredictor::~DecisionTreePredictor() = default; bool DecisionTreePredictor::IsValid() const { return model_ && model_->IsValid(); } void DecisionTreePredictor::Predict( const base::flat_map<std::string, float>& model_features, PredictCallback callback) { DCHECK(IsValid()); metrics::ScopedLatencyRecorder recorder( metrics::kDecisionTreeModelEvaluationLatency); double score = 0.0; mojom::DecisionTreePredictionResult result = model_->Predict(model_features, &score); recorder.RecordTimeElapsed(); UMA_HISTOGRAM_ENUMERATION(metrics::kDecisionTreeModelPredictionResult, result); std::move(callback).Run(result, score); } } // namespace machine_learning
30.385965
76
0.762702
[ "model" ]
62a836b8140cf4d0ec3a6b4d2a726c0d743fefd7
49,659
cpp
C++
gui/mainWindow.cpp
tjhladish/EpiFire
af7b680ae08b7f8d19da882df008927db28f406a
[ "BSD-3-Clause" ]
30
2015-04-29T05:13:02.000Z
2022-03-21T02:07:41.000Z
gui/mainWindow.cpp
tjhladish/EpiFire
af7b680ae08b7f8d19da882df008927db28f406a
[ "BSD-3-Clause" ]
2
2017-11-07T05:42:56.000Z
2020-07-20T16:32:02.000Z
gui/mainWindow.cpp
tjhladish/EpiFire
af7b680ae08b7f8d19da882df008927db28f406a
[ "BSD-3-Clause" ]
14
2015-04-29T20:31:00.000Z
2021-06-10T03:09:53.000Z
#include "mainWindow.h" #include <QRandomGenerator> #include <map> /*############################################################################# # # Class methods / Utilities # #############################################################################*/ void makeEditable(QLineEdit* lineEdit) { lineEdit->setReadOnly(false); QPalette pal = lineEdit->palette(); pal.setColor(lineEdit->backgroundRole(), Qt::white); lineEdit->setPalette(pal); } void makeReadonly(QLineEdit* lineEdit) { lineEdit->setReadOnly(true); QPalette pal = lineEdit->palette(); pal.setColor(lineEdit->backgroundRole(), Qt::transparent); lineEdit->setPalette(pal); } QString frequencyFormat(double numerator, double denominator) { QString text = QString::number(numerator); text.append(" (").append(QString::number(100.0 * numerator/denominator, 'g', 4)).append("%)"); return text; } /*############################################################################# # # Layout methods # #############################################################################*/ MainWindow::MainWindow() { // Constructor for the main interface centralWidget = new QWidget(this); tabWidget = new QTabWidget(this); tabWidget->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed)); leftBox = new QWidget(this); // Allow the leftBox to expand vertically, but not horizontally leftBox->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Expanding)); rightBox = new QSplitter(Qt::Vertical, this); createPlotPanel(); network = new Network("mynetwork",Network::Undirected); Network::seed(QRandomGenerator::global()->generate()); //TODO fully seed all bits? simulator = NULL; networkPlot = new GraphWidget(); maxNodesToPlot = 40000; netAnalysisDialog = new AnalysisDialog(this, AnalysisDialog::NETWORK, "Analysis of current network"); rep_ct = 0; J = 0; J_max = 1; resultsAnalysisDialog = new AnalysisDialog(this, AnalysisDialog::RESULTS, "Analysis of simulation results"); logEditor = new QTextEdit(); logEditor->setReadOnly(true); logEditor->setPlainText(tr("No output yet")); degDistDialog = new TextEditorDialog(this, "Degree distribution editor"); QHBoxLayout *mainLayout = new QHBoxLayout; QVBoxLayout *leftLayout = new QVBoxLayout; createControlButtonsBox(); createNetworkSettingsBox(); createSimulatorSettingsBox(); createPredictionsBox(); defaultSettings(); tabWidget->addTab(networkSettingsGroupBox, "Step &1: Choose a network"); tabWidget->addTab(simulatorSettingsGroupBox, "Step &2: Design a simulation"); leftLayout->addWidget(tabWidget); leftLayout->addWidget(predictionsGroupBox); leftLayout->addWidget(controlButtonsGroupBox); leftLayout->addWidget(logEditor); leftBox->setLayout(leftLayout); leftBox->setContentsMargins(0,0,0,0); setWindowTitle(tr("EpiFire")); createMenu(); mainLayout->setMenuBar(menuBar); mainLayout->addWidget(leftBox); mainLayout->addWidget(rightBox); centralWidget->setLayout(mainLayout); setCentralWidget(centralWidget); statusBar()->showMessage(generateNetMsg); //createNetworkAnalysis(); //createResultsAnalysis(); progressDialog = new QProgressDialog("", "Cancel", 0, 100); progressDialog->setWindowTitle("EpiFire status"); //progressDialog = new QProgressDialog("", "Cancel", 0, 100, this); progressDialog->setWindowModality(Qt::WindowModal); backgroundThread = new BackgroundThread(this); connect(backgroundThread,SIGNAL(completed(bool)),this,SLOT(netDoneUpdate(bool))); connect(backgroundThread,SIGNAL(completed(bool)),this,SLOT(updateNetworkPlot())); connect(backgroundThread,SIGNAL(finished()), this, SLOT(resetCursor())); connect(backgroundThread,SIGNAL(finished()), netAnalysisDialog, SLOT(updateGUI())); connect(this, SIGNAL(progressUpdated(int)),progressDialog,SLOT(setValue(int))); connect(progressDialog,SIGNAL(canceled()),this,SLOT(stopBackgroundThread())); connect(progressDialog,SIGNAL(accepted()),this,SLOT(disableCentralWidget())); connect(progressDialog,SIGNAL(rejected()),this,SLOT(enableCentralWidget())); networkBusy = false; simulatorBusy = false; } void MainWindow::createPlotPanel() { epiCurvePlot = new PlotView(this, "Epidemic curves", "Time", "Prevalence"); epiCurvePlot->setPlotType(PlotView::CURVEPLOT); epiCurvePlot->setToolTip("Absolute frequency of infectious nodes vs. time\nDouble-click plot to save image\nRight-click to save data"); statePlot = new PlotView(this, "Node state evolution", "Time", "Node ID"); statePlot->setPlotType(PlotView::STATEPLOT); statePlot->setToolTip("Progression of node states over time for 100 nodes\nBlue = susceptible, Red = infectious, Yellow = Recovered\nDouble-click plot to save image\nRight-click to save data"); connect(epiCurvePlot, SIGNAL(epiCurveAxisUpdated(double)), statePlot, SLOT(setRangeMax(double))); histPlot = new PlotView(this, "Histogram of epidemic sizes", "Epidemic size", "Frequency"); histPlot->setPlotType(PlotView::HISTPLOT); histPlot->setToolTip("Distribution of final epidemic sizes\nDouble-click plot to save image\nRight-click to save data"); QVBoxLayout *rightLayout = new QVBoxLayout; rightLayout->addWidget(statePlot); rightLayout->addWidget(epiCurvePlot); rightLayout->addWidget(histPlot); rightBox->setLayout(rightLayout); } void MainWindow::createMenu() { //Create 'File' menu menuBar = new QMenuBar(this); fileMenu = new QMenu(tr("&File"), this); openAction = fileMenu->addAction(tr("&Open edgelist file")); QAction* saveNetwork = fileMenu->addAction(tr("&Save network as edgelist")); //QAction* saveDataAction = fileMenu->addAction("Save epidemic curve data"); //QAction* savePlotAction = fileMenu->addAction("Save epidemic curve plot"); QAction* simulateAction = fileMenu->addAction(tr("&Run simulator")); QList<QKeySequence> simKeys; simKeys.append(Qt::Key_Return); simKeys.append(Qt::Key_Enter); simulateAction->setShortcuts(simKeys); QAction* resetToDefaultsAction = fileMenu->addAction(tr("Reset to &default values")); exitAction = fileMenu->addAction(tr("E&xit")); connect(openAction, SIGNAL(triggered()), this, SLOT(readEdgeList())); connect(saveNetwork, SIGNAL(triggered()), this, SLOT(saveEdgeList())); connect(simulateAction, SIGNAL(triggered()), this, SLOT(simulatorWrapper())); connect(resetToDefaultsAction, SIGNAL(triggered()), this, SLOT(defaultSettings())); connect(exitAction, SIGNAL(triggered()), this, SLOT(close())); //connect(saveDataAction, SIGNAL(triggered()), epiCurvePlot, SLOT(saveData())); //connect(savePlotAction, SIGNAL(triggered()), epiCurvePlot, SLOT(savePlot())); //Create 'Plot' menu QMenu* plotMenu = new QMenu(tr("&Plot"), this); QAction* drawNetworkPlot = plotMenu->addAction("Draw network"); plotMenu->addSeparator(); showStatePlot = plotMenu->addAction("Show node state plot"); showStatePlot->setCheckable(true); showStatePlot->setChecked(true); showEpiPlot = plotMenu->addAction("Show epidemic curve plot"); showEpiPlot->setCheckable(true); showEpiPlot->setChecked(true); showHistPlot = plotMenu->addAction("Show histogram"); showHistPlot->setCheckable(true); showHistPlot->setChecked(true); connect(drawNetworkPlot, SIGNAL(triggered()), this, SLOT(plotNetwork())); connect(showStatePlot, SIGNAL(triggered()), this, SLOT( showHideStatePlot() )); connect(showEpiPlot, SIGNAL(triggered()), this, SLOT( showHideEpiCurvePlot() )); connect(showHistPlot, SIGNAL(triggered()), this, SLOT( showHideHistPlot() )); connect(rightBox, SIGNAL(splitterMoved(int, int)), this, SLOT( updatePlotMenuFlags() )); //Create 'Network' menu QMenu* networkMenu = new QMenu(tr("&Network"), this); QAction* generateNetAction = networkMenu->addAction("Generate network"); QAction* showDegDistEditorAction = networkMenu->addAction(tr("Show degree distribution editor")); //QAction* loadNetAction = networkMenu->addAction("Import edge list"); QAction* showNetworkAnalysis = networkMenu->addAction("Network analysis"); QAction* reduceToGiantComponent = networkMenu->addAction("Remove all minor components"); generateNetAction->setShortcut(tr("Ctrl+G")); openAction->setShortcut(tr("Ctrl+O")); connect( generateNetAction, SIGNAL(triggered()), this, SLOT(generate_network_thread())); connect( showDegDistEditorAction, SIGNAL(triggered()), degDistDialog, SLOT(show())); //connect( loadNetAction, SIGNAL(triggered()), this, SLOT(readEdgeList())); connect( showNetworkAnalysis, SIGNAL(triggered()), netAnalysisDialog, SLOT(analyzeNetwork())); connect( reduceToGiantComponent, SIGNAL(triggered()), this, SLOT(removeMinorComponents())); //Create 'Results' menu QMenu* resultsMenu = new QMenu(tr("&Results"), this); QAction* showResultsAnalysis = resultsMenu->addAction("Simulation results analysis"); connect( showResultsAnalysis, SIGNAL(triggered()), resultsAnalysisDialog, SLOT(analyzeResults())); menuBar->addMenu(fileMenu); menuBar->addMenu(plotMenu); menuBar->addMenu(networkMenu); menuBar->addMenu(resultsMenu); } void MainWindow::updateProgress(int x) { emit progressUpdated((100*J + x)/J_max); } void MainWindow::createNetworkSettingsBox() { // Creates the main input forms and their labels // Define text boxes numnodesLine = new QLineEdit(); numnodesLine->setAlignment(Qt::AlignRight); numnodesLine->setValidator( new QIntValidator(2,INT_MAX,numnodesLine) ); poiLambdaLine = new QLineEdit(); poiLambdaLine->setAlignment(Qt::AlignRight); poiLambdaLine->setValidator( new QDoubleValidator(0.0, numeric_limits<double>::max(), 20, poiLambdaLine) ); expBetaLine = new QLineEdit(); expBetaLine->setAlignment(Qt::AlignRight); expBetaLine->setValidator( new QDoubleValidator(expBetaLine) ); powAlphaLine = new QLineEdit(); powAlphaLine->setAlignment(Qt::AlignRight); powAlphaLine->setValidator( new QDoubleValidator(powAlphaLine) ); conValueLine = new QLineEdit(); conValueLine->setAlignment(Qt::AlignRight); conValueLine->setValidator( new QIntValidator(0.0,INT_MAX,conValueLine) ); powKappaLine = new QLineEdit(); powKappaLine->setAlignment(Qt::AlignRight); powKappaLine->setValidator( new QDoubleValidator(0.0, numeric_limits<double>::max(), 20, powKappaLine) ); smwKLine = new QLineEdit(); smwKLine->setAlignment(Qt::AlignRight); smwKLine->setValidator( new QIntValidator(1, INT_MAX, smwKLine) ); smwBetaLine = new QLineEdit(); smwBetaLine->setAlignment(Qt::AlignRight); smwBetaLine->setValidator( new QDoubleValidator(0.0, 1.0, 20, smwBetaLine) ); netsourceLabel = new QLabel(tr("Network source:")); netfileLabel = new QLabel(tr("Filename")); netfileLine = new QLineEdit(); netsourceBox= new QComboBox(this); netsourceBox->addItem("Generate"); netsourceBox->addItem("Load from file"); // Define all of the labels, in order of appearance QLabel *numnodesLabel = new QLabel(tr("Number of nodes:")); distLabel = new QLabel(tr("Degree distribution:")); param1Label = new QLabel(tr("")); param2Label = new QLabel(tr("")); // Build degree distribution dropdown box distBox = new QComboBox; distBox->addItem("Poisson"); distBox->addItem("Exponential"); distBox->addItem("Power law"); distBox->addItem("Urban"); distBox->addItem("Constant"); distBox->addItem("Small world"); distBox->addItem("User-defined"); // Initialize layout to parameters for first distribution listed, and listen for changes defaultNetworkParameters(); connect(distBox,SIGNAL(currentIndexChanged (int)), this, SLOT(changeNetworkParameters(int))); changeNetSource(0); connect(netsourceBox,SIGNAL(currentIndexChanged (int)), this, SLOT(changeNetSource(int))); // Put everything together networkSettingsGroupBox = new QWidget(); networkSettingsGroupBox->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed)); QGridLayout *layout = new QGridLayout; //Network source layout->addWidget(netsourceLabel, 0, 0); layout->addWidget(netsourceBox, 0, 1); //fields for imported net layout->addWidget(netfileLabel, 2, 0); layout->addWidget(netfileLine, 2, 1); //fields for generated net layout->addWidget(numnodesLabel, 1, 0); layout->addWidget(numnodesLine, 1, 1); layout->addWidget(distLabel, 2, 0); layout->addWidget(distBox, 2, 1); layout->addWidget(param1Label, 3, 0); layout->addWidget(poiLambdaLine, 3, 1); layout->addWidget(expBetaLine, 3, 1); layout->addWidget(powAlphaLine, 3, 1); layout->addWidget(conValueLine, 3, 1); layout->addWidget(smwKLine, 3, 1); layout->addWidget(param2Label, 4, 0); layout->addWidget(powKappaLine, 4, 1); layout->addWidget(smwBetaLine, 4, 1); networkSettingsGroupBox->setLayout(layout); } void MainWindow::createSimulatorSettingsBox() { simLabel = new QLabel("Simulation type"); simBox = new QComboBox(this); simBox->addItem("Chain Binomial"); simBox->addItem("Percolation"); QLabel *numrunsLabel = new QLabel(tr("Number of runs:")); numrunsLine = new QLineEdit(); numrunsLine->setAlignment(Qt::AlignRight); numrunsLine->setValidator( new QIntValidator(1,10000,numrunsLine) ); transLine = new QLineEdit(); transLine->setAlignment(Qt::AlignRight); transLine->setValidator( new QDoubleValidator(0.0,1.0,20,transLine) ); transLine->setToolTip("Probability of transmission from infectious to susceptible neighbor\nRange: 0 to 1"); pzeroLine = new QLineEdit(); pzeroLine->setAlignment(Qt::AlignRight); pzeroLine->setValidator( new QIntValidator(1,INT_MAX,pzeroLine) ); pzeroLine->setToolTip("Number of randomly chosen individuals to start epidemic\nRange: [0, network size]"); infectiousPeriodLine = new QLineEdit(); infectiousPeriodLine->setAlignment(Qt::AlignRight); infectiousPeriodLine->setValidator( new QIntValidator(1,INT_MAX,infectiousPeriodLine) ); infectiousPeriodLine->setToolTip("Duration of infectious state (units = time steps)\nRange: positive integers"); QLabel *pzeroLabel = new QLabel(tr("Initially infected:")); QLabel *transLabel = new QLabel(tr("Transmissibility:")); infectiousPeriodLabel = new QLabel(tr("Infectious period:")); changeSimType(0); connect(simBox,SIGNAL(currentIndexChanged (int)), this, SLOT(changeSimType(int))); connect(transLine, SIGNAL(textChanged(QString)), this, SLOT(updateRZero())); connect(infectiousPeriodLine, SIGNAL(textChanged(QString)), this, SLOT(updateRZero())); connect(pzeroLine, SIGNAL(textChanged(QString)), this, SLOT(updateRZero())); // Put everything together simulatorSettingsGroupBox = new QWidget(); simulatorSettingsGroupBox->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed)); QGridLayout *layout = new QGridLayout; //SECOND COLUMN -- Simulation stuff layout->addWidget(simLabel, 0, 1); layout->addWidget(simBox, 0, 2); layout->addWidget(infectiousPeriodLabel, 1, 1); layout->addWidget(infectiousPeriodLine, 1, 2); layout->addWidget(transLabel, 2, 1); layout->addWidget(transLine, 2, 2); layout->addWidget(pzeroLabel, 3, 1); layout->addWidget(pzeroLine, 3, 2); layout->addWidget(numrunsLabel, 4, 1); layout->addWidget(numrunsLine, 4, 2); simulatorSettingsGroupBox->setLayout(layout); } void MainWindow::createControlButtonsBox() { //Creates the horizontal control box at the bottom of the interface controlButtonsGroupBox = new QGroupBox(tr("Step 3: Profit!")); QGridLayout *layout = new QGridLayout; clearNetButton = new QPushButton("Clear Network"); connect(clearNetButton, SIGNAL(clicked()), this, SLOT(clear_network())); layout->addWidget(clearNetButton, 0, 0); clearNetButton->setEnabled(false); //defaultSettingsButton = new QPushButton("Default Settings"); //connect(defaultSettingsButton, SIGNAL(clicked()), this, SLOT(defaultSettings())); //layout->addWidget(defaultSettingsButton, 0, 1); analyzeNetButton = new QPushButton("Analyze network"); connect(analyzeNetButton, SIGNAL(clicked()), netAnalysisDialog, SLOT(analyzeNetwork()) ); layout->addWidget(analyzeNetButton, 0, 1); loadNetButton = new QPushButton("Import Edge List"); connect(loadNetButton, SIGNAL(clicked()), this, SLOT(readEdgeList())); layout->addWidget(loadNetButton, 0, 2); generateNetButton = new QPushButton("Generate Network"); connect(generateNetButton, SIGNAL(clicked()), this, SLOT(generate_network_thread())); //connect(generateNetButton, SIGNAL(clicked()), this, SLOT(updateNetworkPlot())); layout->addWidget(generateNetButton, 0, 2); clearDataButton = new QPushButton("Clear data"); connect(clearDataButton, SIGNAL(clicked()), this, SLOT(clear_data())); layout->addWidget(clearDataButton, 1, 0); clearDataButton->setEnabled(false); //helpButton = new QPushButton("Help"); //connect(helpButton, SIGNAL(clicked()), this, SLOT(open_help())); //layout->addWidget(helpButton, 1, 1); drawNetButton = new QPushButton("Draw network"); connect(drawNetButton, SIGNAL(clicked()), this, SLOT(plotNetwork()) ); layout->addWidget(drawNetButton, 1, 1); runSimulationButton = new QPushButton("Run &Simulation"); connect(runSimulationButton, SIGNAL(clicked()), this, SLOT(simulatorWrapper())); runSimulationButton->setDefault(true); layout->addWidget(runSimulationButton, 1, 2); runSimulationButton->setEnabled(false); //Build checkbox retainDataCheckBox = new QCheckBox(tr("Retain data between runs")); layout->addWidget(retainDataCheckBox,2,1,2,2); controlButtonsGroupBox->setLayout(layout); } void MainWindow::createPredictionsBox() { rzeroLine = new QLineEdit(); makeReadonly(rzeroLine); rzeroLine->setAlignment(Qt::AlignRight); rzeroLine->setToolTip("Expected number of secondary infections caused\nby each infection early in the epidemic"); maPredictionLine = new QLineEdit(); makeReadonly(maPredictionLine); maPredictionLine->setAlignment(Qt::AlignRight); // maPredictionLine->setToolTip("Expected number of secondary infections caused\nby each infection early in the epidemic"); netPredictionLine = new QLineEdit(); makeReadonly(netPredictionLine); netPredictionLine->setAlignment(Qt::AlignRight); //netPredictionLine->setToolTip("Expected number of secondary infections caused\nby each infection early in the epidemic"); QLabel* rzeroLabel = new QLabel(tr("Expected R-zero:")); QLabel* maLabel = new QLabel(tr("Epi size (mass action model):")); QLabel* netLabel = new QLabel(tr("Epi size (network model):")); // Put everything together predictionsGroupBox = new QGroupBox("Theoretical predictions (Expected values given an epidemic occurs)"); predictionsGroupBox->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed)); QGridLayout *layout = new QGridLayout; //SECOND COLUMN -- Simulation stuff layout->addWidget(rzeroLabel, 0, 1); layout->addWidget(rzeroLine, 0, 2); layout->addWidget(maLabel, 1, 1); layout->addWidget(maPredictionLine, 1, 2); layout->addWidget(netLabel, 2, 1); layout->addWidget(netPredictionLine, 2, 2); predictionsGroupBox->setLayout(layout); } /*############################################################################# # # IO methods # #############################################################################*/ void MainWindow::saveEdgeList() { if(!network || network->size() == 0) { appendOutputLine("No network to save."); return;} QString startdir = "."; QString filename = QFileDialog::getSaveFileName( this, "Select file to save to:", startdir, "All Files(*.*)"); if (filename.size() == 0) return; // It would probably be best to have a flag for whether the network was generated (no names) or read in (has names) if (network->size() > 0 and network->get_nodes()[0]->get_name() != "") { // Nodes have names network->write_edgelist(filename.toStdString(), Network::NodeNames, ','); } else { network->write_edgelist(filename.toStdString(), Network::NodeIDs, ','); } } void MainWindow::readEdgeList() { QString startdir = "."; QString fileName = QFileDialog::getOpenFileName( this, "Select edge list file to load:", startdir, "Comma-separated-values (*.csv)(*.csv);;TAB-delimited (*.tab)(*.tab);;Space-delimited (*.space)(*.space)"); if(network) { delete(network); } netComponents.clear(); setCursor(Qt::WaitCursor); appendOutputLine("Importing network . . . "); network = new Network("mynetwork", Network::Undirected); char sep = ','; if ( fileName.endsWith(".tab", Qt::CaseInsensitive)) sep = '\t'; else if ( fileName.endsWith(".space", Qt::CaseInsensitive)) sep = ' '; network->read_edgelist(fileName.toStdString(), sep); //network->dumper(); network->validate(); netfileLine->setText(fileName); numnodesLine->setText(QString::number(network->size())); netDoneUpdate(true); //updateRZero(); //setCursor(Qt::ArrowCursor); } void MainWindow::appendOutput(QString s) { // Used to append output to the main textbox logEditor->moveCursor( QTextCursor::End) ; logEditor->insertPlainText(s); } // Used to append new 'paragraph' to the main textbox void MainWindow::appendOutputLine(QString s) { logEditor->append(s); logEditor->moveCursor( QTextCursor::End) ; } /*############################################################################# # # Update methods # #############################################################################*/ void MainWindow::defaultSettings() { //Resets GUI to its default settings (as specified in .h file) netsourceBox->setCurrentIndex(0); distBox->setCurrentIndex(0); defaultNetworkParameters(); numnodesLine->setText(default_network_size); simBox->setCurrentIndex(0); if (simBox->currentIndex() == 1) changeSimType(0); infectiousPeriodLine->setText(default_infectious_pd); transLine->setText(default_T); numrunsLine->setText(default_num_runs); pzeroLine->setText(default_P0); retainDataCheckBox->setChecked(true); } void MainWindow::changeNetSource(int source) { if(source == 1 ) { // load net from file netfileLabel->show(); netfileLine->show(); makeReadonly(netfileLine); makeReadonly(numnodesLine); loadNetButton->show(); generateNetButton->hide(); if (netfileLine->text() == "") { // it would be better if we had a flag to check numnodesLine->setText("0"); // whether the network had been read from a file statusBar()->showMessage(loadNetMsg); } else { numnodesLine->setText(QString::number(network->size())); statusBar()->showMessage(simulateMsg); } distBox->hide(); distLabel->hide(); changeNetworkParameters(3); } // generate random net else { netfileLabel->hide(); netfileLine->hide(); loadNetButton->hide(); generateNetButton->show(); distBox->show(); distLabel->show(); numnodesLine->setText(default_network_size); makeEditable(numnodesLine); changeNetworkParameters(distBox->currentIndex()); if (netfileLine->text() == "" and network->size() > 0) { // it would be better if we had a flag to check statusBar()->showMessage(simulateMsg); } else { statusBar()->showMessage(generateNetMsg); } } } // parameter line edits should not be recycled. it's the only way to remember what users were doing before. void MainWindow::defaultNetworkParameters() { //Changes the labels for the parameter boxes, and grays them out as appropriate expBetaLine->hide(); powAlphaLine->hide(); conValueLine->hide(); smwKLine->hide(); smwBetaLine->hide(); expBetaLine->setText(default_exp_param1); powAlphaLine->setText(default_pow_param1); conValueLine->setText(default_con_param1); smwKLine->setText(default_smw_param1); smwBetaLine->setText(default_smw_param2); param2Label->setText("Kappa:"); param2Label->hide(); powKappaLine->hide(); powKappaLine->setText(default_pow_param2); param1Label->setText("Lambda:"); param1Label->show(); poiLambdaLine->setText(default_poi_param1); poiLambdaLine->show(); } void MainWindow::changeNetworkParameters(int dist_type) { //Changes the labels for the parameter boxes, and shows/hides them out as appropriate if (dist_type == 0) { // Poisson expBetaLine->hide(); powAlphaLine->hide(); conValueLine->hide(); param2Label->hide(); powKappaLine->hide(); smwKLine->hide(); smwBetaLine->hide(); param1Label->setText("Lambda:"); param1Label->show(); poiLambdaLine->show(); } else if (dist_type == 1) { // Exponential poiLambdaLine->hide(); powAlphaLine->hide(); conValueLine->hide(); param2Label->hide(); powKappaLine->hide(); smwKLine->hide(); smwBetaLine->hide(); param1Label->setText("Beta:"); param1Label->show(); expBetaLine->show(); } else if (dist_type == 2) { // Power law poiLambdaLine->hide(); expBetaLine->hide(); conValueLine->hide(); smwKLine->hide(); smwBetaLine->hide(); param1Label->setText("Alpha:"); param1Label->show(); powAlphaLine->show(); param2Label->setText("Kappa:"); param2Label->show(); powKappaLine->show(); } else if (dist_type == 3) { // Urban param1Label->hide(); poiLambdaLine->hide(); expBetaLine->hide(); powAlphaLine->hide(); conValueLine->hide(); param2Label->hide(); powKappaLine->hide(); smwKLine->hide(); smwBetaLine->hide(); } else if (dist_type == 4) { // Constant poiLambdaLine->hide(); expBetaLine->hide(); powAlphaLine->hide(); param2Label->hide(); powKappaLine->hide(); smwKLine->hide(); smwBetaLine->hide(); param1Label->setText("Fixed degree:"); param1Label->show(); conValueLine->show(); } else if (dist_type == 5) { // Small world poiLambdaLine->hide(); expBetaLine->hide(); powAlphaLine->hide(); powKappaLine->hide(); conValueLine->hide(); param1Label->show(); param1Label->setText("Mean degree (even):"); param2Label->show(); param2Label->setText("Shuffled fraction:"); smwKLine->show(); smwBetaLine->show(); } else if (dist_type == 6) { // User-defined poiLambdaLine->hide(); expBetaLine->hide(); powAlphaLine->hide(); powKappaLine->hide(); conValueLine->hide(); smwKLine->hide(); smwBetaLine->hide(); param1Label->hide(); param1Label->setText(""); param2Label->hide(); param2Label->setText(""); } } void MainWindow::changeSimType(int type) { epiCurvePlot->clearData(); epiCurvePlot->replot(); if (type == 0) { // Chain Binomial double T = (transLine->text()).toDouble(); int d = (infectiousPeriodLine->text()).toInt(); transLine->setText( QString::number( convertTtoTCB(T, d) ) ); infectiousPeriodLabel->show(); infectiousPeriodLine->show(); } else { // Percolation double TCB = (transLine->text()).toDouble(); int d = (infectiousPeriodLine->text()).toInt(); transLine->setText( QString::number( convertTCBtoT(TCB, d) ) ); infectiousPeriodLabel->hide(); infectiousPeriodLine->hide(); } } void MainWindow::clear_data() { epiCurvePlot->clearData(); epiCurvePlot->replot(); statePlot->clearData(); statePlot->replot(); histPlot->clearData(); histPlot->replot(); resultsAnalysisDialog->updateResultsAnalysis(); rep_ct = 0; appendOutputLine("Epidemic data deleted"); clearDataButton->setEnabled(false); statusBar()->showMessage(clearedDataMsg, 1000); } void MainWindow::clear_network() { if(network) network->clear_nodes(); netComponents.clear(); updateRZero(); appendOutputLine("Network deleted"); runSimulationButton->setEnabled(false); netfileLine->setText(""); clearNetButton->setEnabled(false); statusBar()->showMessage(clearedNetMsg, 1000); } bool MainWindow::validateParameters() { double T = (transLine->text()).toDouble(); if (T < 0 || T > 1.0) { appendOutputLine("Transmissibility must be between 0.0 and 1.0"); return false; } int n = network->size(); int p = pzeroLine->text().toInt(); if (p < 0 || p > n) { appendOutputLine("Number of introductions must be between 0 and network size"); return false; } return true; } void MainWindow::updateRZero() { if (!network || network->size() == 0 || !validateParameters()) { rzeroLine->setText( "Undefined" ); maPredictionLine->setText( "Undefined" ); netPredictionLine->setText( "Undefined" ); return; } double T = getPercTransmissibility(); double R0 = convertTtoR0(T); rzeroLine->setText( QString::number(R0)); // final size predictions (mass action and network) int patient_zero_ct = pzeroLine->text().toInt(); int n = network->size(); double predictedSize = 0; double netPredictedSize = 0; if (patient_zero_ct > 0 && patient_zero_ct <= n) { predictedSize = (double) patient_zero_ct + ((double) n - patient_zero_ct) * maExpectedSize(R0, 0.0, 1.0); netPredictedSize = n * netExpectedSize(T, ((double) patient_zero_ct)/n); } maPredictionLine->setText( frequencyFormat( predictedSize, (double) n ) ); netPredictionLine->setText( frequencyFormat( netPredictedSize, (double) n ) ); } /*############################################################################# # # Epidemiology/network methods # #############################################################################*/ void MainWindow::simulatorWrapper() { //Connects the GUI information to the percolation simulator if (simulatorBusy) { return; } else { simulatorBusy = true; } { // Double check that simulation can be performed using current values int patient_zero_ct = pzeroLine->text().toInt(); bool failure = false; if (!network || network->size() == 0 ) { appendOutputLine("Network must be generated first."); failure = true; } else if (patient_zero_ct < 1) { appendOutputLine("Number of initial infections must be at least 1."); failure = true; } else if (patient_zero_ct > network->size()) { appendOutputLine("Number of initial infections cannot be greater than network size."); failure = true; } if (failure) { simulatorBusy = false; return; } } // Get values from textboxes double T = (transLine->text()).toDouble(); //CREATE SIMULATOR if(simulator) { delete(simulator); simulator=NULL; } if ( simBox->currentText() == "Chain Binomial") { int infectious_pd = (infectiousPeriodLine->text()).toInt(); simulator = new ChainBinomial_Sim(network, infectious_pd, T); } else { simulator = new Percolation_Sim(network); ((Percolation_Sim*) simulator)->set_transmissibility(T); } bool retain_data = retainDataCheckBox->isChecked(); if (! retain_data) { epiCurvePlot->clearData(); epiCurvePlot->replot(); // a bit clumsy, but it works } //RUN SIMULATION generate_sim_thread(); // it would be nice to replace disabling buttons with an event handler runSimulationButton->setEnabled(false); generateNetButton->setEnabled(false); loadNetButton->setEnabled(false); while (backgroundThread->isRunning()) { qApp->processEvents(); // qApp->processEvents(QEventLoop::ExcludeUserInputEvents); } runSimulationButton->setEnabled(true); generateNetButton->setEnabled(true); loadNetButton->setEnabled(true); setCursor(Qt::ArrowCursor); clearDataButton->setEnabled(true); statusBar()->showMessage(simDoneMsg, 1000); progressDialog->setLabelText(""); //MAKE PLOTS if ( rightBox->sizes()[1] > 0) epiCurvePlot->replot(); // epicurveplot needs to be done 1st if ( rightBox->sizes()[0] > 0) statePlot->replot(); // b/c stateplot uses epicurve axis if ( rightBox->sizes()[2] > 0) histPlot->replot(); if ( resultsAnalysisDialog->isVisible() ) resultsAnalysisDialog->updateResultsAnalysis(); networkPlot->setNodeStates(statePlot->getData()); if ( networkPlot->isVisible() ) networkPlot->animateNetwork(); } void MainWindow::addStateData() { vector<int> node_states(maxNodesToPlot); vector<Node*> nodelist = network->get_nodes(); for (int i = 0; i < network->size() && (unsigned) i < node_states.size(); i++) { node_states[i] = (int) nodelist[i]->get_state(); } statePlot->addData(node_states); } void MainWindow::updatePlotMenuFlags() { QList<int> sizes = rightBox->sizes(); if (sizes[0] == 0) { showStatePlot->setChecked(false); } else { showStatePlot->setChecked(true); } if (sizes[1] == 0) { showEpiPlot->setChecked(false); } else { showEpiPlot->setChecked(true); } if (sizes[2] == 0) { showHistPlot->setChecked(false); } else { showHistPlot->setChecked(true); } } void MainWindow::showHideStatePlot() { QList<int> old = rightBox->sizes(); QList<int> newSizes; int H = old[0] + old[1] + old[2]; if (H == old[0]) { // means we're trying to close the only pane that's open showStatePlot->setChecked(true); return; } if (old[0] == 0) { newSizes << H/3 << 2*old[1]/3 << 2*old[2]/3; showStatePlot->setChecked(true); } else { newSizes << 0 << H * old[1]/(H-old[0]) << H * old[2]/(H-old[0]); showStatePlot->setChecked(false); } rightBox->setSizes(newSizes); } void MainWindow::showHideEpiCurvePlot() { QList<int> old = rightBox->sizes(); QList<int> newSizes; int H = old[0] + old[1] + old[2]; if (H == old[1]) { // means we're trying to close the only pane that's open showEpiPlot->setChecked(true); return; } if (old[1] == 0) { newSizes << 2*old[0]/3 << H/3 << 2*old[2]/3; showEpiPlot->setChecked(true); } else { newSizes << H * old[0]/(H-old[1]) << 0 << H * old[2]/(H-old[1]); showEpiPlot->setChecked(false); } rightBox->setSizes(newSizes); } void MainWindow::showHideHistPlot() { QList<int> old = rightBox->sizes(); QList<int> newSizes; int H = old[0] + old[1] + old[2]; if (H == old[2]) { // means we're trying to close the only pane that's open showHistPlot->setChecked(true); return; } if (old[2] == 0) { newSizes << 2*old[0]/3 << 2*old[1]/3 << H/3 ; showHistPlot->setChecked(true); } else { newSizes << H * old[0]/(H-old[2]) << H * old[1]/(H-old[2]) << 0; showHistPlot->setChecked(false); } rightBox->setSizes(newSizes); } void MainWindow::updateNetworkPlot() { if(networkPlot->isVisible() == false) return; plotNetwork(); } void MainWindow::plotNetwork() { cerr << "plotting network\n"; if (!network || network->size() == 0) { appendOutputLine("Please generate network first"); return; } else if ( network->size() > maxNodesToPlot ) { appendOutputLine(tr("Network is too large to draw (%1 node limit; < 100 nodes is recommended)").arg(maxNodesToPlot)); networkPlot->clear(); return; } networkPlot->clear(); vector<Node*> nodes = network->get_nodes(); map<int,int> id_to_idx; for (unsigned int idx = 0; idx < nodes.size(); ++idx) { id_to_idx[nodes[idx]->get_id()] = idx; //cerr << "attempting to add node " << idx << endl; networkPlot->addGNode(idx); //GNode* gn = networkPlot->addGNode(node->get_id(),0); // cerr << "e" << node->get_id() << " " << node->deg() << endl; } vector<Edge*> edges = network->get_edges(); set<Edge*> seen; for(unsigned int i=0; i < edges.size(); i++ ) { if (seen.count(edges[i]->get_complement())) continue; seen.insert(edges[i]); int idx1 = id_to_idx[edges[i]->get_start()->get_id()]; int idx2 = id_to_idx[edges[i]->get_end()->get_id()]; GNode* n1 = networkPlot->locateGNode(idx1); GNode* n2 = networkPlot->locateGNode(idx2); networkPlot->addGEdge(n1,n2,tr("%1-%2").arg(idx1).arg(idx2).toStdString(),0); } //networkPlot->setLayoutAlgorithm(GraphWidget::Circular); networkPlot->newLayout(); if (networkPlot->isHidden()) { networkPlot->resetZoom(); networkPlot->show(); } networkPlot->relaxNetwork(); networkPlot->animateNetwork(); } void MainWindow::removeMinorComponents() { netAnalysisDialog->generate_comp_thread(); // this block should instead call a wait function // or something similarly concise runSimulationButton->setEnabled(false); generateNetButton->setEnabled(false); loadNetButton->setEnabled(false); while (backgroundThread->isRunning()) { qApp->processEvents(); } runSimulationButton->setEnabled(true); generateNetButton->setEnabled(true); loadNetButton->setEnabled(true); // end block vector<Node*> giant; unsigned int i; cerr << "num componenets: " << netComponents.size() << endl; for (i = 0; i < netComponents.size(); i++) { if ((signed) netComponents[i].size() > network->size()/2) { giant = netComponents[i]; break; } } if (giant.empty()) { appendOutputLine("Network was not reduced: no giant component"); } else { for (unsigned int j = 0; j < netComponents.size(); j++) { if (j == i) continue; cerr << "deleting " << j << ", size " << netComponents[j].size() << endl; foreach (Node* n, netComponents[j]) { network->delete_node(n); } } netComponents.clear(); netComponents.push_back(giant); numnodesLine->setText(QString::number(network->size())); updateRZero(); updateNetworkPlot(); } } void MainWindow::resetCursor() { setCursor(Qt::ArrowCursor); } void MainWindow::enableCentralWidget() { centralWidget->setEnabled(true); } void MainWindow::disableCentralWidget() { centralWidget->setEnabled(false); } void MainWindow::generate_network_thread() { statusBar()->showMessage(busyNetMsg); setCursor(Qt::WaitCursor); appendOutputLine("Generating network . . . "); if(network) delete(network); netComponents.clear(); netfileLine->setText(""); int n = (numnodesLine->text()).toInt(); network = new Network("mynetwork", Network::Undirected); network->populate(n); backgroundThread->setThreadType(BackgroundThread::GENERATE_NET); progressDialog->setLabelText("Generating network"); backgroundThread->start(); } void MainWindow::generate_sim_thread() { setCursor(Qt::WaitCursor); backgroundThread->setThreadType(BackgroundThread::SIMULATE); progressDialog->setLabelText("Simulation running"); backgroundThread->start(); } void MainWindow::stopBackgroundThread() { if (backgroundThread) backgroundThread->stop(); //cerr << "thread supposedly stopped\n"; appendOutputLine("Process interrupted."); } bool MainWindow::generate_network() { DistType dist_type = (DistType) distBox->currentIndex(); double par1 = 0.0; double par2 = 0.0; if (dist_type == POI) { par1 = (poiLambdaLine->text()).toDouble(); } else if (dist_type == EXP) { par1 = (expBetaLine->text()).toDouble(); } else if (dist_type == POW) { par1 = (powAlphaLine->text()).toDouble(); par2 = (powKappaLine->text()).toDouble(); } else if (dist_type == CON) { par1 = (conValueLine->text()).toDouble(); } else if (dist_type == SMW) { par1 = (smwKLine->text()).toDouble(); par2 = (smwBetaLine->text()).toDouble(); } // 'true' on success, 'false' if interrupted or impossible return connect_network(network, dist_type, par1, par2); } void MainWindow::netDoneUpdate(bool success) { if ( success ) { updateRZero(); appendOutput("Done."); setCursor(Qt::ArrowCursor); runSimulationButton->setEnabled(true); clearNetButton->setEnabled(true); statusBar()->showMessage(simulateMsg); } else { setCursor(Qt::ArrowCursor); clear_network(); statusBar()->showMessage(generateNetMsg); } networkPlot->clearNodeStates(); updateNetworkPlot(); } bool MainWindow::connect_network (Network* net, DistType dist, double param1, double param2) { if (dist == POI) { if (param1 <= 0) { appendOutputLine("Poisson distribution parameter must be > 0"); return false; } return net->fast_random_graph(param1); } else if (dist == EXP) { if (param1 <= 0) { appendOutputLine("Exponential distribution parameter must be > 0"); return false; } return net->rand_connect_exponential(param1); } else if (dist == POW) { if (param2 <= 0) { appendOutputLine("Exponential distribution kappa parameter must be > 0"); return false; } return net->rand_connect_powerlaw(param1, param2); } else if (dist == URB) { vector<double> dist; double deg_array[] = {0, 0, 1, 12, 45, 50, 73, 106, 93, 74, 68, 78, 91, 102, 127, 137, 170, 165, 181, 181, 150, 166, 154, 101, 67, 69, 58, 44, 26, 24, 17, 6, 11, 4, 0, 6, 5, 3, 1, 1, 3, 1, 1, 0, 1, 0, 2}; dist.assign(deg_array,deg_array+47); dist = normalize_dist(dist, sum(dist)); return net->rand_connect_user(dist); } else if (dist == CON) { if (( (int) param1 * net->size()) % 2 == 1) { appendOutputLine("The sum of all degrees must be even\nThis is not possible with the network parameters you have specified"); return false; } vector<double> dist(param1+1, 0); dist[param1] = 1; return net->rand_connect_user(dist); } else if (dist == SMW) { if (param1 <= 0 || ((int) param1) % 2 != 0) { appendOutputLine("Small-world K parameter must be even and > 0"); return false; } if (param2 < 0.0 || param2 > 1.0) { appendOutputLine("Small-world beta parameter must be between 0 and 1"); return false; } return net->small_world( net->size(), (int) (param1/2), param2 ); } return false; } double MainWindow::calculate_T_crit() { vector<double> dist = normalize_dist( network->get_deg_dist() ); double numerator = 0;// mean degree, (= <k>) double denominator = 0; for (unsigned int k=1; k < dist.size(); k++) { numerator += k * dist[k]; denominator += k * (k-1) * dist[k]; } return numerator/denominator; } /* double MainWindow::maExpectedSize(double R0, double P0) { //This calculation is based on the expected epidemic size //for a mass action model. See Tildesley & Keeling (JTB, 2009). double S0 = 1.0 - P0; for (double p = 0.01; p <= 1.0; p += 0.01) { cerr << "i: " << p << endl; if (S0*(1-exp(-R0 * p)) <= p) return p; } return 1.0; }*/ /* double MainWindow::maExpectedSize(double R0, double P0, double guess) { if (R0 != R0) { // not a bug! checks to see if R0 is undefined return P0; } else { //This calculation is based on the expected epidemic size //for a mass action model. See Tildesley & Keeling (JTB, 2009). //cerr << "r: " << guess << endl; double S0 = 1.0 - P0; double p = S0*(1-exp(-R0 * guess)); if (fabs(p-guess) < 0.0001) {return p;} else return maExpectedSize(R0, P0, p); } } */ double MainWindow::maExpectedSize(double R0, double lower, double upper) { //Bisection method //This calculation is based on the expected epidemic size //for a mass action model. See Tildesley & Keeling (JTB, 2009). double S0 = 1.0; // assume no one is recovered or immune double guess = lower + (upper - lower) / 2.0; double p = S0*(1-exp(-R0 * guess)); //int max_itr = 100; int itr = 0; double epsilon = pow(10,-5); while (fabs(p-guess) > epsilon && itr < 100) { itr++; if (guess < p) { lower = guess; } else if (guess > p) { upper = guess; } guess = lower + (upper - lower) / 2.0; p = S0*(1-exp(-R0 * guess)); } return p; } // Calculate the theoretical epidemic size (and probability) based on // a network's degree distribution and transmissibility. Based on // Lauren's AMS 2007 paper. // WARNING: This approach to predicting epidemic size makes certain // assumptions that may be violated if you derive your own simulation class // or if the network you use is not randomly connected. Refer to Meyers (2007) // for more details. double _funcS(vector<double>&p, double u, double T) { // Eqn 25 in Meyers (2007) double S = 1; for (unsigned int k=0; k<p.size(); k++) { S -= p[k]*powl(1 + (u-1)*T, k); } return S; } double _funcU(vector<double>&p, double u, double T) { // Eqn 26 in Meyers (2007) double numerator = 0.0; double denominator = 0.0; for (unsigned int k=0; k<p.size(); k++) { numerator += k*p[k] * powl(1 + (u-1)*T, k-1); denominator += k*p[k]; } return numerator/denominator; } double MainWindow::netExpectedSize(double T, double P0_frac) { // This method uses a binary search with a twist to find the root // The twist is that we know some things about the behavior of the function: // it never goes from positive to negative as u increases; it either stays // positive, stays negative, or goes from negative to positive. double top = 1; // Top of search interval double bottom = 0; // Bottom of search interval double u=0.5; // Starting point vector<int> dist = network->get_deg_dist(); vector<double>p = normalize_dist( dist, sum(dist) ); // Degree distribution int i = 0; int max = 100; // max number of iterations double old_S = _funcS(p,u,T); double S = -1; //double a,b,c,d; double epsilon = pow(10,-10); double small_u = epsilon; double big_u = 1-epsilon; /*a = 0; b = 0.00001; c = 0.99999; d = 1; cout << "Transmissibility: " << T << " Fixed degree: " << deg << endl; cout << "u: " << a << "\t" << b << "\t" << c << "\t" << d << endl; cout << "F: " << a - funcU(p,a,T) << "\t" << b - funcU(p,b,T) << "\t" << c - funcU(p,c,T) << "\t" << d - funcU(p,d,T) << endl; cout << "S: " << funcS(p,0,T) << "\t" << funcS(p,0.00001,T) << "\t" << funcS(p,0.99999,T) << "\t" <<funcS(p,1,T) << endl; */ if (small_u - _funcU(p,small_u,T) > 0) { u = 0; S = 1; } else if (big_u - _funcU(p,big_u,T) < 0) { u = 1; S = 0; } else { while ( fabs(S-old_S) > pow(10,-5) && i < max ) { double y = u - _funcU(p,u,T); //cout << "u= " << u << " y= " << y << " S= " << funcS(p,u,T) << endl; if (y < 0) { bottom = u; u = u + (top - u)/2; } else if (y > 0) { top = u; u = u - (u-bottom)/2; } old_S = S; S = _funcS(p,u,T); } } return S * (1-P0_frac) + P0_frac; //cout << "Final u, S: " << u << " " << S << endl; } double MainWindow::getPercTransmissibility() { double T = (transLine->text()).toDouble(); int d = (infectiousPeriodLine->text()).toInt(); if ( simBox->currentText() == "Chain Binomial") { T = convertTCBtoT(T, d); // convert to perc's transmissibility } return T; } double MainWindow::convertR0toT(double R0) { return R0 * calculate_T_crit(); } double MainWindow::convertTtoR0(double T) { return T / calculate_T_crit(); } double MainWindow::convertTtoTCB (double T, int d) { return 1.0 - pow(1.0 - T, 1.0/(double) d); } double MainWindow::convertTCBtoT (double TCB, int d) { return 1.0 - pow(1.0 - TCB, d); } int MainWindow::percent_complete(int current, double predicted) { return current > predicted ? 99 : (int) (100 * current/predicted); }
35.932706
212
0.633943
[ "vector", "model" ]
62a8f7581c939db29aa7b0df0838558937fdbc88
17,407
cpp
C++
Demo/Nvidia/FXAA/FXAA.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
Demo/Nvidia/FXAA/FXAA.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
Demo/Nvidia/FXAA/FXAA.cpp
Alpha255/Rockcat
f04124b17911fb6148512dd8fb260bd84702ffc1
[ "MIT" ]
null
null
null
#include "FXAA.h" #include <D3DGraphic.h> #include <Camera.h> #include <D3DModel.h> extern D3DGraphic* g_Renderer; namespace FXAA { enum eConstants { eGatherCount = 2, ePatternCount = 5, eFxaaPatternCount = 6, eShadowMapSize = 2048, eRandomRotSize = 16 }; struct D3DTextures { Ref<ID3D11Texture2D> ProxyTex; Ref<ID3D11Texture2D> DepthTex; Ref<ID3D11Texture2D> RandomRotTex; Ref<ID3D11Texture2D> CopyResolveTex; }; struct D3DViews { Ref<ID3D11ShaderResourceView> ProxyTexSRV; Ref<ID3D11ShaderResourceView> DepthTexSRV; Ref<ID3D11ShaderResourceView> RandomRotTexSRV; Ref<ID3D11ShaderResourceView> CopyResolveTexSRV; Ref<ID3D11DepthStencilView> DepthTexDSV; Ref<ID3D11RenderTargetView> ProxyTexRTV; Ref<ID3D11RenderTargetView> EmptyRTV; }; struct D3DShaders { Ref<ID3D11VertexShader> MainVS; Ref<ID3D11VertexShader> ShadowMapVS; Ref<ID3D11VertexShader> FxaaVS; Ref<ID3D11VertexShader> QuadVS; Ref<ID3D11PixelShader> MainPS[ePatternCount]; Ref<ID3D11PixelShader> MainGatherPS[ePatternCount]; Ref<ID3D11PixelShader> FxaaPS[eFxaaPatternCount]; Ref<ID3D11PixelShader> EmptyPS; Ref<ID3D11PixelShader> QuadPS; }; struct D3DStates { Ref<ID3D11BlendState> ColorWritesOn; Ref<ID3D11BlendState> ColorWritesOff; Ref<ID3D11RasterizerState> CullBack; Ref<ID3D11RasterizerState> CullFront; Ref<ID3D11RasterizerState> WireFrame; Ref<ID3D11SamplerState> PointMirror; /// For rotation texture Ref<ID3D11SamplerState> LinearWrap; /// For diffuse texture Ref<ID3D11SamplerState> PointCmpClamp; /// Comparison sampler for shadowmap Ref<ID3D11SamplerState> Anisotropic; /// Anisotropic sampler for FXAA }; struct D3DConstantsBuffers { Ref<ID3D11Buffer> ShadowMap; Ref<ID3D11Buffer> Fxaa; }; struct ConstantsShadowMap { Matrix WVP; Matrix WVPLight; Vec4 AmbientColor; Vec4 DiffuseColor; Vec4 LightPos; Vec4 LightDiffuseClr; float InvRandomRotSize; float InvShadowMapSize; float FilterWidth; float Padding; }; struct ConstantsFxaa { Vec4 Fxaa; }; static bool s_UseGather = false; static uint32_t s_CurPattern = 0U; static uint32_t s_FxaaPreset = 4U; static float s_Radius = 15.0f; static float s_Theta = 1.5f * DirectX::XM_PI; static float s_Phi = DirectX::XM_PIDIV4; static Camera s_DefaultCamera; static Camera s_LightCamera; static D3DTextures s_Textures; static D3DViews s_Views; static D3DShaders s_Shaders; static D3DStates s_States; static D3DConstantsBuffers s_ConstantsBuffers; static Ref<ID3D11InputLayout> s_InputLayout; static Ref<ID3D11InputLayout> s_LayoutShadowMap; static D3D11_VIEWPORT s_Viewport; static D3D11_RECT s_ScissorRect; static D3DModel s_CryptModel; } using namespace FXAA; ApplicationFXAA::ApplicationFXAA() { s_LightCamera.SetViewParams(Vec3(9.0f, 15.0f, 9.0f), Vec3(0.0f, 0.0f, 0.0f)); } void ApplicationFXAA::CreateTextures() { g_Renderer->CreateTexture2D(s_Textures.CopyResolveTex, DXGI_FORMAT_R8G8B8A8_UNORM, m_Width, m_Height, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE); g_Renderer->CreateTexture2D(s_Textures.ProxyTex, DXGI_FORMAT_R8G8B8A8_UNORM, m_Width, m_Height, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE); /// Shadow map surfaces g_Renderer->CreateTexture2D(s_Textures.DepthTex, DXGI_FORMAT_R24G8_TYPELESS, eShadowMapSize, eShadowMapSize, D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE); /// Random rotation texture surface uint32_t texData[eRandomRotSize * eRandomRotSize] = { 0 }; for (uint32_t i = 0; i < eRandomRotSize * eRandomRotSize; ++i) { float angle = (float)rand() / RAND_MAX * DirectX::XM_2PI; float cosAngle = cosf(angle); float sinAngle = sinf(angle); int x1 = (int)(127.0f * cosAngle); int y1 = (int)(127.0f * sinAngle); int x2 = (int)(-127.0f * sinAngle); int y2 = (int)(127.0f * cosAngle); texData[i] = (uint32_t)(((x1 & 0xff) << 24) | ((y1 & 0xff) << 16) | ((x2 & 0xff) << 8) | (y2 & 0xff)); } g_Renderer->CreateTexture2D(s_Textures.RandomRotTex, DXGI_FORMAT_R8G8B8A8_SNORM, eRandomRotSize, eRandomRotSize, D3D11_BIND_SHADER_RESOURCE, 1U, 1U, 0U, 0U, D3D11_USAGE_DEFAULT, texData, sizeof(uint32_t) * eRandomRotSize); } void ApplicationFXAA::CreateViews() { assert(s_Textures.ProxyTex.Valid()); g_Renderer->CreateRenderTargetView(s_Views.ProxyTexRTV, s_Textures.ProxyTex.Ptr(), nullptr); g_Renderer->CreateShaderResourceView(s_Views.ProxyTexSRV, s_Textures.ProxyTex.Ptr()); assert(s_Textures.CopyResolveTex.Valid()); g_Renderer->CreateShaderResourceView(s_Views.CopyResolveTexSRV, s_Textures.CopyResolveTex.Ptr()); /// Shader resource view for shadowmap assert(s_Textures.DepthTex.Valid()); g_Renderer->CreateShaderResourceView(s_Views.DepthTexSRV, s_Textures.DepthTex.Ptr(), DXGI_FORMAT_R24_UNORM_X8_TYPELESS); g_Renderer->CreateDepthStencilView(s_Views.DepthTexDSV, s_Textures.DepthTex.Ptr(), DXGI_FORMAT_D24_UNORM_S8_UINT, D3D11_DSV_DIMENSION_TEXTURE2D); /// Shader resource view for random rotation texture assert(s_Textures.RandomRotTex.Valid()); g_Renderer->CreateShaderResourceView(s_Views.RandomRotTexSRV, s_Textures.RandomRotTex.Ptr(), DXGI_FORMAT_R8G8B8A8_SNORM); } void ApplicationFXAA::CreateInputLayoutAndShaders() { D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; g_Renderer->CreateVertexShaderAndInputLayout(s_Shaders.ShadowMapVS, s_InputLayout, layout, ARRAYSIZE(layout), "Fxaa.hlsl", "VS_ShadowMap"); g_Renderer->CreateVertexShader(s_Shaders.MainVS, "Fxaa.hlsl", "VS_Main"); g_Renderer->CreateVertexShader(s_Shaders.FxaaVS, "Fxaa.hlsl", "VS_Fxaa"); /// Pixel shaders static D3D_SHADER_MACRO PatternMacros[ePatternCount] = { { "PATTERN", "44" }, { "PATTERN", "64" }, { "PATTERN", "38" }, { "PATTERN", "84" }, { "PATTERN", "48" } }; static D3D_SHADER_MACRO GatherMacros[eGatherCount] = { { "NOUSEGATHER4", "" }, { "USEGATHER4", "" } }; static D3D_SHADER_MACRO PresetMacros[eFxaaPatternCount] = { { "FXAA_PRESET", "0" }, { "FXAA_PRESET", "1" }, { "FXAA_PRESET", "2" }, { "FXAA_PRESET", "3" }, { "FXAA_PRESET", "4" }, { "FXAA_PRESET", "5" } }; static D3D_SHADER_MACRO NullMacro = { nullptr, nullptr }; std::vector<D3D_SHADER_MACRO> Macros; for (uint32_t pat = 0U; pat < ePatternCount; ++pat) { Macros.clear(); Macros.push_back(PatternMacros[pat]); Macros.push_back(GatherMacros[0]); Macros.push_back(NullMacro); g_Renderer->CreatePixelShader(s_Shaders.MainPS[pat], "Fxaa.hlsl", "PS_Main", (const D3D_SHADER_MACRO*)&*Macros.begin()); Macros.clear(); Macros.push_back(PatternMacros[pat]); Macros.push_back(GatherMacros[1]); Macros.push_back(NullMacro); g_Renderer->CreatePixelShader(s_Shaders.MainGatherPS[pat], "Fxaa.hlsl", "PS_Main", (const D3D_SHADER_MACRO*)&*Macros.begin()); } for (uint32_t pat = 0U; pat < eFxaaPatternCount; ++pat) { Macros.clear(); Macros.push_back(PresetMacros[pat]); g_Renderer->CreatePixelShader(s_Shaders.FxaaPS[pat], "Fxaa.hlsl", "PS_Fxaa", (const D3D_SHADER_MACRO*)&*Macros.begin()); } } void ApplicationFXAA::CreateMesh() { s_CryptModel.CreateFromSDKMesh(L"crypt.sdkmesh"); } void ApplicationFXAA::CreateStates() { /// Sampler state D3D11_SAMPLER_DESC samDesc; memset(&samDesc, 0, sizeof(D3D11_SAMPLER_DESC)); samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; samDesc.AddressU = D3D11_TEXTURE_ADDRESS_MIRROR; samDesc.AddressV = D3D11_TEXTURE_ADDRESS_MIRROR; samDesc.AddressW = D3D11_TEXTURE_ADDRESS_MIRROR; samDesc.MipLODBias = 0.0f; samDesc.MaxAnisotropy = 1; samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samDesc.BorderColor[0] = samDesc.BorderColor[1] = samDesc.BorderColor[2] = samDesc.BorderColor[3] = 0; samDesc.MinLOD = 0; samDesc.MaxLOD = D3D11_FLOAT32_MAX; g_Renderer->CreateSamplerState(s_States.PointMirror, &samDesc); samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; g_Renderer->CreateSamplerState(s_States.LinearWrap, &samDesc); samDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT; samDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; samDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; samDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; samDesc.ComparisonFunc = D3D11_COMPARISON_LESS; g_Renderer->CreateSamplerState(s_States.PointCmpClamp, &samDesc); samDesc.Filter = D3D11_FILTER_ANISOTROPIC; samDesc.AddressU = samDesc.AddressV = samDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; samDesc.MaxAnisotropy = 4; samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samDesc.MaxLOD = 0.0f; samDesc.MinLOD = 0.0f; g_Renderer->CreateSamplerState(s_States.Anisotropic, &samDesc); /// Blend state D3D11_BLEND_DESC blendDesc; memset(&blendDesc, 0, sizeof(D3D11_BLEND_DESC)); blendDesc.IndependentBlendEnable = false; blendDesc.RenderTarget[0].BlendEnable = false; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; g_Renderer->CreateBlendState(s_States.ColorWritesOn, &blendDesc); blendDesc.RenderTarget[0].RenderTargetWriteMask = 0U; g_Renderer->CreateBlendState(s_States.ColorWritesOff, &blendDesc); /// Rasterizer state g_Renderer->CreateRasterizerState(s_States.CullBack, D3D11_FILL_SOLID, D3D11_CULL_BACK); g_Renderer->CreateRasterizerState(s_States.CullFront, D3D11_FILL_SOLID, D3D11_CULL_FRONT); g_Renderer->CreateRasterizerState(s_States.WireFrame, D3D11_FILL_WIREFRAME); } void ApplicationFXAA::CreateConstantsBuffers() { g_Renderer->CreateConstantBuffer(s_ConstantsBuffers.ShadowMap, sizeof(ConstantsShadowMap), D3D11_USAGE_DYNAMIC, nullptr, D3D11_CPU_ACCESS_WRITE); g_Renderer->CreateConstantBuffer(s_ConstantsBuffers.Fxaa, sizeof(ConstantsFxaa), D3D11_USAGE_DYNAMIC, nullptr, D3D11_CPU_ACCESS_WRITE); } void ApplicationFXAA::SetupScene() { CreateTextures(); CreateViews(); CreateInputLayoutAndShaders(); CreateMesh(); CreateStates(); CreateConstantsBuffers(); s_Viewport = { 0.0f, 0.0f, float(m_Width), float(m_Height), 0.0f, 1.0f }; s_ScissorRect = { 0, 0, (long)m_Width, (long)m_Height }; } void ApplicationFXAA::DrawDebugShadowMap() { if (!s_LayoutShadowMap.Valid() && !s_Shaders.QuadVS.Valid()) { D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; g_Renderer->CreateVertexShaderAndInputLayout(s_Shaders.QuadVS, s_LayoutShadowMap, layout, ARRAYSIZE(layout), "Quad.hlsl", "VSMain"); } if (!s_Shaders.QuadPS.Valid()) { g_Renderer->CreatePixelShader(s_Shaders.QuadPS, "Quad.hlsl", "PSMain"); } g_Renderer->SetRenderTarget(g_Renderer->DefaultRenderTarget()); g_Renderer->SetInputLayout(s_LayoutShadowMap); g_Renderer->SetVertexShader(s_Shaders.QuadVS); g_Renderer->SetPixelShader(s_Shaders.QuadPS); g_Renderer->SetShaderResource(s_Views.DepthTexSRV, 1U, D3DGraphic::ePixelShader); g_Renderer->DrawQuad(0.5f, 0.0f, m_Width / 8.0f, m_Height / 8.0f); } void ApplicationFXAA::DrawShadowMap() { g_Renderer->ClearDepthStencil(g_Renderer->DefaultDepthStencil(), D3D11_CLEAR_DEPTH, 1.0f, 0U); g_Renderer->SetConstantBuffer(s_ConstantsBuffers.ShadowMap, 0U, D3DGraphic::eVertexShader); g_Renderer->SetConstantBuffer(s_ConstantsBuffers.ShadowMap, 0U, D3DGraphic::ePixelShader); Matrix mLightWorldViewInv = (s_LightCamera.GetWorldMatrix() * s_LightCamera.GetViewMatrix()).Inverse(); ConstantsShadowMap cbShadowMap; memset(&cbShadowMap, 0, sizeof(ConstantsShadowMap)); cbShadowMap.LightDiffuseClr = Vec4(1.0f, 1.0f, 1.0f, 1.0f); cbShadowMap.WVP = s_DefaultCamera.GetWorldMatrix() * s_DefaultCamera.GetViewMatrix() * s_DefaultCamera.GetProjMatrix(); cbShadowMap.WVPLight = s_LightCamera.GetWorldMatrix() * s_LightCamera.GetViewMatrix() * s_LightCamera.GetProjMatrix(); cbShadowMap.LightPos = Vec4(0.0f, 0.0f, 0.0f, 1.0f); cbShadowMap.LightPos.Transform(mLightWorldViewInv); cbShadowMap.AmbientColor = Vec4(0.2f, 0.2f, 0.2f, 1.0f); cbShadowMap.DiffuseColor = Vec4(0.8f, 0.8f, 0.8f, 1.0f); cbShadowMap.FilterWidth = 10.0f; cbShadowMap.InvRandomRotSize = 1.0f / eRandomRotSize; cbShadowMap.InvShadowMapSize = 1.0f / eShadowMapSize; g_Renderer->UpdateBuffer(s_ConstantsBuffers.ShadowMap, &cbShadowMap, sizeof(ConstantsShadowMap)); D3D11_RECT shadowMapRect = { 0, eShadowMapSize, 0, eShadowMapSize }; D3D11_VIEWPORT shadowMapViewport = { 0.0f, 0.0f, (float)eShadowMapSize, (float)eShadowMapSize, 0.0f, 1.0f }; g_Renderer->SetScissorRects(&shadowMapRect); g_Renderer->SetViewports(&shadowMapViewport); g_Renderer->SetRenderTarget(s_Views.EmptyRTV); g_Renderer->SetDepthStencil(s_Views.DepthTexDSV); g_Renderer->ClearDepthStencil(s_Views.DepthTexDSV, D3D11_CLEAR_DEPTH, 1.0f, 0U); g_Renderer->SetInputLayout(s_InputLayout); g_Renderer->SetVertexShader(s_Shaders.ShadowMapVS); g_Renderer->SetPixelShader(s_Shaders.EmptyPS); g_Renderer->SetBlendState(s_States.ColorWritesOff, Vec4(0.0f, 0.0f, 0.0f, 0.0f), 0xffffffff); g_Renderer->SetRasterizerState(s_States.CullFront); ///s_CryptModel.DrawCustom(); g_Renderer->SetBlendState(s_States.ColorWritesOn, Vec4(0.0f, 0.0f, 0.0f, 0.0f), 0xffffffff); g_Renderer->SetRasterizerState(s_States.CullBack); g_Renderer->SetScissorRects(&s_ScissorRect); g_Renderer->SetViewports(&s_Viewport); DrawDebugShadowMap(); } void ApplicationFXAA::RenderScene() { if (s_FxaaPreset) { g_Renderer->ClearRenderTarget(s_Views.ProxyTexRTV, nullptr); } else { g_Renderer->ClearRenderTarget(g_Renderer->DefaultRenderTarget(), nullptr); } DrawShadowMap(); //ConstantsFxaa cbFxaa; //memset(&cbFxaa, 0, sizeof(ConstantsFxaa)); //cbFxaa.Fxaa = Vec4(1.0f / m_Width, 1.0f / m_Height, 0.0f, 0.0f); //g_Renderer->UpdateBuffer(s_ConstantsBuffers.Fxaa, &cbFxaa, sizeof(ConstantsFxaa)); //g_Renderer->SetConstantBuffer(s_ConstantsBuffers.Fxaa, 1U, D3DGraphic::eVertexShader); //g_Renderer->SetConstantBuffer(s_ConstantsBuffers.Fxaa, 1U, D3DGraphic::ePixelShader); //if (s_FxaaPreset) //{ // g_Renderer->SetRenderTarget(s_Views.ProxyTexRTV); //} //else //{ // g_Renderer->SetRenderTarget(g_Renderer->DefaultRenderTarget()); //} //g_Renderer->SetVertexShader(s_Shaders.MainVS); //if (s_UseGather) //{ // g_Renderer->SetPixelShader(s_Shaders.MainGatherPS[s_CurPattern]); //} //else //{ // g_Renderer->SetPixelShader(s_Shaders.MainPS[s_CurPattern]); //} //ID3D11SamplerState* ppSamplerStates[4] = { // s_States.PointMirror, // s_States.LinearWrap, // s_States.PointCmpClamp, // s_States.Anisotropic //}; //g_Renderer->SetSamplerStates(ppSamplerStates, 0U, 4U); //ID3D11ShaderResourceView* ppShaderResourceViews[2] = { // s_Views.DepthTexSRV, // s_Views.RandomRotTexSRV //}; //g_Renderer->SetShaderResource(ppShaderResourceViews, 1U, 2U); //s_CryptModel.DrawCustom(); //ID3D11ShaderResourceView* pEmptySRV = nullptr; //g_Renderer->SetShaderResource(&pEmptySRV, 1U, 1U); //if (s_FxaaPreset) //{ // g_Renderer->SetRenderTarget(g_Renderer->DefaultRenderTarget()); // g_Renderer->SetVertexShader(s_Shaders.FxaaVS); // g_Renderer->SetPixelShader(s_Shaders.FxaaPS[s_FxaaPreset - 1]); // D3D11_TEXTURE2D_DESC backBufferDesc; // g_Renderer->GetBackBufferDesc(backBufferDesc); // if (backBufferDesc.SampleDesc.Count > 1U) // { // g_Renderer->ResolveSubResource(s_Textures.CopyResolveTex, s_Textures.ProxyTex, 0U, 0U, DXGI_FORMAT_R8G8B8A8_UNORM); // g_Renderer->SetShaderResource(s_Views.CopyResolveTexSRV.Reference()); // g_Renderer->Draw(4U, 0U, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); // } // else // { // g_Renderer->SetShaderResource(s_Views.ProxyTexSRV.Reference()); // g_Renderer->Draw(4U, 0U); // } //} } void ApplicationFXAA::UpdateScene(float /*elapsedTime*/, float /*totalTime*/) { float x = s_Radius * sinf(s_Phi) * cosf(s_Theta); float z = s_Radius * sinf(s_Phi) * sinf(s_Theta); float y = s_Radius * cosf(s_Phi); s_DefaultCamera.SetViewParams(Vec3(x, y, z), Vec3(0.0f, 0.0f, 0.0f)); s_LightCamera.SetViewParams(Vec3(x, y, z), Vec3(0.0f, 0.0f, 0.0f)); } void ApplicationFXAA::ResizeWindow(uint32_t width, uint32_t height) { s_DefaultCamera.SetProjParams(DirectX::XM_PIDIV4, (float)width / height, 1.0f, 1000.0f); s_LightCamera.SetProjParams(DirectX::XM_PIDIV4, 1.0f, 0.1f, 1000.0f); Base::ResizeWindow(width, height); s_Viewport = { 0.0f, 0.0f, float(m_Width), float(m_Height), 0.0f, 1.0f }; s_ScissorRect = { 0, 0, (long)m_Width, (long)m_Height }; } void ApplicationFXAA::MouseMove(WPARAM wParam, int x, int y) { if ((wParam & MK_LBUTTON) != 0) { float dx = DirectX::XMConvertToRadians(0.25f * static_cast<float>(x - m_LastMousePos[0])); float dy = DirectX::XMConvertToRadians(0.25f * static_cast<float>(y - m_LastMousePos[1])); s_Theta += dx; s_Phi += dy; s_Phi = Math::Clamp(s_Phi, 0.1f, DirectX::XM_PI - 0.1f); } else if ((wParam & MK_RBUTTON) != 0) { float dx = 0.0051f * static_cast<float>(x - m_LastMousePos[0]); float dy = 0.0051f * static_cast<float>(y - m_LastMousePos[1]); s_Radius += dx - dy; s_Radius = Math::Clamp(s_Radius, 3.0f, 15.0f); } m_LastMousePos[0] = x; m_LastMousePos[1] = y; }
32.658537
128
0.75889
[ "vector", "transform" ]
62ab10f73c63383b84daa54aecfe464b14c5977e
3,410
hpp
C++
build/msvs2017/apps/vulkan_glfw_app/vulkan_meshes.hpp
SergeyLebedkin/VulkanPlayground
db90a0272efdc1dc6f164ce7c22ac36bb65e1280
[ "MIT" ]
null
null
null
build/msvs2017/apps/vulkan_glfw_app/vulkan_meshes.hpp
SergeyLebedkin/VulkanPlayground
db90a0272efdc1dc6f164ce7c22ac36bb65e1280
[ "MIT" ]
null
null
null
build/msvs2017/apps/vulkan_glfw_app/vulkan_meshes.hpp
SergeyLebedkin/VulkanPlayground
db90a0272efdc1dc6f164ce7c22ac36bb65e1280
[ "MIT" ]
null
null
null
#pragma once #include "vulkan_material.hpp" #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <array> // VulkanMesh // VulkanMeshMaterial // VulkanMeshMatObj // VulkanMeshMatObjIndexed // VulkanMeshMatObjTBN // VulkanMeshMatObjTBNIndexed // VulkanMeshMatObjSkinned // VulkanMeshMatObjSkinnedIndexed // VulkanMeshMatObjSkinnedTBN // VulkanMeshMatObjSkinnedTBNIndexed // VulkanMesh class VulkanMesh : public VulkanContextDrawableObject { public: // primitive topology VkPrimitiveTopology primitiveTopology{}; public: // constructor and destructor VulkanMesh(VulkanContext& context) : VulkanContextDrawableObject(context) {}; ~VulkanMesh() {} }; // VulkanMeshMaterial class VulkanMeshMaterial : public VulkanMesh { public: // handle to material (can be NULL) VulkanMaterial* material{}; // material usage VulkanMaterialUsage materialUsage{}; public: // constructor and destructor VulkanMeshMaterial(VulkanContext& context) : VulkanMesh(context) {}; }; // VulkanMeshMatObj class VulkanMeshMatObj : public VulkanMeshMaterial { protected: // buffer handles std::array<VkBuffer, 3> bufferHandles; std::array<VkDeviceSize, 3> bufferOffsets; protected: // buffers VulkanBuffer bufferPos{}; VulkanBuffer bufferTex{}; VulkanBuffer bufferNrm{}; uint32_t vertexCount; public: // constructor and destructor VulkanMeshMatObj( VulkanContext& context, std::vector<glm::vec4>& pos, std::vector<glm::vec2>& tex, std::vector<glm::vec3>& nrm); ~VulkanMeshMatObj(); // draw void draw(VulkanCommandBuffer& commandBuffer) override; }; // VulkanMeshMatObjIndexed class VulkanMeshMatObjIndexed : public VulkanMeshMatObj { protected: // index buffer VulkanBuffer bufferInd{}; uint32_t indexCount; public: // constructor and destructor VulkanMeshMatObjIndexed( VulkanContext& context, std::vector<glm::vec4>& pos, std::vector<glm::vec2>& tex, std::vector<glm::vec3>& nrm, std::vector<uint32_t>& ind); ~VulkanMeshMatObjIndexed(); // draw void draw(VulkanCommandBuffer& commandBuffer) override; }; // VulkanMeshMatObjTBN class VulkanMeshMatObjTBN : public VulkanMeshMatObj { protected: // BPR buffer handles handles std::array<VkBuffer, 2> bufferHandlesTB; std::array<VkDeviceSize, 2> bufferOffsetsTB; protected: // buffers VulkanBuffer bufferTng{}; VulkanBuffer bufferBnm{}; public: // constructor and destructor VulkanMeshMatObjTBN( VulkanContext& context, std::vector<glm::vec4>& pos, std::vector<glm::vec2>& tex, std::vector<glm::vec3>& nrm, std::vector<glm::vec3>& tng, std::vector<glm::vec3>& bnm); ~VulkanMeshMatObjTBN(); // draw void draw(VulkanCommandBuffer& commandBuffer) override; }; // VulkanMeshMatObjTBNIndexed class VulkanMeshMatObjTBNIndexed : public VulkanMeshMatObjTBN { protected: // index buffer VulkanBuffer bufferInd{}; uint32_t indexCount; public: // constructor and destructor VulkanMeshMatObjTBNIndexed( VulkanContext& context, std::vector<glm::vec4>& pos, std::vector<glm::vec2>& tex, std::vector<glm::vec3>& nrm, std::vector<glm::vec3>& tng, std::vector<glm::vec3>& bnm, std::vector<uint32_t>& ind); ~VulkanMeshMatObjTBNIndexed(); // draw void draw(VulkanCommandBuffer& commandBuffer) override; }; // VulkanMeshMatObjSkinned class VulkanMeshMatObjSkinned : public VulkanMeshMaterial {};
24.710145
63
0.73871
[ "vector" ]
62aec0aa2b7d0ad4a40c22f12f1ac7a9c20d9014
4,400
cpp
C++
src_count_alleles/read_marker.cpp
schneebergerlab/GameteBinning_prac
c321186afa9fc68834ae6a6553eb7cd07ac66fd5
[ "MIT" ]
null
null
null
src_count_alleles/read_marker.cpp
schneebergerlab/GameteBinning_prac
c321186afa9fc68834ae6a6553eb7cd07ac66fd5
[ "MIT" ]
null
null
null
src_count_alleles/read_marker.cpp
schneebergerlab/GameteBinning_prac
c321186afa9fc68834ae6a6553eb7cd07ac66fd5
[ "MIT" ]
null
null
null
/* pls check the header file: read_marker.h for more info about this function. */ /* Date 2013-04-26 */ #include <fstream> #include <map> #include <vector> #include <cstring> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "is_number.h" #include "split_string.h" #include "globals.h" bool read_marker(char* fmarker, unsigned long* num_given, unsigned long* num_inuse) { if(fmarker==NULL) { printf("ERROR: Marker file is null, exited!\n"); exit(1); } std::ifstream fileMarker (fmarker); if(!fileMarker.is_open()) { printf("SNP file \'%s\' does NOT exist. Exited.\n", fmarker); exit(1); } if (verbose) { ALLELE1.clear(); // ALT allele ALLELE2.clear(); // REF allele QUALITY1.clear(); printf("Reading SNPs from file:\t\t\t%s...", fmarker); } char token='\t'; // caution! std::string line; while(fileMarker.good()) { line.clear(); getline(fileMarker, line); if(line.size() == 0) continue; if(line.find("#") != std::string::npos) {printf("# annotation line skipped.\n");continue;} if(line.find("\t-\t") != std::string::npos) continue; // caution! (*num_given) ++; vector<std::string> infoline=split_string(line, token); if(infoline.size() < 5) { printf("SNP info line requires at least 5 columns: %s. Skipped!\n", line.c_str()); continue; } std::string chr = infoline[1]; if(CHR2SIZE.find(chr) == CHR2SIZE.end()) {continue;} std::string pos = infoline[2]; if(!is_number(pos.c_str())) { printf("Warning: position info of a SNP should be a number (read_marker(...)).\n"); continue; } if (atol(pos.c_str()) > CHR2SIZE[chr]) { printf("Warning: position %ld of a SNP exceeds given chromosome size %ld. Skipped! \n", atol(pos.c_str()), CHR2SIZE[chr]); continue; } std::string pro = infoline[0]; // proj name std::string al1 = infoline[3]; // ref if background2 is not specified; or background allele std::string al2 = infoline[4]; // mut .. std::string qua = pro; // 'proj name' if(infoline.size() >= 6) { /* !!! caution: marker_score is a global variable */ if(atol(infoline[5].c_str()) < marker_score) continue; // filter a marker with quality int addi = 5; while(addi < infoline.size()) { qua += ","; qua += infoline[addi]; // 'proj name,quality, cov, avg_hits...' addi ++; } } // note that alleles created by SHOREmap create (for outcross function) have been swapped in its output, if they are from parentB. // that is, such markers should be treated the same as those from parentA. /* record info about al1, al2 */ if(background2 == 0) { ALLELE1.insert(std::pair<std::string, std::string>(chr+".#."+pos, al2)); // af to calculate ALLELE2.insert(std::pair<std::string, std::string>(chr+".#."+pos, al1)); } else { ALLELE1.insert(std::pair<std::string, std::string>(chr+".#."+pos, al1)); // af to calculate ALLELE2.insert(std::pair<std::string, std::string>(chr+".#."+pos, al2)); } /* QUALITY1 may only contain a project name if there is no quality info provided. */ // printf("%s\n", qua.c_str()); QUALITY1.insert(std::pair<std::string, std::string>(chr+".#."+pos,qua)); (*num_inuse) ++; } fileMarker.close(); if(verbose) { printf("done.\n"); printf("Markers given to inuse:\t\t\t%ld: %ld.\n", *num_given, *num_inuse); } if (ALLELE1.size()>0 || ALLELE2.size()>0) return true; // at least one SNP else return false; // no SNP }
38.26087
138
0.496591
[ "vector" ]
62b23303291ef4196bb5b725386b40eadada3d84
1,949
hh
C++
track/detail/CellInitializer.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
track/detail/CellInitializer.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
track/detail/CellInitializer.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
//---------------------------------*-C++-*-----------------------------------// /*! * \file track/detail/CellInitializer.hh * \brief CellInitializer class declaration * \note Copyright (c) 2020 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #pragma once #include "orange/surfaces/SurfaceContainer.hh" #include "../Definitions.hh" #include "../SenseContainer.hh" #include "CellContainer.hh" namespace celeritas { namespace detail { //---------------------------------------------------------------------------// /*! * See if a position is 'inside' a cell. * * This both *calculates* and *evaluates* senses. It's assumed that the * position is fixed but different cells and senses are being tested. */ class CellInitializer { public: //@{ //! Public type aliases using Cell = CellContainer::mapped_type; //@} public: // Constructor inline CellInitializer(const SurfaceContainer& surfaces, const LocalState& state); // Test the given cell on the given surface with the given sense inline FoundFace operator()(const Cell& cell_def); private: //// DATA //// //! Compressed vector of surface definitions const SurfaceContainer& surfaces_; //! Local position SpanConstReal3 pos_; //! Local surface SurfaceId surface_; //! Local sense if on surface Sense sense_; //! Temporary senses SenseContainer* temp_senses_; }; //---------------------------------------------------------------------------// } // namespace detail } // namespace celeritas //---------------------------------------------------------------------------// // INLINE DEFINITIONS //---------------------------------------------------------------------------// #include "CellInitializer.i.hh" //---------------------------------------------------------------------------//
27.842857
79
0.485377
[ "vector" ]
62b94539ab1fda3b7565756567410774e513cdc1
12,863
hpp
C++
src/bufferManipulation.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
16
2020-07-10T00:04:08.000Z
2022-03-28T03:59:51.000Z
src/bufferManipulation.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
55
2020-06-30T06:26:49.000Z
2022-03-29T18:21:47.000Z
src/bufferManipulation.hpp
GEOSX/LvArray
3ad0795f10023bd9a2fd8a41f0de0caa376845c0
[ "BSD-3-Clause" ]
5
2021-02-03T02:00:20.000Z
2022-03-21T20:37:51.000Z
/* * Copyright (c) 2021, Lawrence Livermore National Security, LLC and LvArray contributors. * All rights reserved. * See the LICENSE file for details. * SPDX-License-Identifier: (BSD-3-Clause) */ /** * @file bufferManipulation.hpp * @brief Contains functions for manipulating buffers. */ #pragma once // Source includes #include "LvArrayConfig.hpp" #include "Macros.hpp" #include "typeManipulation.hpp" #include "arrayManipulation.hpp" // TPL includes #include <camp/resource.hpp> // System includes #include <utility> namespace LvArray { /// @brief an alias for camp::resources::Platform. using MemorySpace = camp::resources::Platform; /** * @brief Output a Platform enum to a stream. * @param os The output stream to write to. * @param space The MemorySpace to output. * @return @p os. */ inline std::ostream & operator<<( std::ostream & os, MemorySpace const space ) { if( space == MemorySpace::undefined ) return os << "undefined"; if( space == MemorySpace::host ) return os << "host"; if( space == MemorySpace::cuda ) return os << "cuda"; if( space == MemorySpace::omp_target ) return os << "omp_target"; if( space == MemorySpace::hip ) return os << "hip"; if( space == MemorySpace::sycl ) return os << "sycl"; LVARRAY_ERROR( "Unrecognized memory space " << static_cast< int >( space ) ); return os; } /** * @brief Contains template functions for performing common operations on buffers. * @details Each function accepts a buffer and a size as the first two arguments. */ namespace bufferManipulation { /** * @brief Defines a static constexpr bool HasMemberFunction_move< @p CLASS > * that is true iff the class has a method move(MemorySpace, bool). * @tparam CLASS The type to test. */ HAS_MEMBER_FUNCTION_NO_RTYPE( move, MemorySpace::host, true ); /** * @class VoidBuffer * @brief This class implements the default behavior for the Buffer methods related * to execution space. This class is not intended to be used directly, instead derive * from it if you would like to inherit the default behavior. */ struct VoidBuffer { /** * @brief Move the buffer to the given execution space, optionally touching it. * @param space The space to move the buffer to. * @param size The size of the buffer. * @param touch Whether the buffer should be touched in the new space or not. * @note The default behavior is that the Buffer can only exist on the CPU and an error * occurs if you try to move it to a different space. */ void moveNested( MemorySpace const space, std::ptrdiff_t const size, bool const touch ) const { LVARRAY_UNUSED_VARIABLE( size ); LVARRAY_UNUSED_VARIABLE( touch ); LVARRAY_ERROR_IF_NE_MSG( space, MemorySpace::host, "This Buffer type can only be used on the CPU." ); } /** * @brief Move the buffer to the given execution space, optionally touching it. * @param space The space to move the buffer to. * @param touch Whether the buffer should be touched in the new space or not. * @note The default behavior is that the Buffer can only exist on the CPU and an error * occurs if you try to move it to a different space. */ void move( MemorySpace const space, bool const touch ) const { LVARRAY_UNUSED_VARIABLE( touch ); LVARRAY_ERROR_IF_NE_MSG( space, MemorySpace::host, "This Buffer type can only be used on the CPU." ); } /** * @return The last space the buffer was moved to. * @note The default behavior is that the Buffer can only exist on the CPU. */ MemorySpace getPreviousSpace() const { return MemorySpace::host; } /** * @brief Touch the buffer in the given space. * @param space the space to touch. * @note The default behavior is that the Buffer can only exist on the CPU and an error * occurs if you try to move it to a different space. */ void registerTouch( MemorySpace const space ) const { LVARRAY_ERROR_IF_NE_MSG( space, MemorySpace::host, "This Buffer type can only be used on the CPU." ); } /** * @tparam The type of the owning object. * @brief Set the name associated with this buffer. * @param name the name of the buffer. */ template< typename=VoidBuffer > LVARRAY_HOST_DEVICE void setName( std::string const & name ) { LVARRAY_UNUSED_VARIABLE( name ); } }; /** * @brief Check that given Buffer and size are valid. * @tparam BUFFER the buffer type. * @param buf The buffer to check. * @param size The size of the buffer. * @note This method is a no-op when LVARRAY_BOUNDS_CHECK is not defined. */ template< typename BUFFER > inline LVARRAY_HOST_DEVICE CONSTEXPR_WITHOUT_BOUNDS_CHECK void check( BUFFER const & buf, std::ptrdiff_t const size ) { #ifdef LVARRAY_BOUNDS_CHECK LVARRAY_ERROR_IF_GT( 0, buf.capacity() ); LVARRAY_ERROR_IF_GT( 0, size ); LVARRAY_ERROR_IF_GT( size, buf.capacity() ); #else LVARRAY_DEBUG_VAR( buf ); LVARRAY_DEBUG_VAR( size ); #endif } /** * @brief Check that given Buffer, size, and insertion position, are valid. * @tparam BUFFER the buffer type. * @param buf The buffer to check. * @param size The size of the buffer. * @param pos The insertion position. * @note This method is a no-op when LVARRAY_BOUNDS_CHECK is not defined. */ template< typename BUFFER > inline void checkInsert( BUFFER const & buf, std::ptrdiff_t const size, std::ptrdiff_t const pos ) { #ifdef LVARRAY_BOUNDS_CHECK check( buf, size ); LVARRAY_ERROR_IF_GT( 0, pos ); LVARRAY_ERROR_IF_GT( pos, size ); #else LVARRAY_DEBUG_VAR( buf ); LVARRAY_DEBUG_VAR( size ); LVARRAY_DEBUG_VAR( pos ); #endif } /** * @brief Destroy the values in the buffer and free it's memory. * @tparam BUFFER the buffer type. * @param buf The buffer to free. * @param size The size of the buffer. */ DISABLE_HD_WARNING template< typename BUFFER > LVARRAY_HOST_DEVICE void free( BUFFER & buf, std::ptrdiff_t const size ) { using T = typename BUFFER::value_type; check( buf, size ); if( !std::is_trivially_destructible< T >::value ) { buf.move( MemorySpace::host, true ); arrayManipulation::destroy( buf.data(), size ); } buf.free(); } /** * @brief Set the capacity of the buffer. * @tparam BUFFER the buffer type. * @param buf The buffer to set the capacity of. * @param size The size of the buffer. * @param space The space to set the capacity in. * @param newCapacity The new capacity of the buffer. */ DISABLE_HD_WARNING template< typename BUFFER > LVARRAY_HOST_DEVICE void setCapacity( BUFFER & buf, std::ptrdiff_t const size, MemorySpace const space, std::ptrdiff_t const newCapacity ) { check( buf, size ); buf.reallocate( size, space, newCapacity ); } /** * @brief Reserve space in the buffer for at least the given capacity. * @tparam BUFFER the buffer type. * @param buf The buffer to reserve space in. * @param size The size of the buffer. * @param space The space to perform the reserve in. * @param newCapacity The new minimum capacity of the buffer. */ template< typename BUFFER > LVARRAY_HOST_DEVICE void reserve( BUFFER & buf, std::ptrdiff_t const size, MemorySpace const space, std::ptrdiff_t const newCapacity ) { check( buf, size ); if( newCapacity > buf.capacity() ) { setCapacity( buf, size, space, newCapacity ); } } /** * @brief If the buffer's capacity is greater than newCapacity this is a no-op. * Otherwise the buffer's capacity is increased to at least 2 * newCapacity. * @tparam BUFFER the buffer type. * @param buf The buffer to reserve space in. * @param size The size of the buffer. * @param newCapacity The new minimum capacity of the buffer. * @note Use this in methods which increase the size of the buffer to efficiently grow * the capacity. */ template< typename BUFFER > void dynamicReserve( BUFFER & buf, std::ptrdiff_t const size, std::ptrdiff_t const newCapacity ) { check( buf, size ); if( newCapacity > buf.capacity() ) { setCapacity( buf, size, MemorySpace::host, 2 * newCapacity ); } } /** * @brief Resize the buffer to the given size. * @tparam BUFFER the buffer type. * @tparam ARGS The types of the arguments to initialize the new values with. * @param buf The buffer to resize. * @param size The current size of the buffer. * @param newSize The new size of the buffer. * @param args The arguments to initialize the new values with. */ template< typename BUFFER, typename ... ARGS > LVARRAY_HOST_DEVICE void resize( BUFFER & buf, std::ptrdiff_t const size, std::ptrdiff_t const newSize, ARGS && ... args ) { check( buf, size ); reserve( buf, size, MemorySpace::host, newSize ); arrayManipulation::resize( buf.data(), size, newSize, std::forward< ARGS >( args )... ); #if !defined(__CUDA_ARCH__) if( newSize > 0 ) { buf.registerTouch( MemorySpace::host ); } #endif } /** * @brief Construct a new value at the end of the buffer. * @tparam BUFFER The buffer type. * @tparam ARGS A variadic pack of argument types. * @param buf The buffer to insert into. * @param size The current size of the buffer. * @param args A variadic pack of parameters to construct the new value with. */ template< typename BUFFER, typename ... ARGS > void emplaceBack( BUFFER & buf, std::ptrdiff_t const size, ARGS && ... args ) { check( buf, size ); dynamicReserve( buf, size, size + 1 ); arrayManipulation::emplaceBack( buf.data(), size, std::forward< ARGS >( args ) ... ); } /** * @brief Construct a new value at position @p pos. * @tparam BUFFER The buffer type. * @tparam ARGS A variadic pack of argument types. * @param buf The buffer to insert into. * @param size The current size of the buffer. * @param pos The position to construct the values at. * @param args A variadic pack of parameters to construct the new value with. */ template< typename BUFFER, typename ... ARGS > void emplace( BUFFER & buf, std::ptrdiff_t const size, std::ptrdiff_t const pos, ARGS && ... args ) { checkInsert( buf, size, pos ); dynamicReserve( buf, size, size + 1 ); arrayManipulation::emplace( buf.data(), size, pos, std::forward< ARGS >( args ) ... ); } /** * @brief Insert multiple values into the buffer. * @tparam BUFFER The buffer type. * @tparam ITER An iterator type. * @param buf The buffer to insert into. * @param size The current size of the buffer. * @param pos The position to insert the values at. * @param first An iterator to the first value to insert. * @param last An iterator to the end of the values to insert. * @return The number of values inserted. */ template< typename BUFFER, typename ITER > std::ptrdiff_t insert( BUFFER & buf, std::ptrdiff_t const size, std::ptrdiff_t const pos, ITER const first, ITER const last ) { checkInsert( buf, size, pos ); std::ptrdiff_t const nVals = arrayManipulation::iterDistance( first, last ); dynamicReserve( buf, size, size + nVals ); arrayManipulation::insert( buf.data(), size, pos, first, nVals ); return nVals; } /** * @brief Remove a value from the end of the buffer. * @tparam BUFFER the buffer type. * @param buf The buffer to remove from. * @param size The current size of the buffer. */ template< typename BUFFER > void popBack( BUFFER & buf, std::ptrdiff_t const size ) { check( buf, size ); arrayManipulation::popBack( buf.data(), size ); } /** * @brief Erase a value from the buffer. * @tparam BUFFER the buffer type. * @param buf The buffer to erase from. * @param size The current size of the buffer. * @param pos The position to erase. */ template< typename BUFFER > void erase( BUFFER & buf, std::ptrdiff_t const size, std::ptrdiff_t const pos ) { check( buf, size ); LVARRAY_ERROR_IF_GE( pos, size ); arrayManipulation::erase( buf.data(), size, pos, std::ptrdiff_t( 1 ) ); } /** * @brief Copy values from the source buffer into the destination buffer. * @tparam DST_BUFFER the destination buffer type. * @tparam SRC_BUFFER the source buffer type. * @param dst The destination buffer. * @param dstSize The size of the destination buffer. * @param src The source buffer. * @param srcSize The size of the source buffer. */ DISABLE_HD_WARNING template< typename DST_BUFFER, typename SRC_BUFFER > LVARRAY_HOST_DEVICE void copyInto( DST_BUFFER & dst, std::ptrdiff_t const dstSize, SRC_BUFFER const & src, std::ptrdiff_t const srcSize ) { check( dst, dstSize ); check( src, srcSize ); resize( dst, dstSize, srcSize ); using T = typename DST_BUFFER::value_type; T * const LVARRAY_RESTRICT dstData = dst.data(); T const * const LVARRAY_RESTRICT srcData = src.data(); for( std::ptrdiff_t i = 0; i < srcSize; ++i ) { dstData[ i ] = srcData[ i ]; } } } // namespace bufferManipulations } // namespace LvArray
30.995181
118
0.694239
[ "object" ]
62bdbc349b7c3de7e3ec26b9b14d1683b169f5f9
14,029
cc
C++
test/file_manip.cc
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
null
null
null
test/file_manip.cc
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T17:50:32.000Z
2017-01-05T17:50:32.000Z
test/file_manip.cc
varqox/simlib
7830472019f88aa0e35dbfa1119b62b5f9dd4b9d
[ "MIT" ]
1
2017-01-05T15:26:48.000Z
2017-01-05T15:26:48.000Z
#include "simlib/file_manip.hh" #include "simlib/debug.hh" #include "simlib/defer.hh" #include "simlib/directory.hh" #include "simlib/file_contents.hh" #include "simlib/file_info.hh" #include "simlib/file_path.hh" #include "simlib/opened_temporary_file.hh" #include "simlib/random_bytes.hh" #include "simlib/temporary_directory.hh" #include "test/get_file_permissions.hh" #include <gtest/gtest.h> using std::max; using std::string; using std::vector; // NOLINTNEXTLINE TEST(DISABLED_file_manip, remove_r) { // TODO: } // NOLINTNEXTLINE TEST(file_manip, mkdir) { TemporaryDirectory tmp_dir("/tmp/filesystem-test.XXXXXX"); EXPECT_EQ(mkdir(concat(tmp_dir.path(), "a")), 0); EXPECT_TRUE(is_directory(concat(tmp_dir.path(), "a"))); EXPECT_EQ(mkdir(concat(tmp_dir.path(), "a/b")), 0); EXPECT_TRUE(is_directory(concat(tmp_dir.path(), "a/b"))); EXPECT_EQ(mkdir(concat(tmp_dir.path(), "x/d")), -1); EXPECT_FALSE(is_directory(concat(tmp_dir.path(), "x"))); } // NOLINTNEXTLINE TEST(file_manip, mkdir_r) { TemporaryDirectory tmp_dir("/tmp/filesystem-test.XXXXXX"); EXPECT_EQ(mkdir_r(concat_tostr(tmp_dir.path(), "x/d")), 0); EXPECT_TRUE(is_directory(concat(tmp_dir.path(), "x"))); EXPECT_TRUE(is_directory(concat(tmp_dir.path(), "x/d"))); } // NOLINTNEXTLINE TEST(file_manip, remove_dir_contents) { TemporaryDirectory tmp_dir("/tmp/filesystem-test.XXXXXX"); EXPECT_EQ(create_file(concat(tmp_dir.path(), "a")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "b")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "c")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "abc")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "xyz")), 0); EXPECT_EQ(mkdir_r(concat_tostr(tmp_dir.path(), "k/l/m/nn/")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "k/l/m/nn/x")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "k/l/m/x")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "k/l/x")), 0); EXPECT_EQ(create_file(concat(tmp_dir.path(), "k/x")), 0); EXPECT_EQ(remove_dir_contents(tmp_dir.path()), 0); for_each_dir_component(tmp_dir.path(), [](dirent* f) { ADD_FAILURE() << f->d_name; }); } // NOLINTNEXTLINE TEST(file_manip, create_subdirectories) { TemporaryDirectory tmp_dir("/tmp/filesystem-test.XXXXXX"); auto file_path = concat(tmp_dir.path(), "a/b/c/d/file.txt"); auto dir_path = concat(tmp_dir.path(), "a/b/c/d/"); EXPECT_EQ(create_subdirectories(file_path), 0); EXPECT_TRUE(path_exists(dir_path)); for_each_dir_component(dir_path, [](dirent* f) { ADD_FAILURE() << f->d_name; }); EXPECT_FALSE(path_exists(file_path)); EXPECT_EQ(remove_dir_contents(tmp_dir.path()), 0); EXPECT_EQ(create_subdirectories(dir_path), 0); EXPECT_TRUE(path_exists(dir_path)); for_each_dir_component(dir_path, [](dirent* f) { ADD_FAILURE() << f->d_name; }); } // NOLINTNEXTLINE TEST(file_manip, blast) { OpenedTemporaryFile a("/tmp/filesystem-test.XXXXXX"); OpenedTemporaryFile b("/tmp/filesystem-test.XXXXXX"); string data = random_bytes(1 << 20); write_all_throw(a, data); EXPECT_EQ(get_file_size(a.path()), data.size()); EXPECT_EQ(get_file_size(b.path()), 0); EXPECT_EQ(lseek(a, 0, SEEK_SET), 0); EXPECT_EQ(blast(a, b), 0); EXPECT_EQ(get_file_size(a.path()), data.size()); EXPECT_EQ(get_file_size(b.path()), data.size()); string b_data = get_file_contents(b.path()); EXPECT_EQ(data.size(), b_data.size()); EXPECT_TRUE(data == b_data); string str = "abcdefghij"; EXPECT_EQ(pwrite(a, str.data(), str.size(), 0), str.size()); string other = "0123456789"; EXPECT_EQ(pwrite(b, other.data(), other.size(), 0), other.size()); EXPECT_EQ(lseek(a, 3, SEEK_SET), 3); EXPECT_EQ(ftruncate(a, 6), 0); EXPECT_EQ(lseek(b, 1, SEEK_SET), 1); EXPECT_EQ(blast(a, b), 0); EXPECT_EQ(get_file_size(b.path()), data.size()); EXPECT_EQ(pread(b, other.data(), other.size(), 0), other.size()); EXPECT_EQ(other, "0def456789"); EXPECT_EQ(blast(a, b), 0); // Nothing should happen now EXPECT_EQ(get_file_size(b.path()), data.size()); EXPECT_EQ(pread(b, other.data(), other.size(), 0), other.size()); EXPECT_EQ(other, "0def456789"); // Copying from already read out fd is no-op for dest fd EXPECT_EQ(blast(a, -1), 0); EXPECT_EQ(blast(-1, b), -1); EXPECT_EQ(blast(b, -1), -1); EXPECT_EQ(get_file_size(b.path()), data.size()); } void copy_test(void (*copy_fn)(FilePath, FilePath, mode_t)) { TemporaryDirectory tmp_dir("/tmp/filesystem-test.XXXXXX"); OpenedTemporaryFile a("/tmp/filesystem-test.XXXXXX"); string data = random_bytes(1 << 18); write_all_throw(a, data); string bigger_data = random_bytes(1 << 19); string smaller_data = random_bytes(1 << 17); std::set<string> allowed_files; auto check_allowed_files = [&](size_t line) { size_t k = 0; for_each_dir_component(tmp_dir.path(), [&](dirent* f) { ++k; if (allowed_files.count(concat_tostr(tmp_dir.path(), f->d_name)) == 0) { ADD_FAILURE() << f->d_name << " (at line: " << line << ')'; } }); EXPECT_EQ(k, allowed_files.size()) << " (at line: " << line << ')'; }; EXPECT_EQ(get_file_size(a.path()), data.size()); check_allowed_files(__LINE__); string b_path = concat_tostr(tmp_dir.path(), "bbb"); allowed_files.emplace(b_path); copy_fn(a.path(), b_path, S_0644); EXPECT_EQ(get_file_size(b_path), data.size()); EXPECT_TRUE(get_file_contents(b_path) == data); EXPECT_EQ(get_file_permissions(b_path), S_0644); check_allowed_files(__LINE__); string c_path = concat_tostr(tmp_dir.path(), "ccc"); allowed_files.emplace(c_path); copy_fn(a.path(), c_path, S_0755); EXPECT_EQ(get_file_size(c_path), data.size()); EXPECT_TRUE(get_file_contents(c_path) == data); EXPECT_EQ(get_file_permissions(c_path), S_0755); check_allowed_files(__LINE__); EXPECT_EQ(lseek(a, 0, SEEK_SET), 0); write_all_throw(a, bigger_data); copy_fn(a.path(), b_path, S_0755); EXPECT_EQ(get_file_size(b_path), bigger_data.size()); EXPECT_TRUE(get_file_contents(b_path) == bigger_data); EXPECT_EQ(get_file_permissions(b_path), S_0755); check_allowed_files(__LINE__); EXPECT_EQ(lseek(a, 0, SEEK_SET), 0); write_all_throw(a, smaller_data); EXPECT_EQ(ftruncate(a, smaller_data.size()), 0); copy_fn(a.path(), c_path, S_0644); EXPECT_EQ(get_file_size(c_path), smaller_data.size()); EXPECT_TRUE(get_file_contents(c_path) == smaller_data); EXPECT_EQ(get_file_permissions(c_path), S_0644); check_allowed_files(__LINE__); EXPECT_EQ(remove(c_path), 0); copy_fn(a.path(), c_path, S_IRUSR); EXPECT_EQ(get_file_size(c_path), smaller_data.size()); EXPECT_TRUE(get_file_contents(c_path) == smaller_data); EXPECT_EQ(get_file_permissions(c_path), S_IRUSR); check_allowed_files(__LINE__); } // NOLINTNEXTLINE TEST(file_manip, copy) { copy_test([](FilePath src, FilePath dest, mode_t mode) { EXPECT_EQ(::copy(src, dest, mode), 0); }); } // NOLINTNEXTLINE TEST(file_manip, copy_using_rename) { copy_test([](FilePath src, FilePath dest, mode_t mode) { EXPECT_EQ(::copy_using_rename(src, dest, mode), 0); }); } // NOLINTNEXTLINE TEST(file_manip, thread_fork_safe_copy) { copy_test(::thread_fork_safe_copy); } // NOLINTNEXTLINE TEST(file_manip, copy_r) { TemporaryDirectory tmp_dir("/tmp/filesystem-test.XXXXXX"); struct FileInfo { string path; string data; bool operator<(const FileInfo& fi) const { return std::pair(path, data) < std::pair(fi.path, fi.data); } bool operator==(const FileInfo& fi) const { return (path == fi.path and data == fi.data); } }; vector<FileInfo> orig_files = { {"a", random_bytes(1023)}, {"b", random_bytes(1024)}, {"c", random_bytes(1025)}, {"dir/a", random_bytes(1023)}, {"dir/aa", random_bytes(100000)}, {"dir/b", random_bytes(1024)}, {"dir/bb", random_bytes(100000)}, {"dir/c", random_bytes(1025)}, {"dir/cc", random_bytes(100000)}, {"dir/dir/a", random_bytes(1023)}, {"dir/dir/aa", random_bytes(100000)}, {"dir/dir/b", random_bytes(1024)}, {"dir/dir/bb", random_bytes(100000)}, {"dir/dir/c", random_bytes(1025)}, {"dir/dir/cc", random_bytes(100000)}, {"dir/dir/xxx/a", random_bytes(1023)}, {"dir/dir/xxx/aa", random_bytes(100000)}, {"dir/dir/xxx/b", random_bytes(1024)}, {"dir/dir/xxx/bb", random_bytes(100000)}, {"dir/dir/xxx/c", random_bytes(1025)}, {"dir/dir/xxx/cc", random_bytes(100000)}, {"dir/dur/a", random_bytes(1023)}, {"dir/dur/aa", random_bytes(100000)}, {"dir/dur/b", random_bytes(1024)}, {"dir/dur/bb", random_bytes(100000)}, {"dir/dur/c", random_bytes(1025)}, {"dir/dur/cc", random_bytes(100000)}, {"dir/dur/xxx/a", random_bytes(1023)}, {"dir/dur/xxx/aa", random_bytes(100000)}, {"dir/dur/xxx/b", random_bytes(1024)}, {"dir/dur/xxx/bb", random_bytes(100000)}, {"dir/dur/xxx/c", random_bytes(1025)}, {"dir/dur/xxx/cc", random_bytes(100000)}, }; throw_assert(is_sorted(orig_files)); for (auto& [path, data] : orig_files) { auto full_path = concat(tmp_dir.path(), path); EXPECT_EQ(create_subdirectories(full_path), 0); put_file_contents(full_path, data); } auto dump_files = [&](FilePath path) { InplaceBuff<PATH_MAX> prefix = {path, '/'}; vector<FileInfo> res; InplaceBuff<PATH_MAX> curr_path; auto process_dir = [&](auto& self) -> void { for_each_dir_component(concat(prefix, curr_path), [&](dirent* file) { Defer undoer = [&, old_len = curr_path.size] { curr_path.size = old_len; }; curr_path.append(file->d_name); if (is_directory(concat(prefix, curr_path))) { curr_path.append('/'); self(self); } else { res.push_back({curr_path.to_string(), get_file_contents(concat(prefix, curr_path))}); } }); }; process_dir(process_dir); sort(res); return res; }; auto orig_files_slice = [&](const StringView& prefix) { vector<FileInfo> res; for (auto& [path, data] : orig_files) { if (has_prefix(path, prefix)) { res.push_back({path.substr(prefix.size()), data}); } } return res; }; auto check_equality = [&](const vector<FileInfo>& fir, const vector<FileInfo>& sec, size_t line) { size_t len = max(fir.size(), sec.size()); for (size_t i = 0; i < len; ++i) { if (i < fir.size() and i < sec.size()) { if (not(fir[i] == sec[i])) { ADD_FAILURE_AT(__FILE__, line) << "Unequal files:\t" << fir[i].path << "\t" << sec[i].path; } continue; } if (i < fir.size()) { ADD_FAILURE_AT(__FILE__, line) << "Extra file in fir:\t" << fir[i].path; } else { ADD_FAILURE_AT(__FILE__, line) << "Extra file in sec:\t" << sec[i].path; } } }; // Typical two levels { TemporaryDirectory dest_dir("/tmp/filesystem-test.XXXXXX"); auto dest_path = concat(dest_dir.path(), "dest/dir"); EXPECT_EQ(copy_r(concat(tmp_dir.path(), "dir"), dest_path), 0); check_equality(dump_files(dest_path), orig_files_slice("dir/"), __LINE__); } // Typical one level { TemporaryDirectory dest_dir("/tmp/filesystem-test.XXXXXX"); auto dest_path = concat(dest_dir.path(), "dest"); EXPECT_EQ(copy_r(concat(tmp_dir.path(), "dir"), dest_path), 0); check_equality(dump_files(dest_path), orig_files_slice("dir/"), __LINE__); } // Typical into existing { TemporaryDirectory dest_dir("/tmp/filesystem-test.XXXXXX"); const auto& dest_path = dest_dir.path(); EXPECT_EQ(copy_r(concat(tmp_dir.path(), "dir"), dest_path), 0); check_equality(dump_files(dest_path), orig_files_slice("dir/"), __LINE__); } // Without creating subdirs into existing { TemporaryDirectory dest_dir("/tmp/filesystem-test.XXXXXX"); const auto& dest_path = dest_dir.path(); EXPECT_EQ(copy_r(concat(tmp_dir.path(), "dir"), dest_path, false), 0); check_equality(dump_files(dest_path), orig_files_slice("dir/"), __LINE__); } // Without creating subdirs one level { TemporaryDirectory dest_dir("/tmp/filesystem-test.XXXXXX"); auto dest_path = concat(dest_dir.path(), "dest/"); EXPECT_EQ(copy_r(concat(tmp_dir.path(), "dir"), dest_path, false), 0); check_equality(dump_files(dest_path), orig_files_slice("dir/"), __LINE__); } // Without creating subdirs two levels { TemporaryDirectory dest_dir("/tmp/filesystem-test.XXXXXX"); auto dest_path = concat(dest_dir.path(), "dest/dir"); errno = 0; EXPECT_EQ(copy_r(concat(tmp_dir.path(), "dir"), dest_path, false), -1); EXPECT_EQ(errno, ENOENT); EXPECT_FALSE(path_exists(dest_path)); } } // NOLINTNEXTLINE TEST(DISABLED_file_manip, move) { // TODO: } // NOLINTNEXTLINE TEST(DISABLED_file_manip, create_file) { // TODO: } // NOLINTNEXTLINE TEST(DISABLED_file_manip, FileRemover) { // TODO: } // NOLINTNEXTLINE TEST(DISABLED_file_manip, DirectoryRemover) { // TODO: }
35.426768
91
0.616366
[ "vector" ]
62bed9f53b0613675eb7c38afdd48ae6ad2489d2
2,366
cpp
C++
SPOJ/ANAGR.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/ANAGR.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/ANAGR.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <sstream> #include <vector> #include <iomanip> #include <cmath> using namespace std; typedef long long LL; typedef pair<int,int> pii; int arr1[26],arr2[26]; int main() { int t,n,l1,l2,cnt1,cnt2,cnt3,cnt4,idx; string s1,s2; cin>>t; string str,sub; char ch = getchar(); while(t--) { sub = str = ""; memset(arr1,0,sizeof(arr1)); memset(arr2,0,sizeof(arr2)); getline(cin,s1); getline(cin,s2); l1 = s1.length(); l2 = s2.length(); for(int i=0;i<l1;i++) if(isalpha(s1[i])) arr1[tolower(s1[i])-'a']++; for(int i=0;i<l2;i++) if(isalpha(s2[i])) arr2[tolower(s2[i])-'a']++; /* for(int i=0;i<26;i++) cout<<arr1[i]<<" "; cout<<endl; for(int i=0;i<26;i++) cout<<arr2[i]<<" "; cout<<endl; */ for(int i=0;i<26;i++) arr1[i] -= arr2[i]; cnt1 = cnt2 = cnt3 = cnt4 = idx = 0; for(int i=0;i<26;i++) { if(arr1[i]>=0) cnt1++; if(arr1[i]<=0) cnt2++; if(arr1[i]==0) cnt3++; if(arr1[i]&1) { cnt4++; idx = i; } } if(cnt4 >=2) { cout<<"NO LUCK"<<endl; continue; } if(cnt3==26) { cout<<"YES"<<endl; continue; } if(cnt1 == 26 || cnt2 == 26) { char c; if(cnt4!=0) { c = 'a'+idx; arr1[idx] += (arr1[idx]<0)?(1):(-1); } for(int i=0;i<26;i++) { arr1[i] = abs(arr1[i]); for(int j=1;j<=arr1[i]/2;j++) { str += ('a' + i ); } } sub = str; reverse(sub.begin(),sub.end()); if(cnt4 != 0) str += c; str += sub; cout<<str<<endl; } else if(cnt2 == 26) { } else { cout<<"NO LUCK"<<endl; } } return 0; }
22.11215
52
0.353339
[ "vector" ]
498ace6210bae6d5d5d27ff17c783e65957fda65
1,771
cpp
C++
Cpp/Kattis/Graph/securitybadge.cpp
kchevali/OnlineJudge
c1d1894078fa45eef05c8785aba29758d9adf0c6
[ "MIT" ]
null
null
null
Cpp/Kattis/Graph/securitybadge.cpp
kchevali/OnlineJudge
c1d1894078fa45eef05c8785aba29758d9adf0c6
[ "MIT" ]
null
null
null
Cpp/Kattis/Graph/securitybadge.cpp
kchevali/OnlineJudge
c1d1894078fa45eef05c8785aba29758d9adf0c6
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long l; typedef tuple<l,l,l> edge; // node, lower, upper // BFS: Unweighted - find path from one source const l N = 1e3 + 10; bool vis[N]; vector<edge> adj[N]; // Complexity O(V+E) bool bfs(l src, l dest, l id) { if(src == dest)return true; queue<l> q; q.push(src); vis[src] = true; while (!q.empty()) { l a = q.front(); q.pop(); for (auto [b, lower, upper] : adj[a]) { if (!vis[b] && id >= lower && id <= upper) { if(dest == b)return true; vis[b] = true, q.push(b); } } } return false; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); l n, m, b; cin >> n >> m >> b; b--; l src, dest; cin >> src >> dest; src--, dest--; unordered_set<l> setIds; setIds.insert(0); setIds.insert(b); for(l i = 0; i < m; i++){ l nodeA, nodeB, badgeA, badgeB; cin >> nodeA >> nodeB >> badgeA >> badgeB; nodeA--, nodeB--, badgeA--, badgeB--; adj[nodeA].push_back({nodeB, badgeA, badgeB}); setIds.insert(badgeA); setIds.insert(badgeB); } vector<l> ids(setIds.begin(), setIds.end()); sort(ids.begin(), ids.end()); l idCount = ids.size(); unordered_map<l,l> idIndex; for(l i = 0; i < idCount; i++) idIndex[ids[i]] = i; for(l i = 0; i < n; i++){ for(auto &[node, badgeA, badgeB] : adj[i]){ badgeA = 2*idIndex[badgeA]; badgeB = 2*idIndex[badgeB]; } } l total = 0; for(l i = 1; i < 2*idCount; i++){ memset(vis,0,sizeof(bool)*n); bool result = bfs(src, dest, i-1); l offset = 1 - i%2; l numA = ids[ i / 2] - offset, numB = ids[i / 2 - offset] + offset; if(numB > numA)continue; total += result * (numA - numB + 1); } cout << total << "\n"; }
22.417722
71
0.540937
[ "vector" ]
498b962cbdc997dda6fec1737048cba18f964ed2
14,530
cpp
C++
pyvfc/vfc.cpp
eokeeffe/pyvfc
d883698aa341d487666f6615092fa1e6c04cd5f2
[ "MIT" ]
1
2021-08-31T10:06:16.000Z
2021-08-31T10:06:16.000Z
pyvfc/vfc.cpp
eokeeffe/pyvfc
d883698aa341d487666f6615092fa1e6c04cd5f2
[ "MIT" ]
null
null
null
pyvfc/vfc.cpp
eokeeffe/pyvfc
d883698aa341d487666f6615092fa1e6c04cd5f2
[ "MIT" ]
1
2021-08-31T09:59:44.000Z
2021-08-31T09:59:44.000Z
#include "vfc.h" // Mismatch removal by vector field consensus (VFC) // Author: Ji Zhao // Date: 01/25/2015 // Email: zhaoji84@gmail.com // // Reference // [1] Jiayi Ma, Ji Zhao, Jinwen Tian, Alan Yuille, and Zhuowen Tu. // Robust Point Matching via Vector Field Consensus, // IEEE Transactions on Image Processing, 23(4), pp. 1706-1721, 2014 // [2] Jiayi Ma, Ji Zhao, Jinwen Tian, Xiang Bai, and Zhuowen Tu. // Regularized Vector Field Learning with Sparse Approximation for Mismatch Removal, // Pattern Recognition, 46(12), pp. 3519-3532, 2013 VFC::VFC() { _lX.clear(); _rX.clear(); _X.clear(); _Y.clear(); _V.clear(); _C.clear(); _P.clear(); _ctrlPts.clear(); _sumP = 0; _sigma2 = 0; _E = 1; _traceCKC = 0; _numPt = 0; _numDim = 2; _numElement = 0; // set the default method //_method = NORMAL_VFC; //_method = FAST_VFC; _method = SPARSE_VFC; _maxIter = 50; _gamma = 0.9f; _beta = 0.1f; _lambda = 3.0f; _theta = 0.75f; _a = 10.0f; _ecr = 1e-5f; _minP = 1e-5f; _numEig = 1; _traceCQSQC = 0; _numCtrlPts = 16; } VFC::~VFC() { } bool VFC::setData(const vector<tuple<float, float>> X1, const vector<tuple<float, float>> X2) { if (X1.size() < MIN_POINT_NUMBER || X2.size() < MIN_POINT_NUMBER || X1.size() != X2.size()) return 0; _numPt = X1.size(); _numElement = _numPt * _numDim; _matchIdx.clear(); for (int i = 0; i < _numPt; i++) { Point2f p(get<0>(X1[i]), get<1>(X1[i])); Point2f q(get<0>(X2[i]), get<1>(X2[i])); _lX.push_back(p); _rX.push_back(q); _matchIdx.push_back(i); } return 1; } vector<int> VFC::obtainCorrectMatch() { return _matchIdx; } void VFC::optimize() { if (!normalize()) return; if (_method == NORMAL_VFC) optimizeVFC(); else if (_method == FAST_VFC) optimizeFastVFC(); else if (_method == SPARSE_VFC) optimizeSparseVFC(); #ifdef PRINT_RESULTS cout << "Removing outliers succesfully completed." << endl << "number of detected matches: " << setw(3) << _matchIdx.size() << endl; #endif } void VFC::optimizeSparseVFC() { _numCtrlPts = min(_numCtrlPts, _numPt); selectSubset(); _K = constructIntraKernel(_ctrlPts); _U = constructInterKernel(_ctrlPts, _X); initialize(); int iter = 0; float tecr = 1; float E_old = float(inf); while (iter < _maxIter && tecr > _ecr && _sigma2 > 1e-8) { // E-step E_old = _E; getP(); calculateTraceCKC(); _E += _lambda / 2 * _traceCKC; tecr = abs((_E - E_old) / _E); #ifdef PRINT_RESULTS cout << "# " << setw(3) << iter << ", gamma: " << setw(5) << _gamma << ", E change rate: " << setw(5) << tecr << ", sigma2: " << setw(5) << _sigma2 << endl; #endif // M-step. Solve linear system for C. calculateC_SparseVFC(); // Update V and sigma^2 calculateV(); calculateSigmaSquare(); // Update gamma calculateGamma(); iter++; } } bool VFC::selectSubset() { _numCtrlPts = min(_numCtrlPts, _numPt); _ctrlPts.clear(); int cnt = 0; int iter = 0; while (cnt < _numCtrlPts && iter < _numCtrlPts*3){ int idx = (rand() % _numPt); float dist = float(inf); for (unsigned int i = 0; i < _ctrlPts.size(); i++){ float tmp = fabs(_ctrlPts[i].x - _X[idx].x) + fabs(_ctrlPts[i].y - _X[idx].y); dist = min(tmp, dist); } if (dist>1e-3) { _ctrlPts.push_back(_X[idx]); cnt++; } iter++; } _numCtrlPts = cnt; return (_numCtrlPts > MIN_POINT_NUMBER); } void VFC::calculateC_SparseVFC() { Mat K(_numCtrlPts, _numCtrlPts, CV_32FC1); for (int i = 0; i < _numCtrlPts; i++) { for (int j = i; j < _numCtrlPts; j++) { float tmp = 0; float* p = _U.ptr<float>(i); float* q = _U.ptr<float>(j); for (int k = 0; k < _numPt; k++) { tmp += _P[k] * p[k] * q[k]; } tmp += _lambda * _sigma2 * _K.at<float>(i, j); K.at<float>(i, j) = tmp; K.at<float>(j, i) = tmp; } } Mat Y(_numCtrlPts, 2, CV_32FC1); for (int i = 0; i < _numCtrlPts; i++) { float tmp1 = 0; float tmp2 = 0; float* p = _U.ptr<float>(i); for (int k = 0; k < _numPt; k++) { float t = _P[k] * p[k]; tmp1 += t * _Y[k].x; tmp2 += t * _Y[k].y; } Y.at<float>(i, 0) = tmp1; Y.at<float>(i, 1) = tmp2; } Mat C; solve(K, Y, C, DECOMP_LU); _C.clear(); for (int i = 0; i < _numCtrlPts; i++) { float t1 = C.at<float>(i, 0); float t2 = C.at<float>(i, 1); _C.push_back(Point2f(t1, t2)); } } void VFC::optimizeFastVFC() { _K = constructIntraKernel(_X); _numEig = static_cast<int>( sqrt(_numPt) + 0.5f ); eigen(_K, _S, _Q); //-1, -1); //the last two parameters are ignored in the current opencv initialize(); int iter = 0; float tecr = 1; float E_old = float(inf); while (iter < _maxIter && tecr > _ecr && _sigma2 > 1e-8) { // E-step E_old = _E; getP(); calculateTraceCQSQC(); _E += _lambda / 2 * _traceCQSQC; tecr = abs((_E - E_old) / _E); #ifdef PRINT_RESULTS cout << "# " << setw(3) << iter << ", gamma: " << setw(5) << _gamma << ", E change rate: " << setw(5) << tecr << ", sigma2: " << setw(5) << _sigma2 << endl; #endif // M-step. Solve linear system for C. calculateCFastVFC(); // Update V and sigma^2 calculateV(); calculateSigmaSquare(); // Update gamma calculateGamma(); iter++; } } void VFC::calculateTraceCQSQC() { _traceCQSQC = 0; for (int i = 0; i < _numEig; i++) { float t1 = 0; float t2 = 0; float* t = _Q.ptr<float>(i); for (int j = 0; j < _numPt; j++) { t1 += t[j] * _C[j].x; t2 += t[j] * _C[j].y; } _traceCQSQC += t1*t1*_S.at<float>(i, 0); _traceCQSQC += t2*t2*_S.at<float>(i, 0); } } void VFC::calculateCFastVFC() { Mat dPQ(_numEig, _numPt, CV_32FC1); Mat F(2, _numPt, CV_32FC1); // dP = spdiags(P,0,N,N); dPQ = dP*Q; for (int i = 0; i < _numEig; i++) { float* p = dPQ.ptr<float>(i); float* q = _Q.ptr<float>(i); for (int j = 0; j < _numPt; j++) { p[j] = _P[j] * q[j]; } } // F = dP*Y; float* p1 = F.ptr<float>(0); float* p2 = F.ptr<float>(1); for (int j = 0; j < _numPt; j++) { p1[j] = _P[j] * _Y[j].x; p2[j] = _P[j] * _Y[j].y; } Mat QF(_numEig, 2, CV_32FC1); for (int i = 0; i < _numEig; i++) { float* q = _Q.ptr<float>(i); float t1 = 0; float t2 = 0; for (int j = 0; j < _numPt; j++) { t1 += q[j] * p1[j]; t2 += q[j] * p2[j]; } QF.at<float>(i, 0) = t1; QF.at<float>(i, 1) = t2; } // Q'*dPQ Mat K(_numEig, _numEig, CV_32FC1); for (int i = 0; i < _numEig; i++) { for (int j = i; j < _numEig; j++) { float tmp = 0; float* p = dPQ.ptr<float>(i); float* q = _Q.ptr<float>(j); for (int k = 0; k < _numPt; k++) { tmp += p[k] * q[k]; } if (i != j) { K.at<float>(i, j) = tmp; K.at<float>(j, i) = tmp; } else { K.at<float>(i, i) = tmp + _lambda * _sigma2 / _S.at<float>(i, 0); } } } Mat T; solve(K, QF, T, DECOMP_LU); //Mat C(2, _numPt, CV_32FC1); Mat C = F - (T.t() * dPQ); C = C / (_lambda*_sigma2); _C.clear(); for (int i = 0; i < _numPt; i++) { float t1 = C.at<float>(0, i); float t2 = C.at<float>(1, i); _C.push_back(Point2f(t1, t2)); } } void VFC::optimizeVFC() { _K = constructIntraKernel(_X); initialize(); int iter = 0; float tecr = 1; float E_old = float(inf); while (iter < _maxIter && tecr > _ecr && _sigma2 > 1e-8) { // E-step E_old = _E; getP(); calculateTraceCKC(); _E += _lambda / 2 * _traceCKC; tecr = abs((_E - E_old) / _E); #ifdef PRINT_RESULTS cout << "# " << setw(3) << iter << ", gamma: " << setw(5) << _gamma << ", E change rate: " << setw(5) << tecr << ", sigma2: " << setw(5) << _sigma2 << endl; #endif // M-step. Solve linear system for C. calculateC(); // Update V and sigma^2 calculateV(); calculateSigmaSquare(); // Update gamma calculateGamma(); iter++; } ///////////////////////////////// // Fix gamma, redo the EM process. initialize(); iter = 0; tecr = 1; E_old = float(inf); _E = 1; while (iter < _maxIter && tecr > _ecr && _sigma2 > 1e-8) { // E-step E_old = _E; getP(); calculateTraceCKC(); _E += _lambda / 2 * _traceCKC; tecr = abs((_E - E_old) / _E); #ifdef PRINT_RESULTS cout << "# " << setw(3) << iter << ", gamma: " << setw(5) << _gamma << ", E change rate: " << setw(5) << tecr << ", sigma2: " << setw(5) << _sigma2 << endl; #endif // M-step. Solve linear system for C. calculateC(); // Update V and sigma^2 calculateV(); calculateSigmaSquare(); // Update gamma //calculateGamma(); iter++; } } void VFC::calculateGamma() { int numcorr = 0; _matchIdx.clear(); for (int i = 0; i < _numPt; i++) { if (_P[i] > _theta) { numcorr++; _matchIdx.push_back(i); } } _gamma = float(numcorr) / _numPt; _gamma = min(_gamma, 0.95f); _gamma = max(_gamma, 0.05f); } void VFC::calculateSigmaSquare() { _sigma2 = 0; _sumP = 0; for (int i = 0; i < _numPt; i++) { float t = pow(_Y[i].x - _V[i].x, 2) + pow(_Y[i].y - _V[i].y, 2); _sigma2 += _P[i] * t; _sumP += _P[i]; } _sigma2 /= (_sumP * _numDim); } void VFC::calculateV() { // calculate V=K*C _V.clear(); if (_method == NORMAL_VFC) { for (int i = 0; i < _numPt; i++) { float *p = _K.ptr<float>(i); float t1 = 0; float t2 = 0; for (int j = 0; j < _numPt; j++) { t1 += p[j] * _C[j].x; t2 += p[j] * _C[j].y; } _V.push_back(Point2f(t1, t2)); } } else if (_method == FAST_VFC) { Mat T(2, _numEig, CV_32FC1); for (int i = 0; i < _numEig; i++) { float* q = _Q.ptr<float>(i); float t1 = 0; float t2 = 0; for (int j = 0; j < _numPt; j++) { t1 += q[j] * _C[j].x; t2 += q[j] * _C[j].y; } T.at<float>(0, i) = _S.at<float>(i,0)*t1; T.at<float>(1, i) = _S.at<float>(i,0)*t2; } for (int i = 0; i < _numPt; i++) { float t1 = 0; float t2 = 0; for (int j = 0; j < _numEig; j++) { float tmp = _Q.at<float>(j, i); t1 += tmp * T.at<float>(0, j); t2 += tmp * T.at<float>(1, j); } _V.push_back(Point2f(t1, t2)); } } else if (_method == SPARSE_VFC) { for (int i = 0; i < _numPt; i++) { float t1 = 0; float t2 = 0; for (int j = 0; j < _numCtrlPts; j++) { float t = _U.at<float>(j, i); t1 += t * _C[j].x; t2 += t * _C[j].y; } _V.push_back(Point2f(t1, t2)); } } } void VFC::calculateC() { Mat K; _K.copyTo(K); for (int i = 0; i < _numPt; i++) { K.at<float>(i, i) += _lambda*_sigma2 / _P[i]; } Mat Y(_numPt, 2, CV_32FC1); for (int i = 0; i < _numPt; i++) { Y.at<float>(i, 0) = _Y[i].x; Y.at<float>(i, 1) = _Y[i].y; } Mat C; solve(K, Y, C, DECOMP_LU); _C.clear(); for (int i = 0; i < _numPt; i++) { float t1 = C.at<float>(i, 0); float t2 = C.at<float>(i, 1); _C.push_back( Point2f(t1, t2) ); } } void VFC::calculateTraceCKC() { // calculate K*C int n = _K.rows; vector<Point2f> KC; KC.clear(); for (int i = 0; i < n; i++) { float *p = _K.ptr<float>(i); float t1 = 0; float t2 = 0; for (int j = 0; j < n; j++) { t1 += p[j] * _C[j].x; t2 += p[j] * _C[j].y; } KC.push_back( Point2f(t1, t2) ); } // calculate C_transpose*(K*C) _traceCKC = 0; for (int i = 0; i < n; i++) { _traceCKC += _C[i].x * KC[i].x + _C[i].y * KC[i].y; } } void VFC::getP() { _E = 0; _sumP = 0; float temp2; temp2 = pow(DOUBLE_PI*_sigma2, _numDim / 2.0f) * (1 - _gamma) / (_gamma*_a); for (int i = 0; i < _numPt; i++) { float t = pow(_Y[i].x - _V[i].x, 2) + pow(_Y[i].y - _V[i].y, 2); float temp1 = expf(-t/(2*_sigma2)); float p = temp1 / (temp1 + temp2); _P[i] = max(_minP, p); _sumP += p; _E += p * t; } _E /= (2 * _sigma2); _E += _sumP * log(_sigma2) * _numDim / 2; } void VFC::initialize() { _V.clear(); _C.clear(); _P.clear(); for (int i = 0; i < _numPt; i++) { _V.push_back( Point2f(0.0f, 0.0f) ); _P.push_back(1.0f); } if (_method == NORMAL_VFC || _method == FAST_VFC) { for (int i = 0; i < _numPt; i++) { _C.push_back(Point2f(0.0f, 0.0f)); } } else if (_method == SPARSE_VFC) { for (int i = 0; i < _numCtrlPts; i++) { _C.push_back(Point2f(0.0f, 0.0f)); } } calculateSigmaSquare(); } Mat VFC::constructIntraKernel(vector<Point2f> X) { int n = X.size(); Mat K; K.create(n, n, CV_32FC1); for (int i = 0; i < n; i++) { K.at<float>(i, i) = 1; for (int j = i+1; j < n; j++) { float t = pow(X[i].x - X[j].x, 2) + pow(X[i].y - X[j].y, 2); t *= -_beta; t = expf(t); K.at<float>(i, j) = t; K.at<float>(j, i) = t; } } return K; } Mat VFC::constructInterKernel(vector<Point2f> X, vector<Point2f> Y) { int m = X.size(); int n = Y.size(); Mat K; K.create(m, n, CV_32FC1); for (int i = 0; i < m; i++) { float* p = K.ptr<float>(i); for (int j = 0; j < n; j++) { float t = pow(X[i].x - Y[j].x, 2) + pow(X[i].y - Y[j].y, 2); p[j] = expf(-_beta * t); } } return K; } bool VFC::normalize() { // calculate mean float x1, y1, x2, y2; x1 = 0; y1 = 0; x2 = 0; y2 = 0; for (int i = 0; i < _numPt; i++) { x1 += _lX[i].x; y1 += _lX[i].y; x2 += _rX[i].x; y2 += _rX[i].y; } x1 /= _numPt; y1 /= _numPt; x2 /= _numPt; y2 /= _numPt; _meanLeftX.x = x1; _meanLeftX.y = y1; _meanRightX.x = x2; _meanRightX.y = y2; // minus mean for (int i = 0; i < _numPt; i++) { _lX[i].x -= x1; _lX[i].y -= y1; _rX[i].x -= x2; _rX[i].y -= y2; } // calculate scale double s1 = 0; double s2 = 0; for (int i = 0; i < _numPt; i++) { s1 += pow(_lX[i].x, 2); s1 += pow(_lX[i].y, 2); s2 += pow(_rX[i].x, 2); s2 += pow(_rX[i].y, 2); } s1 /= _numPt; s2 /= _numPt; s1 = sqrt(s1); s2 = sqrt(s2); _scaleLeftX = static_cast<float> (s1); _scaleRightX = static_cast<float> (s2); if (_scaleLeftX < MIN_STANDARD_DEVIATION || _scaleRightX < MIN_STANDARD_DEVIATION) return 0; // divide by scale, and prepare vector field samples _X.clear(); _Y.clear(); for (int i = 0; i < _numPt; i++) { _lX[i].x /= static_cast<float> (s1); _lX[i].y /= static_cast<float> (s1); _rX[i].x /= static_cast<float> (s2); _rX[i].y /= static_cast<float> (s2); Point2f tmp(_rX[i].x-_lX[i].x, _rX[i].y-_lX[i].y); _X.push_back(_lX[i]); _Y.push_back(tmp); } return 1; }
23.322632
96
0.524639
[ "vector" ]
499d38c26e23a998a07e1d9f77bbe424693112ff
2,511
hpp
C++
AlloServer/H264NALUSource.hpp
tiborgo/AlloStreamer
bf91586a88c3aec8e5603e5606caf3c3d0d53139
[ "BSD-3-Clause" ]
5
2016-04-01T09:43:00.000Z
2019-06-09T19:04:18.000Z
AlloServer/H264NALUSource.hpp
tiborgo/AlloStreamer
bf91586a88c3aec8e5603e5606caf3c3d0d53139
[ "BSD-3-Clause" ]
null
null
null
AlloServer/H264NALUSource.hpp
tiborgo/AlloStreamer
bf91586a88c3aec8e5603e5606caf3c3d0d53139
[ "BSD-3-Clause" ]
3
2016-04-08T00:34:43.000Z
2019-11-15T19:21:13.000Z
#pragma once #include <FramedSource.hh> #include <boost/thread/barrier.hpp> #include <boost/thread/synchronized_value.hpp> #include <boost/thread/condition.hpp> #include <boost/thread.hpp> extern "C" { #include <libavcodec/avcodec.h> #include <libavutil/opt.h> #include <libavutil/imgutils.h> #include <libavutil/time.h> #include <libswscale/swscale.h> #include <libavformat/avformat.h> #include <x264.h> } #include "AlloShared/ConcurrentQueue.hpp" #include "AlloShared/Cubemap.hpp" class H264NALUSource : public FramedSource { public: static H264NALUSource* createNew(UsageEnvironment& env, Frame* content, int avgBitRate, bool robustSyncing); typedef std::function<void(H264NALUSource* self, uint8_t type, size_t size)> OnSentNALU; typedef std::function<void(H264NALUSource* self)> OnEncodedFrame; void setOnSentNALU (const OnSentNALU& callback); void setOnEncodedFrame(const OnEncodedFrame& callback); protected: H264NALUSource(UsageEnvironment& env, Frame* content, int avgBitRate, bool robustSyncing); // called only by createNew(), or by subclass constructors virtual ~H264NALUSource(); OnSentNALU onSentNALU; OnEncodedFrame onEncodedFrame; private: EventTriggerId eventTriggerId; static void deliverFrame0(void* clientData); static boost::mutex triggerEventMutex; static std::vector<H264NALUSource*> sourcesReadyForDelivery; void deliverFrame(); // redefined virtual functions: virtual void doGetNextFrame(); //virtual void doStopGettingFrames(); // optional int x2yuv(AVFrame *xFrame, AVFrame *yuvFrame, AVCodecContext *c); SwsContext *img_convert_ctx; // Stores unencoded frames ConcurrentQueue<AVFrame*> frameBuffer; // Here unused frames are stored. Included so that we can allocate all the frames at startup // and reuse them during runtime ConcurrentQueue<AVFrame*> framePool; // Stores encoded frames ConcurrentQueue<AVPacket> pktBuffer; ConcurrentQueue<AVPacket> pktPool; static unsigned referenceCount; // used to count how many instances of this class currently exist Frame* content; AVCodecContext* codecContext; boost::thread frameContentThread; boost::thread encodeFrameThread; void frameContentLoop(); void encodeFrameLoop(); bool destructing; int64_t lastFrameTime; int_least64_t lastPTS; bool robustSyncing; };
27.293478
98
0.718439
[ "vector" ]
49a0315764547145e85e6f8ba8988f69d896b509
3,713
hpp
C++
source/Kai/Object.hpp
ioquatix/kai
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
[ "Unlicense", "MIT" ]
4
2016-07-19T08:53:09.000Z
2021-08-03T10:06:41.000Z
source/Kai/Object.hpp
ioquatix/kai
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
[ "Unlicense", "MIT" ]
null
null
null
source/Kai/Object.hpp
ioquatix/kai
4f8d00cd05b4123b6389f8dc3187ec1421b4f2da
[ "Unlicense", "MIT" ]
null
null
null
// // Object.h // This file is part of the "Kai" project, and is released under the MIT license. // // Created by Samuel Williams on 28/12/11. // Copyright (c) 2011 Orion Transfer Ltd. All rights reserved. // #ifndef _KAI_OBJECT_H #define _KAI_OBJECT_H #include "Kai.hpp" #include "Reference.hpp" #include "Memory/ManagedObject.hpp" #include <set> namespace Kai { class Object; /// Object Comparison helpers. class InvalidComparison {}; enum ComparisonResult { // LHS > RHS: DESCENDING = -1, // LHS == RHS: EQUAL = 0, // LHS < RHS: ASCENDING = 1 }; template <typename ThisT> inline static ComparisonResult derived_compare(const ThisT * lhs, const Object * rhs) { const ThisT * other = dynamic_cast<const ThisT *>(rhs); if (other) { return lhs->compare(other); } else { throw InvalidComparison(); } } class Symbol; class Frame; /** An object specifies the default behaviour for all objects in Kai. An object provides a specification for looking up and invoking functionality, along with memory management provided by ManagedObject. */ class Object : public Memory::ManagedObject { public: static const char * const NAME; virtual ~Object(); virtual Ref<Symbol> identity(Frame * frame) const; /// A prototype specifies the behaviour of the current value, and is potentially context dependent. virtual Ref<Object> prototype(Frame * frame) const; /// Lookup the given identifier. Defers to prototype by default: virtual Ref<Object> lookup(Frame * frame, Symbol * identifier); /// Evaluate the current value in the given context: virtual Ref<Object> evaluate(Frame * frame); /// Comparing objects: virtual ComparisonResult compare(const Object * other) const; template <typename LeftT, typename RightT> static ComparisonResult compare(LeftT * lhs, RightT * rhs) { if (lhs == rhs) return EQUAL; if (lhs == NULL || rhs == NULL) { throw InvalidComparison(); } else { return lhs->compare(rhs); } } static bool equal(Object * lhs, Object * rhs) { try { return compare(lhs, rhs) == EQUAL; } catch (InvalidComparison ex) { return false; } } /// Converting objects back into readable code for debugging: typedef std::set<const Object *> MarkedT; virtual void to_code(Frame * frame, StringStreamT & buffer, MarkedT & marks, std::size_t indentation) const; inline void to_code(Frame * frame, StringStreamT & buffer) const { MarkedT marks; to_code(frame, buffer, marks, 0); } static StringT to_string(Frame * frame, Object * object); static bool to_boolean(Frame * frame, Object * object); Ref<Object> as_value(Frame * frame); // MARK: - // Converts the argument to a string value static Ref<Object> to_string(Frame * frame); // Converts the argument to a boolean frame->symbol static Ref<Object> to_boolean(Frame * frame); // Compares the given arguments static Ref<Object> compare(Frame * frame); // Compares the given values and returns a true/false value static Ref<Object> equal(Frame * frame); /// Returns a prototype for the given object. static Ref<Object> prototype_(Frame * frame); /// Returns the identity of an object, that is used for context dependent lookup. static Ref<Object> identity_(Frame * frame); // Returns the arguments unevaluated static Ref<Object> value(Frame * frame); // Evaluates arguments one at a time in result of the previous. static Ref<Object> lookup(Frame * frame); // Performs a method call with the given function. static Ref<Object> call(Frame * frame); static void import(Frame * frame); }; } #endif
25.784722
135
0.684891
[ "object" ]
49abd5e192f233a9581e78359b94a98d7f4ea696
7,132
cpp
C++
source/backend/cpu/bf16/BF16Unary.cpp
JujuDel/MNN
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
[ "Apache-2.0" ]
1
2021-09-17T03:22:16.000Z
2021-09-17T03:22:16.000Z
source/backend/cpu/bf16/BF16Unary.cpp
JujuDel/MNN
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
[ "Apache-2.0" ]
null
null
null
source/backend/cpu/bf16/BF16Unary.cpp
JujuDel/MNN
8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a
[ "Apache-2.0" ]
null
null
null
#include <vector> #include "BF16Unary.hpp" #include "VecHalf.hpp" #include "math/Vec.hpp" #include "backend/cpu/UnaryUtils.hpp" #include "BF16Backend.hpp" namespace MNN { using Vec4Half = MNN::Math::VecHalf<4>; using Vec4 = MNN::Math::Vec<float, 4>; struct Vec4Square { Vec4Half operator()(Vec4Half &x) const { return x * x; } }; struct Vec4Neg { Vec4Half operator()(Vec4Half &x) const { return -x; } }; struct Vec4Abs { Vec4Half operator()(Vec4Half &x) const { float v[4]; v[0] = fabs(x.value[0]); v[1] = fabs(x.value[1]); v[2] = fabs(x.value[2]); v[3] = fabs(x.value[3]); auto c = Vec4::load(v); Vec4Half value; value.value = std::move(c.value); return value; } }; template<typename Compute> void BF16VecUnary(void *dstRaw, const void *src0Raw, int elementSize) { Compute Func; auto dst = (int16_t*)dstRaw; auto src0 = (int16_t*)src0Raw; const int sizeDivUnit = elementSize / 4; const int remainCount = elementSize - sizeDivUnit * 4; if (sizeDivUnit > 0) { for (int i = 0; i < sizeDivUnit; ++i) { Vec4Half a = Vec4Half::load(src0); Vec4Half::save(dst, Func(a)); src0 += 4; dst += 4; } } if (remainCount > 0) { int16_t tempSrc0[4]; int16_t tempDst[4]; ::memcpy(tempSrc0, src0, remainCount * sizeof(int16_t)); Vec4Half a = Vec4Half::load(tempSrc0); Vec4Half::save(tempDst, Func(a)); ::memcpy(dst, tempDst, remainCount * sizeof(int16_t)); } } #define BLOCK_SIZE 16 template<typename Compute> static void _Wrap(void* outRaw, const void* inpRaw, int realSize) { Compute execute; float out[BLOCK_SIZE]; float inp[BLOCK_SIZE]; int b = realSize / BLOCK_SIZE; int remain = realSize % BLOCK_SIZE; auto bf16F = BF16Functions::get(); auto outR = (int16_t*)outRaw; auto inpR = (const int16_t*)inpRaw; for (int i=0; i<b; ++i) { bf16F->MNNLowpToFp32(inpR, inp, BLOCK_SIZE); execute(out, inp, BLOCK_SIZE); bf16F->MNNFp32ToLowp(out, outR, BLOCK_SIZE); outR += BLOCK_SIZE; inpR += BLOCK_SIZE; } if (remain > 0) { bf16F->MNNLowpToFp32(inpR, inp, remain); execute(out, inp, remain); bf16F->MNNFp32ToLowp(out, outR, remain); } } struct _Exp { void operator()(void* outRaw, const void* inpRaw, int realSize) const { auto out = (float*)outRaw; auto inp = (const float*)inpRaw; MNNScaleAndAddBiasScalar(out, inp, 0.0f, -1.0f, realSize); MNNExp(out, out, realSize); } }; struct _ExpM1 { void operator()(void* outRaw, const void* inpRaw, int realSize) const { auto out = (float*)outRaw; auto inp = (const float*)inpRaw; MNNScaleAndAddBiasScalar(out, inp, 0.0f, -1.0f, realSize); MNNExp(out, out, realSize); for (int i=0; i<realSize; ++i) { out[i] = out[i] - 1.0f; } } }; struct _Tanh { void operator()(void* outRaw, const void* inpRaw, int realSize) const { auto out = (float*)outRaw; auto inp = (const float*)inpRaw; MNNTanh(out, inp, realSize); } }; struct _Sigmoid { void operator()(void* outRaw, const void* inpRaw, int realSize) const { auto out = (float*)outRaw; auto inp = (const float*)inpRaw; MNNSigmoidLowp(out, inp, realSize); } }; struct _HardSwish { void operator()(void* outRaw, const void* inpRaw, int realSize) const { auto out = (float*)outRaw; auto inp = (const float*)inpRaw; MNNHardSwishCommon(out, inp, realSize); } }; template <typename Func, typename T> struct _Unary { void operator()(void* outputPtr, const void* inputPtr, int elementSize) const { Func f; const T *inputData = (T*)inputPtr; T *outputData = (T *)outputPtr; for (int i=0; i<elementSize; ++i) { outputData[i] = f(inputData[i]); } } }; MNNUnaryExecute BF16UnaryFloatSelect(int type, int precision) { switch (type) { case UnaryOpOperation_ABS: return BF16VecUnary<Vec4Abs>; case UnaryOpOperation_SQUARE: return BF16VecUnary<Vec4Square>; case UnaryOpOperation_NEG: return BF16VecUnary<Vec4Neg>; case UnaryOpOperation_RSQRT: return _Wrap<_Unary<UnaryRsqrt<float>, float>>; case UnaryOpOperation_EXP: return _Wrap<_Exp>; case UnaryOpOperation_COS: return _Wrap<_Unary<UnaryCos<float>, float>>; case UnaryOpOperation_SIN: return _Wrap<_Unary<UnarySin<float>, float>>; case UnaryOpOperation_SIGMOID: return _Wrap<_Sigmoid>; case UnaryOpOperation_TANH: return _Wrap<_Tanh>; case UnaryOpOperation_TAN: return _Wrap<_Unary<UnaryTan<float>, float>>; case UnaryOpOperation_ATAN: return _Wrap<_Unary<UnaryATan<float>, float>>; case UnaryOpOperation_SQRT: return _Wrap<_Unary<UnarySqrt<float>, float>>; case UnaryOpOperation_CEIL: return _Wrap<_Unary<UnaryCeil<float>, float>>; case UnaryOpOperation_RECIPROCAL: return _Wrap<_Unary<UnaryRecipocal<float>, float>>; case UnaryOpOperation_LOG1P: return _Wrap<_Unary<UnaryLog1p<float>, float>>; case UnaryOpOperation_LOG: return _Wrap<_Unary<UnaryLog<float>, float>>; case UnaryOpOperation_FLOOR: return _Wrap<_Unary<UnaryFloor<float>, float>>; case UnaryOpOperation_BNLL: return _Wrap<_Unary<UnaryBNLL<float>, float>>; case UnaryOpOperation_ACOSH: return _Wrap<_Unary<UnaryAcosh<float>, float>>; case UnaryOpOperation_SINH: return _Wrap<_Unary<UnarySinh<float>, float>>; case UnaryOpOperation_ASINH: return _Wrap<_Unary<UnaryAsinh<float>, float>>; case UnaryOpOperation_ATANH: return _Wrap<_Unary<UnaryAtanh<float>, float>>; case UnaryOpOperation_SIGN: return _Wrap<_Unary<UnarySign<float>, float>>; case UnaryOpOperation_ROUND: return _Wrap<_Unary<UnaryRound<float>, float>>; case UnaryOpOperation_COSH: return _Wrap<_Unary<UnaryCosh<float>, float>>; case UnaryOpOperation_ERF: return _Wrap<_Unary<UnaryErf<float>, float>>; case UnaryOpOperation_ERFC: return _Wrap<_Unary<UnaryErfc<float>, float>>; case UnaryOpOperation_ERFINV: return _Wrap<_Unary<UnaryErfinv<float>, float>>; case UnaryOpOperation_EXPM1: return _Wrap<_ExpM1>; case UnaryOpOperation_ASIN: return _Wrap<_Unary<UnaryAsin<float>, float>>; case UnaryOpOperation_ACOS: return _Wrap<_Unary<UnaryAcos<float>, float>>; case UnaryOpOperation_HARDSWISH: return _Wrap<_HardSwish>; default: MNN_ASSERT(false); break; } return nullptr; } };
32.866359
83
0.607824
[ "vector" ]
49ae1baf9191a6c8ad4ad70f20c7da3134ee218f
1,100
cpp
C++
18.5-1.cpp
foram-s1/Competitive-Programming
57426521123c11b03e62997b50dcff344063ccca
[ "MIT" ]
1
2020-10-18T18:40:19.000Z
2020-10-18T18:40:19.000Z
18.5-1.cpp
foram-s1/Competitive-Programming
57426521123c11b03e62997b50dcff344063ccca
[ "MIT" ]
2
2020-10-08T16:10:04.000Z
2020-10-08T16:53:51.000Z
18.5-1.cpp
foram-s1/Competitive-Programming
57426521123c11b03e62997b50dcff344063ccca
[ "MIT" ]
11
2020-10-03T11:39:37.000Z
2020-10-29T04:57:52.000Z
//#include<iostream> //#include<bits/stdc++.h> //#include<algorithm> //#include<vector> //#include<string> // //using namespace std; // //int main(){ // long long int N; // cin >> N; // for(int i=1;i<=N;i++){ // if(i%3==0 && i%5==0){ // cout << "FizzBuzz" << endl; // } // else if(i%3==0){ // cout << "Fizz" << endl; // } // else if(i%5==0){ // cout << "Buzz" << endl; // } // else if(i%3!=0 && i%5!=0){ // cout << i << endl; // } // } // return 0; //} #include<bits/stdc++.h> #include<iostream> using namespace std; int main(){ long long int n,arr[100],k; cin >> n; for(int i=1;i<=n;i++){ cin >> arr[i]; } cin >> k; int i; for(int i=1;i<=n;i++){ if(arr[i]==k){ cout << "YES" << endl; break; } else{ cout << "NO" << endl; break; } break; } return 0; } #include<bits/stdc++.h> #include<iostream> using namespace std; int main(){ int T; cin >> T; while(T--){ } return 0; }
16.176471
35
0.420909
[ "vector" ]
49b4a3c6374b1bfa3ce4bdac650abd4196eba8b8
3,136
cpp
C++
renderer/rend/mesh.cpp
flaming0/software-renderer
dfeb24eb4ac6f90552e65cc7e0cf97d7d693ad7b
[ "MIT" ]
14
2015-03-22T16:18:32.000Z
2017-08-08T14:07:44.000Z
renderer/rend/mesh.cpp
nslobodin/software-renderer
dfeb24eb4ac6f90552e65cc7e0cf97d7d693ad7b
[ "MIT" ]
null
null
null
renderer/rend/mesh.cpp
nslobodin/software-renderer
dfeb24eb4ac6f90552e65cc7e0cf97d7d693ad7b
[ "MIT" ]
2
2015-08-31T03:01:57.000Z
2016-12-20T06:09:32.000Z
/* * mesh.cpp * * Author: flamingo * E-mail: epiforce57@gmail.com */ #include "stdafx.h" #include "mesh.h" #include "m33.h" #include "renderlist.h" #include "vertexbuffer.h" namespace rend { Mesh::Mesh() { } Mesh::~Mesh() { } void Mesh::appendSubmesh(const VertexBuffer &submesh) { m_submeshes.push_back(submesh); // m_submeshes.sort(); // sort by alpha value of material } void Mesh::computeBoundingSphere(const math::M44 &transform) { int sz = 0; for (auto &vb : m_submeshes) sz += vb.numVertices(); std::vector<math::vec3> points(sz); int j = 0; for (auto &vb : m_submeshes) { for (size_t i = 0; i < vb.m_vertices.size(); i++, j++) points[j] = vb.m_vertices[i].p; } // apply transformation const math::M33 &rotsc = transform.getM(); std::for_each(points.begin(), points.end(), [&](math::vec3 &v) { v = v * rotsc; }); m_boundingSphere.calculate(points); } const BoundingSphere &Mesh::getBoundingSphere() const { return m_boundingSphere; } int Mesh::numVertices() const { int n = 0; std::for_each(m_submeshes.begin(), m_submeshes.end(), [&](const VertexBuffer &buffer) { n += buffer.numVertices(); }); return n; } int Mesh::numSubMeshes() const { return m_submeshes.size(); } int Mesh::numTriangles() const { // TODO: do not compute count of triangles every time. int trianglesCount = 0; for (auto &vb : m_submeshes) { switch (vb.getType()) { case VertexBuffer::INDEXEDTRIANGLELIST: trianglesCount += vb.numIndices() / 3; break; case VertexBuffer::TRIANGLELIST: trianglesCount += vb.numVertices() / 3; break; default: break; } } return trianglesCount; } void Mesh::setShadingMode(Material::ShadeMode shMode) { for (auto &vb : m_submeshes) vb.getMaterial()->shadeMode = shMode; // ? } void Mesh::setAlpha(int alpha) { if (alpha < 0 || alpha > 255) return; for (auto &vb : m_submeshes) vb.getMaterial()->alpha = alpha; } void Mesh::setTexture(sptr(Texture) texture) { for (auto &vb : m_submeshes) { vb.getMaterial()->texture = texture; // ? vb.getMaterial()->shadeMode = Material::SM_TEXTURE; } } void Mesh::setSideType(Material::SideType side) { for (auto &vb : m_submeshes) vb.getMaterial()->sideType = side; // ? } sptr(Mesh) Mesh::clone() const { sptr(Mesh) objMesh = std::make_shared<Mesh>(); for (auto &submesh : m_submeshes) { VertexBuffer vb; vb.m_type = submesh.m_type; vb.m_material = submesh.m_material->clone(); vb.m_vertices = submesh.m_vertices; vb.m_indices = submesh.m_indices; vb.m_uvs = submesh.m_uvs; vb.m_uvsIndices = submesh.m_uvsIndices; objMesh->appendSubmesh(vb); } return objMesh; } }
20.631579
88
0.563776
[ "mesh", "vector", "transform" ]
49b4b5febe3ce6dd8c7dec0370e80c66e718e197
14,045
cpp
C++
adaptors/default/file/default_dir.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
adaptors/default/file/default_dir.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
adaptors/default/file/default_dir.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// Copyright (c) 2005-2009 Hartmut Kaiser // Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <map> #include <vector> #include <saga/saga/util.hpp> #include <saga/saga/exception.hpp> #include <saga/saga/url.hpp> #include <saga/impl/config.hpp> #include <saga/saga/path_leaf.hpp> #include <boost/system/system_error.hpp> #include <boost/filesystem/convenience.hpp> #include "default_dir.hpp" #include "default_file.hpp" #include <saga/saga/adaptors/task.hpp> #include "default_namespace_dir.hpp" #include "default_namespace_dir_impl.hpp" #include "common_helpers.hpp" #ifndef MAX_PATH # define MAX_PATH _POSIX_PATH_MAX #endif /* * constructor */ dir_cpi_impl::dir_cpi_impl (saga::impl::proxy* p, saga::impl::v1_0::cpi_info const & info, saga::ini::ini const & glob_ini, saga::ini::ini const & adap_ini, TR1::shared_ptr<saga::adaptor> adaptor) : base_type (p, info, glob_ini, adap_ini, adaptor, cpi::Noflags) { namespace fs = boost::filesystem; instance_data data (this); saga::url dir_url(data->location_); try { #if BOOST_FILESYSTEM_VERSION == 3 fs::path path (saga::url::unescape(dir_url.get_path())); #else fs::path path (saga::url::unescape(dir_url.get_path()), fs::native); #endif if ( ! ::detail::file_islocal (dir_url) ) { SAGA_OSSTREAM strm; strm << "dir_cpi_impl::init: cannot handle file: " << dir_url.get_url(); SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined); } // check if file exists AND is a dir (not a file) bool exists = fs::exists(path); bool is_dir = false; if(exists) is_dir = fs::is_directory(path); // check for openmode // saga::filesystem::flags OpenMode = (saga::filesystem::flags)data->mode_; if (exists) { if (!is_dir) { SAGA_ADAPTOR_THROW ("URL does not point to a directory: " + data->location_.get_url(), saga::BadParameter); } else { if ((OpenMode & saga::filesystem::Create) && (OpenMode & saga::filesystem::Exclusive)) { SAGA_ADAPTOR_THROW ("Directory " + data->location_.get_url() + " already exists.", saga::AlreadyExists); } } } else { // !exists if (!(OpenMode & saga::filesystem::Create)) { SAGA_ADAPTOR_THROW ("Directory does not exist and saga::filesystem::Create flag not given: " + data->location_.get_url(), saga::DoesNotExist); } else { try { saga::detail::remove_trailing_dot(path); if ((OpenMode & saga::filesystem::CreateParents)) { if ( !fs::create_directories(path)) { SAGA_ADAPTOR_THROW(path.string() + ": couldn't create the directory hierarchy", saga::DoesNotExist); } } else if (!fs::create_directory (path)) { SAGA_ADAPTOR_THROW(path.string() + ": couldn't create the directory", saga::DoesNotExist); } } catch (boost::system::system_error const& e) { SAGA_ADAPTOR_THROW(path.string() + ": couldn't create the directory (" + e.what() + ")", saga::DoesNotExist); } } } // make sure directory exists if ((data->mode_ & saga::filesystem::Create || data->mode_ & saga::filesystem::CreateParents) && data->mode_ & saga::filesystem::Exclusive) { // is_directory if (fs::exists(path)) { SAGA_ADAPTOR_THROW(path.string () + ": already exists", saga::AlreadyExists); } } if (!fs::exists(path)) { try { // create directory, if needed saga::detail::remove_trailing_dot(path); if (OpenMode & saga::filesystem::CreateParents) { if (!fs::create_directories (path)) { SAGA_ADAPTOR_THROW(path.string () + ": couldn't create the directory hierarchy", saga::DoesNotExist); } } else if (OpenMode & saga::filesystem::Create) { if (!fs::create_directory (path)) { SAGA_ADAPTOR_THROW(path.string() + ": couldn't create the directory", saga::DoesNotExist); } } } catch (boost::system::system_error const& e) { SAGA_ADAPTOR_THROW(path.string () + ": couldn't create the directory (" + e.what() + ")", saga::DoesNotExist); } } // we don't need to create the directory twice data->mode_ &= ~(saga::filesystem::Create | saga::filesystem::CreateParents); if (data->mode_ & saga::filesystem::Read || data->mode_ & saga::filesystem::Write || data->mode_ & saga::filesystem::ReadWrite) { if (!fs::exists(path) || !fs::is_directory (path)) { SAGA_ADAPTOR_THROW( path.string () + ": doesn't refer to a directory object", saga::BadParameter); } } if (data->mode_ & ~( saga::filesystem::Create | saga::filesystem::CreateParents | saga::filesystem::Exclusive | saga::filesystem::Overwrite | saga::filesystem::Read | saga::filesystem::Write | saga::filesystem::ReadWrite )) { SAGA_ADAPTOR_THROW("Unknown openmode value: " + boost::lexical_cast<std::string>(data->mode_), saga::BadParameter); } } catch (boost::system::system_error const& e) { SAGA_ADAPTOR_THROW( dir_url.get_string() + ": caught filesystem exception: " + e.what(), saga::NoSuccess); } } /* * destructor */ dir_cpi_impl::~dir_cpi_impl (void) { } /* * SAGA API functions */ /////////////////////////////////////////////////////////////////////////////// void dir_cpi_impl::sync_get_size (saga::off_t& size, saga::url name_to_open, int flags) { namespace fs = boost::filesystem; saga::url file_url; { instance_data data (this); this->check_if_open ("dir_cpi_impl::sync_get_size", data->location_); // verify the file can be handled if (!::detail::file_islocal(name_to_open)) { SAGA_OSSTREAM strm; strm << "dir_cpi_impl::sync_get_size: " "cannot handle remote target directory: " << name_to_open.get_url(); SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined); } file_url = data->location_; if (!::detail::file_islocal(file_url)) { SAGA_OSSTREAM strm; strm << "dir_cpi_impl::sync_get_size: " "cannot handle remote current directory: " << file_url.get_url(); SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined); } } try { #if BOOST_FILESYSTEM_VERSION == 3 fs::path name (saga::url::unescape(::detail::get_filepath(name_to_open))); fs::path path (saga::url::unescape(file_url.get_path())); #else fs::path name (saga::url::unescape(::detail::get_filepath(name_to_open)), fs::native); fs::path path (saga::url::unescape(file_url.get_path()), fs::native); #endif if ( ! name.has_root_path () ) { path /= name; file_url.set_path(path.string()); } else { path = name; file_url = saga::url(name.string()); } if ( fs::exists(path) && fs::is_directory (path) ) { SAGA_ADAPTOR_THROW(path.string () + ": doesn't refer to a file object", saga::DoesNotExist); } size = saga::off_t(fs::file_size(path)); } catch (boost::system::system_error const& e) { SAGA_ADAPTOR_THROW( file_url.get_string() + ": caught filesystem exception: " + e.what(), saga::NoSuccess); } } /////////////////////////////////////////////////////////////////////////////// void dir_cpi_impl::sync_open (saga::filesystem::file & entry, saga::url name_to_open, int openmode) { namespace fs = boost::filesystem; instance_data data (this); this->check_if_open ("dir_cpi_impl::sync_open", data->location_); // verify the file can be handled if (!::detail::file_islocal(name_to_open)) { SAGA_OSSTREAM strm; strm << "dir_cpi_impl::sync_open: " "cannot handle remote target directory: " << name_to_open.get_url(); SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined); } saga::url file_url(data->location_); if (!::detail::file_islocal(file_url)) { SAGA_OSSTREAM strm; strm << "dir_cpi_impl::sync_open: " "cannot handle remote current directory: " << file_url.get_url(); SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined); } try { #if BOOST_FILESYSTEM_VERSION == 3 fs::path name (saga::url::unescape(::detail::get_filepath(name_to_open))); fs::path path (saga::url::unescape(file_url.get_path())); #else fs::path name (saga::url::unescape(::detail::get_filepath(name_to_open)), fs::native); fs::path path (saga::url::unescape(file_url.get_path()), fs::native); #endif if ( ! name.has_root_path () ) { path /= name; file_url.set_path(path.string()); } else { path = name; file_url = saga::url(name.string()); } if ( fs::exists(path) && fs::is_directory (path) ) { SAGA_ADAPTOR_THROW(path.string () + ": doesn't refer to a file object", saga::DoesNotExist); } // is_entry # FIXME: what? (also below...) -- AM entry = saga::filesystem::file (this->get_proxy()->get_session(), file_url.get_url(), openmode); } catch (boost::system::system_error const& e) { SAGA_ADAPTOR_THROW( file_url.get_string() + ": caught filesystem exception: " + e.what(), saga::NoSuccess); } } /////////////////////////////////////////////////////////////////////////////// void dir_cpi_impl::sync_open_dir(saga::filesystem::directory & entry, saga::url name_to_open, int openmode) { namespace fs = boost::filesystem; instance_data data (this); this->check_if_open ("dir_cpi_impl::sync_open_dir", data->location_); // verify the file can be handled if (!::detail::file_islocal(name_to_open)) { SAGA_OSSTREAM strm; strm << "dir_cpi_impl::sync_open_dir: " "cannot handle remote target directory: " << name_to_open.get_url(); SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined); } saga::url file_url(data->location_); if (!::detail::file_islocal(file_url)) { SAGA_OSSTREAM strm; strm << "dir_cpi_impl::sync_open_dir: " "cannot handle remote current directory: " << file_url.get_url(); SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::adaptors::AdaptorDeclined); } try { #if BOOST_FILESYSTEM_VERSION == 3 fs::path name (saga::url::unescape(::detail::get_filepath(name_to_open))); fs::path path (saga::url::unescape(file_url.get_path())); #else fs::path name (saga::url::unescape(::detail::get_filepath(name_to_open)), fs::native); fs::path path (saga::url::unescape(file_url.get_path()), fs::native); #endif if ( ! name.has_root_path () ) { path /= name; file_url.set_path(path.string()); } else { path = name; file_url = saga::url(name.string()); } if ( fs::exists(path) && !fs::is_directory(path)) { SAGA_ADAPTOR_THROW(path.string () + ": doesn't refer to a file object", saga::DoesNotExist); } entry = saga::filesystem::directory (this->get_proxy()->get_session(), file_url.get_url(), openmode); } catch (boost::system::system_error const& e) { SAGA_ADAPTOR_THROW( file_url.get_string() + ": caught filesystem exception: " + e.what(), saga::NoSuccess); } } #if ! defined (SAGA_DEFAULT_FILE_ADAPTOR_NO_ASYNCS) /////////////////////////////////////////////////////////////////////////////// // This adaptor implements the async functions based on its own synchronous // functions for testing purposes only. SInce there is no principal need // to do so, we allow these to be 'switched off'. saga::task dir_cpi_impl::async_get_size (saga::url name, int flags) { return saga::adaptors::task("dir_cpi_impl::sync_get_size", shared_from_this(), &dir_cpi_impl::sync_get_size, name, flags); } saga::task dir_cpi_impl::async_open (saga::url name, int openmode) { return saga::adaptors::task("dir_cpi_impl::sync_open", shared_from_this(), &dir_cpi_impl::sync_open, name, openmode ); } saga::task dir_cpi_impl::async_open_dir(saga::url name, int openmode) { return saga::adaptors::task("dir_cpi_impl::sync_open_dir", shared_from_this(), &dir_cpi_impl::sync_open_dir, name, openmode); } #endif // SAGA_DEFAULT_FILE_ADAPTOR_NO_ASYNCS
34.937811
110
0.563759
[ "object", "vector" ]
49b7db5c1192b86256980342dc9a5f02ce10de10
502
cpp
C++
src/basic/looping_while.cpp
iguntur/cpp-playground
6b4053059549f02947ddc552cca5b7adfa43aed9
[ "MIT" ]
null
null
null
src/basic/looping_while.cpp
iguntur/cpp-playground
6b4053059549f02947ddc552cca5b7adfa43aed9
[ "MIT" ]
null
null
null
src/basic/looping_while.cpp
iguntur/cpp-playground
6b4053059549f02947ddc552cca5b7adfa43aed9
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> int main() { std::cout << "Looping array > keyword: `while`" << std::endl; std::vector<std::string> instruments; instruments.push_back("guitar"); instruments.push_back("bass"); instruments.push_back("keyboard"); instruments.push_back("violin"); instruments.push_back("saxophone"); unsigned int i = 0; while (i < instruments.size()) { std::cout << "Element[" << i << "] = " << instruments[i] << std::endl; i++; } return 0; }
18.592593
72
0.645418
[ "vector" ]
49b9d453b9f6b3fbabd5670d1822e2c8012f8386
5,607
cpp
C++
src/py/wrapper/wrapper_177b7fc9d89d56c7a5ffb03f3a4d37f1.cpp
jpeyhardi/GLM
6f0fd763aec2a0ccdef3901b71ed990f20119510
[ "Apache-2.0" ]
null
null
null
src/py/wrapper/wrapper_177b7fc9d89d56c7a5ffb03f3a4d37f1.cpp
jpeyhardi/GLM
6f0fd763aec2a0ccdef3901b71ed990f20119510
[ "Apache-2.0" ]
null
null
null
src/py/wrapper/wrapper_177b7fc9d89d56c7a5ffb03f3a4d37f1.cpp
jpeyhardi/GLM
6f0fd763aec2a0ccdef3901b71ed990f20119510
[ "Apache-2.0" ]
null
null
null
#include "_glm.h" namespace autowig { class Wrap_177b7fc9d89d56c7a5ffb03f3a4d37f1 : public ::statiskit::glm::Design, public boost::python::wrapper< struct ::statiskit::glm::Design > { public: virtual class ::std::unique_ptr< struct ::statiskit::glm::Design, struct ::std::default_delete< struct ::statiskit::glm::Design > > copy() const { ::std::unique_ptr< struct ::statiskit::glm::Design, struct ::std::default_delete< struct ::statiskit::glm::Design > > ::element_type* result = this->get_override("copy")(); return ::std::unique_ptr< struct ::statiskit::glm::Design, struct ::std::default_delete< struct ::statiskit::glm::Design > > (result); } virtual class ::statiskit::glm::VectorPredictor * build_predictor(struct ::statiskit::MultivariateSampleSpace const & param_0, ::statiskit::Index const & param_1) const { return this->get_override("build_predictor")(param_0, param_1); } virtual ::statiskit::Index beta_size(class ::statiskit::UnivariateConditionalData const & param_0) const { return this->get_override("beta_size")(param_0); } virtual class ::std::vector< class ::Eigen::Matrix< double, -1, -1, 0, -1, -1 >, class ::std::allocator< class ::Eigen::Matrix< double, -1, -1, 0, -1, -1 > > > Z_init(class ::statiskit::UnivariateConditionalData const & param_0) const { return this->get_override("Z_init")(param_0); } protected: private: }; } #if defined(_MSC_VER) #if (_MSC_VER == 1900) namespace boost { template <> autowig::Wrap_177b7fc9d89d56c7a5ffb03f3a4d37f1 const volatile * get_pointer<autowig::Wrap_177b7fc9d89d56c7a5ffb03f3a4d37f1 const volatile >(autowig::Wrap_177b7fc9d89d56c7a5ffb03f3a4d37f1 const volatile *c) { return c; } template <> struct ::statiskit::glm::Design const volatile * get_pointer<struct ::statiskit::glm::Design const volatile >(struct ::statiskit::glm::Design const volatile *c) { return c; } } #endif #endif void wrapper_177b7fc9d89d56c7a5ffb03f3a4d37f1() { std::string name_fa414b05d29e5f4ea0b6d6cb5cf81b01 = boost::python::extract< std::string >(boost::python::scope().attr("__name__") + ".statiskit"); boost::python::object module_fa414b05d29e5f4ea0b6d6cb5cf81b01(boost::python::handle< >(boost::python::borrowed(PyImport_AddModule(name_fa414b05d29e5f4ea0b6d6cb5cf81b01.c_str())))); boost::python::scope().attr("statiskit") = module_fa414b05d29e5f4ea0b6d6cb5cf81b01; boost::python::scope scope_fa414b05d29e5f4ea0b6d6cb5cf81b01 = module_fa414b05d29e5f4ea0b6d6cb5cf81b01; std::string name_dfc470f00ed658a8838b0d698570f3bc = boost::python::extract< std::string >(boost::python::scope().attr("__name__") + ".glm"); boost::python::object module_dfc470f00ed658a8838b0d698570f3bc(boost::python::handle< >(boost::python::borrowed(PyImport_AddModule(name_dfc470f00ed658a8838b0d698570f3bc.c_str())))); boost::python::scope().attr("glm") = module_dfc470f00ed658a8838b0d698570f3bc; boost::python::scope scope_dfc470f00ed658a8838b0d698570f3bc = module_dfc470f00ed658a8838b0d698570f3bc; class ::std::vector< class ::Eigen::Matrix< double, -1, -1, 0, -1, -1 >, class ::std::allocator< class ::Eigen::Matrix< double, -1, -1, 0, -1, -1 > > > (::statiskit::glm::Design::*method_pointer_e4bff1767d4c5024943c6a3e34c37298)(class ::statiskit::UnivariateConditionalData const &) const = &::statiskit::glm::Design::Z_init; ::statiskit::Index (::statiskit::glm::Design::*method_pointer_03749ad541855dfdb16bf974f84e692d)(class ::statiskit::UnivariateConditionalData const &) const = &::statiskit::glm::Design::beta_size; class ::statiskit::glm::VectorPredictor * (::statiskit::glm::Design::*method_pointer_ca02a0be11a256df81e12e7e45b9eb90)(struct ::statiskit::MultivariateSampleSpace const &, ::statiskit::Index const &) const = &::statiskit::glm::Design::build_predictor; class ::std::unique_ptr< struct ::statiskit::glm::Design, struct ::std::default_delete< struct ::statiskit::glm::Design > > (::statiskit::glm::Design::*method_pointer_23d863b31f4659699b1bdce91783ce4d)() const = &::statiskit::glm::Design::copy; boost::python::class_< autowig::Wrap_177b7fc9d89d56c7a5ffb03f3a4d37f1, autowig::Held< autowig::Wrap_177b7fc9d89d56c7a5ffb03f3a4d37f1 >::Type, boost::noncopyable > class_177b7fc9d89d56c7a5ffb03f3a4d37f1("Design", "", boost::python::no_init); class_177b7fc9d89d56c7a5ffb03f3a4d37f1.def("z__init", boost::python::pure_virtual(method_pointer_e4bff1767d4c5024943c6a3e34c37298), ""); class_177b7fc9d89d56c7a5ffb03f3a4d37f1.def("beta_size", boost::python::pure_virtual(method_pointer_03749ad541855dfdb16bf974f84e692d), ""); class_177b7fc9d89d56c7a5ffb03f3a4d37f1.def("build_predictor", boost::python::pure_virtual(method_pointer_ca02a0be11a256df81e12e7e45b9eb90), boost::python::return_value_policy< boost::python::reference_existing_object >(), ""); class_177b7fc9d89d56c7a5ffb03f3a4d37f1.def("copy", boost::python::pure_virtual(method_pointer_23d863b31f4659699b1bdce91783ce4d), ""); if(autowig::Held< struct ::statiskit::glm::Design >::is_class) { boost::python::implicitly_convertible< autowig::Held< autowig::Wrap_177b7fc9d89d56c7a5ffb03f3a4d37f1 >::Type, autowig::Held< struct ::statiskit::glm::Design >::Type >(); boost::python::register_ptr_to_python< autowig::Held< struct ::statiskit::glm::Design >::Type >(); } }
74.76
330
0.713751
[ "object", "vector" ]
49bc905ea12ab70eb651706ed817a0577b50ba66
5,188
cpp
C++
2019/day03.cpp
winks/adventofcode
6d2a97c148048a2d95b62862d1fe11d5760bd79f
[ "0BSD" ]
null
null
null
2019/day03.cpp
winks/adventofcode
6d2a97c148048a2d95b62862d1fe11d5760bd79f
[ "0BSD" ]
1
2019-12-08T14:45:28.000Z
2019-12-27T23:11:11.000Z
2019/day03.cpp
winks/adventofcode
6d2a97c148048a2d95b62862d1fe11d5760bd79f
[ "0BSD" ]
null
null
null
#include <fstream> #include <iostream> #include <sstream> #include <stdlib.h> #include <tuple> #include <vector> void pprint(std::vector<std::tuple<int,int>> v, std::string prefix = "") { return; if (prefix.size() > 0) std::cout << prefix << " :: "; for (auto it = v.begin(); it != v.end(); ++it) { std::tuple<int,int> x = *it; std::cout << "(" << std::get<0>(x) << "/" << std::get<1>(x) << ")"; } std::cout << std::endl; } std::vector<std::tuple<int,int>> go(std::tuple<std::string,int> s, std::tuple<int,int> origin) { std::vector<std::tuple<int,int>> coords; std::string d = std::get<0>(s); int len = std::get<1>(s); int x = std::get<0>(origin); int y = std::get<1>(origin); std::cout << "going " << d << " " << len << " from " << x << "/" << y << std::endl; if (d == "R") { for (int i=1; i<=len; ++i) { x++; std::tuple<int,int> p = std::make_tuple(x, y); coords.push_back(p); } } else if (d == "U") { for (int i=1; i<=len; ++i) { y++; std::tuple<int,int> p = std::make_tuple(x, y); coords.push_back(p); } } else if (d == "L") { for (int i=1; i<=len; ++i) { x--; std::tuple<int,int> p = std::make_tuple(x, y); coords.push_back(p); } } else if (d == "D") { for (int i=1; i<=len; ++i) { y--; std::tuple<int,int> p = std::make_tuple(x, y); coords.push_back(p); } } else { return coords; } pprint(coords, "go"); return coords; } std::vector<std::tuple<int,int>> path(std::vector<std::tuple<std::string,int>> ops, std::tuple<int,int> zero) { std::vector<std::tuple<int,int>> coords; std::tuple<int,int> start = zero; for (uint i=0; i<ops.size(); ++i) { std::cout << ". i: " << i << " start: (" << std::get<0>(start) << "/" << std::get<1>(start) << ") len:" << coords.size() << std::endl; std::vector<std::tuple<int,int>> c2 = go(ops[i], start); for (auto it = c2.begin(); it != c2.end(); ++it) { coords.push_back(*it); } start = coords.back(); std::cout << ".. i: " << i << " start: (" << std::get<0>(start) << "/" << std::get<1>(start) << ") len:" << coords.size() << std::endl; pprint(coords, "path"); } return coords; } std::vector<std::tuple<std::string,int>> parse(const std::string & arg) { std::stringstream ss(arg); std::string token; std::string::size_type sz; std::vector<std::tuple<std::string, int>> rv; std::tuple<std::string, int> rvx; while (std::getline(ss, token, ',')) { if (token.size() < 2) continue; int num = std::stoi(token.substr(1, std::string::npos), &sz); rvx = std::make_tuple(token.substr(0, 1), num); rv.push_back(rvx); } return rv; } int manhattan(std::tuple<int,int> p1, std::tuple<int,int> p2) { int a = std::abs(std::get<0>(p1) - std::get<0>(p2)); int b = std::abs(std::get<1>(p1) - std::get<1>(p2)); return a + b; } std::vector<std::tuple<int,int>> crossed(std::vector<std::tuple<int,int>> p1, std::vector<std::tuple<int,int>> p2) { std::vector<std::tuple<int,int>> tmp; int64_t counter = 0; for (auto it1 = p1.begin(); it1 != p1.end(); ++it1) { int x1 = std::get<0>(*it1); int y1 = std::get<1>(*it1); for (auto it2 = p2.begin(); it2 != p2.end(); ++it2) { int x2 = std::get<0>(*it2); int y2 = std::get<1>(*it2); if (x1 == x2 && y1 == y2) { tmp.push_back(*it1); } ++counter; if (counter % 1000000 == 0) std::cout << counter << " | " << tmp.size() << std::endl; if (counter % 1000000000 == 0) { for (auto it3 = tmp.begin(); it3 != tmp.end(); ++it3) { std::cout << " A " << std::get<0>(*it3) << "/" << std::get<1>(*it3); } std::cout << std::endl; } } } pprint(tmp, "crossed"); return tmp; } std::tuple<int,int> find(std::vector<std::tuple<int,int>> v, std::tuple<int, int> origin) { std::tuple<int,int> rv = origin; int lowest = 0; for (auto it = v.begin(); it != v.end(); ++it) { int man = manhattan(origin, *it); if (lowest == 0) { lowest = man; rv = *it; } else if (man < lowest) { lowest = man; rv = *it; } std::cout << lowest << std::endl; } return rv; } int main(int argc, char *argv[]) { std::vector<std::string> allops; std::ifstream infile; if (argc < 2) { std::cout << "Usage: " << argv[0] << " /path/to/filename" << std::endl; return 0; } infile = std::ifstream(argv[1]); std::string input; while (infile >> input) { if (input.size() > 2) allops.push_back(input); } std::cout << "lines: " << allops.size() << std::endl; if (allops.size() != 2) return 3; std::tuple<int,int> zero(0, 0); std::vector<std::tuple<std::string,int>> ops1 = parse(allops[0]); std::vector<std::tuple<int,int>> p1 = path(ops1, zero); std::cout << "line 1: " << p1.size() << std::endl; pprint(p1, "LINE1"); std::vector<std::tuple<std::string,int>> ops2 = parse(allops[1]); std::vector<std::tuple<int,int>> p2 = path(ops2, zero); std::cout << "line 2: " << p2.size() << std::endl; pprint(p2, "LINE2"); std::vector<std::tuple<int,int>> crx = crossed(p1, p2); std::tuple<int,int> rv = find(crx, zero); if (rv == zero) { std::cout << "NOPE" << std::endl; } else { std::cout << "YES " << std::get<0>(rv) << "/" << std::get<1>(rv) << " ~ " << manhattan(rv, zero) << std::endl; } }
24.704762
114
0.545104
[ "vector" ]
49bd1e3897bf11936735752afa9ebac91a50f9ea
2,148
cpp
C++
plugins/community/repos/DHE-Modules/src/gui/stage-widget.cpp
x42/VeeSeeVSTRack
0f5576f92e026ac1480e1477e55084911eca4052
[ "Zlib", "BSD-3-Clause" ]
null
null
null
plugins/community/repos/DHE-Modules/src/gui/stage-widget.cpp
x42/VeeSeeVSTRack
0f5576f92e026ac1480e1477e55084911eca4052
[ "Zlib", "BSD-3-Clause" ]
null
null
null
plugins/community/repos/DHE-Modules/src/gui/stage-widget.cpp
x42/VeeSeeVSTRack
0f5576f92e026ac1480e1477e55084911eca4052
[ "Zlib", "BSD-3-Clause" ]
null
null
null
#include <componentlibrary.hpp> #include "modules/stage-module.h" #include "stage-widget.h" namespace rack_plugin_DHE_Modules { struct StagePort : rack::SVGPort { StagePort() { background->svg = rack::SVG::load(rack::assetPlugin(plugin, "res/stage/port.svg")); background->wrap(); box.size = background->box.size; } }; struct StageKnobLarge : rack::RoundKnob { StageKnobLarge() { setSVG(rack::SVG::load(rack::assetPlugin(plugin, "res/stage/knob-large.svg"))); shadow->opacity = 0.f; } }; StageWidget::StageWidget(rack::Module *module) : ModuleWidget(module, 5, "res/stage/panel.svg") { auto widget_right_edge = width(); auto left_x = width()/4.f + 0.333333f; auto center_x = widget_right_edge/2.f; auto right_x = widget_right_edge - left_x; auto top_row_y = 25.f; auto row_spacing = 18.5f; auto row = 0; install_knob<StageKnobLarge>(StageModule::LEVEL_KNOB, {center_x, top_row_y + row*row_spacing}); row++; install_knob<StageKnobLarge>(StageModule::CURVE_KNOB, {center_x, top_row_y + row*row_spacing}); row++; install_knob<StageKnobLarge>(StageModule::DURATION_KNOB, {center_x, top_row_y + row*row_spacing}); top_row_y = 82.f; row_spacing = 15.f; row = 0; install_input<StagePort>(StageModule::DEFER_IN, {left_x, top_row_y + row*row_spacing}); install_output<StagePort>(StageModule::ACTIVE_OUT, {right_x, top_row_y + row*row_spacing}); row++; install_input<StagePort>(StageModule::TRIGGER_IN, {left_x, top_row_y + row*row_spacing}); install_output<StagePort>(StageModule::EOC_OUT, {right_x, top_row_y + row*row_spacing}); row++; install_input<StagePort>(StageModule::ENVELOPE_IN, {left_x, top_row_y + row*row_spacing}); install_output<StagePort>(StageModule::ENVELOPE_OUT, {right_x, top_row_y + row*row_spacing}); } } // namespace rack_plugin_DHE_Modules using namespace rack_plugin_DHE_Modules; RACK_PLUGIN_MODEL_INIT(DHE_Modules, Stage) { Model *modelStage = rack_plugin_DHE_Modules::createModel<rack_plugin_DHE_Modules::StageModule, rack_plugin_DHE_Modules::StageWidget, rack::ModelTag>("Stage", rack::ENVELOPE_GENERATOR_TAG); return modelStage; }
32.545455
191
0.738361
[ "model" ]
49be97709413d9aa18a52e71c92177bae26ddc68
2,464
hpp
C++
src/graphApp.hpp
Montag55/gl-playground
7501718726f8933e7550abfacaeff9708a4ab270
[ "MIT" ]
null
null
null
src/graphApp.hpp
Montag55/gl-playground
7501718726f8933e7550abfacaeff9708a4ab270
[ "MIT" ]
null
null
null
src/graphApp.hpp
Montag55/gl-playground
7501718726f8933e7550abfacaeff9708a4ab270
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <chrono> #include <variant> #include <application.hpp> #include <utils.hpp> #include <structs.hpp> #include <boxSelect.hpp> #include <axisDrag.hpp> #include <timeSeries.hpp> // assure compile class will be there class BoxSelect; class AxisDrag; class TimeSeries; class GraphApp : public Application, public std::enable_shared_from_this<GraphApp> { public: GraphApp(); ~GraphApp(); bool draw() const override; void updateColor(const std::vector<int>& ids, bool reset = false) const; void updateAxis(const std::vector<float>& axis) const; void updateVertexIndicies() const; const std::vector<Vertex>* getVertecies(); const std::vector<unsigned short>* getIndicies(); const std::vector<float>* getAxis(); const std::vector<float>* getData(); const std::vector<glm::vec4>* getColor(); const glm::mat4& getModel(); const std::vector<glm::vec2>* getRanges(); const std::vector<int>* getAxisOrder(); const GraphApp* getPtr(); const GLuint* getVAO(); const GLuint* getAttribute_SSBO(); const int* getNumTimeAxis(); void updateOrder(const std::vector<int>& order) const; void updateExcludedAxis(const std::vector<int>& axis) const; private: std::vector<float> initializeData(); std::vector<float> initializeAxis(); std::vector<glm::vec2> initializeRanges(); void initializeColor(); void initializeVertexBuffers(); void initializeStorageBuffers(); void initializeIndexBuffer(); void drawPolyLines() const; void mouseEventListener() const; protected: glm::mat4 m_model; GLuint m_polyline_program; GLuint m_axis_program; GLuint m_vao; GLuint m_vbo; GLuint m_ibo; GLuint m_data_ssbo; GLuint m_color_ssbo; GLuint m_attribute_ssbo; GLuint m_range_ssbo; int m_num_attributes; int m_num_timeAxis; std::vector<float> m_axis; std::vector<float> m_data; std::vector<Vertex> m_vertices; std::vector<glm::vec2> m_ranges; std::vector<glm::vec4> m_colors; std::vector<Vertex> m_selection; std::vector<unsigned short> m_indicies; std::vector<int> m_axisOrder; std::vector<int> m_excludedAxis; bool m_selecting; BoxSelect* m_boxSelect_tool; AxisDrag* m_axisDrag_tool; TimeSeries* m_timeSeries_tool; MouseStatus m_prevMouseState; };
28.651163
77
0.677354
[ "vector" ]
49c13faf50f4ffc78b45fd84d97df7ebd0eda56f
16,677
cpp
C++
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/MSStateHandler.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/MSStateHandler.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/MSStateHandler.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file MSStateHandler.cpp /// @author Daniel Krajzewicz /// @author Michael Behrisch /// @author Jakob Erdmann /// @date Thu, 13 Dec 2012 /// // Parser and output filter for routes and vehicles state saving and loading /****************************************************************************/ #include <config.h> #ifdef HAVE_VERSION_H #include <version.h> #endif #include <sstream> #include <utils/common/StringUtils.h> #include <utils/options/OptionsCont.h> #include <utils/iodevices/OutputDevice.h> #include <utils/xml/SUMOXMLDefinitions.h> #include <utils/vehicle/SUMOVehicleParserHelper.h> #include <microsim/devices/MSDevice_Routing.h> #include <microsim/devices/MSDevice_BTreceiver.h> #include <microsim/devices/MSDevice_ToC.h> #include <microsim/transportables/MSTransportableControl.h> #include <microsim/MSEdge.h> #include <microsim/MSLane.h> #include <microsim/MSGlobals.h> #include <microsim/MSNet.h> #include <microsim/MSVehicleTransfer.h> #include <microsim/MSInsertionControl.h> #include <microsim/MSRoute.h> #include <microsim/MSVehicleControl.h> #include <microsim/MSDriverState.h> #include "MSStateHandler.h" #include <mesosim/MESegment.h> #include <mesosim/MELoop.h> // =========================================================================== // method definitions // =========================================================================== MSStateHandler::MSStateHandler(const std::string& file, const SUMOTime offset, bool onlyReadTime) : MSRouteHandler(file, true), myOffset(offset), mySegment(nullptr), myCurrentLane(nullptr), myCurrentLink(nullptr), myAttrs(nullptr), myLastParameterised(nullptr), myOnlyReadTime(onlyReadTime) { myAmLoadingState = true; const std::vector<std::string> vehIDs = OptionsCont::getOptions().getStringVector("load-state.remove-vehicles"); myVehiclesToRemove.insert(vehIDs.begin(), vehIDs.end()); } MSStateHandler::~MSStateHandler() { } void MSStateHandler::saveState(const std::string& file, SUMOTime step) { OutputDevice& out = OutputDevice::getDevice(file); out.writeHeader<MSEdge>(SUMO_TAG_SNAPSHOT); out.writeAttr("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance").writeAttr("xsi:noNamespaceSchemaLocation", "http://sumo.dlr.de/xsd/state_file.xsd"); out.writeAttr(SUMO_ATTR_VERSION, VERSION_STRING).writeAttr(SUMO_ATTR_TIME, time2string(step)); if (OptionsCont::getOptions().getBool("save-state.rng")) { saveRNGs(out); } MSRoute::dict_saveState(out); MSNet::getInstance()->getInsertionControl().saveState(out); MSNet::getInstance()->getVehicleControl().saveState(out); if (OptionsCont::getOptions().getBool("save-state.transportables")) { if (MSNet::getInstance()->hasPersons()) { out.openTag(SUMO_TAG_TRANSPORTABLES).writeAttr(SUMO_ATTR_TYPE, "person"); MSNet::getInstance()->getPersonControl().saveState(out); out.closeTag(); } if (MSNet::getInstance()->hasContainers()) { out.openTag(SUMO_TAG_TRANSPORTABLES).writeAttr(SUMO_ATTR_TYPE, "container"); MSNet::getInstance()->getContainerControl().saveState(out); out.closeTag(); } } MSVehicleTransfer::getInstance()->saveState(out); if (MSGlobals::gUseMesoSim) { for (int i = 0; i < MSEdge::dictSize(); i++) { for (MESegment* s = MSGlobals::gMesoNet->getSegmentForEdge(*MSEdge::getAllEdges()[i]); s != nullptr; s = s->getNextSegment()) { s->saveState(out); } } } else { for (int i = 0; i < MSEdge::dictSize(); i++) { const std::vector<MSLane*>& lanes = MSEdge::getAllEdges()[i]->getLanes(); for (std::vector<MSLane*>::const_iterator it = lanes.begin(); it != lanes.end(); ++it) { (*it)->saveState(out); } } } out.close(); } void MSStateHandler::myStartElement(int element, const SUMOSAXAttributes& attrs) { MSRouteHandler::myStartElement(element, attrs); MSVehicleControl& vc = MSNet::getInstance()->getVehicleControl(); switch (element) { case SUMO_TAG_SNAPSHOT: { myTime = string2time(attrs.getString(SUMO_ATTR_TIME)); if (myOnlyReadTime) { throw AbortParsing("Abort state parsing after reading time"); } const std::string& version = attrs.getString(SUMO_ATTR_VERSION); if (version != VERSION_STRING) { WRITE_WARNING("State was written with sumo version " + version + " (present: " + VERSION_STRING + ")!"); } break; } case SUMO_TAG_RNGSTATE: { if (attrs.hasAttribute(SUMO_ATTR_RNG_DEFAULT)) { RandHelper::loadState(attrs.getString(SUMO_ATTR_RNG_DEFAULT)); } if (attrs.hasAttribute(SUMO_ATTR_RNG_ROUTEHANDLER)) { RandHelper::loadState(attrs.getString(SUMO_ATTR_RNG_DEFAULT), MSRouteHandler::getParsingRNG()); } if (attrs.hasAttribute(SUMO_ATTR_RNG_INSERTIONCONTROL)) { RandHelper::loadState(attrs.getString(SUMO_ATTR_RNG_DEFAULT), MSNet::getInstance()->getInsertionControl().getFlowRNG()); } if (attrs.hasAttribute(SUMO_ATTR_RNG_DEVICE)) { RandHelper::loadState(attrs.getString(SUMO_ATTR_RNG_DEFAULT), MSDevice::getEquipmentRNG()); } if (attrs.hasAttribute(SUMO_ATTR_RNG_DEVICE_BT)) { RandHelper::loadState(attrs.getString(SUMO_ATTR_RNG_DEFAULT), MSDevice_BTreceiver::getEquipmentRNG()); } if (attrs.hasAttribute(SUMO_ATTR_RNG_DRIVERSTATE)) { RandHelper::loadState(attrs.getString(SUMO_ATTR_RNG_DEFAULT), OUProcess::getRNG()); } if (attrs.hasAttribute(SUMO_ATTR_RNG_DEVICE_TOC)) { RandHelper::loadState(attrs.getString(SUMO_ATTR_RNG_DEFAULT), MSDevice_ToC::getResponseTimeRNG()); } break; } case SUMO_TAG_RNGLANE: { const int index = attrs.getInt(SUMO_ATTR_INDEX); const std::string state = attrs.getString(SUMO_ATTR_STATE); MSLane::loadRNGState(index, state); break; } case SUMO_TAG_DELAY: { vc.setState(attrs.getInt(SUMO_ATTR_NUMBER), attrs.getInt(SUMO_ATTR_BEGIN), attrs.getInt(SUMO_ATTR_END), attrs.getFloat(SUMO_ATTR_DEPART), attrs.getFloat(SUMO_ATTR_TIME)); break; } case SUMO_TAG_FLOWSTATE: { SUMOVehicleParameter* pars = new SUMOVehicleParameter(); pars->id = attrs.getString(SUMO_ATTR_ID); bool ok; if (attrs.getOpt<bool>(SUMO_ATTR_REROUTE, nullptr, ok, false)) { pars->parametersSet |= VEHPARS_FORCE_REROUTE; } MSNet::getInstance()->getInsertionControl().addFlow(pars, attrs.getInt(SUMO_ATTR_INDEX)); break; } case SUMO_TAG_VTYPE: { myLastParameterised = myCurrentVType; break; } case SUMO_TAG_VEHICLE: { myLastParameterised = myVehicleParameter; myAttrs = attrs.clone(); break; } case SUMO_TAG_DEVICE: { myDeviceAttrs.push_back(attrs.clone()); break; } case SUMO_TAG_VEHICLETRANSFER: { MSVehicleTransfer::getInstance()->loadState(attrs, myOffset, vc); break; } case SUMO_TAG_SEGMENT: { if (mySegment == nullptr) { mySegment = MSGlobals::gMesoNet->getSegmentForEdge(*MSEdge::getAllEdges()[0]); } else if (mySegment->getNextSegment() == nullptr) { mySegment = MSGlobals::gMesoNet->getSegmentForEdge(*MSEdge::getAllEdges()[mySegment->getEdge().getNumericalID() + 1]); } else { mySegment = mySegment->getNextSegment(); } myQueIndex = 0; break; } case SUMO_TAG_LANE: { bool ok; const std::string laneID = attrs.get<std::string>(SUMO_ATTR_ID, nullptr, ok); myCurrentLane = MSLane::dictionary(laneID); if (myCurrentLane == nullptr) { throw ProcessError("Unknown lane '" + laneID + "' in loaded state"); } break; } case SUMO_TAG_VIEWSETTINGS_VEHICLES: { try { const std::vector<std::string>& vehIDs = attrs.getStringVector(SUMO_ATTR_VALUE); if (MSGlobals::gUseMesoSim) { mySegment->loadState(vehIDs, MSNet::getInstance()->getVehicleControl(), StringUtils::toLong(attrs.getString(SUMO_ATTR_TIME)) - myOffset, myQueIndex); } else { myCurrentLane->loadState(vehIDs, MSNet::getInstance()->getVehicleControl()); } } catch (EmptyData&) {} // attr may be empty myQueIndex++; break; } case SUMO_TAG_LINK: { bool ok; myCurrentLink = nullptr; const std::string toLaneID = attrs.get<std::string>(SUMO_ATTR_TO, nullptr, ok); for (MSLink* link : myCurrentLane->getLinkCont()) { if (link->getViaLaneOrLane()->getID() == toLaneID) { myCurrentLink = link; } } if (myCurrentLink == nullptr) { throw ProcessError("Unknown link from lane '" + myCurrentLane->getID() + "' to lane '" + toLaneID + "' in loaded state"); } break; } case SUMO_TAG_APPROACHING: { bool ok; const std::string vehID = attrs.get<std::string>(SUMO_ATTR_ID, nullptr, ok); const SUMOTime arrivalTime = attrs.get<SUMOTime>(SUMO_ATTR_ARRIVALTIME, nullptr, ok); const double arrivalSpeed = attrs.get<double>(SUMO_ATTR_ARRIVALSPEED, nullptr, ok); const double leaveSpeed = attrs.get<double>(SUMO_ATTR_DEPARTSPEED, nullptr, ok); const bool setRequest = attrs.get<bool>(SUMO_ATTR_REQUEST, nullptr, ok); const SUMOTime arrivalTimeBraking = attrs.get<SUMOTime>(SUMO_ATTR_ARRIVALTIMEBRAKING, nullptr, ok); const double arrivalSpeedBraking = attrs.get<double>(SUMO_ATTR_ARRIVALSPEEDBRAKING, nullptr, ok); const SUMOTime waitingTime = attrs.get<SUMOTime>(SUMO_ATTR_WAITINGTIME, nullptr, ok); const double dist = attrs.get<double>(SUMO_ATTR_DISTANCE, nullptr, ok); SUMOVehicle* veh = vc.getVehicle(vehID); myCurrentLink->setApproaching(veh, arrivalTime, arrivalSpeed, leaveSpeed, setRequest, arrivalTimeBraking, arrivalSpeedBraking, waitingTime, dist); if (!MSGlobals::gUseMesoSim) { MSVehicle* microVeh = dynamic_cast<MSVehicle*>(veh); microVeh->loadPreviousApproaching(myCurrentLink, setRequest, arrivalTime, arrivalSpeed, arrivalTimeBraking, arrivalSpeedBraking, dist, leaveSpeed); } break; } case SUMO_TAG_PARAM: { bool ok; const std::string key = attrs.get<std::string>(SUMO_ATTR_KEY, nullptr, ok); // circumventing empty string test const std::string val = attrs.hasAttribute(SUMO_ATTR_VALUE) ? attrs.getString(SUMO_ATTR_VALUE) : ""; assert(myLastParameterised != 0); if (myLastParameterised != nullptr) { myLastParameterised->setParameter(key, val); } break; } case SUMO_TAG_TRANSPORTABLES: if (attrs.getString(SUMO_ATTR_TYPE) == "person") { MSNet::getInstance()->getPersonControl().loadState(attrs.getString(SUMO_ATTR_STATE)); } if (attrs.getString(SUMO_ATTR_TYPE) == "container") { MSNet::getInstance()->getContainerControl().loadState(attrs.getString(SUMO_ATTR_STATE)); } break; case SUMO_TAG_PERSON: case SUMO_TAG_CONTAINER: myAttrs = attrs.clone(); break; default: break; } } void MSStateHandler::myEndElement(int element) { MSRouteHandler::myEndElement(element); switch (element) { case SUMO_TAG_PERSON: case SUMO_TAG_CONTAINER: { MSTransportableControl& tc = (element == SUMO_TAG_PERSON ? MSNet::getInstance()->getPersonControl() : MSNet::getInstance()->getContainerControl()); tc.get(myAttrs->getString(SUMO_ATTR_ID))->loadState(myAttrs->getString(SUMO_ATTR_STATE)); delete myAttrs; myAttrs = nullptr; break; } default: break; } if (element != SUMO_TAG_PARAM && myVehicleParameter == nullptr && myCurrentVType == nullptr) { myLastParameterised = nullptr; } } void MSStateHandler::closeVehicle() { assert(myVehicleParameter != 0); myVehicleParameter->depart -= myOffset; // the vehicle was already counted in MSVehicleControl::setState MSVehicleControl& vc = MSNet::getInstance()->getVehicleControl(); // make a copy because myVehicleParameter is reset in closeVehicle() const std::string vehID = myVehicleParameter->id; if (myVehiclesToRemove.count(vehID) == 0) { MSRouteHandler::closeVehicle(); // reset depart vc.discountStateLoaded(); SUMOVehicle* v = vc.getVehicle(vehID); if (v == nullptr) { throw ProcessError("Could not load vehicle '" + vehID + "' from state"); } v->setChosenSpeedFactor(myAttrs->getFloat(SUMO_ATTR_SPEEDFACTOR)); v->loadState(*myAttrs, myOffset); if (v->hasDeparted()) { // vehicle already departed: disable pre-insertion rerouting and enable regular routing behavior MSDevice_Routing* routingDevice = static_cast<MSDevice_Routing*>(v->getDevice(typeid(MSDevice_Routing))); if (routingDevice != nullptr) { routingDevice->notifyEnter(*v, MSMoveReminder::NOTIFICATION_DEPARTED); } MSNet::getInstance()->getInsertionControl().alreadyDeparted(v); } while (!myDeviceAttrs.empty()) { const std::string attrID = myDeviceAttrs.back()->getString(SUMO_ATTR_ID); for (MSVehicleDevice* const dev : v->getDevices()) { if (dev->getID() == attrID) { dev->loadState(*myDeviceAttrs.back()); } } delete myDeviceAttrs.back(); myDeviceAttrs.pop_back(); } } else { vc.discountStateLoaded(true); delete myVehicleParameter; myVehicleParameter = nullptr; } delete myAttrs; } void MSStateHandler::saveRNGs(OutputDevice& out) { out.openTag(SUMO_TAG_RNGSTATE); out.writeAttr(SUMO_ATTR_RNG_DEFAULT, RandHelper::saveState()); out.writeAttr(SUMO_ATTR_RNG_ROUTEHANDLER, RandHelper::saveState(MSRouteHandler::getParsingRNG())); out.writeAttr(SUMO_ATTR_RNG_INSERTIONCONTROL, RandHelper::saveState(MSNet::getInstance()->getInsertionControl().getFlowRNG())); out.writeAttr(SUMO_ATTR_RNG_DEVICE, RandHelper::saveState(MSDevice::getEquipmentRNG())); out.writeAttr(SUMO_ATTR_RNG_DEVICE_BT, RandHelper::saveState(MSDevice_BTreceiver::getRNG())); out.writeAttr(SUMO_ATTR_RNG_DRIVERSTATE, RandHelper::saveState(OUProcess::getRNG())); out.writeAttr(SUMO_ATTR_RNG_DEVICE_TOC, RandHelper::saveState(MSDevice_ToC::getResponseTimeRNG())); MSLane::saveRNGStates(out); out.closeTag(); } /****************************************************************************/
44.236074
169
0.61336
[ "vector" ]
49c18802b2c095bf023cb9833121c02fe375a48e
891
cpp
C++
515-find-largest-value-in-each-tree-row/find-largest-value-in-each-tree-row_[AC1_13ms].cpp
i-square/LeetCode
9b15114b7a3de8638d44b3030edb72f41d9a274e
[ "MIT" ]
1
2019-10-09T11:25:10.000Z
2019-10-09T11:25:10.000Z
515-find-largest-value-in-each-tree-row/find-largest-value-in-each-tree-row_[AC1_13ms].cpp
i-square/LeetCode
9b15114b7a3de8638d44b3030edb72f41d9a274e
[ "MIT" ]
null
null
null
515-find-largest-value-in-each-tree-row/find-largest-value-in-each-tree-row_[AC1_13ms].cpp
i-square/LeetCode
9b15114b7a3de8638d44b3030edb72f41d9a274e
[ "MIT" ]
1
2021-03-31T08:45:51.000Z
2021-03-31T08:45:51.000Z
// You need to find the largest value in each row of a binary tree. // // Example: // // Input: // // 1 // / \ // 3 2 // / \ \ // 5 3 9 // // Output: [1, 3, 9] /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(const TreeNode* node, const int depth, vector<int>& ans) { if (!node) return; if (ans.size() <= depth) ans.emplace_back(node->val); else ans[depth] = std::max(ans[depth], node->val); dfs(node->left, depth + 1, ans); dfs(node->right, depth + 1, ans); } public: vector<int> largestValues(TreeNode* root) { vector<int> ans; if (root) dfs(root, 0, ans); return ans; } };
21.214286
69
0.499439
[ "vector" ]
49c29954f1ed5278699ded38d5b666513035efb1
6,482
cpp
C++
Immortal/Platform/D3D12/Pipeline.cpp
QSXW/Immortal
32adcc8609b318752dd97f1c14dc7368b47d47d1
[ "Apache-2.0" ]
6
2021-09-15T08:56:28.000Z
2022-03-29T15:55:02.000Z
Immortal/Platform/D3D12/Pipeline.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
null
null
null
Immortal/Platform/D3D12/Pipeline.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
4
2021-12-05T17:28:57.000Z
2022-03-29T15:55:05.000Z
#include "Pipeline.h" #include "Device.h" #include "Buffer.h" #include "RenderTarget.h" namespace Immortal { namespace D3D12 { Pipeline::Pipeline(Device *device, std::shared_ptr<Shader::Super> shader) : Super{ shader }, device{ device }, state{ new State{} }, descriptorAllocator{ DescriptorPool::Type::ShaderResourceView, DescriptorPool::Flag::ShaderVisible } { descriptorAllocator.Init(device); } Pipeline::~Pipeline() { IfNotNullThenRelease(pipelineState); } void Pipeline::Set(std::shared_ptr<Buffer::Super> &superBuffer) { Super::Set(superBuffer); auto buffer = std::dynamic_pointer_cast<Buffer>(superBuffer); if (buffer->GetType() == Buffer::Type::Vertex) { bufferViews.vertex.BufferLocation = *buffer; bufferViews.vertex.SizeInBytes = buffer->Size(); } else if (buffer->GetType() == Buffer::Type::Index) { bufferViews.index.BufferLocation = *buffer; bufferViews.index.SizeInBytes = buffer->Size(); } } void Pipeline::Set(const InputElementDescription &description) { Super::Set(description); THROWIF(!state, SError::NullPointerReference); auto &inputElementDesc = state->InputElementDescription; inputElementDesc.resize(desc.layout.Size()); for (size_t i = 0; i < desc.layout.Size(); i++) { inputElementDesc[i].SemanticName = desc.layout[i].Name().c_str(); inputElementDesc[i].SemanticIndex = 0; inputElementDesc[i].Format = desc.layout[i].BaseType<DXGI_FORMAT>(); inputElementDesc[i].InputSlot = 0; inputElementDesc[i].AlignedByteOffset = desc.layout[i].Offset(); inputElementDesc[i].InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; inputElementDesc[i].InstanceDataStepRate = 0; } bufferViews.vertex.StrideInBytes = desc.layout.Stride(); } void Pipeline::Create(const std::shared_ptr<RenderTarget::Super> &renderTarget) { Reconstruct(renderTarget); } void Pipeline::Reconstruct(const std::shared_ptr<RenderTarget::Super> &superRenderTarget) { auto shader = std::dynamic_pointer_cast<Shader>(desc.shader); auto &bytesCodes = shader->ByteCodes(); auto &descriptorRanges = shader->DescriptorRanges(); std::vector<D3D12_STATIC_SAMPLER_DESC> samplers; std::vector<RootParameter> rootParameters{}; for (size_t i = 0; i < descriptorRanges.size(); i++) { auto &range = descriptorRanges[i].first; if (range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV) { if (samplers.empty()) { D3D12_STATIC_SAMPLER_DESC sampler = {}; sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER; sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER; sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER; sampler.MipLODBias = 0; sampler.MaxAnisotropy = 0; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; sampler.MinLOD = 0.0f; sampler.MaxLOD = D3D12_FLOAT32_MAX; sampler.ShaderRegister = i; sampler.RegisterSpace = 0; sampler.ShaderVisibility = descriptorRanges[i].second; samplers.emplace_back(std::move(sampler)); } } RootParameter rootParameter; rootParameter.InitAsDescriptorTable(1, &range, descriptorRanges[i].second); rootParameters.emplace_back(std::move(rootParameter)); } RootSignature::Description rootSignatureDesc{ U32(rootParameters.size()), rootParameters.data(), U32(samplers.size()), samplers.data(), RootSignature::Flag::AllowInputAssemblerInputLayout }; ComPtr<ID3DBlob> signature; ComPtr<ID3DBlob> error; if (FAILED(D3D12SerializeVersionedRootSignature(&rootSignatureDesc, &signature, &error)) && error) { const char *msg = rcast<const char *>(error->GetBufferPointer()); LOG::ERR("{0}", msg); THROWIF(true, msg); } device->Create(0, signature.Get(), &rootSignature); D3D12_INPUT_LAYOUT_DESC inputLayoutDesc = { state->InputElementDescription.data(), U32(state->InputElementDescription.size()) }; D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineStateDesc{}; CleanUpObject(&pipelineStateDesc); pipelineStateDesc.InputLayout = inputLayoutDesc; pipelineStateDesc.pRootSignature = rootSignature; pipelineStateDesc.VS = bytesCodes[Shader::VertexShaderPos]; pipelineStateDesc.PS = bytesCodes[Shader::PixelShaderPos ]; pipelineStateDesc.RasterizerState = RasterizerDescription{}; pipelineStateDesc.BlendState = BlendDescription{}; pipelineStateDesc.DepthStencilState.DepthEnable = FALSE; pipelineStateDesc.DepthStencilState.StencilEnable = FALSE; pipelineStateDesc.SampleMask = UINT_MAX; pipelineStateDesc.PrimitiveTopologyType = SuperToBase(desc.PrimitiveType); pipelineStateDesc.NumRenderTargets = 1; pipelineStateDesc.SampleDesc.Count = 1; auto renderTarget = std::dynamic_pointer_cast<RenderTarget>(superRenderTarget); auto &colorBuffers = renderTarget->GetColorBuffers(); THROWIF(colorBuffers.size() > SL_ARRAY_LENGTH(pipelineStateDesc.RTVFormats), SError::OutOfBound); pipelineStateDesc.NumRenderTargets = colorBuffers.size(); for (int i = 0; i < pipelineStateDesc.NumRenderTargets; i++) { pipelineStateDesc.RTVFormats[i] = colorBuffers[i].Format; } auto &depthBuffer = renderTarget->GetDepthBuffer(); pipelineStateDesc.DSVFormat = depthBuffer.Format; device->Create(&pipelineStateDesc, &pipelineState); } void Pipeline::Bind(const std::string &name, const Buffer::Super *superConstantBuffer) { auto constantBuffer = RemoveConst(dcast<const Buffer *>(superConstantBuffer)); auto cbvDescriptor = descriptorAllocator.Bind(device, constantBuffer->Binding()); device->CreateView(&constantBuffer->Desc(), cbvDescriptor.cpu); } } }
37.252874
104
0.657667
[ "vector" ]
49c9bacff72cf28b9d4e66d0ff17267f9ca18862
32,810
cpp
C++
src/providers/wfs/qgswfscapabilities.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/providers/wfs/qgswfscapabilities.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/providers/wfs/qgswfscapabilities.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgswfscapabilities.cpp --------------------- begin : October 2011 copyright : (C) 2011 by Martin Dobias (C) 2016 by Even Rouault email : wonder dot sk at gmail dot com even.rouault at spatialys.com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgswfscapabilities.h" #include "qgswfsconstants.h" #include "qgswfsutils.h" #include "qgslogger.h" #include "qgsmessagelog.h" #include "qgsogcutils.h" #include "qgssettings.h" #include <cpl_minixml.h> #include <QDomDocument> #include <QStringList> QgsWfsCapabilities::QgsWfsCapabilities( const QString &uri, const QgsDataProvider::ProviderOptions &options ) : QgsWfsRequest( QgsWFSDataSourceURI( uri ) ), mOptions( options ) { // Using Qt::DirectConnection since the download might be running on a different thread. // In this case, the request was sent from the main thread and is executed with the main // thread being blocked in future.waitForFinished() so we can run code on this object which // lives in the main thread without risking havoc. connect( this, &QgsWfsRequest::downloadFinished, this, &QgsWfsCapabilities::capabilitiesReplyFinished, Qt::DirectConnection ); } bool QgsWfsCapabilities::requestCapabilities( bool synchronous, bool forceRefresh ) { QUrl url( mUri.baseURL( ) ); url.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "GetCapabilities" ) ); const QString &version = mUri.version(); if ( version == QgsWFSConstants::VERSION_AUTO ) // MapServer honours the order with the first value being the preferred one url.addQueryItem( QStringLiteral( "ACCEPTVERSIONS" ), QStringLiteral( "2.0.0,1.1.0,1.0.0" ) ); else url.addQueryItem( QStringLiteral( "VERSION" ), version ); if ( !sendGET( url, synchronous, forceRefresh ) ) { emit gotCapabilities(); return false; } return true; } QgsWfsCapabilities::Capabilities::Capabilities() { clear(); } void QgsWfsCapabilities::Capabilities::clear() { maxFeatures = 0; supportsHits = false; supportsPaging = false; supportsJoins = false; version.clear(); featureTypes.clear(); spatialPredicatesList.clear(); functionList.clear(); setAllTypenames.clear(); mapUnprefixedTypenameToPrefixedTypename.clear(); setAmbiguousUnprefixedTypename.clear(); useEPSGColumnFormat = false; } QString QgsWfsCapabilities::Capabilities::addPrefixIfNeeded( const QString &name ) const { if ( name.contains( ':' ) ) return name; if ( setAmbiguousUnprefixedTypename.contains( name ) ) return QString(); return mapUnprefixedTypenameToPrefixedTypename[name]; } class CPLXMLTreeUniquePointer { public: //! Constructor explicit CPLXMLTreeUniquePointer( CPLXMLNode *data ) { the_data_ = data; } //! Destructor ~CPLXMLTreeUniquePointer() { if ( the_data_ ) CPLDestroyXMLNode( the_data_ ); } /** * Returns the node pointer/ * Modifying the contents pointed to by the return is allowed. * \return the node pointer */ CPLXMLNode *get() const { return the_data_; } /** * Returns the node pointer/ * Modifying the contents pointed to by the return is allowed. * \return the node pointer */ CPLXMLNode *operator->() const { return get(); } private: CPLXMLNode *the_data_; }; void QgsWfsCapabilities::capabilitiesReplyFinished() { const QByteArray &buffer = mResponse; QgsDebugMsgLevel( QStringLiteral( "parsing capabilities: " ) + buffer, 4 ); // parse XML QString capabilitiesDocError; QDomDocument capabilitiesDocument; if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) ) { mErrorCode = QgsWfsRequest::XmlError; mErrorMessage = capabilitiesDocError; emit gotCapabilities(); return; } CPLXMLTreeUniquePointer oCPLXML( CPLParseXMLString( buffer.constData() ) ); QDomElement doc = capabilitiesDocument.documentElement(); // handle exceptions if ( doc.tagName() == QLatin1String( "ExceptionReport" ) ) { QDomNode ex = doc.firstChild(); QString exc = ex.toElement().attribute( QStringLiteral( "exceptionCode" ), QStringLiteral( "Exception" ) ); QDomElement ext = ex.firstChild().toElement(); mErrorCode = QgsWfsRequest::ServerExceptionError; mErrorMessage = exc + ": " + ext.firstChild().nodeValue(); emit gotCapabilities(); return; } mCaps.clear(); //test wfs version mCaps.version = doc.attribute( QStringLiteral( "version" ) ); if ( !mCaps.version.startsWith( QLatin1String( "1.0" ) ) && !mCaps.version.startsWith( QLatin1String( "1.1" ) ) && !mCaps.version.startsWith( QLatin1String( "2.0" ) ) ) { mErrorCode = WFSVersionNotSupported; mErrorMessage = tr( "WFS version %1 not supported" ).arg( mCaps.version ); emit gotCapabilities(); return; } // WFS 2.0 implementation are supposed to implement resultType=hits, and some // implementations (GeoServer) might advertize it, whereas others (MapServer) do not. // WFS 1.1 implementation too I think, but in the examples of the GetCapabilities // response of the WFS 1.1 standard (and in common implementations), this is // explicitly advertized if ( mCaps.version.startsWith( QLatin1String( "2.0" ) ) ) mCaps.supportsHits = true; // Note: for conveniency, we do not use the elementsByTagNameNS() method as // the WFS and OWS namespaces URI are not the same in all versions if ( mCaps.version.startsWith( QLatin1String( "1.0" ) ) ) { QDomElement capabilityElem = doc.firstChildElement( QStringLiteral( "Capability" ) ); if ( !capabilityElem.isNull() ) { QDomElement requestElem = capabilityElem.firstChildElement( QStringLiteral( "Request" ) ); if ( !requestElem.isNull() ) { QDomElement getFeatureElem = requestElem.firstChildElement( QStringLiteral( "GetFeature" ) ); if ( !getFeatureElem.isNull() ) { QDomElement resultFormatElem = getFeatureElem.firstChildElement( QStringLiteral( "ResultFormat" ) ); if ( !resultFormatElem.isNull() ) { QDomElement child = resultFormatElem.firstChildElement(); while ( !child.isNull() ) { mCaps.outputFormats << child.tagName(); child = child.nextSiblingElement(); } } } } } } // find <ows:OperationsMetadata> QDomElement operationsMetadataElem = doc.firstChildElement( QStringLiteral( "OperationsMetadata" ) ); if ( !operationsMetadataElem.isNull() ) { QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Constraint" ) ); for ( int i = 0; i < contraintList.size(); ++i ) { QDomElement contraint = contraintList.at( i ).toElement(); if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "DefaultMaxFeatures" ) /* WFS 1.1 */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "Value" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QStringLiteral( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } } else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) /* WFS 2.0 (e.g. MapServer) */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QStringLiteral( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } } else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsResultPaging" ) /* WFS 2.0 */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) ) { mCaps.supportsPaging = true; QgsDebugMsg( QStringLiteral( "Supports paging" ) ); } } else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsStandardJoins" ) || contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsSpatialJoins" ) /* WFS 2.0 */ ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) ) { mCaps.supportsJoins = true; QgsDebugMsg( QStringLiteral( "Supports joins" ) ); } } } // In WFS 2.0, max features can also be set in Operation.GetFeature (e.g. GeoServer) // and we are also interested by resultType=hits for WFS 1.1 QDomNodeList operationList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Operation" ) ); for ( int i = 0; i < operationList.size(); ++i ) { QDomElement operation = operationList.at( i ).toElement(); QString name = operation.attribute( QStringLiteral( "name" ) ); // Search for DCP/HTTP QDomNodeList operationHttpList = operation.elementsByTagName( QStringLiteral( "HTTP" ) ); for ( int j = 0; j < operationHttpList.size(); ++j ) { QDomElement value = operationHttpList.at( j ).toElement(); QDomNodeList httpGetMethodList = value.elementsByTagName( QStringLiteral( "Get" ) ); QDomNodeList httpPostMethodList = value.elementsByTagName( QStringLiteral( "Post" ) ); if ( httpGetMethodList.size() > 0 ) { mCaps.operationGetEndpoints[name] = httpGetMethodList.at( 0 ).toElement().attribute( QStringLiteral( "href" ) ); QgsDebugMsgLevel( QStringLiteral( "Adding DCP Get %1 %2" ).arg( name, mCaps.operationGetEndpoints[name] ), 3 ); } if ( httpPostMethodList.size() > 0 ) { mCaps.operationPostEndpoints[name] = httpPostMethodList.at( 0 ).toElement().attribute( QStringLiteral( "href" ) ); QgsDebugMsgLevel( QStringLiteral( "Adding DCP Post %1 %2" ).arg( name, mCaps.operationPostEndpoints[name] ), 3 ); } } if ( name == QLatin1String( "GetFeature" ) ) { QDomNodeList operationContraintList = operation.elementsByTagName( QStringLiteral( "Constraint" ) ); for ( int j = 0; j < operationContraintList.size(); ++j ) { QDomElement contraint = operationContraintList.at( j ).toElement(); if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) ) { QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QStringLiteral( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } break; } } QDomNodeList parameterList = operation.elementsByTagName( QStringLiteral( "Parameter" ) ); for ( int j = 0; j < parameterList.size(); ++j ) { QDomElement parameter = parameterList.at( j ).toElement(); if ( parameter.attribute( QStringLiteral( "name" ) ) == QLatin1String( "resultType" ) ) { QDomNodeList valueList = parameter.elementsByTagName( QStringLiteral( "Value" ) ); for ( int k = 0; k < valueList.size(); ++k ) { QDomElement value = valueList.at( k ).toElement(); if ( value.text() == QLatin1String( "hits" ) ) { mCaps.supportsHits = true; QgsDebugMsg( QStringLiteral( "Support hits" ) ); break; } } } else if ( parameter.attribute( QStringLiteral( "name" ) ) == QLatin1String( "outputFormat" ) ) { QDomNodeList valueList = parameter.elementsByTagName( QStringLiteral( "Value" ) ); for ( int k = 0; k < valueList.size(); ++k ) { QDomElement value = valueList.at( k ).toElement(); mCaps.outputFormats << value.text(); } } } break; } } } //go to <FeatureTypeList> QDomElement featureTypeListElem = doc.firstChildElement( QStringLiteral( "FeatureTypeList" ) ); if ( featureTypeListElem.isNull() ) { emit gotCapabilities(); return; } // Parse operations supported for all feature types bool insertCap = false; bool updateCap = false; bool deleteCap = false; // WFS < 2 if ( mCaps.version.startsWith( QLatin1String( "1" ) ) ) { parseSupportedOperations( featureTypeListElem.firstChildElement( QStringLiteral( "Operations" ) ), insertCap, updateCap, deleteCap ); } else // WFS 2.0.0 tested on GeoServer { QDomNodeList operationNodes = doc.elementsByTagName( QStringLiteral( "Operation" ) ); for ( int i = 0; i < operationNodes.count(); i++ ) { QDomElement operationElement = operationNodes.at( i ).toElement(); if ( operationElement.isElement() && "Transaction" == operationElement.attribute( QStringLiteral( "name" ) ) ) { insertCap = true; updateCap = true; deleteCap = true; } } } // This is messy, but there's apparently no way to get the xmlns:ci attribute value with QDom API // in snippets like // <wfs:FeatureType xmlns:ci="http://www.interactive-instruments.de/namespaces/demo/cities/4.0/cities"> // <wfs:Name>ci:City</wfs:Name> // so fallback to using GDAL XML parser for that... CPLXMLNode *psFeatureTypeIter = nullptr; if ( oCPLXML.get() ) { psFeatureTypeIter = CPLGetXMLNode( oCPLXML.get(), "=wfs:WFS_Capabilities.wfs:FeatureTypeList" ); if ( psFeatureTypeIter ) psFeatureTypeIter = psFeatureTypeIter->psChild; } // get the <FeatureType> elements QDomNodeList featureTypeList = featureTypeListElem.elementsByTagName( QStringLiteral( "FeatureType" ) ); for ( int i = 0; i < featureTypeList.size(); ++i ) { FeatureType featureType; QDomElement featureTypeElem = featureTypeList.at( i ).toElement(); for ( ; psFeatureTypeIter; psFeatureTypeIter = psFeatureTypeIter->psNext ) { if ( psFeatureTypeIter->eType != CXT_Element ) continue; break; } //Name QDomNodeList nameList = featureTypeElem.elementsByTagName( QStringLiteral( "Name" ) ); if ( nameList.length() > 0 ) { featureType.name = nameList.at( 0 ).toElement().text(); QgsDebugMsgLevel( QStringLiteral( "featureType.name = %1" ) . arg( featureType.name ), 4 ); if ( featureType.name.contains( ':' ) ) { QString prefixOfTypename = featureType.name.section( ':', 0, 0 ); // for some Deegree servers that requires a NAMESPACES parameter for GetFeature if ( psFeatureTypeIter ) { featureType.nameSpace = CPLGetXMLValue( psFeatureTypeIter, ( "xmlns:" + prefixOfTypename ).toUtf8().constData(), "" ); } } } if ( psFeatureTypeIter ) psFeatureTypeIter = psFeatureTypeIter->psNext; //Title QDomNodeList titleList = featureTypeElem.elementsByTagName( QStringLiteral( "Title" ) ); if ( titleList.length() > 0 ) { featureType.title = titleList.at( 0 ).toElement().text(); } //Abstract QDomNodeList abstractList = featureTypeElem.elementsByTagName( QStringLiteral( "Abstract" ) ); if ( abstractList.length() > 0 ) { featureType.abstract = abstractList.at( 0 ).toElement().text(); } //DefaultSRS is always the first entry in the feature srs list QDomNodeList defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultSRS" ) ); if ( defaultCRSList.length() == 0 ) // In WFS 2.0, this is spelled DefaultCRS... defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultCRS" ) ); if ( defaultCRSList.length() > 0 ) { QString srsname( defaultCRSList.at( 0 ).toElement().text() ); // Some servers like Geomedia advertize EPSG:XXXX even in WFS 1.1 or 2.0 if ( srsname.startsWith( QLatin1String( "EPSG:" ) ) ) mCaps.useEPSGColumnFormat = true; featureType.crslist.append( NormalizeSRSName( srsname ) ); } //OtherSRS QDomNodeList otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherSRS" ) ); if ( otherCRSList.length() == 0 ) // In WFS 2.0, this is spelled OtherCRS... otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherCRS" ) ); for ( int i = 0; i < otherCRSList.size(); ++i ) { featureType.crslist.append( NormalizeSRSName( otherCRSList.at( i ).toElement().text() ) ); } //Support <SRS> for compatibility with older versions QDomNodeList srsList = featureTypeElem.elementsByTagName( QStringLiteral( "SRS" ) ); for ( int i = 0; i < srsList.size(); ++i ) { featureType.crslist.append( NormalizeSRSName( srsList.at( i ).toElement().text() ) ); } // Get BBox WFS 1.0 way QDomElement latLongBB = featureTypeElem.firstChildElement( QStringLiteral( "LatLongBoundingBox" ) ); if ( latLongBB.hasAttributes() ) { // Despite the name LatLongBoundingBox, the coordinates are supposed to // be expressed in <SRS>. From the WFS schema; // <!-- The LatLongBoundingBox element is used to indicate the edges of // an enclosing rectangle in the SRS of the associated feature type. featureType.bbox = QgsRectangle( latLongBB.attribute( QStringLiteral( "minx" ) ).toDouble(), latLongBB.attribute( QStringLiteral( "miny" ) ).toDouble(), latLongBB.attribute( QStringLiteral( "maxx" ) ).toDouble(), latLongBB.attribute( QStringLiteral( "maxy" ) ).toDouble() ); featureType.bboxSRSIsWGS84 = false; // But some servers do not honour this and systematically reproject to WGS84 // such as GeoServer. See http://osgeo-org.1560.x6.nabble.com/WFS-LatLongBoundingBox-td3813810.html // This is also true of TinyOWS if ( !featureType.crslist.isEmpty() && featureType.bbox.xMinimum() >= -180 && featureType.bbox.yMinimum() >= -90 && featureType.bbox.xMaximum() <= 180 && featureType.bbox.yMaximum() < 90 ) { QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( featureType.crslist[0] ); if ( !crs.isGeographic() ) { // If the CRS is projected then check that projecting the corner of the bbox, assumed to be in WGS84, // into the CRS, and then back to WGS84, works (check that we are in the validity area) QgsCoordinateReferenceSystem crsWGS84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "CRS:84" ) ); QgsCoordinateTransform ct( crsWGS84, crs, mOptions.transformContext ); QgsPointXY ptMin( featureType.bbox.xMinimum(), featureType.bbox.yMinimum() ); QgsPointXY ptMinBack( ct.transform( ct.transform( ptMin, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) ); QgsPointXY ptMax( featureType.bbox.xMaximum(), featureType.bbox.yMaximum() ); QgsPointXY ptMaxBack( ct.transform( ct.transform( ptMax, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) ); QgsDebugMsg( featureType.bbox.toString() ); QgsDebugMsg( ptMinBack.toString() ); QgsDebugMsg( ptMaxBack.toString() ); if ( std::fabs( featureType.bbox.xMinimum() - ptMinBack.x() ) < 1e-5 && std::fabs( featureType.bbox.yMinimum() - ptMinBack.y() ) < 1e-5 && std::fabs( featureType.bbox.xMaximum() - ptMaxBack.x() ) < 1e-5 && std::fabs( featureType.bbox.yMaximum() - ptMaxBack.y() ) < 1e-5 ) { QgsDebugMsg( QStringLiteral( "Values of LatLongBoundingBox are consistent with WGS84 long/lat bounds, so as the CRS is projected, assume they are indeed in WGS84 and not in the CRS units" ) ); featureType.bboxSRSIsWGS84 = true; } } } } else { // WFS 1.1 way QDomElement WGS84BoundingBox = featureTypeElem.firstChildElement( QStringLiteral( "WGS84BoundingBox" ) ); if ( !WGS84BoundingBox.isNull() ) { QDomElement lowerCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "LowerCorner" ) ); QDomElement upperCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "UpperCorner" ) ); if ( !lowerCorner.isNull() && !upperCorner.isNull() ) { QStringList lowerCornerList = lowerCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts ); QStringList upperCornerList = upperCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts ); if ( lowerCornerList.size() == 2 && upperCornerList.size() == 2 ) { featureType.bbox = QgsRectangle( lowerCornerList[0].toDouble(), lowerCornerList[1].toDouble(), upperCornerList[0].toDouble(), upperCornerList[1].toDouble() ); featureType.bboxSRSIsWGS84 = true; } } } } // Parse Operations specific to the type name parseSupportedOperations( featureTypeElem.firstChildElement( QStringLiteral( "Operations" ) ), featureType.insertCap, featureType.updateCap, featureType.deleteCap ); featureType.insertCap |= insertCap; featureType.updateCap |= updateCap; featureType.deleteCap |= deleteCap; mCaps.featureTypes.push_back( featureType ); } Q_FOREACH ( const FeatureType &f, mCaps.featureTypes ) { mCaps.setAllTypenames.insert( f.name ); QString unprefixed( QgsWFSUtils::removeNamespacePrefix( f.name ) ); if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixed ) ) { if ( mCaps.mapUnprefixedTypenameToPrefixedTypename.contains( unprefixed ) ) { mCaps.setAmbiguousUnprefixedTypename.insert( unprefixed ); mCaps.mapUnprefixedTypenameToPrefixedTypename.remove( unprefixed ); } else { mCaps.mapUnprefixedTypenameToPrefixedTypename[unprefixed] = f.name; } } } //go to <Filter_Capabilities> QDomElement filterCapabilitiesElem = doc.firstChildElement( QStringLiteral( "Filter_Capabilities" ) ); if ( !filterCapabilitiesElem.isNull() ) parseFilterCapabilities( filterCapabilitiesElem ); // Hard-coded functions Function f_ST_GeometryFromText( QStringLiteral( "ST_GeometryFromText" ), 1, 2 ); f_ST_GeometryFromText.returnType = QStringLiteral( "gml:AbstractGeometryType" ); f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "wkt" ), QStringLiteral( "xs:string" ) ); f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_GeometryFromText; Function f_ST_GeomFromGML( QStringLiteral( "ST_GeomFromGML" ), 1 ); f_ST_GeomFromGML.returnType = QStringLiteral( "gml:AbstractGeometryType" ); f_ST_GeomFromGML.argumentList << Argument( QStringLiteral( "gml" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_GeomFromGML; Function f_ST_MakeEnvelope( QStringLiteral( "ST_MakeEnvelope" ), 4, 5 ); f_ST_MakeEnvelope.returnType = QStringLiteral( "gml:AbstractGeometryType" ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "minx" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "miny" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxx" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxy" ), QStringLiteral( "xs:double" ) ); f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_MakeEnvelope; emit gotCapabilities(); } QString QgsWfsCapabilities::NormalizeSRSName( QString crsName ) { QRegExp re( "urn:ogc:def:crs:([^:]+).+([^:]+)", Qt::CaseInsensitive ); if ( re.exactMatch( crsName ) ) { return re.cap( 1 ) + ':' + re.cap( 2 ); } // urn:x-ogc:def:crs:EPSG:xxxx as returned by http://maps.warwickshire.gov.uk/gs/ows? in WFS 1.1 QRegExp re2( "urn:x-ogc:def:crs:([^:]+).+([^:]+)", Qt::CaseInsensitive ); if ( re2.exactMatch( crsName ) ) { return re2.cap( 1 ) + ':' + re2.cap( 2 ); } return crsName; } int QgsWfsCapabilities::defaultExpirationInSec() { QgsSettings s; return s.value( QStringLiteral( "qgis/defaultCapabilitiesExpiry" ), "24" ).toInt() * 60 * 60; } void QgsWfsCapabilities::parseSupportedOperations( const QDomElement &operationsElem, bool &insertCap, bool &updateCap, bool &deleteCap ) { insertCap = false; updateCap = false; deleteCap = false; if ( operationsElem.isNull() ) { return; } QDomNodeList childList = operationsElem.childNodes(); for ( int i = 0; i < childList.size(); ++i ) { QDomElement elt = childList.at( i ).toElement(); QString elemName = elt.tagName(); /* WFS 1.0 */ if ( elemName == QLatin1String( "Insert" ) ) { insertCap = true; } else if ( elemName == QLatin1String( "Update" ) ) { updateCap = true; } else if ( elemName == QLatin1String( "Delete" ) ) { deleteCap = true; } /* WFS 1.1 */ else if ( elemName == QLatin1String( "Operation" ) ) { QString elemText = elt.text(); if ( elemText == QLatin1String( "Insert" ) ) { insertCap = true; } else if ( elemText == QLatin1String( "Update" ) ) { updateCap = true; } else if ( elemText == QLatin1String( "Delete" ) ) { deleteCap = true; } } } } static QgsWfsCapabilities::Function getSpatialPredicate( const QString &name ) { QgsWfsCapabilities::Function f; // WFS 1.0 advertize Intersect, but for conveniency we internally convert it to Intersects if ( name == QLatin1String( "Intersect" ) ) f.name = QStringLiteral( "ST_Intersects" ); else f.name = ( name == QLatin1String( "BBOX" ) ) ? QStringLiteral( "BBOX" ) : "ST_" + name; f.returnType = QStringLiteral( "xs:boolean" ); if ( name == QLatin1String( "DWithin" ) || name == QLatin1String( "Beyond" ) ) { f.minArgs = 3; f.maxArgs = 3; f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "distance" ) ); } else { f.minArgs = 2; f.maxArgs = 2; f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); } return f; } void QgsWfsCapabilities::parseFilterCapabilities( const QDomElement &filterCapabilitiesElem ) { // WFS 1.0 QDomElement spatial_Operators = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Spatial_Capabilities" ) ).firstChildElement( QStringLiteral( "Spatial_Operators" ) ); QDomElement spatial_Operator = spatial_Operators.firstChildElement(); while ( !spatial_Operator.isNull() ) { QString name = spatial_Operator.tagName(); if ( !name.isEmpty() ) { mCaps.spatialPredicatesList << getSpatialPredicate( name ); } spatial_Operator = spatial_Operator.nextSiblingElement(); } // WFS 1.1 and 2.0 QDomElement spatialOperators = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Spatial_Capabilities" ) ).firstChildElement( QStringLiteral( "SpatialOperators" ) ); QDomElement spatialOperator = spatialOperators.firstChildElement( QStringLiteral( "SpatialOperator" ) ); while ( !spatialOperator.isNull() ) { QString name = spatialOperator.attribute( QStringLiteral( "name" ) ); if ( !name.isEmpty() ) { mCaps.spatialPredicatesList << getSpatialPredicate( name ); } spatialOperator = spatialOperator.nextSiblingElement( QStringLiteral( "SpatialOperator" ) ); } // WFS 1.0 QDomElement function_Names = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Scalar_Capabilities" ) ) .firstChildElement( QStringLiteral( "Arithmetic_Operators" ) ) .firstChildElement( QStringLiteral( "Functions" ) ) .firstChildElement( QStringLiteral( "Function_Names" ) ); QDomElement function_NameElem = function_Names.firstChildElement( QStringLiteral( "Function_Name" ) ); while ( !function_NameElem.isNull() ) { Function f; f.name = function_NameElem.text(); bool ok; int nArgs = function_NameElem.attribute( QStringLiteral( "nArgs" ) ).toInt( &ok ); if ( ok ) { if ( nArgs >= 0 ) { f.minArgs = nArgs; f.maxArgs = nArgs; } else { f.minArgs = -nArgs; } } mCaps.functionList << f; function_NameElem = function_NameElem.nextSiblingElement( QStringLiteral( "Function_Name" ) ); } // WFS 1.1 QDomElement functionNames = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Scalar_Capabilities" ) ) .firstChildElement( QStringLiteral( "ArithmeticOperators" ) ) .firstChildElement( QStringLiteral( "Functions" ) ) .firstChildElement( QStringLiteral( "FunctionNames" ) ); QDomElement functionNameElem = functionNames.firstChildElement( QStringLiteral( "FunctionName" ) ); while ( !functionNameElem.isNull() ) { Function f; f.name = functionNameElem.text(); bool ok; int nArgs = functionNameElem.attribute( QStringLiteral( "nArgs" ) ).toInt( &ok ); if ( ok ) { if ( nArgs >= 0 ) { f.minArgs = nArgs; f.maxArgs = nArgs; } else { f.minArgs = -nArgs; } } mCaps.functionList << f; functionNameElem = functionNameElem.nextSiblingElement( QStringLiteral( "FunctionName" ) ); } QDomElement functions = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Functions" ) ); QDomElement functionElem = functions.firstChildElement( QStringLiteral( "Function" ) ); while ( !functionElem.isNull() ) { QString name = functionElem.attribute( QStringLiteral( "name" ) ); if ( !name.isEmpty() ) { Function f; f.name = name; QDomElement returnsElem = functionElem.firstChildElement( QStringLiteral( "Returns" ) ); f.returnType = returnsElem.text(); QDomElement argumentsElem = functionElem.firstChildElement( QStringLiteral( "Arguments" ) ); QDomElement argumentElem = argumentsElem.firstChildElement( QStringLiteral( "Argument" ) ); while ( !argumentElem.isNull() ) { Argument arg; arg.name = argumentElem.attribute( QStringLiteral( "name" ) ); arg.type = argumentElem.firstChildElement( QStringLiteral( "Type" ) ).text(); f.argumentList << arg; argumentElem = argumentElem.nextSiblingElement( QStringLiteral( "Argument" ) ); } f.minArgs = f.argumentList.count(); f.maxArgs = f.argumentList.count(); mCaps.functionList << f; } functionElem = functionElem.nextSiblingElement( QStringLiteral( "Function" ) ); } } QString QgsWfsCapabilities::errorMessageWithReason( const QString &reason ) { return tr( "Download of capabilities failed: %1" ).arg( reason ); }
40.406404
204
0.640079
[ "geometry", "object", "transform" ]
49cfcbc323334b8d4e4a0daef476c146a9306763
2,065
cpp
C++
OGMM/gui/panels/ModInfoPanel.cpp
Moneyl/OGMM
52a4bcc051fab160c55f0cc7228bd99de3ff5c47
[ "MIT" ]
null
null
null
OGMM/gui/panels/ModInfoPanel.cpp
Moneyl/OGMM
52a4bcc051fab160c55f0cc7228bd99de3ff5c47
[ "MIT" ]
null
null
null
OGMM/gui/panels/ModInfoPanel.cpp
Moneyl/OGMM
52a4bcc051fab160c55f0cc7228bd99de3ff5c47
[ "MIT" ]
null
null
null
#include "ModInfoPanel.h" #include "render/imgui/imgui_ext.h" #include "render/imgui/ImGuiFontManager.h" #include "application/mods/Mod.h" #include "application/mods/ModManager.h" void ModInfoPanel::Update(GuiState* state, bool* open) { if (!ImGui::Begin("Mod info", open)) { ImGui::End(); return; } state->FontManager->FontL.Push(); ImGui::Text(ICON_FA_INFO_CIRCLE " Info"); state->FontManager->FontL.Pop(); ImGui::Separator(); Mod* mod = state->SelectedMod; if (!mod) { ImGui::TextWrapped("%s Click a mod to see its info here.", ICON_FA_EXCLAMATION_CIRCLE); ImGui::End(); return; } //General info gui::LabelAndValue("Name:", mod->Name); gui::LabelAndValue("Author:", mod->Author); gui::LabelAndValue("Description:", mod->Description, true); const f32 indent = 8.0f; ImGui::Unindent(indent); ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 0.9f); if (ImGui::TreeNode("Changes")) { for (auto& change : mod->Changes) for (auto& changeStr : change->GetChangeList()) ImGui::BulletText(changeStr.c_str()); ImGui::TreePop(); } ImGui::PopStyleVar(); ImGui::Indent(indent); if (mod->Input.size() > 0) { ImGui::Separator(); state->FontManager->FontL.Push(); ImGui::Text(ICON_FA_COG " Config"); state->FontManager->FontL.Pop(); ImGui::Separator(); //User input for (auto& input : mod->Input) { const char* selectedOptionValue = input.Options[input.SelectedIndex].Name.c_str(); if (ImGui::BeginCombo(input.DisplayName.c_str(), selectedOptionValue)) { for (u32 i = 0; i < input.Options.size(); i++) { if (ImGui::Selectable(input.Options[i].Name.c_str())) input.SelectedIndex = i; } ImGui::EndCombo(); } } } ImGui::End(); }
28.287671
95
0.566102
[ "render" ]
49d28f3f2508823bde0f90450c740e84359939be
2,798
cpp
C++
structure/segment-tree/segment-tree.cpp
fairy-lettuce/library
0c2cf9ba668f33db7586d5e0ea3818fe49920249
[ "Unlicense" ]
127
2019-07-22T03:52:01.000Z
2022-03-11T07:20:21.000Z
structure/segment-tree/segment-tree.cpp
fairy-lettuce/library
0c2cf9ba668f33db7586d5e0ea3818fe49920249
[ "Unlicense" ]
39
2019-09-16T12:04:53.000Z
2022-03-29T15:43:35.000Z
structure/segment-tree/segment-tree.cpp
fairy-lettuce/library
0c2cf9ba668f33db7586d5e0ea3818fe49920249
[ "Unlicense" ]
29
2019-08-10T11:27:06.000Z
2022-03-11T07:02:43.000Z
/** * @brief Segment Tree(セグメント木) * @docs docs/segment-tree.md */ template< typename Monoid, typename F > struct SegmentTree { int n, sz; vector< Monoid > seg; const F f; const Monoid M1; SegmentTree() = default; explicit SegmentTree(int n, const F f, const Monoid &M1) : n(n), f(f), M1(M1) { sz = 1; while(sz < n) sz <<= 1; seg.assign(2 * sz, M1); } explicit SegmentTree(const vector< Monoid > &v, const F f, const Monoid &M1) : SegmentTree((int) v.size(), f, M1) { build(v); } void build(const vector< Monoid > &v) { assert(n == (int) v.size()); for(int k = 0; k < n; k++) seg[k + sz] = v[k]; for(int k = sz - 1; k > 0; k--) { seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]); } } void set(int k, const Monoid &x) { k += sz; seg[k] = x; while(k >>= 1) { seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]); } } Monoid get(int k) const { return seg[k + sz]; } Monoid operator[](const int &k) const { return get(k); } void apply(int k, const Monoid &x) { k += sz; seg[k] = f(seg[k], x); while(k >>= 1) { seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]); } } Monoid prod(int l, int r) const { Monoid L = M1, R = M1; for(l += sz, r += sz; l < r; l >>= 1, r >>= 1) { if(l & 1) L = f(L, seg[l++]); if(r & 1) R = f(seg[--r], R); } return f(L, R); } Monoid all_prod() const { return seg[1]; } template< typename C > int find_first(int l, const C &check) const { if(l >= n) return n; l += sz; Monoid sum = M1; do { while((l & 1) == 0) l >>= 1; if(check(f(sum, seg[l]))) { while(l < sz) { l <<= 1; auto nxt = f(sum, seg[l]); if(not check(nxt)) { sum = nxt; l++; } } return l + 1 - sz; } sum = f(sum, seg[l++]); } while((l & -l) != l); return n; } template< typename C > int find_last(int r, const C &check) const { if(r <= 0) return -1; r += sz; Monoid sum = 0; do { r--; while(r > 1 and (r & 1)) r >>= 1; if(check(f(seg[r], sum))) { while(r < sz) { r = (r << 1) + 1; auto nxt = f(seg[r], sum); if(not check(nxt)) { sum = nxt; r--; } } return r - sz; } sum = f(seg[r], sum); } while((r & -r) != r); return -1; } }; template< typename Monoid, typename F > SegmentTree< Monoid, F > get_segment_tree(int N, const F &f, const Monoid &M1) { return SegmentTree{N, f, M1}; } template< typename Monoid, typename F > SegmentTree< Monoid, F > get_segment_tree(const vector< Monoid > &v, const F &f, const Monoid &M1) { return SegmentTree{v, f, M1}; }
21.859375
100
0.466047
[ "vector" ]
49db1164dc815f88ad946f0f93044341edb32874
13,876
cxx
C++
Tracing/TraceEdit/VolumeOfInterest.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
1
2016-11-19T03:15:59.000Z
2016-11-19T03:15:59.000Z
Tracing/TraceEdit/VolumeOfInterest.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
Tracing/TraceEdit/VolumeOfInterest.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
#include "VolumeOfInterest.h" VolumeOfInterest::VolumeOfInterest() { this->VOIPolyData.clear();// = std::vector<vtkPolyData*>; this->ROIPoints.clear(); } int VolumeOfInterest::AddVOIPoint(double* newPT) { this->ROIPoints.push_back(newPT); return (int) this->ROIPoints.size(); } bool VolumeOfInterest::ExtrudeVOI() { if (this->ROIPoints.size() < 3) { std::cout<< "not enough points\n"; return false; } //// Add the points to a vtkPoints object vtkSmartPointer<vtkPoints> vtkROIpoints = vtkSmartPointer<vtkPoints>::New(); std::vector<double*>::iterator ROIPoints_iter; int count = 0; for (ROIPoints_iter = this->ROIPoints.begin(); ROIPoints_iter != ROIPoints.end(); ROIPoints_iter++) { vtkROIpoints->InsertNextPoint(*ROIPoints_iter); //this->EditLogDisplay->append((QString("%1\t%2\t%3").arg((*ROIPoints_iter)[0]).arg((*ROIPoints_iter)[1]).arg((*ROIPoints_iter)[2]))); //can do with string stream delete *ROIPoints_iter; *ROIPoints_iter = NULL; count++; //size of polygon vertex } // build a polygon vtkSmartPointer<vtkPolygon> ROI_Poly = vtkSmartPointer<vtkPolygon>::New(); ROI_Poly->GetPointIds()->SetNumberOfIds(count); for (int i =0; i< count; i++) { ROI_Poly->GetPointIds()->SetId(i,i); } //build cell array vtkSmartPointer<vtkCellArray> ROI_Poly_CellArray = vtkSmartPointer<vtkCellArray>::New(); ROI_Poly_CellArray->InsertNextCell(ROI_Poly); // Create a 2d polydata to store outline in vtkSmartPointer<vtkPolyData> ROIpolydata = vtkSmartPointer<vtkPolyData>::New(); ROIpolydata->SetPoints(vtkROIpoints); ROIpolydata->SetPolys(ROI_Poly_CellArray); //extrude the outline vtkSmartPointer<vtkLinearExtrusionFilter> extrude = vtkSmartPointer<vtkLinearExtrusionFilter>::New(); extrude->SetInput( ROIpolydata); extrude->SetExtrusionTypeToNormalExtrusion(); extrude->SetScaleFactor (100); //adjust depending upon size of image stack extrude->Update(); this->VOIPolyData.push_back( extrude->GetOutput()); return true; } vtkSmartPointer<vtkQuadricLODActor> VolumeOfInterest::GetActor() { vtkSmartPointer<vtkPolyDataMapper> VOImapper = vtkSmartPointer<vtkPolyDataMapper>::New(); VOImapper->SetInput(this->VOIPolyData.back()); vtkSmartPointer<vtkQuadricLODActor> VOIactor = vtkSmartPointer<vtkQuadricLODActor>::New(); //VOIactor->GetProperty()->SetRepresentationToSurface(); VOIactor->SetMapper(VOImapper); VOIactor->GetProperty()->SetInterpolationToFlat(); return VOIactor; } void VolumeOfInterest::CalculateCellDistanceToVOI(CellTraceModel *CellModel) { vtkSmartPointer<vtkCellLocator> cellLocator = vtkSmartPointer<vtkCellLocator>::New(); cellLocator->SetDataSet(this->VOIPolyData.back()); cellLocator->BuildLocator(); std::map< int ,CellTrace*>::iterator cellCount = CellModel->GetCelliterator(); for (; cellCount != CellModel->GetCelliteratorEnd(); cellCount++) { //double testPoint[3] = {500, 600, 50}; double somaPoint[3]; CellTrace* currCell = (*cellCount).second; currCell->getSomaCoord(somaPoint); //Find the closest points to TestPoint double closestPoint[3];//the coordinates of the closest point will be returned here double closestPointDist2; //the squared distance to the closest point will be returned here vtkIdType cellId; //the cell id of the cell containing the closest point will be returned here int subId; //this is rarely used (in triangle strips only, I believe) cellLocator->FindClosestPoint(somaPoint, closestPoint, cellId, subId, closestPointDist2); currCell->setDistanceToROI( std::sqrt(closestPointDist2), closestPoint[0], closestPoint[1], closestPoint[2]); }//end for cell count } float* VolumeOfInterest::CalculateCentroidDistanceToVOI(vtkSmartPointer<vtkTable> tbl) { vtkSmartPointer<vtkCellLocator> cellLocator = vtkSmartPointer<vtkCellLocator>::New(); cellLocator->SetDataSet(this->VOIPolyData.back()); cellLocator->BuildLocator(); float* dist_object = new float[(int)tbl->GetNumberOfRows()]; for (int row=0; row < (int)tbl->GetNumberOfRows(); row++) { //double testPoint[3] = {500, 600, 50}; double centroid[3]; centroid[0] = tbl->GetValueByName(row,"centroid_x").ToDouble(); centroid[1] = tbl->GetValueByName(row,"centroid_y").ToDouble(); centroid[2] = tbl->GetValueByName(row,"centroid_z").ToDouble(); //Find the closest points to TestPoint double closestPoint[3];//the coordinates of the closest point will be returned here double closestPointDist2; //the squared distance to the closest point will be returned here vtkIdType cellId; //the cell id of the cell containing the closest point will be returned here int subId; //this is rarely used (in triangle strips only, I believe) cellLocator->FindClosestPoint(centroid, closestPoint, cellId, subId, closestPointDist2); dist_object[row] = sqrt(closestPointDist2); }//end for cell count return dist_object; } void VolumeOfInterest::ReadVesselDistanceMap(std::string fileName) { ReaderType::Pointer vesselMaskReader = ReaderType::New(); vesselMaskReader->SetFileName(fileName.c_str()); try { vesselMaskReader->Update(); } catch( itk::ExceptionObject & exp ) { std::cerr << "Exception thrown while reading the input file " << std::endl; std::cerr << exp << std::endl; //return EXIT_FAILURE; } vesselMaskImage = vesselMaskReader->GetOutput(); this->vesselImageRegion = vesselMaskImage->GetLargestPossibleRegion(); ImageType::SizeType size = this->vesselImageRegion.GetSize(); std::cout << "Vessel image size: " << size << std::endl; } void VolumeOfInterest::ReadImageTypeFloat3D(std::string fileName, FloatImageType::Pointer& data_ptr){ ReaderTypeFloat::Pointer image_reader = ReaderTypeFloat::New(); image_reader->SetFileName(fileName); try{ image_reader->Update(); } catch( itk::ExceptionObject & exp ){ std::cerr << "Exception thrown while reading the input file " << std::endl; std::cerr << exp << std::endl; //return EXIT_FAILURE; } data_ptr = image_reader->GetOutput(); } FloatImageType::Pointer VolumeOfInterest::GetVesselMaskDistanceMap() { typedef itk::BinaryThresholdImageFilter<ImageType, ImageType> ThresholdFilterType; ThresholdFilterType::Pointer threshold_filter = ThresholdFilterType::New(); threshold_filter->SetLowerThreshold(1); threshold_filter->SetInsideValue(255); threshold_filter->SetOutsideValue(0); threshold_filter->SetInput(this->vesselMaskImage); //threshold_filter->Update(); SignedMaurerDistanceMapImageFilterType::Pointer MaurerFilter = SignedMaurerDistanceMapImageFilterType::New(); MaurerFilter->SetInput(threshold_filter->GetOutput()); MaurerFilter->SetSquaredDistance(false); MaurerFilter->SetUseImageSpacing(false); MaurerFilter->SetInsideIsPositive(false); MaurerFilter->Update(); FloatImageType::Pointer distance_Map = MaurerFilter->GetOutput(); return distance_Map; } void VolumeOfInterest::ReadBinaryVOI(std::string filename) { ReaderType::Pointer contourReader = ReaderType::New(); contourReader->SetFileName(filename.c_str()); try { contourReader->Update(); } catch( itk::ExceptionObject & exp ) { std::cerr << "Exception thrown while reading the input file " << std::endl; std::cerr << exp << std::endl; //return EXIT_FAILURE; } ConnectorType::Pointer connector = ConnectorType::New(); connector->SetInput( contourReader->GetOutput() ); vtkSmartPointer<vtkMarchingCubes> ContourFilter = vtkSmartPointer<vtkMarchingCubes>::New(); ContourFilter->ComputeNormalsOff(); ContourFilter->ComputeScalarsOff(); ContourFilter->ComputeGradientsOff(); ContourFilter->SetInput(connector->GetOutput() ); ContourFilter->SetNumberOfContours(1); ContourFilter->SetValue(0,1); vtkSmartPointer<vtkUnsignedCharArray> colorArray = vtkSmartPointer<vtkUnsignedCharArray>::New(); colorArray->SetNumberOfComponents(3); unsigned char color[3] = {255,255,255}; ContourFilter->Update(); for (vtkIdType count = 0; count < ContourFilter->GetOutput()->GetNumberOfCells(); count++) { colorArray->InsertNextTupleValue(color); } ContourFilter->GetOutput()->GetCellData()->SetScalars(colorArray); this->VOIPolyData.push_back( ContourFilter->GetOutput()); } void VolumeOfInterest::ReadVTPVOI(std::string filename) { // Read volume data from VTK's .vtp file vtkSmartPointer<vtkXMLPolyDataReader> reader = vtkSmartPointer<vtkXMLPolyDataReader>::New(); reader->SetFileName(filename.c_str()); reader->Update(); this->VOIPolyData.push_back( reader->GetOutput()); } void VolumeOfInterest::ReadOBJVOI(std::string filename) { // Read volume data from VTK's .vtp file vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader->SetFileName(filename.c_str()); reader->Update(); this->VOIPolyData.push_back( reader->GetOutput()); } void VolumeOfInterest::WriteVTPVOI(std::string filename) { vtkSmartPointer<vtkXMLPolyDataWriter> writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New(); writer->SetFileName(filename.c_str()); writer->SetInput(this->VOIPolyData.back()); writer->Write(); } //Voronoi void VolumeOfInterest::ReadNucleiLabelImage(std::string filename) { //! Read the label image ReaderType::Pointer labelImageReader = ReaderType::New(); labelImageReader->SetFileName(filename.c_str()); try { labelImageReader->Update(); } catch( itk::ExceptionObject & exp ) { std::cerr << "Exception thrown while reading the input file " << std::endl; std::cerr << exp << std::endl; //return EXIT_FAILURE; } nucleiLabelImage = labelImageReader->GetOutput(); } void VolumeOfInterest::CalculateVoronoiLabelImage() { //! Calculates the voronoi and its distance map VoronoiImageFilterType::Pointer voronoiFilter = VoronoiImageFilterType::New(); voronoiFilter->SetInput(nucleiLabelImage); voronoiFilter->Update(); voronoiImage = voronoiFilter->GetVoronoiMap(); voronoiDistMapImage = voronoiFilter->GetDistanceMap(); } void VolumeOfInterest::GetVoronoiBoundingBox() { LabelGeometryImageFilterType::Pointer labelGeometryImageFilter = LabelGeometryImageFilterType::New(); labelGeometryImageFilter->SetInput( voronoiImage ); labelGeometryImageFilter->CalculateOrientedBoundingBoxOn(); labelGeometryImageFilter->Update(); LabelGeometryImageFilterType::LabelsType allLabels = labelGeometryImageFilter->GetLabels(); LabelGeometryImageFilterType::LabelsType::iterator allLabelsIt; std::cout << "Number of labels: " << labelGeometryImageFilter->GetNumberOfLabels() << std::endl; std::cout << std::endl; for( allLabelsIt = allLabels.begin(); allLabelsIt != allLabels.end(); allLabelsIt++ ) { LabelGeometryImageFilterType::LabelPixelType labelValue = *allLabelsIt; std::cout << "\tCentroid: " << labelGeometryImageFilter->GetOrientedBoundingBoxOrigin(labelValue) << std::endl; std::cout << "\tSize: " << labelGeometryImageFilter->GetOrientedBoundingBoxSize(labelValue) << std::endl; std::cout << "\tVertices 1: " << labelGeometryImageFilter->GetOrientedBoundingBoxVertices(labelValue)[0] << std::endl; std::cout << "\tVertices 2: " << labelGeometryImageFilter->GetOrientedBoundingBoxVertices(labelValue)[1] << std::endl; std::cout << "\tVertices 3: " << labelGeometryImageFilter->GetOrientedBoundingBoxVertices(labelValue)[2] << std::endl; std::cout << "\tVertices 4: " << labelGeometryImageFilter->GetOrientedBoundingBoxVertices(labelValue)[3] << std::endl; std::cout << "\tVolume: " << labelGeometryImageFilter->GetOrientedBoundingBoxVolume(labelValue) << std::endl; std::cout << "\tRegion: " << labelGeometryImageFilter->GetOrientedLabelImage(labelValue) << std::endl; //std::cout << "\tVolume: " << labelGeometryImageFilter->GetVolume(labelValue) << std::endl; //std::cout << "\tIntegrated Intensity: " << labelGeometryImageFilter->GetIntegratedIntensity(labelValue) << std::endl; //std::cout << "\tCentroid: " << labelGeometryImageFilter->GetCentroid(labelValue) << std::endl; //std::cout << "\tWeighted Centroid: " << labelGeometryImageFilter->GetWeightedCentroid(labelValue) << std::endl; //std::cout << "\tAxes Length: " << labelGeometryImageFilter->GetAxesLength(labelValue) << std::endl; //std::cout << "\tMajorAxisLength: " << labelGeometryImageFilter->GetMajorAxisLength(labelValue) << std::endl; //std::cout << "\tMinorAxisLength: " << labelGeometryImageFilter->GetMinorAxisLength(labelValue) << std::endl; //std::cout << "\tEccentricity: " << labelGeometryImageFilter->GetEccentricity(labelValue) << std::endl; //std::cout << "\tElongation: " << labelGeometryImageFilter->GetElongation(labelValue) << std::endl; //std::cout << "\tOrientation: " << labelGeometryImageFilter->GetOrientation(labelValue) << std::endl; //std::cout << "\tBounding box: " << labelGeometryImageFilter->GetBoundingBox(labelValue) << std::endl; std::cout << std::endl << std::endl; } } void VolumeOfInterest::WriteVoronoiLabelImage(std::string filename) { //! Writes the voronoi label image and the distance map to file //Voronoi std::string saveVoronoiFile = filename.substr(0, filename.size()-4)+"_voronoi.tif"; WriterType::Pointer voronoiImageWriter = WriterType::New(); voronoiImageWriter->SetFileName(saveVoronoiFile); std::cout << "Set input..." << std::endl; voronoiImageWriter->SetInput( voronoiImage ); std::cout << "Update writer" << std::endl; try { voronoiImageWriter->Update(); } catch (itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; } //Distance Map //tif does not support float values std::string saveVoronoiDistMapFile = filename.substr(0, filename.size()-4)+"_voronoiDistMap.mhd"; FloatWriterType::Pointer voronoiDistMapImageWriter = FloatWriterType::New(); voronoiDistMapImageWriter->SetFileName(saveVoronoiDistMapFile); std::cout << "Set input..." << std::endl; voronoiDistMapImageWriter->SetInput( voronoiDistMapImage ); std::cout << "Update writer" << std::endl; try { voronoiDistMapImageWriter->Update(); } catch (itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; } }
40.104046
136
0.749784
[ "object", "vector" ]
49e1a2de1151276875fce6852a3c79cd85dac3df
6,343
cpp
C++
Tridiagonal_CUDA/third_party/BPLib/BPLib.cpp
NIC0NIC0NI/TridiagonalSolver
9330103243acc4c811249ec4ffdb8df63c003350
[ "MIT" ]
null
null
null
Tridiagonal_CUDA/third_party/BPLib/BPLib.cpp
NIC0NIC0NI/TridiagonalSolver
9330103243acc4c811249ec4ffdb8df63c003350
[ "MIT" ]
null
null
null
Tridiagonal_CUDA/third_party/BPLib/BPLib.cpp
NIC0NIC0NI/TridiagonalSolver
9330103243acc4c811249ec4ffdb8df63c003350
[ "MIT" ]
null
null
null
//- ======================================================================= //+ BPLib v1.0 //+ Butterfly Processing Library //- ----------------------------------------------------------------------- //+ Designed to improve general signal type handling //- ======================================================================= //----- System Include Section ------------------------------------------- #include <cstdio> #include <cstdlib> #include <algorithm> #include <complex> using namespace std; //---- Custom Include Section -------------------------------------------- #include "tools/timer.hxx" #include "tools/cuvector.hxx" #include "tools/cfgmgr.hxx" #include "implicitCfg.hxx" #include "alg/Transform.hxx" //---- Helper functions -------------------------------------------------- #define tError(...) { fprintf(stderr, "%s(%i) : %s > ", __FILE__, __LINE__, __FUNCTION__); \ fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n\n"); exit(-1); } typedef std::complex<float> Complex; enum FFT_DIR { ALG_FWD_E = 3, // Mode forward, for comparing results ALG_FWD = 1, // Mode forward by default, direct transform ALG_DEBUG = 0, // Mode debug, only exchange ALG_INV = -1, // Mode backward by default, inverse transform ALG_INV_E = -3 // Mode backward, for comparing results }; #ifdef _DEBUG const int debug = 1; #else const int debug = 0; #endif //---- Signal Processing Algorithms -------------------------------------- // GPU Algorithms, based on BPLGFFT #include "alg/BPLG/BPLGFourier.hxx" #include "alg/BPLG/BPLGHartley.hxx" #include "alg/BPLG/BPLGCosine.hxx" #include "alg/BPLG/BPLGRealFT.hxx" #include "alg/BPLG/BPLGScanLF.hxx" #include "alg/BPLG/BPLGScanKS.hxx" #include "alg/BPLG/BPLGSort.hxx" #include "alg/BPLG/BPLGTridiagLF.hxx" #include "alg/BPLG/BPLGTridiagCR.hxx" #include "alg/BPLG/BPLGTridiagPCR.hxx" #include "alg/BPLG/BPLGTridiagWM.hxx" Transform* algInstance(int algNum, int dimx, int dimy = 1, int dimz = 1) { switch(algNum) { case 1: return new BPLGFourier (dimx, dimy, dimz); case 2: return new BPLGHartley (dimx, dimy, dimz); case 3: return new BPLGCosine (dimx, dimy, dimz); case 4: return new BPLGRealFT (dimx, dimy, dimz); case 5: return new BPLGScanLF (dimx, dimy, dimz); case 6: return new BPLGScanKS (dimx, dimy, dimz); case 7: return new BPLGSort (dimx, dimy, dimz); case 8: return new BPLGTridiagWM(dimx, dimy, dimz); case 9: return new BPLGTridiagCR(dimx,dimy,dimz); case 10: return new BPLGTridiagPCR(dimx,dimy,dimz); case 11: return new BPLGTridiagLF(dimx, dimy,dimz); default: tError("Invalid algorithm parameter"); break; } return 0; } //---- Main Code --------------------------------------------------------- int main(int argc, char *argv[]) { // Load configuration char defaultCfg[16] = "config.ini"; if(argc == 1) return printf("%s", implicitCfg); ConfigManager config(implicitCfg); // First, configuration by default config.load(argc == 2 ? argv[1] : defaultCfg); // Second, using the file config.setDomain(debug ? "debug" : "release"); config.load(argc, argv); // Finally, argv configuration // Obtaining parameters int fft_xmin = config.getInt("xmin"); // Minimum Size 1D int fft_xmax = config.getInt("xmax"); // Maximum Size 1D int fft_ymin = config.getInt("ymin"); // Minimum Size 2D int fft_ymax = config.getInt("ymax"); // Maximum Size 2D int fft_alg = config.getInt("alg"); // Choosen Algorithm int fft_mem = config.getInt("mem"); // Allocated memory int fft_sec = config.getInt("sec"); // Benchmark time int fft_nxn = config.getInt("nxn"); // Only square problems int verbose = config.getInt("verbose"); // Mode verbose // Parameters checking if(fft_xmax == 1) fft_xmin = 1; if(fft_xmax < fft_xmin) fft_xmax = fft_xmin; if(fft_ymax == 1) fft_ymin = 1; if(fft_ymax < fft_ymin) fft_ymax = fft_ymin; if(fft_xmin < 1) tError("X Dimension must be >= 1"); if(fft_ymin < 1) tError("Y Dimension must be >= 1"); // Blocking rows for Tridiagonal Systems if((fft_alg) > 7) { fft_ymin = fft_ymax = 4; fft_nxn = 0; } // GPU Initialization (by default id = 0) int gpuId = config.getInt("gpuid"); printf("BPLib> Trying to use gpuid=%i\n", gpuId); CUVector<float>::gpuInit(gpuId); // Can the algorithm be instanced? Transform* testAlg = algInstance(fft_alg, 2); printf("BPLib> Algorithm '%s', %s mode\n", testAlg->toString(), debug ? "debug" : "release"); delete testAlg; long long iters = 0; // Number of performed iters. Timer clk; // Timer for measuring // Iterating over vertical sizes, power of two for(int dimY = fft_ymin; dimY <= fft_ymax; dimY *= 2) { if(dimY * fft_xmin > fft_mem) break; if(!fft_nxn) printf("BPLib> Launching N = {%i..%i, %i}:\n", fft_xmin, fft_xmax, dimY); for(int dimX = fft_xmin; dimX <= fft_xmax; dimX *= 2) { const int dimXY = dimX * dimY; if(dimXY == 1) continue; if(dimXY > fft_mem) break; // Out of range const int batchXY = verbose & 0x02 ? 1 : fft_mem / dimXY; Transform *alg = 0, *ref = 0; // Ignoring no-square problems (optionally) if(fft_nxn && fft_ymax > 1 && dimX != dimY) continue; // Create an algorithm with the desired configuration alg = algInstance(fft_alg, dimX, dimY, batchXY)->init(!debug); // Checking if size can be executed by desired algorithm if(!alg->calc(ALG_FWD_E)) goto freeResources; if(fft_alg<=4) { // Executing taking time and iters. for(clk.start(), iters = 0; clk.time() <= fft_sec; iters++) { alg->calc(ALG_FWD); // Forward alg->calc(ALG_INV); // Backward } } else { for(clk.start(), iters = 0; clk.time() <= fft_sec; iters++) { alg->calc(ALG_FWD); // Forward } } alg->compare(NULL); // Showing results printf("BPLib> NxM = (%7i,%4i), b =%8i, it =%5lli", dimX, dimY, batchXY, iters); // Printing performance, FWD+REV => 2*batch if(iters > 0) { double time = clk.time(); double sigTime = time / (2 * iters * batchXY); double gflops = (fft_alg<=4)?alg->gflops(time, 2 * iters) : alg->gflops(time, iters); printf(", t = %.1e, GF =%7.2f", sigTime, gflops); } printf("\n"); freeResources: if(alg) delete alg; if(ref) delete ref; } } cudaDeviceReset(); printf("BPLib> End.\n"); }
31.093137
92
0.609333
[ "transform" ]
49e4d6dc8445826a12323df8062975d09ab38bb8
17,696
cpp
C++
src/comptonscattering.cpp
JPETTomography/j-pet-ortho-simulations
2da46ec994ed9480a9efe5b3cd379eb0a80256d4
[ "Apache-2.0" ]
1
2018-01-26T17:49:34.000Z
2018-01-26T17:49:34.000Z
src/comptonscattering.cpp
JPETTomography/j-pet-ortho-simulations
2da46ec994ed9480a9efe5b3cd379eb0a80256d4
[ "Apache-2.0" ]
2
2017-06-21T08:21:44.000Z
2017-10-24T07:29:47.000Z
src/comptonscattering.cpp
JPETTomography/j-pet-ortho-simulations
2da46ec994ed9480a9efe5b3cd379eb0a80256d4
[ "Apache-2.0" ]
1
2017-05-25T13:27:45.000Z
2017-05-25T13:27:45.000Z
#include "TImage.h" #include "TCanvas.h" #include "TLine.h" #include "comptonscattering.h" unsigned ComptonScattering::objectID_= 1; /// /// \brief ComptonScattering::ComptonScattering The only constructor used. /// \param type Type of the decay, can be: TWO, THREE or TWOandTHREE. /// \param low Lower limit for smearing effect. /// \param high Higher limit for smearing effect. /// ComptonScattering::ComptonScattering(DecayType type, float low, float high) : fSilentMode_(false), fDecayType_(type), fSmearLowLimit_(low), fSmearHighLimit_(high) { if(fDecayType_==THREE) { fTypeString_ = "3"; fH_photon_E_depos_ = new TH1F((std::string("fH_photon_E_depos_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_photon_E_depos_", 52, 0.0, 0.600); fH_electron_E_ = new TH1F((std::string("fH_electron_E_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_", 52, 0.0, 0.511); fH_electron_E_blur_ = new TH1F((std::string("fH_electron_E_blur_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_blur_", 52, 0.0, 0.511); } else if(fDecayType_==TWO) { fTypeString_ = "2"; fH_photon_E_depos_ = new TH1F((std::string("fH_photon_E_depos_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_photon_E_depos_", 21, 0.510, 0.512); fH_photon_E_depos_->GetXaxis()->SetNdivisions(7, false); fH_electron_E_ = new TH1F((std::string("fH_electron_E_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_", 52, 0.0, 0.511); fH_electron_E_blur_ = new TH1F((std::string("fH_electron_E_blur_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_blur_", 52, 0.0, 0.511); } else if(fDecayType_==TWOandONE) { fTypeString_ = "2&1"; fH_photon_E_depos_ = new TH1F((std::string("fH_photon_E_depos_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_photon_E_depos_", 52, 0.3, 1.3); fH_electron_E_ = new TH1F((std::string("fH_electron_E_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_", 52, 0.0, 1.3); fH_electron_E_blur_ = new TH1F((std::string("fH_electron_E_blur_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_blur_", 52, 0.0, 1.3); } else if(fDecayType_==TWOandN) { fTypeString_ = "2&N"; fH_photon_E_depos_ = new TH1F((std::string("fH_photon_E_depos_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_photon_E_depos_", 104, 0.0, 4.0); fH_electron_E_ = new TH1F((std::string("fH_electron_E_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_", 104, 0.0, 4.0); fH_electron_E_blur_ = new TH1F((std::string("fH_electron_E_blur_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_blur_", 104, 0.0, 4.0); } else if(fDecayType_==ONE) { fTypeString_ = "1"; fH_photon_E_depos_ = new TH1F((std::string("fH_photon_E_depos_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_photon_E_depos_", 52, 0.0, 2.0); fH_electron_E_ = new TH1F((std::string("fH_electron_E_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_", 52, 0.0, 2.0); fH_electron_E_blur_ = new TH1F((std::string("fH_electron_E_blur_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_electron_E_blur_", 52, 0.0, 2.0); } fH_electron_E_->SetFillColor(kBlue); fH_electron_E_->SetTitle("Electrons' energy distribution"); fH_electron_E_->GetXaxis()->SetTitle("E [MeV]"); fH_electron_E_->GetYaxis()->SetTitle("dN/dE"); fH_electron_E_->GetYaxis()->SetTitleOffset(1.8); fH_electron_E_blur_->SetFillColor(kBlue); fH_electron_E_blur_->SetTitle("Electrons' energy distribution, smear effect"); fH_electron_E_blur_->GetXaxis()->SetTitle("E [MeV]"); fH_electron_E_blur_->GetYaxis()->SetTitle("dN/dE"); fH_electron_E_blur_->GetYaxis()->SetTitleOffset(1.8); fH_photon_E_depos_->SetFillColor(kBlue); fH_photon_E_depos_->SetTitle("Incident photon energy deposition"); fH_photon_E_depos_->GetXaxis()->SetTitle("E [MeV]"); fH_photon_E_depos_->GetYaxis()->SetTitle("dN/dE"); fH_photon_E_depos_->GetYaxis()->SetTitleOffset(1.8); fH_photon_theta_ = new TH1F((std::string("fH_photon_theta_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_photon_theta_", 50, 0.0, TMath::Pi()); fH_photon_theta_->SetFillColor(kBlue); fH_photon_theta_->SetTitle("Scattering angle distribution"); fH_photon_theta_->GetXaxis()->SetTitle("#theta"); fH_photon_theta_->GetYaxis()->SetTitle("dN/d#theta"); fH_photon_theta_->GetYaxis()->SetTitleOffset(1.8); fH_PDF_ = new TH2D((std::string("fH_PDF_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_PDF_", 1000, 0.0, 1.022, 1000, 0.0, TMath::Pi()); fH_PDF_->SetTitle("Klein-Nishima function"); fH_PDF_->GetXaxis()->SetTitle("E [MeV]"); fH_PDF_->GetYaxis()->SetTitle("#theta'"); fH_PDF_->SetStats(kFALSE); fH_PDF_cross = new TH1D((std::string("fH_PDF_cross_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_PDF_cross", 1000, 0.0, TMath::Pi()); fH_PDF_cross->GetYaxis()->SetTitle("d N/ d #Omega"); fH_PDF_cross->GetXaxis()->SetTitle("#theta'"); fH_PDF_cross->SetStats(kFALSE); fH_PDF_Theta_ = new TH2D((std::string("fH_PDF_Theta_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_PDF_Theta_", 1000, 0.0, 1.022, 1000, 0.0, TMath::Pi()); fH_PDF_Theta_->SetTitle("Klein-Nishima function * 2*#pi*sin(#theta)"); fH_PDF_Theta_->GetXaxis()->SetTitle("E [MeV]"); fH_PDF_Theta_->GetYaxis()->SetTitle("#theta'"); fH_PDF_Theta_->SetStats(kFALSE); fH_PDF_Theta_cross = new TH1D((std::string("fH_PDF_Theta_cross_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), "fH_PDF_Theta_cross_", 1000, 0.0, TMath::Pi()); fH_PDF_Theta_cross->GetYaxis()->SetTitle("d #N/ d #theta"); fH_PDF_Theta_cross->GetXaxis()->SetTitle("#theta'"); fH_PDF_Theta_cross->SetStats(kFALSE); //creating function wrapper around KleinNishina_ function fPDF = new TF1((std::string("KleinNishima_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), KleinNishina_, 0.0 , TMath::Pi(), 1); fPDF_Theta = new TF1((std::string("KleinNishimaTheta_")+fTypeString_+"_"+std::to_string(objectID_)).c_str(), KleinNishinaTheta_, 0.0 , TMath::Pi(), 1); objectID_++; } /// /// \brief ComptonScattering::ComptonScattering Copy constructor. /// \param est ComptonScattering instance to be copied. /// ComptonScattering::ComptonScattering(const ComptonScattering &est) { fDecayType_=est.fDecayType_; fSilentMode_=est.fSilentMode_; fTypeString_=est.fTypeString_; fSmearLowLimit_=est.fSmearLowLimit_; fSmearHighLimit_=est.fSmearHighLimit_; fPDF = new TF1(*est.fPDF); //special root object fPDF_Theta = new TF1(*est.fPDF_Theta); fH_photon_E_depos_=new TH1F(*est.fH_photon_E_depos_); //distribution of energy deposited by incident photons fH_electron_E_ = new TH1F(*est.fH_electron_E_); //energy distribution for electrons fH_electron_E_blur_ = new TH1F(*est.fH_electron_E_blur_); fH_photon_theta_ = new TH1F(*est.fH_photon_theta_); //angle distribution for electrons fH_PDF_ = new TH2D(*est.fH_PDF_); // Klein-Nishina function plot, for testing purpose only fH_PDF_cross = new TH1D(*est.fH_PDF_cross); fH_PDF_Theta_ = new TH2D(*est.fH_PDF_Theta_); fH_PDF_Theta_cross = new TH1D(*est.fH_PDF_Theta_cross); } /// /// \brief ComptonScattering::operator = Copies histograms and field values. /// \param est ComptonScattering instance to be copied. /// \return Reference to ComptonScattering instance with copied fields. /// ComptonScattering& ComptonScattering::operator=(const ComptonScattering &est) { fDecayType_=est.fDecayType_; fSilentMode_=est.fSilentMode_; fTypeString_=est.fTypeString_; fSmearLowLimit_=est.fSmearLowLimit_; fSmearHighLimit_=est.fSmearHighLimit_; fPDF = new TF1(*est.fPDF); //special root object fPDF_Theta = new TF1(*est.fPDF_Theta); fH_photon_E_depos_=new TH1F(*est.fH_photon_E_depos_); //distribution of energy deposited by incident photons fH_electron_E_ = new TH1F(*est.fH_electron_E_); //energy distribution for electrons fH_electron_E_blur_ = new TH1F(*est.fH_electron_E_blur_); fH_photon_theta_ = new TH1F(*est.fH_photon_theta_); //angle distribution for electrons fH_PDF_ = new TH2D(*est.fH_PDF_); // Klein-Nishina function plot, for testing purpose only fH_PDF_cross = new TH1D(*est.fH_PDF_cross); fH_PDF_Theta_ = new TH2D(*est.fH_PDF_Theta_); fH_PDF_Theta_cross = new TH1D(*est.fH_PDF_Theta_cross); return *this; } /// /// \brief equal_histograms Checks integral, number of entries and mean of two histograms. /// \param h1 First histogram to be compared. /// \param h2 Second histogram to be compared. /// \return True if integral, number of entries and mean are equal. False otherwise. /// bool equal_histograms(const TH1* h1, const TH1* h2) { return (h1->Integral() == h2->Integral() && h1->GetEntries() == h2->GetEntries() && h1->GetMean() == h2->GetMean()); } bool ComptonScattering::operator==(const ComptonScattering &est) const { bool isEqual = (fDecayType_==est.fDecayType_) && (fSilentMode_==est.fSilentMode_) && (fTypeString_==est.fTypeString_) && (fSmearLowLimit_==est.fSmearLowLimit_) && (fSmearHighLimit_==est.fSmearHighLimit_) && \ equal_histograms(fH_photon_E_depos_, est.fH_photon_E_depos_) && equal_histograms(fH_electron_E_, est.fH_electron_E_) &&\ equal_histograms(fH_electron_E_blur_, est.fH_electron_E_blur_) && equal_histograms(fH_photon_theta_, est.fH_photon_theta_); return isEqual; } /// /// \brief ComptonScattering::~ComptonScattering Destructor, releases memory after histograms. /// ComptonScattering::~ComptonScattering() { if(fH_electron_E_) delete fH_electron_E_; if(fH_electron_E_blur_) delete fH_electron_E_blur_; if(fH_photon_theta_) delete fH_photon_theta_; if(fH_photon_E_depos_) delete fH_photon_E_depos_; if(fH_PDF_) delete fH_PDF_; if(fH_PDF_cross) delete fH_PDF_cross; if(fPDF) delete fPDF; if(fH_PDF_Theta_) delete fH_PDF_Theta_; if(fH_PDF_Theta_cross) delete fH_PDF_Theta_cross; if(fPDF_Theta) delete fPDF_Theta; } /// /// \brief ComptonScattering::DrawPDF Draws Klein-Nishina function and saves to a file. /// \param filePrefix Prefix of the output file, may contain path. /// \param crossSectionE Value of energy to draw a cross section. /// void ComptonScattering::DrawPDF(std::string filePrefix, double crossSectionE) { std::cout<<"\n[INFO] Drawing Klein-Nishima function."<<std::endl; int range = 1000; //Two loops create a grid, where the value of function is calculated. double crossE[1] = {crossSectionE}; for(int xx=0; xx<range; xx++) { double E[1] = {xx/((float)range)*1.022}; for(int yy=0; yy<range; yy++) { double theta[1] = {yy/((float)range)*TMath::Pi()}; long double valPDF = fPDF->EvalPar(theta, E); long double valPDFTheta = fPDF_Theta->EvalPar(theta, E); fH_PDF_->SetBinContent(xx, yy, valPDF); fH_PDF_Theta_->SetBinContent(xx, yy, valPDFTheta); long double valCross = fPDF->EvalPar(theta, crossE); fH_PDF_cross->SetBinContent(yy, valCross); long double valCrossTheta = fPDF_Theta->EvalPar(theta, crossE); fH_PDF_Theta_cross->SetBinContent(yy, valCrossTheta); } } //drawing and saving to file TCanvas* c = new TCanvas("c", "c", 1300, 380); c->Divide(2); c->cd(1); fH_PDF_->Draw("colz"); c->cd(2); fH_PDF_cross->SetTitle((std::string("Klein-Nishima function for ")+std::to_string(crossSectionE)+std::string(" [MeV]")).c_str()); fH_PDF_cross->Draw(); TImage *img = TImage::Create(); img->FromPad(c); img->WriteImage((filePrefix+std::string("Klein-Nishina.png")).c_str()); //drawing dN/d theta TCanvas* c2 = new TCanvas("c2", "c2", 1300, 380); c2->Divide(2); c2->cd(1); fH_PDF_Theta_->Draw("colz"); c2->cd(2); fH_PDF_Theta_cross->SetTitle((std::string("Scattering angle distribution for ")+std::to_string(crossSectionE)+std::string(" [MeV]")).c_str()); fH_PDF_Theta_cross->Draw(); TImage *img2 = TImage::Create(); img2->FromPad(c2); img2->WriteImage((filePrefix+std::string("Klein-Nishina_Theta.png")).c_str()); std::cout<<"[INFO] Klein-Nishina function saved to file.\n"<<std::endl; delete c; delete c2; delete img; delete img2; } /// /// \brief ComptonScattering::DrawComptonHistograms Draws histograms and saves to file(s). /// \param filePrefix Prefix of the filename. /// \param output Type of output, can be PNG, TREE, or BOTH. /// void ComptonScattering::DrawComptonHistograms(std::string filePrefix, OutputOptions output) { if(!fSilentMode_) std::cout<<"[INFO] Drawing histograms for Compton electrons and scattered photons."<<std::endl; TCanvas* c = new TCanvas((fTypeString_+"-gammas_compton_distr").c_str(), "Compton effect distributions", 1300, 1200); TLine *line = new TLine(0.511, 0.0, 0.511,fH_photon_E_depos_->GetMaximum()*1.05); line->SetLineColor(kRed+2); line->SetLineWidth(4); TLine *lowLimit = new TLine(fSmearLowLimit_, 0.0, fSmearLowLimit_,fH_electron_E_blur_->GetMaximum()*1.05); lowLimit->SetLineColor(kRed+2); lowLimit->SetLineWidth(4); TLine *highLimit = new TLine(fSmearHighLimit_, 0.0, fSmearHighLimit_,fH_electron_E_blur_->GetMaximum()*1.05); highLimit->SetLineColor(kRed+2); highLimit->SetLineWidth(4); c->Divide(2,2); c->cd(1); fH_photon_E_depos_->Draw(); if(fDecayType_!=ONE) line->Draw(); c->cd(2); fH_photon_theta_->Draw(); c->cd(3); fH_electron_E_ ->Draw(); c->cd(4); fH_electron_E_blur_->Draw(); lowLimit->Draw(); highLimit->Draw(); //writing depends on the 'output' value if(output==BOTH || output==PNG) { TImage *img = TImage::Create(); img->FromPad(c); img->WriteImage((filePrefix+fTypeString_+"-gammas_compton_distr.png").c_str()); delete img; } if(output==BOTH || output==TREE) { c->Write(); } delete c; delete line; delete lowLimit; delete highLimit; if(!fSilentMode_) std::cout<<"[INFO] Saving histograms for Compton effect.\n"<<std::endl; } /// /// \brief ComptonScattering::Scatter Scatters gammas from the event, performs smearing and fills histograms. /// \param event Pointer to Event object that is to be scattered. /// void ComptonScattering::Scatter(Event* event, int index) const { int lowLimit = 0; int highLimit = event->GetNumberOfDecayProducts(); if(index > -1) { lowLimit = index; highLimit = index+1; } for(int ii=lowLimit; ii<highLimit; ii++) { if(event->GetFourMomentumOf(ii) != nullptr && event->GetCutPassingOf(ii)) { double E = event->GetFourMomentumOf(ii)->Energy(); fH_photon_E_depos_->Fill(E); fPDF_Theta->SetParameter(0, E); //set incident photon energy double theta = fPDF_Theta->GetRandom(); //get scattering angle fH_photon_theta_->Fill(theta); double new_E = E * (1.0 - 1.0/(1.0+(E/(e_mass_MeV))*(1-TMath::Cos(theta)))); //E*(1-P) -- Compton electron's energy fH_electron_E_->Fill(new_E); event->SetEdepOf(ii, new_E); //if new_E is within limit -- smear, otherwise fill histogram with new_E if((new_E >= fSmearLowLimit_) && (new_E <= fSmearHighLimit_)) { double Esmear = gRandom->Gaus(new_E, sigmaE(E)); fH_electron_E_blur_->Fill(Esmear); event->SetEdepSmearOf(ii, Esmear); } else { fH_electron_E_blur_->Fill(new_E); event->SetEdepSmearOf(ii, new_E); } } } } /// /// \brief ComptonScattering::KleinNishina_ Klein-Nishina formula /// \param angle Scattering angle. /// \param energy Incident's photon energy in MeV. /// \return Compton effect cross section. /// long double ComptonScattering::KleinNishina_(double* angle, double* energy) { long double denom = 1L+(energy[0]/(e_mass_MeV))*(1-TMath::Cos(angle[0])); long double P = 1.0L/denom; return 0.5L*fine_structure_const_*fine_structure_const_*r_Compton_SI*r_Compton_SI\ *P*P*(P + denom - TMath::Sin(angle[0])*TMath::Sin(angle[0])); } /// /// \brief ComptonScattering::KleinNishinaTheta_ PDF of occuring a Compton scattering with a given angle and energy. /// \param angle Scattering angle. /// \param energy Incident's photon energy in MeV. /// \return PDF function value based on Klein-Nishina formula. /// long double ComptonScattering::KleinNishinaTheta_(double* angle, double* energy) { long double denom = 1L+(energy[0]/(e_mass_MeV))*(1-TMath::Cos(angle[0])); long double P = 1.0L/denom; return 0.5L*fine_structure_const_*fine_structure_const_*r_Compton_SI*r_Compton_SI\ *P*P*(P + denom - TMath::Sin(angle[0])*TMath::Sin(angle[0]))\ *2*TMath::Pi()*TMath::Sin(angle[0]); //corrections suggested by W.Krzemien } /// /// \brief ComptonScattering::sigmaE Calculates std dev for the smearing effect. /// \param E Incident photon's energy. /// \param coeff Phenomenological coeff. /// \return std dev for electron's energy distribution /// double ComptonScattering::sigmaE(double E, double coeff) const { return coeff*E/TMath::Sqrt(E); }
46.814815
171
0.683149
[ "object" ]
49e998bce3e28d8b7fc9c17eef731c66f022828c
28,284
cpp
C++
gui/src/Nodes.cpp
JRegimbal/Syntacts
29380edbd41b3f148eff8a5e9bb76d082af909b4
[ "MIT" ]
32
2020-03-22T05:31:00.000Z
2022-01-14T00:18:02.000Z
gui/src/Nodes.cpp
JRegimbal/Syntacts
29380edbd41b3f148eff8a5e9bb76d082af909b4
[ "MIT" ]
6
2020-10-29T21:08:47.000Z
2021-11-08T10:00:32.000Z
gui/src/Nodes.cpp
WHC2021SIC/Syntacts
4831fbc9aef8c7d46c1e962a267c3987cbe0439d
[ "MIT" ]
7
2020-05-26T21:38:31.000Z
2021-03-26T20:38:11.000Z
#include "Nodes.hpp" #include "Gui.hpp" using namespace mahi::gui; namespace { int g_nextNodeId = 0; } /////////////////////////////////////////////////////////////////////////////// void NodeSlot(const char *label, const ImVec2 &size) { BeginPulsable(true,true); ImGui::Button(label, size); EndPulsable(); } std::shared_ptr<Node> makeNode(PItem id) { if (id == PItem::Time) return std::make_shared<TimeNode>(); if (id == PItem::Scalar) return std::make_shared<ScalarNode>(); if (id == PItem::Ramp) return std::make_shared<RampNode>(); if (id == PItem::Noise) return std::make_shared<NoiseNode>(); if (id == PItem::Expression) return std::make_shared<ExpressionNode>(); if (id == PItem::Sum) return std::make_shared<SumNode>(); if (id == PItem::Product) return std::make_shared<ProductNode>(); if (id == PItem::Sine) return std::make_shared<OscillatorNode>(tact::Sine()); if (id == PItem::Square) return std::make_shared<OscillatorNode>(tact::Square()); if (id == PItem::Saw) return std::make_shared<OscillatorNode>(tact::Saw()); if (id == PItem::Triangle) return std::make_shared<OscillatorNode>(tact::Triangle()); if (id == PItem::Chirp) return std::make_shared<ChirpNode>(); if (id == PItem::Envelope) return std::make_shared<EnvelopeNode>(); if (id == PItem::KeyedEnvelope) return std::make_shared<KeyedEnvelopeNode>(); if (id == PItem::ASR) return std::make_shared<ASRNode>(); if (id == PItem::ADSR) return std::make_shared<ADSRNode>(); if (id == PItem::ExponentialDecay) return std::make_shared<ExponentialDecayNode>(); if (id == PItem::SignalEnvelope) return std::make_shared<SignalEnvelopeNode>(); if (id == PItem::PolyBezier) return std::make_shared<PolyBezierNode>(); if (id == PItem::Stretcher) return std::make_shared<StretcherNode>(); if (id == PItem::Repeater) return std::make_shared<RepeaterNode>(); if (id == PItem::Reverser) return std::make_shared<ReverserNode>(); if (id == PItem::Sequencer) return std::make_shared<SequencerNode>(); if (id == PItem::Pwm) return std::make_shared<PwmNode>(); if (id == PItem::FM) return std::make_shared<FmNode>(); return nullptr; } template <typename T> std::shared_ptr<Node> makeOscNode(const tact::Signal& sig, int idx) { auto osc = sig.getAs<T>(); if (osc->x.template isType<tact::Time>()) { auto node = std::make_shared<OscillatorNode>(T()); node->sig = sig; return node; } else if (osc->x.template isType<tact::Product>()) { auto x = osc->x.template getAs<tact::Product>(); if (x->lhs.template isType<tact::Time>() && x->rhs.template isType<tact::Time>()) { auto node = std::make_shared<ChirpNode>(); node->f = x->lhs.bias / tact::TWO_PI; node->r = x->lhs.gain / tact::PI; return node; } } else if (osc->x.template isType<tact::Sum>()) { auto x = osc->x.template getAs<tact::Sum>(); if (x->lhs.template isType<tact::Time>() && x->rhs.template isType<tact::Sine>()) { auto node = std::make_shared<FmNode>(); node->f = x->lhs.gain / tact::TWO_PI; node->index = x->rhs.gain; node->ftype = idx; node->m = x->rhs.template getAs<tact::Sine>()->x.gain / tact::TWO_PI; return node; } } return nullptr; } bool recurseProduct(std::shared_ptr<ProductNode> root, const tact::Signal& sig) { auto prod = sig.getAs<tact::Product>(); if (prod->lhs.isType<tact::Product>()) recurseProduct(root, prod->lhs); else if (auto lhs = makeNode(prod->lhs)) root->m_nodes.push_back(lhs); else return false; if (prod->rhs.isType<tact::Product>()) recurseProduct(root, prod->rhs); else if (auto rhs = makeNode(prod->rhs)) root->m_nodes.push_back(rhs); else return false; return true; } bool recurseSum(std::shared_ptr<SumNode> root, const tact::Signal& sig) { auto prod = sig.getAs<tact::Sum>(); if (prod->lhs.isType<tact::Sum>()) recurseSum(root, prod->lhs); else if (auto lhs = makeNode(prod->lhs)) root->m_nodes.push_back(lhs); else return false; if (prod->rhs.isType<tact::Sum>()) recurseSum(root, prod->rhs); else if (auto rhs = makeNode(prod->rhs)) root->m_nodes.push_back(rhs); else return false; return true; } template <typename N, typename S> std::shared_ptr<N> makeProcessNode(const tact::Signal& sig) { auto pro = sig.getAs<S>(); if (auto root = makeRoot(pro->signal)) { auto node = std::make_shared<N>(); node->sig = sig; node->root = root; return node; } return nullptr; } std::shared_ptr<Node> makeNode(const tact::Signal& sig) { if (sig.isType<tact::Scalar>()) return std::make_shared<ScalarNode>(sig); else if (sig.isType<tact::Time>()) return std::make_shared<TimeNode>(sig); else if (sig.isType<tact::Ramp>()) return std::make_shared<RampNode>(sig); else if (sig.isType<tact::Noise>()) return std::make_shared<NoiseNode>(sig); else if (sig.isType<tact::Expression>()) return std::make_shared<ExpressionNode>(sig); else if (sig.isType<tact::PolyBezier>()) return std::make_shared<PolyBezierNode>(sig); else if (sig.isType<tact::Samples>()) return std::make_shared<SamplesNode>(sig); else if (sig.isType<tact::Sum>()) { auto node = std::make_shared<SumNode>(); if (recurseSum(node, sig)) return node; } else if (sig.isType<tact::Product>()) { auto node = std::make_shared<ProductNode>(); if (recurseProduct(node, sig)) return node; } else if (sig.isType<tact::Sequence>()) { auto seq = sig.getAs<tact::Sequence>(); return std::make_shared<SequencerNode>(*seq); } else if (sig.isType<tact::Sine>()) return makeOscNode<tact::Sine>(sig, 0); else if (sig.isType<tact::Square>()) return makeOscNode<tact::Square>(sig, 1); else if (sig.isType<tact::Saw>()) return makeOscNode<tact::Saw>(sig, 2); else if (sig.isType<tact::Triangle>()) return makeOscNode<tact::Triangle>(sig, 3); else if (sig.isType<tact::Pwm>()) return std::make_shared<PwmNode>(sig); else if (sig.isType<tact::Envelope>()) return std::make_shared<EnvelopeNode>(sig); else if (sig.isType<tact::KeyedEnvelope>()) return std::make_shared<KeyedEnvelopeNode>(sig); else if (sig.isType<tact::ASR>()) return std::make_shared<ASRNode>(sig); else if (sig.isType<tact::ADSR>()) return std::make_shared<ADSRNode>(sig); else if (sig.isType<tact::ExponentialDecay>()) return std::make_shared<ExponentialDecayNode>(sig); else if (sig.isType<tact::SignalEnvelope>()) return makeProcessNode<SignalEnvelopeNode, tact::SignalEnvelope>(sig); else if (sig.isType<tact::Repeater>()) return makeProcessNode<RepeaterNode, tact::Repeater>(sig); else if (sig.isType<tact::Stretcher>()) return makeProcessNode<StretcherNode, tact::Stretcher>(sig); else if (sig.isType<tact::Reverser>()) return makeProcessNode<ReverserNode, tact::Reverser>(sig); return nullptr; } /// Make Node from Signal std::shared_ptr<Node> makeRoot(const tact::Signal& sig) { auto root = std::make_shared<ProductNode>(); if (sig.isType<tact::Product>()) { if (recurseProduct(root, sig)) return root; } else { auto node = makeNode(sig); if (node) { root->m_nodes.push_back(node); return root; } } return nullptr; } /////////////////////////////////////////////////////////////////////////////// Node::Node() : active(true), id(g_nextNodeId++) { } /////////////////////////////////////////////////////////////////////////////// void NodeList::update() { // render nodes for (std::size_t i = 0; i < m_nodes.size(); ++i) { std::string header = m_nodes[i]->name() + "###SignalSlot"; ImGui::PushID(m_nodes[i]->id); ImGui::PushStyleColor(ImGuiCol_Header, ImGui::GetStyle().Colors[ImGuiCol_TabActive]); if (ImGui::CollapsingHeader(header.c_str(), &m_nodes[i]->active, ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Indent(); m_nodes[i]->update(); ImGui::Unindent(); } ImGui::PopStyleColor(); ImGui::PopID(); } // node slot if (m_nodes.size() == 0 || SignalHeld() || PaletteHeld()) NodeSlot("##EmptySlot", ImVec2(-1, 0)); // check for incoming palette items if (PaletteTarget()) { auto node = makeNode(PalettePayload()); if (node) m_nodes.emplace_back(node); } // check for incoming library items if (SignalTarget()) { auto node = std::make_shared<LibrarySignalNode>(SignalPayload().first); m_nodes.emplace_back(node); } // clean up std::vector<std::shared_ptr<Node>> newNodes; newNodes.reserve(m_nodes.size()); std::vector<int> newIds; for (int i = 0; i < m_nodes.size(); ++i) { if (m_nodes[i]->active) newNodes.emplace_back(std::move(m_nodes[i])); } m_nodes = std::move(newNodes); } /////////////////////////////////////////////////////////////////////////////// tact::Signal ProductNode::signal() { if (m_nodes.size() > 0) { auto sig = m_nodes[0]->signal(); for (int i = 1; i < m_nodes.size(); ++i) sig = sig * m_nodes[i]->signal(); return sig; } return tact::Signal(); } const std::string &ProductNode::name() { static std::string n = "Product"; return n; } /////////////////////////////////////////////////////////////////////////////// tact::Signal SumNode::signal() { if (m_nodes.size() > 0) { auto sig = m_nodes[0]->signal(); for (int i = 1; i < m_nodes.size(); ++i) sig = sig + m_nodes[i]->signal(); return sig; } return tact::Signal(); } const std::string &SumNode::name() { static std::string n = "Sum"; return n; } /////////////////////////////////////////////////////////////////////////////// LibrarySignalNode::LibrarySignalNode(const std::string &name) : libName(name) { tact::Library::loadSignal(sig, libName); } tact::Signal LibrarySignalNode::signal() { return sig; } const std::string &LibrarySignalNode::name() { return libName; } // float* LibrarySignalNode::gain() { return &sig.scale; } // float* LibrarySignalNode::bias() { return &sig.offset; } void LibrarySignalNode::update() { } /////////////////////////////////////////////////////////////////////////////// void StretcherNode::update() { auto cast = (tact::Stretcher *)sig.get(); root->update(); cast->signal = root->signal(); float factor = (float)cast->factor; if (ImGui::SliderFloat("Factor", &factor, 0, 10)) cast->factor = factor; } /////////////////////////////////////////////////////////////////////////////// void RepeaterNode::update() { auto cast = (tact::Repeater *)sig.get(); root->update(); cast->signal = root->signal(); ImGui::SliderInt("Repetitions", &cast->repetitions, 1, 100); float delay = (float)cast->delay; if (ImGui::SliderFloat("Delay", &delay, 0, 1)) cast->delay = delay; } /////////////////////////////////////////////////////////////////////////////// void ReverserNode::update() { auto cast = (tact::Repeater *)sig.get(); root->update(); cast->signal = root->signal(); } /////////////////////////////////////////////////////////////////////////////// SequencerNode::SequencerNode() { interface.activeColor = mahi::gui::Purples::Plum; interface.inactiveColor = mahi::gui::Grays::Gray50; } SequencerNode::SequencerNode(tact::Sequence _seq) : SequencerNode() { seq = _seq; int key_count = seq.keyCount(); for (int i = 0; i < key_count; ++i) { auto& key = seq.getKey(i); ImGui::SeqInterface::Track track; track.signal = key.signal; track.label = "Track " + std::to_string(i+1); track.t = key.t; track.populated = true; interface.tracks.push_back(track); } interface.fitThisFrame = true; } tact::Signal SequencerNode::signal() { seq.clear(); for (auto& track : interface.tracks) { if (track.populated && track.visible) seq.insert(track.signal, track.t); } return seq; } const std::string& SequencerNode::name() { static const std::string n = "Sequencer"; return n; } void SequencerNode::update() { ImGui::Sequencer("Sequencer", interface, false); } /////////////////////////////////////////////////////////////////////////////// OscillatorNode::OscillatorNode(tact::Signal osc) { sig = std::move(osc); } void OscillatorNode::update() { auto cast = (tact::IOscillator *)sig.get(); if (ImGui::RadioButton("Sine", sig.isType<tact::Sine>())) { sig = tact::Sine(cast->x); } ImGui::SameLine(); if (ImGui::RadioButton("Square", sig.isType<tact::Square>())) { sig = tact::Square(cast->x); } ImGui::SameLine(); if (ImGui::RadioButton("Saw", sig.isType<tact::Saw>())) { sig = tact::Saw(cast->x); } ImGui::SameLine(); if (ImGui::RadioButton("Triangle", sig.isType<tact::Triangle>())) { sig = tact::Triangle(cast->x); } cast = (tact::IOscillator *)sig.get(); if (cast->x.isType<tact::Time>()) { float f = (float)cast->x.gain / (float)tact::TWO_PI; ImGui::DragFloat("##Frequency", &f, 1, 0, 1000, "%.0f Hz"); ImGui::SameLine(); ImGui::Text("Frequency"); cast->x.gain = f * tact::TWO_PI; } else { ImGui::Indent(); ImGui::Text("Oops!"); ImGui::Unindent(); } } /////////////////////////////////////////////////////////////////////////////// namespace { const std::string& oscName(int type) { static std::vector<std::string> types = {"Sine", "Square", "Saw", "Triangle"}; return types[type]; } template <typename ... Args> tact::Signal makeOsc(int type, Args ... args) { if (type == 0) return tact::Sine(args ...); else if (type == 1) return tact::Square(args ...); else if (type == 2) return tact::Saw(args ...); else return tact::Triangle(args ...); } } void ChirpNode::update() { for (int i = 0; i < 4; ++i) { if (ImGui::RadioButton(oscName(i).c_str(), ftype == i)) ftype = i; if (i != 3) ImGui::SameLine(); } ImGui::DragDouble("Frequency", &f, 1, 0, 1000, "%.0f Hz"); ImGui::DragDouble("Rate", &r, 1, 0, 1000, "%.0f Hz/s"); } tact::Signal ChirpNode::signal() { return makeOsc(ftype, f, r); } const std::string &ChirpNode::name() { static std::string fmName = "Chirp"; return fmName; } /////////////////////////////////////////////////////////////////////////////// void FmNode::update() { for (int i = 0; i < 4; ++i) { if (ImGui::RadioButton(oscName(i).c_str(), ftype == i)) ftype = i; if (i != 3) ImGui::SameLine(); } ImGui::DragDouble("Frequency", &f, 1, 0, 1000, "%.0f Hz"); ImGui::DragDouble("Modulation", &m, 0.1f, 0, 100, "%.0f Hz"); ImGui::DragDouble("Index", &index, 0.01f, 0, 10); } tact::Signal FmNode::signal() { return makeOsc(ftype, f, tact::Sine(m), index); } const std::string &FmNode::name() { static std::string fmName = "FM"; return fmName; } /////////////////////////////////////////////////////////////////////////////// void PwmNode::update() { auto cast = (tact::Pwm *)sig.get(); float f = (float)cast->frequency; float d = (float)cast->dutyCycle; if (ImGui::DragFloat("Frequency", &f, 1, 0, 1000)) cast->frequency = f; if (ImGui::DragFloat("Duty Cycle", &d, 0.001f, 0, 1.0f)) cast->dutyCycle = d; } /////////////////////////////////////////////////////////////////////////////// ExpressionNode::ExpressionNode() { getString(); } ExpressionNode::ExpressionNode(const tact::Signal& _sig) { sig = _sig; getString(); } void ExpressionNode::getString() { auto cast = (tact::Expression *)sig.get(); strcpy(buffer, cast->getExpression().c_str()); } void ExpressionNode::update() { if (!ok) ImGui::PushStyleColor(ImGuiCol_FrameBg, Reds::FireBrick); bool entered = ImGui::InputText("f(t)", buffer, 256, ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue); if (!ok) ImGui::PopStyleColor(); if (entered) { auto cast = (tact::Expression *)sig.get(); std::string oldExpr = cast->getExpression(); std::string newExpr(buffer); if (!cast->setExpression(newExpr)) { cast->setExpression(oldExpr); ok = false; } else { ok = true; } } } /////////////////////////////////////////////////////////////////////////////// PolyBezierNode::PolyBezierNode() : pb(ImGui::GetStyle().Colors[ImGuiCol_PlotLines], ImVec2(0, 0), ImVec2(1, 1)) { sync(); } PolyBezierNode::PolyBezierNode(const tact::Signal& _sig) : SignalNode<tact::PolyBezier>(_sig), pb(ImGui::GetStyle().Colors[ImGuiCol_PlotLines], ImVec2(0, 0), ImVec2(1, 1)) { bounds[2] = (float)(sig.length()); auto tpb = *sig.getAs<tact::PolyBezier>(); pb.clearPoints(); for (auto& p : tpb.points) pb.addPoint({(float)p.cpL.t, (float)p.cpL.y}, {(float)p.p.t, (float)p.p.y}, {(float)p.cpR.t, (float)p.cpR.y}); } void PolyBezierNode::update() { ImGui::PushItemWidth(-1); ImGui::PolyBezierEdit("##PolyBezier", &pb, 10, 10, ImVec2(-1, 125)); if (HelpTarget()) ImGui::OpenPopup("PolyBezier Editor"); if (ImGui::BeginHelpPopup("PolyBezier Editor")) { ImGui::BulletText("Drag points and handles with left mouse"); ImGui::BulletText("Ctrl + left-click handles to toggle tangency constraints"); ImGui::BulletText("Right-click to add new points"); ImGui::BulletText("Press the Delete key to remove the selected point"); ImGui::EndPopup(); } ImGui::PopItemWidth(); ImGui::DragFloat("Duration", &bounds[2], 0.1f, 0, 10, "%.3f s"); pb.min.x = bounds[0]; pb.min.y = bounds[1]; pb.max.x = bounds[2]; pb.max.y = bounds[3]; sync(); } void PolyBezierNode::sync() { auto cast = (tact::PolyBezier *)sig.get(); int points = pb.pointCount(); cast->points.resize(points); for (int i = 0; i < points; ++i) { ImVec2 cpL, pos, cpR; pb.getPoint(i, &cpL, &pos, &cpR); cast->points[i].cpL = {cpL.x, cpL.y}; cast->points[i].p = {pos.x, pos.y}; cast->points[i].cpR = {cpR.x, cpR.y}; } cast->solve(); } //////////////////////////////////////////////////////////////////////////////// void SamplesNode::update() { auto samples = sig.getAs<tact::Samples>(); ImGui::Text("Sample Count: %d", samples->sampleCount()); ImGui::Text("Sample Rate: %.0f Hz", samples->sampleRate()); } /////////////////////////////////////////////////////////////////////////////// void EnvelopeNode::update() { auto cast = (tact::Envelope *)sig.get(); ImGui::DragDouble("Duration", &cast->duration, 0.001f, 0, 1, "%0.3f s"); ImGui::DragDouble("Amplitude", &cast->amplitude, 0.01f, 0, 1); } /////////////////////////////////////////////////////////////////////////////// static const char* CURVE_NAMES[] = { "Instant", "Delayed", "Linear", "Smoothstep", "Smootherstep", "Smootheststep", "Quadratic::In", "Quadratic::Out", "Quadratic::InOut", "Quadratic::In", "Quadratic::Out", "Quadratic::InOut", "Cubic::In", "Cubic::Out", "Cubic::InOut", "Quartic::In", "Quartic::Out", "Quartic::InOut", "Quintic::In", "Quintic::Out", "Quintic::InOut", "Sinusoidal::In", "Sinusoidal::Out", "Sinusoidal::InOut", "Exponential::In", "Exponential::Out", "Exponential::InOut", "Circular::In", "Circular::Out", "Circular::InOut", "Elastic::In", "Elastic::Out", "Elastic::InOut", "Back::In", "Back::Out", "Back::InOut", "Bounce::In", "Bounce::Out", "Bounce::InOut", }; static const tact::Curve CURVES[] = { tact::Curves::Instant(), tact::Curves::Delayed(), tact::Curves::Linear(), tact::Curves::Smoothstep(), tact::Curves::Smootherstep(), tact::Curves::Smootheststep(), tact::Curves::Quadratic::In(), tact::Curves::Quadratic::Out(), tact::Curves::Quadratic::InOut(), tact::Curves::Quadratic::In(), tact::Curves::Quadratic::Out(), tact::Curves::Quadratic::InOut(), tact::Curves::Cubic::In(), tact::Curves::Cubic::Out(), tact::Curves::Cubic::InOut(), tact::Curves::Quartic::In(), tact::Curves::Quartic::Out(), tact::Curves::Quartic::InOut(), tact::Curves::Quintic::In(), tact::Curves::Quintic::Out(), tact::Curves::Quintic::InOut(), tact::Curves::Sinusoidal::In(), tact::Curves::Sinusoidal::Out(), tact::Curves::Sinusoidal::InOut(), tact::Curves::Exponential::In(), tact::Curves::Exponential::Out(), tact::Curves::Exponential::InOut(), tact::Curves::Circular::In(), tact::Curves::Circular::Out(), tact::Curves::Circular::InOut(), tact::Curves::Elastic::In(), tact::Curves::Elastic::Out(), tact::Curves::Elastic::InOut(), tact::Curves::Back::In(), tact::Curves::Back::Out(), tact::Curves::Back::InOut(), tact::Curves::Bounce::In(), tact::Curves::Bounce::Out(), tact::Curves::Bounce::InOut() }; void KeyedEnvelopeNode::update() { auto cast = sig.getAs<tact::KeyedEnvelope>(); Ts.clear(); As.clear(); Cs.clear(); int key_count = cast->keys.size(); int i = 0; for (auto it = cast->keys.begin(); it != cast->keys.end(); ++it) { double t = it->first; double a = it->second.first; tact::Curve c = it->second.second; bool first_key = it == cast->keys.begin(); bool last_key = std::next(it) == cast->keys.end(); double tprev, tnext; if (first_key) tprev = 0; else tprev = std::prev(it)->first; if (last_key) tnext = 0; else tnext = std::next(it)->first; double tmin = first_key ? 0 : tprev + 0.001; double tmax = last_key ? t + 1000 : tnext - 0.001; ImGui::PushID(i); ImGui::BeginDisabled(first_key); ImGui::SetNextItemWidth(160); ImGui::DragDouble("##T",&t, 0.0005f, tmin, tmax, "%.3f s"); ImGui::EndDisabled(); ImGui::SameLine(); ImGui::SetNextItemWidth(160); ImGui::DragDouble("##A",&a,0.005f,0,1); ImGui::SameLine(); ImGui::BeginDisabled(first_key); ImGui::SetNextItemWidth(160); if (ImGui::BeginCombo("##Curve", c.name())) { for (int i = 0; i < 39; ++i) { bool selected = strcmp(c.name(),CURVE_NAMES[i]) == 0; if (ImGui::Selectable(CURVE_NAMES[i],&selected)) c = CURVES[i]; } ImGui::EndCombo(); } ImGui::SameLine(); if (!ImGui::Button(ICON_FA_MINUS)) { Ts.push_back(first_key ? 0 : t); As.push_back(a); Cs.push_back(c); } ImGui::EndDisabled(); ImGui::SameLine(); if (ImGui::Button(ICON_FA_PLUS)) { double tp = last_key ? + t + 0.1f : (t + tnext) / 2; Ts.push_back(tp); As.push_back(a); Cs.push_back(tact::Curves::Linear()); } ImGui::PopID(); i++; } cast->keys.clear(); for (int i = 0; i < Ts.size(); ++i) cast->addKey(Ts[i], As[i], Cs[i]); } /////////////////////////////////////////////////////////////////////////////// void ASRNode::update() { static const float minDur = 0.001f; auto cast = (tact::ASR *)sig.get(); auto it = cast->keys.begin(); it++; auto &a = *(it++); auto &s = *(it++); auto &r = *(it++); float asr[3]; asr[0] = a.first; asr[1] = s.first - a.first; asr[2] = r.first - s.first; float amp = a.second.first; bool changed = false; if (ImGui::DragFloat3("Durations", asr, 0.001f, minDur, 1.0f, "%0.3f s")) changed = true; if (ImGui::DragFloat("Amplitude", &amp, 0.001f, 0, 1)) changed = true; for (int i = 0; i < 3; ++i) { if (asr[i] <= 0) asr[i] = minDur; } if (changed) sig = tact::ASR(asr[0], asr[1], asr[2], amp); } /////////////////////////////////////////////////////////////////////////////// void ADSRNode::update() { static const float minDur = 0.001f; auto cast = (tact::ASR *)sig.get(); auto it = cast->keys.begin(); it++; auto &a = *(it++); auto &d = *(it++); auto &s = *(it++); auto &r = *(it++); float adsr[4]; adsr[0] = a.first; adsr[1] = d.first - a.first; adsr[2] = s.first - d.first; adsr[3] = r.first - s.first; float amp[2]; amp[0] = a.second.first; amp[1] = d.second.first; bool changed = false; if (ImGui::DragFloat4("Durations", adsr, 0.001f, minDur, 1, "%0.3f s")) changed = true; if (ImGui::DragFloat2("Amplitudes", amp, 0.001f, 0, 1)) changed = true; for (int i = 0; i < 4; ++i) { if (adsr[i] <= 0) adsr[i] = minDur; } if (changed) sig = tact::ADSR(adsr[0], adsr[1], adsr[2], adsr[3], amp[0], amp[1]); } void ExponentialDecayNode::update() { bool changed = false; auto cast = (tact::ExponentialDecay*)sig.get(); float amplitude = (float)cast->amplitude; float decay = (float)cast->decay; if (ImGui::DragFloat("Amplitude", &amplitude, 0.001, 0, 1)) changed = true; if (ImGui::DragFloat("Decay", &decay, 0.01, 0.000001, 100)) changed = true; if (changed) sig = tact::ExponentialDecay(amplitude, decay); } /////////////////////////////////////////////////////////////////////////////// void SignalEnvelopeNode::update() { auto cast = sig.getAs<tact::SignalEnvelope>(); root->update(); cast->signal = root->signal(); ImGui::DragDouble("Duration", &cast->duration, 0.001f, 0, 1, "%0.3f s"); ImGui::DragDouble("Amplitude", &cast->amplitude, 0.01f, 0, 1); } /////////////////////////////////////////////////////////////////////////////// void NoiseNode::update() { float gain = (float)sig.gain; float bias = (float)sig.bias; ImGui::DragFloat("Gain", &gain, 0.001f, -1, 1, "%0.3f"); ImGui::DragFloat("Bias", &bias, 0.001f, -1, 1, "%0.3f"); sig.gain = gain; sig.bias = bias; } /////////////////////////////////////////////////////////////////////////////// void TimeNode::update() {} /////////////////////////////////////////////////////////////////////////////// void ScalarNode::update() { auto cast = (tact::Scalar *)sig.get(); float value = (float)cast->value; ImGui::DragFloat("Value", &value, 0.01f, -10, 10); cast->value = value; } /////////////////////////////////////////////////////////////////////////////// void RampNode::update() { auto cast = (tact::Ramp *)sig.get(); float initial = (float)cast->initial; float rate = (float)cast->rate; ImGui::DragFloat("Initial", &initial, 0.01f, -10, 10); ImGui::DragFloat("Rate", &rate, 0.01f, -10, 10); cast->initial = initial; cast->rate = rate; } ///////////////////////////////////////////////////////////////////////////////
30.057386
166
0.526587
[ "render", "vector" ]
49ea90956574d07a1cff71e3db14a56a46302376
2,264
cpp
C++
src/Core/OakVR/Sprite.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/Core/OakVR/Sprite.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/Core/OakVR/Sprite.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
#include "Sprite.h" #include "Utils/RenderUtils.h" #include "Utils/Buffer.h" #include "Interface.h" namespace oakvr { namespace render { Sprite::Sprite(const std::string &name, const oakvr::math::Vector3 &center, float width, float height, const std::string &textureName) : m_name( name ), m_center( center ), m_width{ width }, m_height{ height }, m_textureName( textureName ) { std::vector<oakvr::render::VertexElementDescriptor> ved{ oakvr::render::VertexElementDescriptor::Semantic::position, oakvr::render::VertexElementDescriptor::Semantic::tex_coord, }; oakvr::core::MemoryBuffer vb{ 4 * ComputeVertexStride(ved) * sizeof(float) }; oakvr::core::MemoryBuffer ib{ 2 * 3 * sizeof(uint32_t) }; float pVertices[] = { -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, +0.5f, -0.5f, 0.0f, 1.0f, 0.0f, +0.5f, +0.5f, 0.0f, 1.0f, 1.0f, -0.5f, +0.5f, 0.0f, 0.0f, 1.0f, }; uint32_t pIndices[] = { 0, 1, 2, 0, 2, 3, }; memcpy(vb.GetDataPtr(), pVertices, vb.Size()); memcpy(ib.GetDataPtr(), pIndices, ib.Size()); auto pMaterial = std::make_shared<oakvr::render::Material>("Default"); m_pMesh = oakvr::render::CreateMesh(m_name, ved, vb, 4, ib, pMaterial, { m_textureName }); auto scaleMatrix = oakvr::math::Matrix::Scale(width, height, 1.0f); auto translationMatrix = oakvr::math::Matrix::Translation(m_center); m_pMesh->SetWorldMatrix(translationMatrix * scaleMatrix); } auto Sprite::SetCenterPosition(const oakvr::math::Vector3 &vec) -> void { m_center = vec; auto pMesh = oakvr::render::GetMesh(m_name); auto scaleMatrix = oakvr::math::Matrix::Scale(m_width, m_height, 1.0f); auto translationMatrix = oakvr::math::Matrix::Translation(m_center); m_pMesh->SetWorldMatrix(translationMatrix * scaleMatrix); } auto Sprite::SetScaleFactor(float newScaleFactor) -> void { m_scaleFactor = newScaleFactor; auto pMesh = oakvr::render::GetMesh(m_name); auto scaleMatrix = oakvr::math::Matrix::Scale(m_width * m_scaleFactor, m_height * m_scaleFactor, 1.0f); auto translationMatrix = oakvr::math::Matrix::Translation(m_center); m_pMesh->SetWorldMatrix(translationMatrix * scaleMatrix); } Sprite::~Sprite() { oakvr::render::RemoveMesh(m_name); } } }
32.811594
136
0.67977
[ "render", "vector" ]
49ebc091694ffb176336129ca18f4c4bffc2a32d
1,478
cpp
C++
irg_gazebo_plugins/src/IRGLightFrustaPlugin/LightFrustaPlugin.cpp
nasa/irg_open
737c75fa48f7f72bd8aef54b2faa6d41b5dcfd69
[ "NASA-1.3" ]
7
2020-07-31T10:24:42.000Z
2022-01-06T19:02:56.000Z
irg_gazebo_plugins/src/IRGLightFrustaPlugin/LightFrustaPlugin.cpp
nasa/irg_open
737c75fa48f7f72bd8aef54b2faa6d41b5dcfd69
[ "NASA-1.3" ]
5
2021-02-05T04:43:12.000Z
2022-03-25T18:05:05.000Z
irg_gazebo_plugins/src/IRGLightFrustaPlugin/LightFrustaPlugin.cpp
nasa/irg_open
737c75fa48f7f72bd8aef54b2faa6d41b5dcfd69
[ "NASA-1.3" ]
3
2021-05-07T21:28:51.000Z
2021-11-04T23:25:27.000Z
// The Notices and Disclaimers for Ocean Worlds Autonomy Testbed for Exploration // Research and Simulation can be found in README.md in the root directory of // this repository. #include "LightFrustaPlugin.h" #include <gazebo/rendering/rendering.hh> using namespace irg; using namespace gazebo; GZ_REGISTER_SYSTEM_PLUGIN(LightFrustaPlugin) LightFrustaPlugin::~LightFrustaPlugin() { m_update.reset(); } void LightFrustaPlugin::Load(int _argc, char **_argv) { m_update = event::Events::ConnectPreRender(std::bind(&LightFrustaPlugin::disableLightFrusta, this)); } void LightFrustaPlugin::disableLightFrusta() { rendering::ScenePtr scene = rendering::get_scene(); if (!scene || !scene->Initialized()) { return; } // Iterate over the children for (uint32_t l = 0; l < scene->LightCount(); l++) { rendering::LightPtr light = scene->LightByIndex(l); if (!light) { continue; } // Get the light's visual rendering::VisualPtr visual = scene->GetVisual(light->Name()); if (!visual) { continue; } // Get the scene node and hide its frustum model Ogre::SceneNode* node = visual->GetSceneNode(); // numAttachedObjects() usually returns 0 for link lights. Is it a bug? for (auto i = 0; i < node->numAttachedObjects(); i++) { Ogre::MovableObject* obj = node->getAttachedObject(i); if (obj->getMovableType() != "Light") { obj->setVisible(false); } } } }
24.633333
102
0.668471
[ "model" ]
49eeca26c5447264fd64d78cdfb79465cbba8cdf
77,938
cc
C++
EnergyPlus/HeatBalanceIntRadExchange.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
EnergyPlus/HeatBalanceIntRadExchange.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
1
2020-07-08T13:32:09.000Z
2020-07-08T13:32:09.000Z
EnergyPlus/HeatBalanceIntRadExchange.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
// EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois, // The Regents of the University of California, through Lawrence Berkeley National Laboratory // (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge // National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other // contributors. All rights reserved. // // NOTICE: This Software was developed under funding from the U.S. Department of Energy and the // U.S. Government consequently retains certain rights. As such, the U.S. Government has been // granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable, // worldwide license in the Software to reproduce, distribute copies to the public, prepare // derivative works, and perform publicly and display publicly, and to permit others to do so. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory, // the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form // without changes from the version obtained under this License, or (ii) Licensee makes a // reference solely to the software portion of its product, Licensee must refer to the // software as "EnergyPlus version X" software, where "X" is the version number Licensee // obtained under this License and may not use a different name for the software. Except as // specifically required in this Section (4), Licensee shall not use in a company name, a // product name, in advertising, publicity, or other promotional activities any name, trade // name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly // similar designation, without the U.S. Department of Energy's prior written consent. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // C++ Headers #include <cassert> #include <cmath> // ObjexxFCL Headers #include <ObjexxFCL/Array.functions.hh> #include <ObjexxFCL/ArrayS.functions.hh> #include <ObjexxFCL/Fmath.hh> #include <ObjexxFCL/gio.hh> // EnergyPlus Headers #include <DataEnvironment.hh> #include <DataGlobals.hh> #include <DataHeatBalance.hh> #include <DataIPShortCuts.hh> #include <DataPrecisionGlobals.hh> #include <DataSurfaces.hh> #include <DataSystemVariables.hh> #include <DataTimings.hh> #include <DataViewFactorInformation.hh> #include <DisplayRoutines.hh> #include <General.hh> #include <HeatBalanceIntRadExchange.hh> #include <HeatBalanceMovableInsulation.hh> #include <InputProcessing/InputProcessor.hh> #include <Timer.h> #include <UtilityRoutines.hh> #include <WindowEquivalentLayer.hh> namespace EnergyPlus { #define EP_HBIRE_SEQ namespace HeatBalanceIntRadExchange { // Module containing the routines dealing with the interior radiant exchange // between surfaces. // MODULE INFORMATION: // AUTHOR Rick Strand // DATE WRITTEN September 2000 // MODIFIED Aug 2001, FW: recalculate ScriptF for a zone if window interior // shade/blind status is different from previous time step. This is // because ScriptF, which is used to calculate interior LW // exchange between surfaces, depends on inside surface emissivities, // which, for a window, depends on whether or not an interior // shade or blind is in place. // RE-ENGINEERED na // PURPOSE OF THIS MODULE: // Part of the heat balance modularization/re-engineering. Purpose of this // module is to replace the MRT with RBAL method of modeling radiant exchange // between interior surfaces. // METHODOLOGY EMPLOYED: // Standard EnergyPlus methodology // REFERENCES: // ASHRAE Loads Toolkit "Script F" routines by Curt Pedersen // Hottel, H.C., and A.F. Sarofim. "Radiative Transfer" (mainly chapter 3), // McGraw-Hill, Inc., New York, 1967. // OTHER NOTES: none // Using/Aliasing using namespace DataPrecisionGlobals; using namespace DataGlobals; using namespace DataEnvironment; using namespace DataHeatBalance; using namespace DataSurfaces; using namespace DataSystemVariables; using namespace DataViewFactorInformation; using namespace DataTimings; // Data // MODULE PARAMETER DEFINITIONS static gio::Fmt fmtLD("*"); static gio::Fmt fmtA("(A)"); static gio::Fmt fmtx("(A,I4,1x,A,1x,6f16.8)"); static gio::Fmt fmty("(A,1x,6f16.8)"); // DERIVED TYPE DEFINITIONS // na // MODULE VARIABLE DECLARATIONS: int MaxNumOfZoneSurfaces(0); // Max saved to get large enough space for user input view factors namespace { bool CalcInteriorRadExchangefirstTime(true); // Logical flag for one-time initializations } // SUBROUTINE SPECIFICATIONS FOR MODULE HeatBalanceIntRadExchange // Functions void clear_state() { MaxNumOfZoneSurfaces = 0; CalcInteriorRadExchangefirstTime = true; } void CalcInteriorRadExchange(Array1S<Real64> const SurfaceTemp, // Current surface temperatures int const SurfIterations, // Number of iterations in calling subroutine Array1<Real64> &NetLWRadToSurf, // Net long wavelength radiant exchange from other surfaces Optional_int_const ZoneToResimulate, // if passed in, then only calculate for this zone std::string const &EP_UNUSED(CalledFrom)) { // SUBROUTINE INFORMATION: // AUTHOR Rick Strand // DATE WRITTEN September 2000 // MODIFIED 6/18/01, FCW: calculate IR on windows // Jan 2002, FCW: add blinds with movable slats // Sep 2011 LKL/BG - resimulate only zones needing it for Radiant systems // PURPOSE OF THIS SUBROUTINE: // Determines the interior radiant exchange between surfaces using // Hottel's ScriptF method for the grey interchange between surfaces // in an enclosure. // REFERENCES: // Hottel, H. C. and A. F. Sarofim, Radiative Transfer, Ch 3, McGraw Hill, 1967. // Types typedef Array1<Real64>::size_type size_type; // Using/Aliasing using General::InterpSlatAng; // Function for slat angle interpolation using namespace DataTimings; using HeatBalanceMovableInsulation::EvalInsideMovableInsulation; using WindowEquivalentLayer::EQLWindowInsideEffectiveEmiss; // Argument array dimensioning // SUBROUTINE PARAMETER DEFINITIONS: Real64 const StefanBoltzmannConst(5.6697e-8); // Stefan-Boltzmann constant in W/(m2*K4) static gio::Fmt fmtLD("*"); // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int RecSurfNum; // Counter within DO loop (refers to main surface derived type index) RECEIVING SURFACE int SendSurfNum; // Counter within DO loop (refers to main surface derived type index) SENDING SURFACE int ConstrNumRec; // Receiving surface construction number int ConstrNumSend; // Sending surface construction number Real64 RecSurfTemp; // Receiving surface temperature (C) Real64 SendSurfTemp; // Sending surface temperature (C) Real64 RecSurfEmiss; // Inside surface emissivity int SurfNum; // Surface number int ConstrNum; // Construction number bool IntShadeOrBlindStatusChanged; // True if status of interior shade or blind on at least // one window in a zone has changed from previous time step int ShadeFlag; // Window shading status current time step int ShadeFlagPrev; // Window shading status previous time step // variables added as part of strategy to reduce calculation time - Glazer 2011-04-22 Real64 RecSurfTempInKTo4th; // Receiving surface temperature in K to 4th power static Array1D<Real64> SendSurfaceTempInKto4thPrecalc; // FLOW: #ifdef EP_Detailed_Timings epStartTime("CalcInteriorRadExchange="); #endif if (CalcInteriorRadExchangefirstTime) { InitInteriorRadExchange(); #ifdef EP_HBIRE_SEQ SendSurfaceTempInKto4thPrecalc.allocate(MaxNumOfZoneSurfaces); #else SendSurfaceTempInKto4thPrecalc.allocate(TotSurfaces); #endif CalcInteriorRadExchangefirstTime = false; if (DeveloperFlag) { std::string tdstring; gio::write(tdstring, fmtLD) << " OMP turned off, HBIRE loop executed in serial"; DisplayString(tdstring); } } if (KickOffSimulation || KickOffSizing) return; bool const PartialResimulate(present(ZoneToResimulate)); #ifdef EP_Count_Calls if (!PartialResimulate) { ++NumIntRadExchange_Calls; } else { ++NumIntRadExchangeZ_Calls; } if (CalledFrom.empty()) { // do nothing } else if (CalledFrom == "Main") { ++NumIntRadExchangeMain_Calls; } else if (CalledFrom == "Outside") { ++NumIntRadExchangeOSurf_Calls; } else if (CalledFrom == "Inside") { ++NumIntRadExchangeISurf_Calls; } #endif ConstrNumRec = 0; if (PartialResimulate) { auto const &zone(Zone(ZoneToResimulate)); NetLWRadToSurf({zone.SurfaceFirst, zone.SurfaceLast}) = 0.0; for (int i = zone.SurfaceFirst; i <= zone.SurfaceLast; ++i) SurfaceWindow(i).IRfromParentZone = 0.0; } else { NetLWRadToSurf = 0.0; for (auto &e : SurfaceWindow) e.IRfromParentZone = 0.0; } for (int ZoneNum = (PartialResimulate ? ZoneToResimulate() : 1), ZoneNum_end = (PartialResimulate ? ZoneToResimulate() : NumOfZones); ZoneNum <= ZoneNum_end; ++ZoneNum) { auto const &zone(Zone(ZoneNum)); auto &zone_info(ZoneInfo(ZoneNum)); auto &zone_ScriptF(zone_info.ScriptF); // Tuned Transposed auto &zone_SurfacePtr(zone_info.SurfacePtr); int const n_zone_Surfaces(zone_info.NumOfSurfaces); size_type const s_zone_Surfaces(n_zone_Surfaces); // Calculate ScriptF if first time step in environment and surface heat-balance iterations not yet started; // recalculate ScriptF if status of window interior shades or blinds has changed from // previous time step. This recalculation is required since ScriptF depends on the inside // emissivity of the inside surfaces, which, for windows, is (1) the emissivity of the // inside face of the inside glass layer if there is no interior shade/blind, or (2) the effective // emissivity of the shade/blind if the shade/blind is in place. (The "effective emissivity" // in this case is (1) the shade/blind emissivity if the shade/blind IR transmittance is zero, // or (2) a weighted average of the shade/blind emissivity and inside glass emissivity if the // shade/blind IR transmittance is not zero (which is sometimes the case for a "shade" and // usually the case for a blind). It assumed for switchable glazing that the inside surface // emissivity does not change if the glazing is switched on or off. // Determine if status of interior shade/blind on one or more windows in the zone has changed // from previous time step. Also make a check for any changes in interior movable insulation. if (SurfIterations == 0) { Real64 HMovInsul; // "Resistance" value of movable insulation (if present) Real64 AbsInt; // Absorptivity of movable insulation material (supercedes that of the construction if interior movable insulation is // present) bool IntMovInsulChanged; // True if the status of interior movable insulation has changed IntShadeOrBlindStatusChanged = false; IntMovInsulChanged = false; if (!BeginEnvrnFlag) { // Check for change in shade/blind status for (SurfNum = zone.SurfaceFirst; SurfNum <= zone.SurfaceLast; ++SurfNum) { if (IntShadeOrBlindStatusChanged || IntMovInsulChanged) break; // Need only check if one window's status or one movable insulation status has changed ConstrNum = Surface(SurfNum).Construction; if (Construct(ConstrNum).TypeIsWindow) { ShadeFlag = SurfaceWindow(SurfNum).ShadingFlag; ShadeFlagPrev = SurfaceWindow(SurfNum).ExtIntShadePrevTS; if ((ShadeFlagPrev != IntShadeOn && ShadeFlag == IntShadeOn) || (ShadeFlagPrev != IntBlindOn && ShadeFlag == IntBlindOn) || (ShadeFlagPrev == IntShadeOn && ShadeFlag != IntShadeOn) || (ShadeFlagPrev == IntBlindOn && ShadeFlag != IntBlindOn)) IntShadeOrBlindStatusChanged = true; } else { UpdateMovableInsulationFlag(IntMovInsulChanged, SurfNum); } } } if (IntShadeOrBlindStatusChanged || IntMovInsulChanged || BeginEnvrnFlag) { // Calc inside surface emissivities for this time step for (int ZoneSurfNum = 1; ZoneSurfNum <= n_zone_Surfaces; ++ZoneSurfNum) { SurfNum = zone_SurfacePtr(ZoneSurfNum); ConstrNum = Surface(SurfNum).Construction; zone_info.Emissivity(ZoneSurfNum) = Construct(ConstrNum).InsideAbsorpThermal; auto const &surface_window(SurfaceWindow(SurfNum)); if (Construct(ConstrNum).TypeIsWindow && (surface_window.ShadingFlag == IntShadeOn || surface_window.ShadingFlag == IntBlindOn)) { zone_info.Emissivity(ZoneSurfNum) = InterpSlatAng(surface_window.SlatAngThisTS, surface_window.MovableSlats, surface_window.EffShBlindEmiss) + InterpSlatAng(surface_window.SlatAngThisTS, surface_window.MovableSlats, surface_window.EffGlassEmiss); } if (Surface(SurfNum).MovInsulIntPresent) { HeatBalanceMovableInsulation::EvalInsideMovableInsulation(SurfNum, HMovInsul, AbsInt); zone_info.Emissivity(ZoneSurfNum) = Material(Surface(SurfNum).MaterialMovInsulInt).AbsorpThermal; } } CalcScriptF(n_zone_Surfaces, zone_info.Area, zone_info.F, zone_info.Emissivity, zone_ScriptF); // precalc - multiply by StefanBoltzmannConstant zone_ScriptF *= StefanBoltzmannConst; } } // End of check if SurfIterations = 0 // precalculate the fourth power of surface temperature as part of strategy to reduce calculation time - Glazer 2011-04-22 for (size_type SendZoneSurfNum = 0; SendZoneSurfNum < s_zone_Surfaces; ++SendZoneSurfNum) { SendSurfNum = zone_SurfacePtr[SendZoneSurfNum]; auto const &surface_window(SurfaceWindow(SendSurfNum)); ConstrNumSend = Surface(SendSurfNum).Construction; auto const &construct(Construct(ConstrNumSend)); if (construct.WindowTypeEQL || construct.WindowTypeBSDF) { SendSurfTemp = surface_window.EffInsSurfTemp; } else if (construct.TypeIsWindow && surface_window.OriginalClass != SurfaceClass_TDD_Diffuser) { if (SurfIterations == 0 && surface_window.ShadingFlag <= 0) { SendSurfTemp = surface_window.ThetaFace(2 * construct.TotGlassLayers) - KelvinConv; } else if (surface_window.ShadingFlag == IntShadeOn || surface_window.ShadingFlag == IntBlindOn) { SendSurfTemp = surface_window.EffInsSurfTemp; } else { SendSurfTemp = SurfaceTemp(SendSurfNum); } } else { SendSurfTemp = SurfaceTemp(SendSurfNum); } #ifdef EP_HBIRE_SEQ SendSurfaceTempInKto4thPrecalc[SendZoneSurfNum] = pow_4(SendSurfTemp + KelvinConv); #else SendSurfaceTempInKto4thPrecalc(SendSurfNum) = pow_4(SendSurfTemp + KelvinConv); #endif } // These are the money loops size_type lSR(0u); for (size_type RecZoneSurfNum = 0; RecZoneSurfNum < s_zone_Surfaces; ++RecZoneSurfNum) { RecSurfNum = zone_SurfacePtr[RecZoneSurfNum]; ConstrNumRec = Surface(RecSurfNum).Construction; auto const &construct(Construct(ConstrNumRec)); auto &surface_window(SurfaceWindow(RecSurfNum)); auto &netLWRadToRecSurf(NetLWRadToSurf(RecSurfNum)); if (construct.WindowTypeEQL) { RecSurfEmiss = EQLWindowInsideEffectiveEmiss(ConstrNumRec); RecSurfTemp = surface_window.EffInsSurfTemp; } else if (construct.WindowTypeBSDF && surface_window.ShadingFlag == IntShadeOn) { RecSurfTemp = surface_window.EffInsSurfTemp; RecSurfEmiss = surface_window.EffShBlindEmiss[0] + surface_window.EffGlassEmiss[0]; } else if (construct.TypeIsWindow && surface_window.OriginalClass != SurfaceClass_TDD_Diffuser) { if (SurfIterations == 0 && surface_window.ShadingFlag <= 0) { // If the window is bare this TS and it is the first time through we use the previous TS glass // temperature whether or not the window was shaded in the previous TS. If the window was shaded // the previous time step this temperature is a better starting value than the shade temperature. RecSurfTemp = surface_window.ThetaFace(2 * construct.TotGlassLayers) - KelvinConv; RecSurfEmiss = construct.InsideAbsorpThermal; // For windows with an interior shade or blind an effective inside surface temp // and emiss is used here that is a weighted combination of shade/blind and glass temp and emiss. } else if (surface_window.ShadingFlag == IntShadeOn || surface_window.ShadingFlag == IntBlindOn) { RecSurfTemp = surface_window.EffInsSurfTemp; RecSurfEmiss = InterpSlatAng(surface_window.SlatAngThisTS, surface_window.MovableSlats, surface_window.EffShBlindEmiss) + InterpSlatAng(surface_window.SlatAngThisTS, surface_window.MovableSlats, surface_window.EffGlassEmiss); } else { RecSurfTemp = SurfaceTemp(RecSurfNum); RecSurfEmiss = construct.InsideAbsorpThermal; } } else { RecSurfTemp = SurfaceTemp(RecSurfNum); RecSurfEmiss = construct.InsideAbsorpThermal; } // precalculate the fourth power of surface temperature as part of strategy to reduce calculation time - Glazer 2011-04-22 RecSurfTempInKTo4th = pow_4(RecSurfTemp + KelvinConv); // IF (ABS(RecSurfTempInKTo4th) > 1.d100) THEN // SendZoneSurfNum=0 // ENDIF // Calculate net long-wave radiation for opaque surfaces and incident // long-wave radiation for windows. if (construct.TypeIsWindow) { // Window Real64 scriptF_acc(0.0); // Local accumulator Real64 netLWRadToRecSurf_cor(0.0); // Correction Real64 IRfromParentZone_acc(0.0); // Local accumulator for (size_type SendZoneSurfNum = 0; SendZoneSurfNum < s_zone_Surfaces; ++SendZoneSurfNum, ++lSR) { Real64 const scriptF(zone_ScriptF[lSR]); // [ lSR ] == ( SendZoneSurfNum+1, RecZoneSurfNum+1 ) #ifdef EP_HBIRE_SEQ Real64 const scriptF_temp_ink_4th(scriptF * SendSurfaceTempInKto4thPrecalc[SendZoneSurfNum]); #else SendSurfNum = zone_SurfacePtr[SendZoneSurfNum] - 1; Real64 const scriptF_temp_ink_4th(scriptF * SendSurfaceTempInKto4thPrecalc[SendSurfNum]); #endif // Calculate interior LW incident on window rather than net LW for use in window layer heat balance calculation. IRfromParentZone_acc += scriptF_temp_ink_4th; if (RecZoneSurfNum != SendZoneSurfNum) { scriptF_acc += scriptF; } else { netLWRadToRecSurf_cor = scriptF_temp_ink_4th; } // Per BG -- this should never happened. (CR6346,CR6550 caused this to be put in. Now removed. LKL 1/2013) // IF (SurfaceWindow(RecSurfNum)%IRfromParentZone < 0.0) THEN // CALL ShowRecurringWarningErrorAtEnd('CalcInteriorRadExchange: Window_IRFromParentZone negative, Window="'// & // TRIM(Surface(RecSurfNum)%Name)//'"', & // SurfaceWindow(RecSurfNum)%IRErrCount) // CALL ShowRecurringContinueErrorAtEnd('..occurs in Zone="'//TRIM(Surface(RecSurfNum)%ZoneName)// & // '", reset to 0.0 for remaining calculations.',SurfaceWindow(RecSurfNum)%IRErrCountC) // SurfaceWindow(RecSurfNum)%IRfromParentZone=0.0 // ENDIF } netLWRadToRecSurf += IRfromParentZone_acc - netLWRadToRecSurf_cor - (scriptF_acc * RecSurfTempInKTo4th); surface_window.IRfromParentZone += IRfromParentZone_acc / RecSurfEmiss; } else { Real64 netLWRadToRecSurf_acc(0.0); // Local accumulator for (size_type SendZoneSurfNum = 0; SendZoneSurfNum < s_zone_Surfaces; ++SendZoneSurfNum, ++lSR) { if (RecZoneSurfNum != SendZoneSurfNum) { #ifdef EP_HBIRE_SEQ netLWRadToRecSurf_acc += zone_ScriptF[lSR] * (SendSurfaceTempInKto4thPrecalc[SendZoneSurfNum] - RecSurfTempInKTo4th); // [ lSR ] == ( SendZoneSurfNum+1, RecZoneSurfNum+1 ) #else SendSurfNum = zone_SurfacePtr[SendZoneSurfNum] - 1; netLWRadToRecSurf_acc += zone_ScriptF[lSR] * (SendSurfaceTempInKto4thPrecalc[SendSurfNum] - RecSurfTempInKTo4th); // [ lSR ] == ( SendZoneSurfNum+1, RecZoneSurfNum+1 ) #endif } } netLWRadToRecSurf += netLWRadToRecSurf_acc; } } } #ifdef EP_Detailed_Timings epStopTime("CalcInteriorRadExchange="); #endif } void UpdateMovableInsulationFlag(bool &MovableInsulationChange, int const SurfNum) { // SUBROUTINE INFORMATION: // AUTHOR Rick Strand // DATE WRITTEN July 2016 // PURPOSE OF THIS SUBROUTINE: // To determine if any changes in interior movable insulation have happened. // If there have been changes due to a schedule change AND a change in properties, // then the matrices which are used to calculate interior radiation must be recalculated. MovableInsulationChange = false; if (Surface(SurfNum).MaterialMovInsulInt > 0) { Real64 HMovInsul; // "Resistance" value of movable insulation (if present) Real64 AbsInt; // Absorptivity of movable insulation material (supercedes that of the construction if interior movable insulation is present) HeatBalanceMovableInsulation::EvalInsideMovableInsulation(SurfNum, HMovInsul, AbsInt); } else { Surface(SurfNum).MovInsulIntPresent = false; } if ((Surface(SurfNum).MovInsulIntPresent != Surface(SurfNum).MovInsulIntPresentPrevTS)) { auto const &thissurf(Surface(SurfNum)); Real64 AbsorpDiff; AbsorpDiff = abs(Construct(thissurf.Construction).InsideAbsorpThermal - Material(thissurf.MaterialMovInsulInt).AbsorpThermal); if (AbsorpDiff > 0.01) MovableInsulationChange = true; } } void InitInteriorRadExchange() { // SUBROUTINE INFORMATION: // AUTHOR Rick Strand // DATE WRITTEN September 2000 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Initializes the various parameters for Hottel's ScriptF method for // the grey interchange between surfaces in an enclosure. // Using/Aliasing using namespace DataIPShortCuts; using General::RoundSigDigits; using General::ScanForReports; // SUBROUTINE PARAMETER DEFINITIONS: static gio::Fmt AFormat("(A)"); // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int NumOfZoneSurfaces; // total number of surfaces in the zone. int ZoneNum; // DO loop counter for zones int ZoneSurfNum; // DO loop counter for surfaces within a zone (refers to local derived type arrays) int Findex; // index to print view factors int Vindex; // index for vertices int NumZonesWithUserFbyS; // Zones with user input, used for flag here bool NoUserInputF; // Logical flag signifying no input F's for zone static bool ViewFactorReport; // Flag to output view factor report in eio file static bool ErrorsFound(false); Real64 CheckValue1; Real64 CheckValue2; Real64 FinalCheckValue; Array2D<Real64> SaveApproximateViewFactors; // Save for View Factor reporting Real64 RowSum; Real64 FixedRowSum; int NumIterations; std::string Option1; // view factor report option // FLOW: ZoneInfo.allocate(NumOfZones); // Allocate the entire derived type ScanForReports("ViewFactorInfo", ViewFactorReport, _, Option1); if (ViewFactorReport) { // Print heading gio::write(OutputFileInits, fmtA) << "! <Surface View Factor and Grey Interchange Information>"; gio::write(OutputFileInits, fmtA) << "! <View Factor - Zone Information>,Zone Name,Number of Surfaces"; gio::write(OutputFileInits, fmtA) << "! <View Factor - Surface Information>,Surface Name,Surface Class,Area {m2},Azimuth,Tilt,Thermal Emissivity,#Sides,Vertices"; gio::write(OutputFileInits, fmtA) << "! <View Factor / Grey Interchange Type>,Surface Name(s)"; gio::write(OutputFileInits, fmtA) << "! <View Factor>,Surface Name,Surface Class,Row Sum,View Factors for each Surface"; } cCurrentModuleObject = "ZoneProperty:UserViewFactors:bySurfaceName"; NumZonesWithUserFbyS = inputProcessor->getNumObjectsFound(cCurrentModuleObject); MaxNumOfZoneSurfaces = 0; for (ZoneNum = 1; ZoneNum <= NumOfZones; ++ZoneNum) { if (ZoneNum == 1) { if (DisplayAdvancedReportVariables) gio::write(OutputFileInits, fmtA) << "! <Surface View Factor Check Values>,Zone Name,Original Check Value,Calculated Fixed Check " "Value,Final Check Value,Number of Iterations,Fixed RowSum Convergence,Used RowSum " "Convergence"; } ZoneInfo(ZoneNum).Name = Zone(ZoneNum).Name; NumOfZoneSurfaces = 0; for (int SurfNum = Zone(ZoneNum).SurfaceFirst, SurfNum_end = Zone(ZoneNum).SurfaceLast; SurfNum <= SurfNum_end; ++SurfNum) { if (Surface(SurfNum).HeatTransSurf) ++NumOfZoneSurfaces; } ZoneInfo(ZoneNum).NumOfSurfaces = NumOfZoneSurfaces; MaxNumOfZoneSurfaces = max(MaxNumOfZoneSurfaces, NumOfZoneSurfaces); if (NumOfZoneSurfaces < 1) ShowFatalError("No surfaces in a zone in InitInteriorRadExchange"); // Allocate the parts of the derived type ZoneInfo(ZoneNum).F.dimension(NumOfZoneSurfaces, NumOfZoneSurfaces, 0.0); ZoneInfo(ZoneNum).ScriptF.dimension(NumOfZoneSurfaces, NumOfZoneSurfaces, 0.0); ZoneInfo(ZoneNum).Area.dimension(NumOfZoneSurfaces, 0.0); ZoneInfo(ZoneNum).Emissivity.dimension(NumOfZoneSurfaces, 0.0); ZoneInfo(ZoneNum).Azimuth.dimension(NumOfZoneSurfaces, 0.0); ZoneInfo(ZoneNum).Tilt.dimension(NumOfZoneSurfaces, 0.0); ZoneInfo(ZoneNum).SurfacePtr.dimension(NumOfZoneSurfaces, 0); // Initialize the surface pointer array ZoneSurfNum = 0; for (int SurfNum = Zone(ZoneNum).SurfaceFirst, SurfNum_end = Zone(ZoneNum).SurfaceLast; SurfNum <= SurfNum_end; ++SurfNum) { if (!Surface(SurfNum).HeatTransSurf) continue; ++ZoneSurfNum; ZoneInfo(ZoneNum).SurfacePtr(ZoneSurfNum) = SurfNum; } // Initialize the area and emissivity arrays for (ZoneSurfNum = 1; ZoneSurfNum <= NumOfZoneSurfaces; ++ZoneSurfNum) { int const SurfNum = ZoneInfo(ZoneNum).SurfacePtr(ZoneSurfNum); //************************************************ if (!Construct(Surface(SurfNum).Construction).TypeIsIRT) { ZoneInfo(ZoneNum).Area(ZoneSurfNum) = Surface(SurfNum).Area; } else { // Double area for infrared transparent (IRT) surfaces ZoneInfo(ZoneNum).Area(ZoneSurfNum) = 2.0 * Surface(SurfNum).Area; } //*********************************************** ZoneInfo(ZoneNum).Emissivity(ZoneSurfNum) = Construct(Surface(SurfNum).Construction).InsideAbsorpThermal; ZoneInfo(ZoneNum).Azimuth(ZoneSurfNum) = Surface(SurfNum).Azimuth; ZoneInfo(ZoneNum).Tilt(ZoneSurfNum) = Surface(SurfNum).Tilt; } if (NumOfZoneSurfaces == 1) { // If there is only one surface in a zone, then there is no radiant exchange ZoneInfo(ZoneNum).F = 0.0; ZoneInfo(ZoneNum).ScriptF = 0.0; if (DisplayAdvancedReportVariables) gio::write(OutputFileInits, fmtA) << "Surface View Factor Check Values," + Zone(ZoneNum).Name + ",0,0,0,-1,0,0"; continue; // Go to the next zone in the ZoneNum DO loop } // Get user supplied view factors if available in idf. NoUserInputF = true; if (NumZonesWithUserFbyS > 0) { GetInputViewFactorsbyName(ZoneInfo(ZoneNum).Name, NumOfZoneSurfaces, ZoneInfo(ZoneNum).F, ZoneInfo(ZoneNum).SurfacePtr, NoUserInputF, ErrorsFound); // Obtains user input view factors from input file } if (NoUserInputF) { // Calculate the view factors and make sure they satisfy reciprocity CalcApproximateViewFactors(NumOfZoneSurfaces, ZoneInfo(ZoneNum).Area, ZoneInfo(ZoneNum).Azimuth, ZoneInfo(ZoneNum).Tilt, ZoneInfo(ZoneNum).F, ZoneInfo(ZoneNum).SurfacePtr); } if (ViewFactorReport) { // Allocate and save user or approximate view factors for reporting. SaveApproximateViewFactors.allocate(NumOfZoneSurfaces, NumOfZoneSurfaces); SaveApproximateViewFactors = ZoneInfo(ZoneNum).F; } FixViewFactors(NumOfZoneSurfaces, ZoneInfo(ZoneNum).Area, ZoneInfo(ZoneNum).F, ZoneNum, CheckValue1, CheckValue2, FinalCheckValue, NumIterations, FixedRowSum); // Calculate the script F factors CalcScriptF(NumOfZoneSurfaces, ZoneInfo(ZoneNum).Area, ZoneInfo(ZoneNum).F, ZoneInfo(ZoneNum).Emissivity, ZoneInfo(ZoneNum).ScriptF); if (ViewFactorReport) { // Write to SurfInfo File // Zone Surface Information Output gio::write(OutputFileInits, fmtA) << "Surface View Factor - Zone Information," + ZoneInfo(ZoneNum).Name + ',' + RoundSigDigits(NumOfZoneSurfaces); for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { gio::write(OutputFileInits, "(A,',',A,$)") << "Surface View Factor - Surface Information," + Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name + ',' + cSurfaceClass(Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Class) << RoundSigDigits(ZoneInfo(ZoneNum).Area(SurfNum), 4) + ',' + RoundSigDigits(ZoneInfo(ZoneNum).Azimuth(SurfNum), 4) + ',' + RoundSigDigits(ZoneInfo(ZoneNum).Tilt(SurfNum), 4) + ',' + RoundSigDigits(ZoneInfo(ZoneNum).Emissivity(SurfNum), 4) + ',' + RoundSigDigits(Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Sides); for (Vindex = 1; Vindex <= Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Sides; ++Vindex) { auto &Vertex = Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Vertex(Vindex); gio::write(OutputFileInits, "(3(',',A),$)") << RoundSigDigits(Vertex.x, 4) << RoundSigDigits(Vertex.y, 4) << RoundSigDigits(Vertex.z, 4); } gio::write(OutputFileInits); } gio::write(OutputFileInits, "(A,A,$)") << "Approximate or User Input ViewFactors" << ",To Surface,Surface Class,RowSum"; for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { gio::write(OutputFileInits, "(',',A,$)") << Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name; } gio::write(OutputFileInits); for (Findex = 1; Findex <= NumOfZoneSurfaces; ++Findex) { RowSum = sum(SaveApproximateViewFactors(_, Findex)); gio::write(OutputFileInits, "(A,3(',',A),$)") << "View Factor" << Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Name << cSurfaceClass(Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Class) << RoundSigDigits(RowSum, 4); for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { gio::write(OutputFileInits, "(',',A,$)") << RoundSigDigits(SaveApproximateViewFactors(SurfNum, Findex), 4); } gio::write(OutputFileInits); } } if (ViewFactorReport) { gio::write(OutputFileInits, "(A,A,$)") << "Final ViewFactors" << ",To Surface,Surface Class,RowSum"; for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { gio::write(OutputFileInits, "(',',A,$)") << Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name; } gio::write(OutputFileInits); for (Findex = 1; Findex <= NumOfZoneSurfaces; ++Findex) { RowSum = sum(ZoneInfo(ZoneNum).F(_, Findex)); gio::write(OutputFileInits, "(A,3(',',A),$)") << "View Factor" << Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Name << cSurfaceClass(Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Class) << RoundSigDigits(RowSum, 4); for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { gio::write(OutputFileInits, "(',',A,$)") << RoundSigDigits(ZoneInfo(ZoneNum).F(SurfNum, Findex), 4); } gio::write(OutputFileInits); } if (Option1 == "IDF") { gio::write(OutputFileDebug, fmtA) << "!======== original input factors ==========================="; gio::write(OutputFileDebug, fmtA) << "ZoneProperty:UserViewFactors:bySurfaceName," + ZoneInfo(ZoneNum).Name + ','; for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { for (Findex = 1; Findex <= NumOfZoneSurfaces; ++Findex) { if (!(SurfNum == NumOfZoneSurfaces && Findex == NumOfZoneSurfaces)) { gio::write(OutputFileDebug, fmtA) << " " + Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name + ',' + Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Name + ',' + RoundSigDigits(ZoneInfo(ZoneNum).F(Findex, SurfNum), 6) + ','; } else { gio::write(OutputFileDebug, fmtA) << " " + Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name + ',' + Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Name + ',' + RoundSigDigits(ZoneInfo(ZoneNum).F(Findex, SurfNum), 6) + ';'; } } } gio::write(OutputFileDebug, fmtA) << "!============= end of data ======================"; gio::write(OutputFileDebug, fmtA) << "!============ final view factors ======================="; gio::write(OutputFileDebug, fmtA) << "ZoneProperty:UserViewFactors:bySurfaceName," + ZoneInfo(ZoneNum).Name + ','; for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { for (Findex = 1; Findex <= NumOfZoneSurfaces; ++Findex) { if (!(SurfNum == NumOfZoneSurfaces && Findex == NumOfZoneSurfaces)) { gio::write(OutputFileDebug, fmtA) << " " + Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name + ',' + Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Name + ',' + RoundSigDigits(ZoneInfo(ZoneNum).F(Findex, SurfNum), 6) + ','; } else { gio::write(OutputFileDebug, fmtA) << " " + Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name + ',' + Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Name + ',' + RoundSigDigits(ZoneInfo(ZoneNum).F(Findex, SurfNum), 6) + ';'; } } } gio::write(OutputFileDebug, fmtA) << "!============= end of data ======================"; } } if (ViewFactorReport) { gio::write(OutputFileInits, "(A,A,$)") << "Script F Factors" << ",X Surface"; for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { gio::write(OutputFileInits, "(',',A,$)") << Surface(ZoneInfo(ZoneNum).SurfacePtr(SurfNum)).Name; } gio::write(OutputFileInits); for (Findex = 1; Findex <= NumOfZoneSurfaces; ++Findex) { gio::write(OutputFileInits, "(A,',',A,$)") << "Script F Factor" << Surface(ZoneInfo(ZoneNum).SurfacePtr(Findex)).Name; for (int SurfNum = 1; SurfNum <= NumOfZoneSurfaces; ++SurfNum) { gio::write(OutputFileInits, "(',',A,$)") << RoundSigDigits(ZoneInfo(ZoneNum).ScriptF(Findex, SurfNum), 4); } gio::write(OutputFileInits); } } if (ViewFactorReport) { // Deallocate saved approximate/user view factors SaveApproximateViewFactors.deallocate(); } RowSum = 0.0; for (Findex = 1; Findex <= NumOfZoneSurfaces; ++Findex) { RowSum += sum(ZoneInfo(ZoneNum).F(_, Findex)); } RowSum = std::abs(RowSum - NumOfZoneSurfaces); FixedRowSum = std::abs(FixedRowSum - NumOfZoneSurfaces); if (DisplayAdvancedReportVariables) { gio::write(OutputFileInits, "(8A)") << "Surface View Factor Check Values," + Zone(ZoneNum).Name + ',' + RoundSigDigits(CheckValue1, 6) + ',' + RoundSigDigits(CheckValue2, 6) + ',' + RoundSigDigits(FinalCheckValue, 6) + ',' + RoundSigDigits(NumIterations) + ',' + RoundSigDigits(FixedRowSum, 6) + ',' + RoundSigDigits(RowSum, 6); } } if (ErrorsFound) { ShowFatalError("InitInteriorRadExchange: Errors found during initialization of radiant exchange. Program terminated."); } } void GetInputViewFactors(std::string const &ZoneName, // Needed to check for user input view factors. int const N, // NUMBER OF SURFACES Array2A<Real64> F, // USER INPUT DIRECT VIEW FACTOR MATRIX (N X N) Array1A_int const SPtr, // pointer to actual surface number bool &NoUserInputF, // Flag signifying no input F's for this bool &ErrorsFound // True when errors are found in number of fields vs max args ) { // SUBROUTINE INFORMATION: // AUTHOR Curt Pedersen // DATE WRITTEN September 2005 // MODIFIED Linda Lawrie;September 2010 // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This routine gets the user view factor info. // Using/Aliasing using namespace DataIPShortCuts; using General::TrimSigDigits; // Argument array dimensioning F.dim(N, N); SPtr.dim(N); // SUBROUTINE LOCAL VARIABLE DECLARATIONS: // INTEGER :: NumZonesWithUserF int UserFZoneIndex; int NumAlphas; int NumNums; int IOStat; int index; int inx1; int inx2; // unused CHARACTER(len=MaxNameLength), ALLOCATABLE, DIMENSION(:) :: ZoneSurfaceNames NoUserInputF = true; UserFZoneIndex = inputProcessor->getObjectItemNum("ZoneProperty:UserViewFactors", ZoneName); if (UserFZoneIndex > 0) { NoUserInputF = false; inputProcessor->getObjectItem("ZoneProperty:UserViewFactors", UserFZoneIndex, cAlphaArgs, NumAlphas, rNumericArgs, NumNums, IOStat, lNumericFieldBlanks, lAlphaFieldBlanks, cAlphaFieldNames, cNumericFieldNames); if (NumNums < 3 * pow_2(N)) { ShowSevereError("GetInputViewFactors: " + cCurrentModuleObject + "=\"" + ZoneName + "\", not enough values."); ShowContinueError("...Number of input values [" + TrimSigDigits(NumNums) + "] is less than the required number=[" + TrimSigDigits(3 * pow_2(N)) + "]."); ErrorsFound = true; NumNums = 0; } F = 0.0; for (index = 1; index <= NumNums; index += 3) { inx1 = rNumericArgs(index); inx2 = rNumericArgs(index + 1); F(inx2, inx1) = rNumericArgs(index + 2); } } } void GetInputViewFactorsbyName(std::string const &ZoneName, // Needed to check for user input view factors. int const N, // NUMBER OF SURFACES Array2A<Real64> F, // USER INPUT DIRECT VIEW FACTOR MATRIX (N X N) Array1A_int const SPtr, // pointer to actual surface number bool &NoUserInputF, // Flag signifying no input F's for this bool &ErrorsFound // True when errors are found in number of fields vs max args ) { // SUBROUTINE INFORMATION: // AUTHOR Curt Pedersen // DATE WRITTEN September 2005 // MODIFIED Linda Lawrie;September 2010 // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This routine gets the user view factor info. // Using/Aliasing using namespace DataIPShortCuts; using General::TrimSigDigits; // Argument array dimensioning F.dim(N, N); SPtr.dim(N); // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int UserFZoneIndex; int NumAlphas; int NumNums; int IOStat; int index; int numinx1; int inx1; int inx2; Array1D_string ZoneSurfaceNames; NoUserInputF = true; UserFZoneIndex = inputProcessor->getObjectItemNum("ZoneProperty:UserViewFactors:bySurfaceName", "zone_name", ZoneName); if (UserFZoneIndex > 0) { ZoneSurfaceNames.allocate(N); for (index = 1; index <= N; ++index) { ZoneSurfaceNames(index) = Surface(SPtr(index)).Name; } NoUserInputF = false; inputProcessor->getObjectItem("ZoneProperty:UserViewFactors:bySurfaceName", UserFZoneIndex, cAlphaArgs, NumAlphas, rNumericArgs, NumNums, IOStat, lNumericFieldBlanks, lAlphaFieldBlanks, cAlphaFieldNames, cNumericFieldNames); if (NumNums < pow_2(N)) { ShowSevereError("GetInputViewFactors: " + cCurrentModuleObject + "=\"" + ZoneName + "\", not enough values."); ShowContinueError("...Number of input values [" + TrimSigDigits(NumNums) + "] is less than the required number=[" + TrimSigDigits(pow_2(N)) + "]."); ErrorsFound = true; NumNums = 0; // cancel getting any coordinates } F = 0.0; numinx1 = 0; for (index = 2; index <= NumAlphas; index += 2) { inx1 = UtilityRoutines::FindItemInList(cAlphaArgs(index), ZoneSurfaceNames, N); inx2 = UtilityRoutines::FindItemInList(cAlphaArgs(index + 1), ZoneSurfaceNames, N); if (inx1 == 0) { ShowSevereError("GetInputViewFactors: " + cCurrentModuleObject + "=\"" + ZoneName + "\", invalid surface name."); ShowContinueError("...Surface name=\"" + cAlphaArgs(index) + "\", not in this zone."); ErrorsFound = true; } if (inx2 == 0) { ShowSevereError("GetInputViewFactors: " + cCurrentModuleObject + "=\"" + ZoneName + "\", invalid surface name."); ShowContinueError("...Surface name=\"" + cAlphaArgs(index + 2) + "\", not in this zone."); ErrorsFound = true; } ++numinx1; if (inx1 > 0 && inx2 > 0) F(inx2, inx1) = rNumericArgs(numinx1); } ZoneSurfaceNames.deallocate(); } } void CalcApproximateViewFactors(int const N, // NUMBER OF SURFACES Array1A<Real64> const A, // AREA VECTOR- ASSUMED,BE N ELEMENTS LONG Array1A<Real64> const Azimuth, // Facing angle of the surface (in degrees) Array1A<Real64> const Tilt, // Tilt angle of the surface (in degrees) Array2A<Real64> F, // APPROXIMATE DIRECT VIEW FACTOR MATRIX (N X N) Array1A_int const SPtr // pointer to REAL(r64) surface number (for error message) ) { // SUBROUTINE INFORMATION: // AUTHOR Curt Pedersen // DATE WRITTEN July 2000 // MODIFIED March 2001 (RKS) to disallow surfaces facing the same direction to interact radiatively // May 2002 (COP) to include INTMASS, FLOOR, ROOF and CEILING. // RE-ENGINEERED September 2000 (RKS for EnergyPlus) // PURPOSE OF THIS SUBROUTINE: // This subroutine approximates view factors using an area weighting. // This is improved by one degree by not allowing surfaces facing the same // direction to "see" each other. // METHODOLOGY EMPLOYED: // Each surface sees some area of other surfaces within the zone. The view // factors from the surface to the other seen surfaces are defined by their // area over the summed area of seen surfaces. Surfaces facing the same angle // are assumed to not be able to see each other. // Modified May 2002 to cover poorly defined surface orientation. Now all thermal masses, roofs and // ceilings are "seen" by other surfaces. Floors are seen by all other surfaces, but // not by other floors. // REFERENCES: // na // USE STATEMENTS: // na // Argument array dimensioning A.dim(N); Azimuth.dim(N); Tilt.dim(N); F.dim(N, N); SPtr.dim(N); // Locals // SUBROUTINE ARGUMENTS: // SUBROUTINE PARAMETER DEFINITIONS: Real64 const SameAngleLimit(10.0); // If the difference in the azimuth angles are above this value (degrees), // then the surfaces are assumed to be facing different directions. // INTERFACE BLOCK SPECIFICATIONS // na // DERIVED TYPE DEFINITIONS // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int i; // DO loop counters for surfaces in the zone int j; Array1D<Real64> ZoneArea; // Sum of the area of all zone surfaces seen // FLOW: // Calculate the sum of the areas seen by all zone surfaces ZoneArea.dimension(N, 0.0); for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { // Assumption is that a surface cannot see itself or any other surface // that is facing the same direction (has the same azimuth) // Modified to use Class of surface to permit INTMASS to be seen by all surfaces, // FLOOR to be seen by all except other floors, and ROOF and CEILING by all. // Skip same surface if (i == j) continue; // Include INTMASS, FLOOR(for others), CEILING, ROOF and different facing surfaces. // Roofs/ceilings always see floors if ((Surface(SPtr(j)).Class == SurfaceClass_IntMass) || (Surface(SPtr(j)).Class == SurfaceClass_Floor) || (Surface(SPtr(j)).Class == SurfaceClass_Roof && Surface(SPtr(i)).Class == SurfaceClass_Floor) || ((std::abs(Azimuth(i) - Azimuth(j)) > SameAngleLimit) || (std::abs(Tilt(i) - Tilt(j)) > SameAngleLimit))) { // Everything sees internal mass surfaces | Everything except other floors sees floors ZoneArea(i) += A(j); } } if (ZoneArea(i) <= 0.0) { ShowWarningError("CalcApproximateViewFactors: Zero area for all other zone surfaces."); ShowContinueError("Happens for Surface=\"" + Surface(SPtr(i)).Name + "\" in Zone=" + Zone(Surface(SPtr(i)).Zone).Name); } } // Set up the approximate view factors. First these are initialized to all zero. // This will clear out any junk leftover from whenever. Then, for each zone // surface, set the view factor from that surface to other surfaces as the // area of the other surface divided by the sum of the area of all zone surfaces // that the original surface can actually see (calculated above). This will // allow that the sum of all view factors from the original surface to all other // surfaces will equal unity. F(I,J)=0 if I=J or if the surfaces face the same // direction. // Modified to use Class of surface to permit INTMASS to be seen by all surfaces, // FLOOR to be seen by all except other floors, and ROOF and CEILING by all. // The second IF statement is intended to avoid a divide by zero if // there are no other surfaces in the zone that can be seen. F = 0.0; for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { // Skip same surface if (i == j) continue; // Include INTMASS, FLOOR(for others), CEILING/ROOF and different facing surfaces. if ((Surface(SPtr(j)).Class == SurfaceClass_IntMass) || (Surface(SPtr(j)).Class == SurfaceClass_Floor) || (Surface(SPtr(j)).Class == SurfaceClass_Roof) || ((std::abs(Azimuth(i) - Azimuth(j)) > SameAngleLimit) || (std::abs(Tilt(i) - Tilt(j)) > SameAngleLimit))) { if (ZoneArea(i) > 0.0) F(j, i) = A(j) / (ZoneArea(i)); } } } ZoneArea.deallocate(); } void FixViewFactors(int const N, // NUMBER OF SURFACES Array1A<Real64> const A, // AREA VECTOR- ASSUMED,BE N ELEMENTS LONG Array2A<Real64> F, // APPROXIMATE DIRECT VIEW FACTOR MATRIX (N X N) int const ZoneNum, // Zone number being fixe Real64 &OriginalCheckValue, // check of SUM(F) - N Real64 &FixedCheckValue, // check after fixed of SUM(F) - N Real64 &FinalCheckValue, // the one to go with int &NumIterations, // number of iterations to fixed Real64 &RowSum // RowSum of Fixed ) { // SUBROUTINE INFORMATION: // AUTHOR Curt Pedersen // DATE WRITTEN July 2000 // MODIFIED September 2000 (RKS for EnergyPlus) // April 2005,COP added capability to handle a // surface larger than sum of all others (nonenclosure) // by using a Fii view factor for that surface. Process is // now much more robust and stable. // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine fixes approximate view factors and enforces reciprocity // and completeness. // METHODOLOGY EMPLOYED: // A(i)*F(i,j)=A(j)*F(j,i); F(i,i)=0.; SUM(F(i,j)=1.0, j=1,N) // Subroutine takes approximate view factors and enforces reciprocity by // averaging AiFij and AjFji. Then it determines a set of row coefficients // which can be multipled by each AF product to force the sum of AiFij for // each row to equal Ai, and applies them. Completeness is checked, and if // not satisfied, the AF averaging and row modifications are repeated until // completeness is within a preselected small deviation from 1.0 // The routine also checks the number of surfaces and if N<=3, just enforces reciprocity. // REFERENCES: // na // Using/Aliasing using General::RoundSigDigits; // Argument array dimensioning A.dim(N); F.dim(N, N); // Locals // SUBROUTINE ARGUMENTS: // SUBROUTINE PARAMETER DEFINITIONS: Real64 const PrimaryConvergence(0.001); Real64 const DifferenceConvergence(0.00001); // INTERFACE BLOCK SPECIFICATIONS // na // DERIVED TYPE DEFINITIONS // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: Real64 LargestArea; Real64 ConvrgNew; Real64 ConvrgOld; Real64 Accelerator; // RowCoefficient multipler to accelerate convergence Real64 CheckConvergeTolerance; // check value for actual warning bool Converged; int i; int j; static int LargestSurf(0); // FLOW: OriginalCheckValue = std::abs(sum(F) - N); // Allocate and zero arrays Array2D<Real64> FixedAF(F); // store for largest area check Accelerator = 1.0; ConvrgOld = 10.0; LargestArea = maxval(A); // Check for Strange Geometry if (LargestArea > (sum(A) - LargestArea)) { for (i = 1; i <= N; ++i) { if (LargestArea != A(i)) continue; LargestSurf = i; break; } FixedAF(LargestSurf, LargestSurf) = min(0.9, 1.2 * LargestArea / sum(A)); // Give self view to big surface } // Set up AF matrix. Array2D<Real64> AF(N, N); // = (AREA * DIRECT VIEW FACTOR) MATRIX for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { AF(j, i) = FixedAF(j, i) * A(i); } } // Enforce reciprocity by averaging AiFij and AjFji FixedAF = 0.5 * (AF + transpose(AF)); // Performance Slow way to average with transpose (heap use) AF.deallocate(); Array2D<Real64> FixedF(N, N); // CORRECTED MATRIX OF VIEW FACTORS (N X N) NumIterations = 0; RowSum = 0.0; // Check for physically unreasonable enclosures. if (N <= 3) { for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { FixedF(j, i) = FixedAF(j, i) / A(i); } } ShowWarningError("Surfaces in Zone=\"" + Zone(ZoneNum).Name + "\" do not define an enclosure."); ShowContinueError("Number of surfaces <= 3, view factors are set to force reciprocity but may not fulfill completeness."); ShowContinueError("Reciprocity means that radiant exchange between two surfaces will match and not lead to an energy loss."); ShowContinueError("Completeness means that all of the view factors between a surface and the other surfaces in a zone add up to unity."); ShowContinueError("So, when there are three or less surfaces in a zone, EnergyPlus will make sure there are no losses of energy but"); ShowContinueError( "it will not exchange the full amount of radiation with the rest of the zone as it would if there was a completed enclosure."); RowSum = sum(FixedF); if (RowSum > (N + 0.01)) { // Reciprocity enforced but there is more radiation than possible somewhere since the sum of one of the rows // is now greater than unity. This should not be allowed as it can cause issues with the heat balance. // Correct this by finding the largest row summation and dividing all of the elements in the F matrix by // this max summation. This will provide a cap on radiation so that no row has a sum greater than unity // and will still maintain reciprocity. Array1D<Real64> sumFixedF; Real64 MaxFixedFRowSum; sumFixedF.allocate(N); sumFixedF = 0.0; for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { sumFixedF(i) += FixedF(i, j); } if (i == 1) { MaxFixedFRowSum = sumFixedF(i); } else { if (sumFixedF(i) > MaxFixedFRowSum) MaxFixedFRowSum = sumFixedF(i); } } sumFixedF.deallocate(); if (MaxFixedFRowSum < 1.0) { ShowFatalError(" FixViewFactors: Three surface or less zone failing ViewFactorFix correction which should never happen."); } else { FixedF *= (1.0 / MaxFixedFRowSum); } RowSum = sum(FixedF); // needs to be recalculated } FinalCheckValue = FixedCheckValue = std::abs(RowSum - N); F = FixedF; Zone(ZoneNum).EnforcedReciprocity = true; return; // Do not iterate, stop with reciprocity satisfied. } // N <= 3 Case // Regular fix cases Array1D<Real64> RowCoefficient(N); Converged = false; while (!Converged) { ++NumIterations; for (i = 1; i <= N; ++i) { // Determine row coefficients which will enforce closure. Real64 const sum_FixedAF_i(sum(FixedAF(_, i))); if (std::abs(sum_FixedAF_i) > 1.0e-10) { RowCoefficient(i) = A(i) / sum_FixedAF_i; } else { RowCoefficient(i) = 1.0; } FixedAF(_, i) *= RowCoefficient(i); } // Enforce reciprocity by averaging AiFij and AjFji FixedAF = 0.5 * (FixedAF + transpose(FixedAF)); // Form FixedF matrix for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { FixedF(j, i) = FixedAF(j, i) / A(i); if (std::abs(FixedF(j, i)) < 1.e-10) { FixedF(j, i) = 0.0; FixedAF(j, i) = 0.0; } } } ConvrgNew = std::abs(sum(FixedF) - N); if (std::abs(ConvrgOld - ConvrgNew) < DifferenceConvergence || ConvrgNew <= PrimaryConvergence) { // Change in sum of Fs must be small. Converged = true; } ConvrgOld = ConvrgNew; if (NumIterations > 400) { // If everything goes bad,enforce reciprocity and go home. // Enforce reciprocity by averaging AiFij and AjFji FixedAF = 0.5 * (FixedAF + transpose(FixedAF)); // Form FixedF matrix for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { FixedF(j, i) = FixedAF(j, i) / A(i); } } Real64 const sum_FixedF(sum(FixedF)); FinalCheckValue = FixedCheckValue = CheckConvergeTolerance = std::abs(sum_FixedF - N); if (CheckConvergeTolerance > 0.005) { ShowWarningError("FixViewFactors: View factors not complete. Check for bad surface descriptions or unenclosed zone=\"" + Zone(ZoneNum).Name + "\"."); ShowContinueError("Enforced reciprocity has tolerance (ideal is 0)=[" + RoundSigDigits(CheckConvergeTolerance, 6) + "], Row Sum (ideal is " + RoundSigDigits(N) + ")=[" + RoundSigDigits(RowSum, 2) + "]."); ShowContinueError("If zone is unusual, or tolerance is on the order of 0.001, view factors are probably OK."); } if (std::abs(FixedCheckValue) < std::abs(OriginalCheckValue)) { F = FixedF; FinalCheckValue = FixedCheckValue; } RowSum = sum_FixedF; return; } } FixedCheckValue = ConvrgNew; if (FixedCheckValue < OriginalCheckValue) { F = FixedF; FinalCheckValue = FixedCheckValue; } else { FinalCheckValue = OriginalCheckValue; RowSum = sum(FixedF); if (std::abs(RowSum - N) < PrimaryConvergence) { F = FixedF; FinalCheckValue = FixedCheckValue; } else { ShowWarningError("FixViewFactors: View factors not complete. Check for bad surface descriptions or unenclosed zone=\"" + Zone(ZoneNum).Name + "\"."); } } } void CalcScriptF(int const N, // Number of surfaces Array1<Real64> const &A, // AREA VECTOR- ASSUMED,BE N ELEMENTS LONG Array2<Real64> const &F, // DIRECT VIEW FACTOR MATRIX (N X N) Array1<Real64> &EMISS, // VECTOR OF SURFACE EMISSIVITIES Array2<Real64> &ScriptF // MATRIX OF SCRIPT F FACTORS (N X N) //Tuned Transposed ) { // SUBROUTINE INFORMATION: // AUTHOR Curt Pedersen // DATE WRITTEN 1980 // MODIFIED July 2000 (COP for the ASHRAE Loads Toolkit) // RE-ENGINEERED September 2000 (RKS for EnergyPlus) // RE-ENGINEERED June 2014 (Stuart Mentzer): Performance tuned // PURPOSE OF THIS SUBROUTINE: // Determines Hottel's ScriptF coefficients which account for the total // grey interchange between surfaces in an enclosure. // METHODOLOGY EMPLOYED: // See reference // REFERENCES: // Hottel, H. C. and A. F. Sarofim, Radiative Transfer, Ch 3, McGraw Hill, 1967. // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENTS: // --Must satisfy reciprocity and completeness: // A(i)*F(i,j)=A(j)*F(j,i); F(i,i)=0.; SUM(F(i,j)=1.0, j=1,N) // SUBROUTINE PARAMETER DEFINITIONS: Real64 const MaxEmissLimit(0.99999); // Limit the emissivity internally/avoid a divide by zero error // INTERFACE BLOCK SPECIFICATIONS // na // DERIVED TYPE DEFINITIONS // na // Validate argument array dimensions assert(N >= 0); // Do we need to allow for N==0? assert((A.l() == 1) && (A.u() == N)); assert((F.l1() == 1) && (F.u1() == N)); assert((F.l2() == 1) && (F.u2() == N)); assert((EMISS.l() == 1) && (EMISS.u() == N)); assert(equal_dimensions(F, ScriptF)); // SUBROUTINE LOCAL VARIABLE DECLARATIONS: // FLOW: #ifdef EP_Count_Calls ++NumCalcScriptF_Calls; #endif // Load Cmatrix with AF (AREA * DIRECT VIEW FACTOR) matrix Array2D<Real64> Cmatrix(N, N); // = (AF - EMISS/REFLECTANCE) matrix (but plays other roles) assert(equal_dimensions(Cmatrix, F)); // For linear indexing Array2D<Real64>::size_type l(0u); for (int j = 1; j <= N; ++j) { for (int i = 1; i <= N; ++i, ++l) { Cmatrix[l] = A(i) * F[l]; // [ l ] == ( i, j ) } } // Load Cmatrix with (AF - EMISS/REFLECTANCE) matrix Array1D<Real64> Excite(N); // Excitation vector = A*EMISS/REFLECTANCE l = 0u; for (int i = 1; i <= N; ++i, l += N + 1) { Real64 EMISS_i(EMISS(i)); if (EMISS_i > MaxEmissLimit) { // Check/limit EMISS for this surface to avoid divide by zero below EMISS_i = EMISS(i) = MaxEmissLimit; ShowWarningError("A thermal emissivity above 0.99999 was detected. This is not allowed. Value was reset to 0.99999"); } Real64 const EMISS_i_fac(A(i) / (1.0 - EMISS_i)); Excite(i) = -EMISS_i * EMISS_i_fac; // Set up matrix columns for partial radiosity calculation Cmatrix[l] -= EMISS_i_fac; // Coefficient matrix for partial radiosity calculation // [ l ] == ( i, i ) } Array2D<Real64> Cinverse(N, N); // Inverse of Cmatrix CalcMatrixInverse(Cmatrix, Cinverse); // SOLVE THE LINEAR SYSTEM Cmatrix.clear(); // Release memory ASAP // Scale Cinverse colums by excitation to get partial radiosity matrix l = 0u; for (int j = 1; j <= N; ++j) { Real64 const e_j(Excite(j)); for (int i = 1; i <= N; ++i, ++l) { Cinverse[l] *= e_j; // [ l ] == ( i, j ) } } Excite.clear(); // Release memory ASAP // Form Script F matrix transposed assert(equal_dimensions(Cinverse, ScriptF)); // For linear indexing Array2D<Real64>::size_type m(0u); for (int i = 1; i <= N; ++i) { // Inefficient order for cache but can reuse multiplier so faster choice depends on N Real64 const EMISS_i(EMISS(i)); Real64 const EMISS_fac(EMISS_i / (1.0 - EMISS_i)); l = static_cast<Array2D<Real64>::size_type>(i - 1); for (int j = 1; j <= N; ++j, l += N, ++m) { if (i == j) { // ScriptF(I,J) = EMISS(I)/(1.0d0-EMISS(I))*(Jmatrix(I,J)-Delta*EMISS(I)), where Delta=1 ScriptF[m] = EMISS_fac * (Cinverse[l] - EMISS_i); // [ l ] = ( i, j ), [ m ] == ( j, i ) } else { // ScriptF(I,J) = EMISS(I)/(1.0d0-EMISS(I))*(Jmatrix(I,J)-Delta*EMISS(I)), where Delta=0 ScriptF[m] = EMISS_fac * Cinverse[l]; // [ l ] == ( i, j ), [ m ] == ( j, i ) } } } } void CalcMatrixInverse(Array2<Real64> &A, // Matrix: Gets reduced to L\U form Array2<Real64> &I // Returned as inverse matrix ) { // SUBROUTINE INFORMATION: // AUTHOR Jakob Asmundsson // DATE WRITTEN January 1999 // MODIFIED September 2000 (RKS for EnergyPlus) // RE-ENGINEERED June 2014 (Stuart Mentzer): Performance/memory tuning rewrite // PURPOSE OF THIS SUBROUTINE: // To find the inverse of Matrix, using partial pivoting. // METHODOLOGY EMPLOYED: // Inverse is found using partial pivoting and Gauss elimination // REFERENCES: // Any Linear Algebra book // Validation assert(A.square()); assert(A.I1() == A.I2()); assert(equal_dimensions(A, I)); // Initialization int const l(A.l1()); int const u(A.u1()); int const n(u - l + 1); I.to_identity(); // I starts out as identity // Could do row scaling here to improve condition and then check min pivot isn't too small // Compute in-place LU decomposition of [A|I] with row pivoting for (int i = l; i <= u; ++i) { // Find pivot row in column i below diagonal int iPiv = i; Real64 aPiv(std::abs(A(i, i))); auto ik(A.index(i, i + 1)); for (int k = i + 1; k <= u; ++k, ++ik) { Real64 const aAki(std::abs(A[ik])); // [ ik ] == ( i, k ) if (aAki > aPiv) { iPiv = k; aPiv = aAki; } } assert(aPiv != 0.0); //? Is zero pivot possible for some user inputs? If so if test/handler needed // Swap row i with pivot row if (iPiv != i) { auto ji(A.index(l, i)); // [ ji ] == ( j, i ) auto pj(A.index(l, iPiv)); // [ pj ] == ( j, iPiv ) for (int j = l; j <= u; ++j, ji += n, pj += n) { Real64 const Aij(A[ji]); A[ji] = A[pj]; A[pj] = Aij; Real64 const Iij(I[ji]); I[ji] = I[pj]; I[pj] = Iij; } } // Put multipliers in column i and reduce block below A(i,i) Real64 const Aii_inv(1.0 / A(i, i)); for (int k = i + 1; k <= u; ++k) { Real64 const multiplier(A(i, k) * Aii_inv); A(i, k) = multiplier; if (multiplier != 0.0) { auto ji(A.index(i + 1, i)); // [ ji ] == ( j, i ) auto jk(A.index(i + 1, k)); // [ jk ] == ( j, k ) for (int j = i + 1; j <= u; ++j, ji += n, jk += n) { A[jk] -= multiplier * A[ji]; } ji = A.index(l, i); jk = A.index(l, k); for (int j = l; j <= u; ++j, ji += n, jk += n) { Real64 const Iij(I[ji]); if (Iij != 0.0) { I[jk] -= multiplier * Iij; } } } } } // Perform back-substitution on [U|I] to put inverse in I for (int k = u; k >= l; --k) { Real64 const Akk_inv(1.0 / A(k, k)); auto jk(A.index(l, k)); // [ jk ] == ( j, k ) for (int j = l; j <= u; ++j, jk += n) { I[jk] *= Akk_inv; } auto ik(A.index(k, l)); // [ ik ] == ( i, k ) for (int i = l; i < k; ++i, ++ik) { // Eliminate kth column entries from I in rows above k Real64 const Aik(A[ik]); auto ji(A.index(l, i)); // [ ji ] == ( j, i ) auto jk(A.index(l, k)); // [ jk ] == ( k, j ) for (int j = l; j <= u; ++j, ji += n, jk += n) { I[ji] -= Aik * I[jk]; } } } } } // namespace HeatBalanceIntRadExchange } // namespace EnergyPlus
50.906597
150
0.547243
[ "geometry", "vector" ]
49f6c306e8b6bd4cba8c38247a2e728c0cf04afa
17,413
cpp
C++
brlycmbd/CrdBrlyRly/PnlBrlyRlyList_blks.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
brlycmbd/CrdBrlyRly/PnlBrlyRlyList_blks.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
brlycmbd/CrdBrlyRly/PnlBrlyRlyList_blks.cpp
mpsitech/brly-BeamRelay
481ccb3e83ea6151fb78eba293b44ade62a0ec78
[ "MIT" ]
null
null
null
/** * \file PnlBrlyRlyList_blks.cpp * job handler for job PnlBrlyRlyList (implementation of blocks) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 11 Jan 2021 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlBrlyRlyList::VecVDo ******************************************************************************/ uint PnlBrlyRlyList::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butminimizeclick") return BUTMINIMIZECLICK; if (s == "butregularizeclick") return BUTREGULARIZECLICK; if (s == "butnewclick") return BUTNEWCLICK; if (s == "butdeleteclick") return BUTDELETECLICK; if (s == "butfilterclick") return BUTFILTERCLICK; if (s == "butrefreshclick") return BUTREFRESHCLICK; return(0); }; string PnlBrlyRlyList::VecVDo::getSref( const uint ix ) { if (ix == BUTMINIMIZECLICK) return("ButMinimizeClick"); if (ix == BUTREGULARIZECLICK) return("ButRegularizeClick"); if (ix == BUTNEWCLICK) return("ButNewClick"); if (ix == BUTDELETECLICK) return("ButDeleteClick"); if (ix == BUTFILTERCLICK) return("ButFilterClick"); if (ix == BUTREFRESHCLICK) return("ButRefreshClick"); return(""); }; /****************************************************************************** class PnlBrlyRlyList::ContIac ******************************************************************************/ PnlBrlyRlyList::ContIac::ContIac( const uint numFTos ) : Block() { this->numFTos = numFTos; mask = {NUMFTOS}; }; bool PnlBrlyRlyList::ContIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacBrlyRlyList"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacBrlyRlyList"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFTos", numFTos)) add(NUMFTOS); }; return basefound; }; void PnlBrlyRlyList::ContIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacBrlyRlyList"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacBrlyRlyList"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "numFTos", numFTos); xmlTextWriterEndElement(wr); }; set<uint> PnlBrlyRlyList::ContIac::comm( const ContIac* comp ) { set<uint> items; if (numFTos == comp->numFTos) insert(items, NUMFTOS); return(items); }; set<uint> PnlBrlyRlyList::ContIac::diff( const ContIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFTOS}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlBrlyRlyList::ContInf ******************************************************************************/ PnlBrlyRlyList::ContInf::ContInf( const bool ButFilterOn , const uint numFCsiQst ) : Block() { this->ButFilterOn = ButFilterOn; this->numFCsiQst = numFCsiQst; mask = {BUTFILTERON, NUMFCSIQST}; }; void PnlBrlyRlyList::ContInf::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfBrlyRlyList"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfBrlyRlyList"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "ButFilterOn", ButFilterOn); writeUintAttr(wr, itemtag, "sref", "numFCsiQst", numFCsiQst); xmlTextWriterEndElement(wr); }; set<uint> PnlBrlyRlyList::ContInf::comm( const ContInf* comp ) { set<uint> items; if (ButFilterOn == comp->ButFilterOn) insert(items, BUTFILTERON); if (numFCsiQst == comp->numFCsiQst) insert(items, NUMFCSIQST); return(items); }; set<uint> PnlBrlyRlyList::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTFILTERON, NUMFCSIQST}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlBrlyRlyList::StatShr ******************************************************************************/ PnlBrlyRlyList::StatShr::StatShr( const uint ixBrlyVExpstate , const bool ButDeleteActive ) : Block() { this->ixBrlyVExpstate = ixBrlyVExpstate; this->ButDeleteActive = ButDeleteActive; mask = {IXBRLYVEXPSTATE, BUTDELETEACTIVE}; }; void PnlBrlyRlyList::StatShr::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrBrlyRlyList"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrBrlyRlyList"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "srefIxBrlyVExpstate", VecBrlyVExpstate::getSref(ixBrlyVExpstate)); writeBoolAttr(wr, itemtag, "sref", "ButDeleteActive", ButDeleteActive); xmlTextWriterEndElement(wr); }; set<uint> PnlBrlyRlyList::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ixBrlyVExpstate == comp->ixBrlyVExpstate) insert(items, IXBRLYVEXPSTATE); if (ButDeleteActive == comp->ButDeleteActive) insert(items, BUTDELETEACTIVE); return(items); }; set<uint> PnlBrlyRlyList::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXBRLYVEXPSTATE, BUTDELETEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlBrlyRlyList::StgIac ******************************************************************************/ PnlBrlyRlyList::StgIac::StgIac( const uint TcoStaWidth , const uint TcoStoWidth , const uint TcoConWidth , const uint TcoDirWidth , const uint TcoCtdWidth ) : Block() { this->TcoStaWidth = TcoStaWidth; this->TcoStoWidth = TcoStoWidth; this->TcoConWidth = TcoConWidth; this->TcoDirWidth = TcoDirWidth; this->TcoCtdWidth = TcoCtdWidth; mask = {TCOSTAWIDTH, TCOSTOWIDTH, TCOCONWIDTH, TCODIRWIDTH, TCOCTDWIDTH}; }; bool PnlBrlyRlyList::StgIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StgIacBrlyRlyList"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StgitemIacBrlyRlyList"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoStaWidth", TcoStaWidth)) add(TCOSTAWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoStoWidth", TcoStoWidth)) add(TCOSTOWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoConWidth", TcoConWidth)) add(TCOCONWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoDirWidth", TcoDirWidth)) add(TCODIRWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoCtdWidth", TcoCtdWidth)) add(TCOCTDWIDTH); }; return basefound; }; void PnlBrlyRlyList::StgIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StgIacBrlyRlyList"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StgitemIacBrlyRlyList"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "TcoStaWidth", TcoStaWidth); writeUintAttr(wr, itemtag, "sref", "TcoStoWidth", TcoStoWidth); writeUintAttr(wr, itemtag, "sref", "TcoConWidth", TcoConWidth); writeUintAttr(wr, itemtag, "sref", "TcoDirWidth", TcoDirWidth); writeUintAttr(wr, itemtag, "sref", "TcoCtdWidth", TcoCtdWidth); xmlTextWriterEndElement(wr); }; set<uint> PnlBrlyRlyList::StgIac::comm( const StgIac* comp ) { set<uint> items; if (TcoStaWidth == comp->TcoStaWidth) insert(items, TCOSTAWIDTH); if (TcoStoWidth == comp->TcoStoWidth) insert(items, TCOSTOWIDTH); if (TcoConWidth == comp->TcoConWidth) insert(items, TCOCONWIDTH); if (TcoDirWidth == comp->TcoDirWidth) insert(items, TCODIRWIDTH); if (TcoCtdWidth == comp->TcoCtdWidth) insert(items, TCOCTDWIDTH); return(items); }; set<uint> PnlBrlyRlyList::StgIac::diff( const StgIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TCOSTAWIDTH, TCOSTOWIDTH, TCOCONWIDTH, TCODIRWIDTH, TCOCTDWIDTH}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlBrlyRlyList::Tag ******************************************************************************/ void PnlBrlyRlyList::Tag::writeXML( const uint ixBrlyVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagBrlyRlyList"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemBrlyRlyList"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixBrlyVLocale == VecBrlyVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "Cpt", "Relays"); writeStringAttr(wr, itemtag, "sref", "TcoSta", "Start"); writeStringAttr(wr, itemtag, "sref", "TcoSto", "Stop"); writeStringAttr(wr, itemtag, "sref", "TcoCon", "Connection"); writeStringAttr(wr, itemtag, "sref", "TcoDir", "Direction"); writeStringAttr(wr, itemtag, "sref", "TcoCtd", "Connected"); } else if (ixBrlyVLocale == VecBrlyVLocale::DECH) { writeStringAttr(wr, itemtag, "sref", "Cpt", "Verbindungsketten"); writeStringAttr(wr, itemtag, "sref", "TcoSta", "Start"); writeStringAttr(wr, itemtag, "sref", "TcoSto", "Stopp"); writeStringAttr(wr, itemtag, "sref", "TcoCon", "Verbindung"); writeStringAttr(wr, itemtag, "sref", "TcoDir", "Richtung"); writeStringAttr(wr, itemtag, "sref", "TcoCtd", "Verbunden"); }; writeStringAttr(wr, itemtag, "sref", "TxtRecord1", StrMod::cap(VecBrlyVTag::getTitle(VecBrlyVTag::REC, ixBrlyVLocale))); writeStringAttr(wr, itemtag, "sref", "TxtRecord2", StrMod::cap(VecBrlyVTag::getTitle(VecBrlyVTag::EMPLONG, ixBrlyVLocale))); writeStringAttr(wr, itemtag, "sref", "Trs", StrMod::cap(VecBrlyVTag::getTitle(VecBrlyVTag::GOTO, ixBrlyVLocale)) + " ..."); writeStringAttr(wr, itemtag, "sref", "TxtShowing1", StrMod::cap(VecBrlyVTag::getTitle(VecBrlyVTag::SHOWLONG, ixBrlyVLocale))); writeStringAttr(wr, itemtag, "sref", "TxtShowing2", StrMod::cap(VecBrlyVTag::getTitle(VecBrlyVTag::EMPLONG, ixBrlyVLocale))); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlBrlyRlyList::DpchAppData ******************************************************************************/ PnlBrlyRlyList::DpchAppData::DpchAppData() : DpchAppBrly(VecBrlyVDpch::DPCHAPPBRLYRLYLISTDATA) { }; string PnlBrlyRlyList::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlBrlyRlyList::DpchAppData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppBrlyRlyListData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC); if (stgiac.readXML(docctx, basexpath, true)) add(STGIAC); if (stgiacqry.readXML(docctx, basexpath, true)) add(STGIACQRY); } else { contiac = ContIac(); stgiac = StgIac(); stgiacqry = QryBrlyRlyList::StgIac(); }; }; /****************************************************************************** class PnlBrlyRlyList::DpchAppDo ******************************************************************************/ PnlBrlyRlyList::DpchAppDo::DpchAppDo() : DpchAppBrly(VecBrlyVDpch::DPCHAPPBRLYRLYLISTDO) { ixVDo = 0; }; string PnlBrlyRlyList::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlBrlyRlyList::DpchAppDo::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; string srefIxVDo; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppBrlyRlyListDo"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) { ixVDo = VecVDo::getIx(srefIxVDo); add(IXVDO); }; } else { }; }; /****************************************************************************** class PnlBrlyRlyList::DpchEngData ******************************************************************************/ PnlBrlyRlyList::DpchEngData::DpchEngData( const ubigint jref , ContIac* contiac , ContInf* continf , Feed* feedFCsiQst , Feed* feedFTos , StatShr* statshr , StgIac* stgiac , ListBrlyQRlyList* rst , QryBrlyRlyList::StatShr* statshrqry , QryBrlyRlyList::StgIac* stgiacqry , const set<uint>& mask ) : DpchEngBrly(VecBrlyVDpch::DPCHENGBRLYRLYLISTDATA, jref) { if (find(mask, ALL)) this->mask = {JREF, CONTIAC, CONTINF, FEEDFCSIQST, FEEDFTOS, STATSHR, STGIAC, TAG, RST, STATAPPQRY, STATSHRQRY, STGIACQRY}; else this->mask = mask; if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac; if (find(this->mask, CONTINF) && continf) this->continf = *continf; if (find(this->mask, FEEDFCSIQST) && feedFCsiQst) this->feedFCsiQst = *feedFCsiQst; if (find(this->mask, FEEDFTOS) && feedFTos) this->feedFTos = *feedFTos; if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr; if (find(this->mask, STGIAC) && stgiac) this->stgiac = *stgiac; if (find(this->mask, RST) && rst) this->rst = *rst; if (find(this->mask, STATSHRQRY) && statshrqry) this->statshrqry = *statshrqry; if (find(this->mask, STGIACQRY) && stgiacqry) this->stgiacqry = *stgiacqry; }; string PnlBrlyRlyList::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(CONTINF)) ss.push_back("continf"); if (has(FEEDFCSIQST)) ss.push_back("feedFCsiQst"); if (has(FEEDFTOS)) ss.push_back("feedFTos"); if (has(STATSHR)) ss.push_back("statshr"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(TAG)) ss.push_back("tag"); if (has(RST)) ss.push_back("rst"); if (has(STATAPPQRY)) ss.push_back("statappqry"); if (has(STATSHRQRY)) ss.push_back("statshrqry"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlBrlyRlyList::DpchEngData::merge( DpchEngBrly* dpcheng ) { DpchEngData* src = (DpchEngData*) dpcheng; if (src->has(JREF)) {jref = src->jref; add(JREF);}; if (src->has(CONTIAC)) {contiac = src->contiac; add(CONTIAC);}; if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);}; if (src->has(FEEDFCSIQST)) {feedFCsiQst = src->feedFCsiQst; add(FEEDFCSIQST);}; if (src->has(FEEDFTOS)) {feedFTos = src->feedFTos; add(FEEDFTOS);}; if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);}; if (src->has(STGIAC)) {stgiac = src->stgiac; add(STGIAC);}; if (src->has(TAG)) add(TAG); if (src->has(RST)) {rst = src->rst; add(RST);}; if (src->has(STATAPPQRY)) add(STATAPPQRY); if (src->has(STATSHRQRY)) {statshrqry = src->statshrqry; add(STATSHRQRY);}; if (src->has(STGIACQRY)) {stgiacqry = src->stgiacqry; add(STGIACQRY);}; }; void PnlBrlyRlyList::DpchEngData::writeXML( const uint ixBrlyVLocale , xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchEngBrlyRlyListData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/brly"); if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref)); if (has(CONTIAC)) contiac.writeXML(wr); if (has(CONTINF)) continf.writeXML(wr); if (has(FEEDFCSIQST)) feedFCsiQst.writeXML(wr); if (has(FEEDFTOS)) feedFTos.writeXML(wr); if (has(STATSHR)) statshr.writeXML(wr); if (has(STGIAC)) stgiac.writeXML(wr); if (has(TAG)) Tag::writeXML(ixBrlyVLocale, wr); if (has(RST)) rst.writeXML(wr); if (has(STATAPPQRY)) QryBrlyRlyList::StatApp::writeXML(wr); if (has(STATSHRQRY)) statshrqry.writeXML(wr); if (has(STGIACQRY)) stgiacqry.writeXML(wr); xmlTextWriterEndElement(wr); };
30.283478
145
0.646414
[ "vector" ]
49f87971f6082e432280fb1b1e3859c8944442b1
775
cpp
C++
src/math/quaternion.cpp
kullken/ugl
ec8651967643d5cb8bd9ae9e39a082469e96841a
[ "BSD-2-Clause" ]
null
null
null
src/math/quaternion.cpp
kullken/ugl
ec8651967643d5cb8bd9ae9e39a082469e96841a
[ "BSD-2-Clause" ]
null
null
null
src/math/quaternion.cpp
kullken/ugl
ec8651967643d5cb8bd9ae9e39a082469e96841a
[ "BSD-2-Clause" ]
null
null
null
#include "ugl/math/quaternion.h" #include <cassert> #include <cmath> #include "ugl/math/vector.h" namespace ugl::math { UnitQuaternion exp(const Quaternion& q) { [[maybe_unused]] constexpr double tolerance = 1e-6; assert(std::abs(q.w()) < tolerance); // Imaginary quaternion required. Vector3 u = q.vec(); double u_norm = u.norm(); Vector3 v = u.normalized() * std::sin(u_norm); return Quaternion(std::cos(u_norm), v.x(), v.y(), v.z()); } Quaternion log(const UnitQuaternion& q) { [[maybe_unused]] constexpr double tolerance = 1e-6; assert(std::abs(q.norm() - 1) < tolerance); // Unit-norm quaternion required. Vector3 u = q.vec(); Vector3 v = u.normalized() * std::acos(q.w()); return Quaternion(0, v.x(), v.y(), v.z()); } }
25.833333
81
0.634839
[ "vector" ]
49fcecd44f1e29dfa56b105efbbb48838f8b39a2
1,611
cpp
C++
oneEngine/oneGame/source/after/entities/world/environment/CloudSphere.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
8
2017-12-08T02:59:31.000Z
2022-02-02T04:30:03.000Z
oneEngine/oneGame/source/after/entities/world/environment/CloudSphere.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
2
2021-04-16T03:44:42.000Z
2021-08-30T06:48:44.000Z
oneEngine/oneGame/source/after/entities/world/environment/CloudSphere.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
1
2021-04-16T02:09:54.000Z
2021-04-16T02:09:54.000Z
#include "CloudSphere.h" #include "renderer/camera/CCamera.h" #include "renderer/material/glMaterial.h" #include "renderer/logic/model/CModel.h" #include "renderer/texture/CTexture.h" CloudSphere::CloudSphere ( void ) : CGameBehavior() { // Cloudsphere pCloudMat = new glMaterial(); pCloudMat->setTexture( 0, new CTexture( ".res/textures/cloudmap_hf.png" ) ); pCloudMat->passinfo.push_back( glPass() ); pCloudMat->passinfo[0].m_transparency_mode = Renderer::ALPHAMODE_TRANSLUCENT; pCloudMat->passinfo[0].b_depthmask = false; pCloudMat->passinfo[0].shader = new glShader ( ".res/shaders/sky/cloud_stepped.glsl" ); pCloudMat->removeReference(); cloudModel = new CModel ( string("models/geosphere.FBX") ); cloudModel->SetMaterial( pCloudMat ); cloudModel->SetRenderType( Renderer::Secondary ); cloudModel->transform.scale = Vector3d( 300.0,300.0f,-300.0f ); cloudModel->SetFrustumCulling( false ); //cloudModel->SetVisibility( false ); // Disable clouds for now cloudDensity = 0; } CloudSphere::~CloudSphere ( void ) { delete cloudModel; } void CloudSphere::PostUpdate ( void ) { if ( CCamera::activeCamera ) { cloudModel->transform.position = CCamera::activeCamera->transform.position; } /*pCloudMat->setUniform( "gm_Datettime", timeofDay/3600 ); pCloudMat->setUniform( "gm_Stormvalue", cloudDensity );*/ cloudModel->SetShaderUniform( "gm_Datettime", timeofDay/3600 ); cloudModel->SetShaderUniform( "gm_Stormvalue", cloudDensity ); } void CloudSphere::SetTimeOfDay ( const ftype tm ) { timeofDay = tm; } void CloudSphere::SetCloudDensity ( const ftype dn ) { cloudDensity = dn; }
30.396226
88
0.742396
[ "model", "transform" ]
49ffeef3ca792241c94d568a65d8a043cd9b0a23
1,153
hpp
C++
DisjSet.hpp
niceyeti/UnionFind
6c31eb549494f83c0c5d9b0791d7a4fc01094664
[ "Unlicense" ]
null
null
null
DisjSet.hpp
niceyeti/UnionFind
6c31eb549494f83c0c5d9b0791d7a4fc01094664
[ "Unlicense" ]
null
null
null
DisjSet.hpp
niceyeti/UnionFind
6c31eb549494f83c0c5d9b0791d7a4fc01094664
[ "Unlicense" ]
null
null
null
#ifndef DISJ_SET_H #define DISJ_SET_H // DisjSets class // // CONSTRUCTION: with int representing initial number of sets // // ******************PUBLIC OPERATIONS********************* // void union( root1, root2 ) --> Merge two sets // int find( x ) --> Return set containing x // ******************ERRORS******************************** // No error checking is performed #include <vector> #include <iostream> #include "MazeCell.hpp" #define MATRIX_ROWS 25 #define ROWS MATRIX_ROWS #define MATRIX_COLS 50 #define COLS MATRIX_COLS #define LEFT 0 #define DOWN 1 #define RIGHT 2 #define UP 3 using std::vector; using std::cout; using std::endl; using std::string; /** * Disjoint set class. * Use union by rank and path compression. * Elements in the set are numbered starting at 0. */ class DisjSet { public: explicit DisjSet( int numElements ); ~DisjSet(); void clearWall(int cell1, int cell2); void printSet(); void printMaze(); bool sameSets(int i, int j); int find( int x ) const; int findCompress( int x ); void unionSets( int root1, int root2 ); vector<MazeCell> maze; }; #endif
19.542373
61
0.627927
[ "vector" ]
8e6da1175083f0c77e4a5ddfeaa0e71752272e82
5,180
cpp
C++
ABC/loadchecking/loadchecking.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/loadchecking/loadchecking.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
ABC/loadchecking/loadchecking.cpp
keitaronaruse/AtCoderTraining
9fb8f0d492be678a788080c96b06c33992cb6db2
[ "MIT" ]
null
null
null
/** * @file loadchecking.cpp * @brief Load Checking Contest A - 好きな順列 * @author Keitaro Naruse * @date 2022-02-13 * @copyright MIT License * @details https://atcoder.jp/contests/loadchecking/tasks/loadchecking_a */ // # Solution #include <iostream> #include <vector> int main() { // make Ai const int N = 20; std::vector< int > A = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; // make Bi std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 7, 5, 1, 6 }; // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 7, 5, 1, 6 }; // 990 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 7, 5, 6, 1 }; // 995 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 7, 5, 1, 1 }; // 994 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 7, 6, 1, 1 }; // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 7, 1, 1, 1 }; // 991 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 7, 1, 1, 1 }; // 982 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 16, 1, 1, 1 }; // 985 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 18, 1, 1, 1, 1 }; // 968 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 11, 1, 1, 1, 1, 1 }; // 961 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 18, 1, 1, 1, 1, 1 }; // 958 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 16, 1, 1, 1, 1, 1, 1 }; // 956 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 18, 1, 1, 1, 1, 1, 1 }; // 943 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 3, 1, 1, 1, 1, 1, 1, 1 }; // 928 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 18, 1, 1, 1, 1, 1, 1, 1 }; // 941 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 8, 1, 1, 1, 1, 1, 1, 1, 1 }; // 931 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 18, 1, 1, 1, 1, 1, 1, 1, 1 }; // 934 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 920 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 931 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 15, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 928 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 917 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 14, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 913 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 904 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 899 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 892 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 883 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 884 // std::vector< int > B = { 2, 20, 19, 10, 17, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 878 // std::vector< int > B = { 2, 20, 19, 10, 17, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 873 // std::vector< int > B = { 2, 20, 19, 10, 17, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 872 // std::vector< int > B = { 2, 20, 19, 10, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 857 // std::vector< int > B = { 2, 20, 19, 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 849 // std::vector< int > B = { 2, 20, 19, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 848 // std::vector< int > B = { 2, 20, 19, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 830 // std::vector< int > B = { 2, 20, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 811 // std::vector< int > B = { 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // 810 // std::vector< int > B = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // Main for( int i = 0; i < N; i ++ ) { std::cout << B.at( i ) << std::endl; } // Finalize return( 0 ); }
50.291262
114
0.368533
[ "vector" ]
8e6e39063e8b6dc8a218166c50d7132868287d03
4,685
cc
C++
AICSE-demo-student/demo/style_transfer_bcl/src/tf-implementation/tf-add-power-diff/cwise_op_power_difference.cc
iuming/AI_Computer_Systems
b47c4914a23acfdc469e1a80735bf68191b2acba
[ "MIT" ]
5
2020-12-07T03:16:49.000Z
2022-01-08T13:59:20.000Z
AICSE-demo-student/demo/style_transfer_bcl/src/tf-implementation/tf-add-power-diff/cwise_op_power_difference.cc
iuming/AI_Computer_Systems
b47c4914a23acfdc469e1a80735bf68191b2acba
[ "MIT" ]
21
2020-09-25T22:41:00.000Z
2022-03-12T00:50:43.000Z
AICSE-demo-student/demo/style_transfer_bcl/src/tf-implementation/tf-add-power-diff/cwise_op_power_difference.cc
iuming/AI_Computer_Systems
b47c4914a23acfdc469e1a80735bf68191b2acba
[ "MIT" ]
1
2022-02-18T09:01:43.000Z
2022-02-18T09:01:43.000Z
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/cwise_ops_common.h" #include "tensorflow/core/kernels/broadcast_to_op.h" #include "tensorflow/core/util/bcast.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/op.h" //#include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/op_kernel.h" #if CAMBRICON_MLU #include "tensorflow/core/kernels/cwise_op_power_difference_mlu.h" #endif // CAMBRICON_MLU namespace tensorflow { #if CAMBRICON_MLU #define REGISTER_MLU(T) \ REGISTER_KERNEL_BUILDER( \ Name("PowerDifference") \ .Device(DEVICE_MLU) \ .TypeConstraint<T>("T"), \ MLUPowerDifferenceOp<T>); TF_CALL_MLU_FLOAT_TYPES(REGISTER_MLU); #endif // CAMBRICON_MLU //#if CAMBRICON_MLU //REGISTER_KERNEL_BUILDER(Name("PowerDifference") // .Device(DEVICE_MLU) // .TypeConstraint<Eigen::half>("T") // .HostMemory("y"), // MLUPowerDifferenceOp<Eigen::half>); //#endif // CAMBRICON_MLU template <typename T> class PowerDifferenceOp : public OpKernel { public: explicit PowerDifferenceOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& input_x_tensor = context->input(0); const Tensor& input_y_tensor = context->input(1); const Tensor& input_pow_tensor = context->input(2); const Eigen::ThreadPoolDevice& device = context->eigen_device<Eigen::ThreadPoolDevice>(); BCast bcast(BCast::FromShape(input_y_tensor.shape()), BCast::FromShape(input_x_tensor.shape()), /*fewer_dims_optimization=*/true); Tensor* output_tensor = nullptr; TensorShape output_shape = BCast::ToShape(bcast.output_shape()); OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_tensor)); Tensor input_x_broad(input_x_tensor.dtype(), output_shape); Tensor input_y_broad(input_y_tensor.dtype(), output_shape); OP_REQUIRES_OK(context, context->allocate_temp(input_x_tensor.dtype(), output_shape, &input_x_broad)); OP_REQUIRES_OK(context, context->allocate_temp(input_y_tensor.dtype(), output_shape, &input_y_broad)); if (input_x_tensor.IsSameSize(input_x_broad) == false) { functor::BroadcastTo<Eigen::ThreadPoolDevice, T>()(device, context, input_x_broad, output_shape, input_x_tensor, input_x_tensor.shape(), bcast); } else { input_x_broad = input_x_tensor; } if (input_y_tensor.IsSameSize(input_y_broad) == false) { functor::BroadcastTo<Eigen::ThreadPoolDevice, T>()(device, context, input_y_broad, output_shape, input_y_tensor, input_y_tensor.shape(), bcast); } else { input_y_broad = input_y_tensor; } auto input_x = input_x_broad.flat<T>(); auto input_y = input_y_broad.flat<T>(); auto input_pow = input_pow_tensor.flat<T>(); auto output = output_tensor->flat<T>(); const int N = input_x.size(); const int POW = input_pow(0); float tmp = 0; for (int i = 0; i < N; i++) { //output(i) = (input_x(i) - input_y(i)) * (input_x(i) - input_y(i)); tmp = input_x(i) - input_y(i); output(i) = tmp; for (int j = 0; j < POW - 1; j++){ output(i) = output(i) * tmp; } } } }; REGISTER_KERNEL_BUILDER(Name("PowerDifference").Device(DEVICE_CPU), PowerDifferenceOp<float>); } // namespace tensorflow
40.387931
104
0.605977
[ "shape" ]
8e71669cb40ba470503b42446093f8d0eabb706c
727
cc
C++
cpp/984.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/984.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/984.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
/* * https://leetcode.com/problems/string-without-aaa-or-bbb/ */ #include <iostream> #include <vector> #include <string> #include <algorithm> #include <iomanip> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <deque> #include <queue> using namespace std; class Solution984 { public: string strWithout3a3b(int A, int B) { string s; while (A > 0 || B > 0) { if (s.length() >= 2 && s[s.length() - 1] == 'a' && s[s.length() - 2] == 'a') { s += "b"; B--; } else if (s.length() >= 2 && s[s.length() - 1] == 'b' && s[s.length() - 2] == 'b') { s += "a"; A--; } else if (A > B) { s += "a"; A--; } else { s += "b"; B--; } } return s; } };
16.906977
86
0.502063
[ "vector" ]
8e76485ffec55f1db12028e2aadd614d98d381c8
5,511
cpp
C++
examples/cpp/opencv/Example_13_5_LeapDemo.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
135
2015-01-08T03:27:23.000Z
2022-03-06T08:30:21.000Z
examples/cpp/opencv/Example_13_5_LeapDemo.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
34
2015-01-03T10:40:12.000Z
2021-04-15T18:24:02.000Z
examples/cpp/opencv/Example_13_5_LeapDemo.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
80
2015-01-10T08:41:28.000Z
2022-03-06T08:30:24.000Z
#include "Config.h" #ifdef HAVE_LEAP #include <Leap.h> #endif #include "Common.h" #ifdef HAVE_LEAP #include <thread> #include <mutex> /** Minimal demo of using the Leap Motion controller. Unlike other demos, this file relies on the Leap SDK which is not provided on our Github repo. The Leap SDK evolves rapidly, so downloading it and updating the three Leap-specific fields in your CMake config is left as an exercise for the reader. */ struct CaptureData { glm::mat4 leapPose; Leap::Frame frame; }; class LeapHandler : public Leap::Listener { private: bool hasFrame{ false }; Leap::Controller controller; std::thread captureThread; std::mutex mutex; CaptureData frame; ovrHmd hmd; public: LeapHandler(ovrHmd & hmd) : hmd(hmd) { } void startCapture() { controller.addListener(*this); } void stopCapture() { controller.removeListener(*this); } void set(const CaptureData & newFrame) { std::lock_guard<std::mutex> guard(mutex); frame = newFrame; hasFrame = true; } bool get(CaptureData & out) { if (!hasFrame) { return false; } std::lock_guard<std::mutex> guard(mutex); out = frame; hasFrame = false; return true; } void onConnect(const Leap::Controller & controller) { controller.setPolicyFlags(Leap::Controller::PolicyFlag::POLICY_OPTIMIZE_HMD); } void onFrame(const Leap::Controller & controller) { CaptureData frame; frame.frame = controller.frame(); frame.leapPose = ovr::toGlm(ovrHmd_GetTrackingState(hmd, 0.0).HeadPose.ThePose); set(frame); } }; class LeapApp : public RiftApp { const float BALL_RADIUS = 0.05f; protected: LeapHandler captureHandler; ShapeWrapperPtr sphere; ProgramPtr program; CaptureData latestFrame; glm::vec3 ballCenter; public: LeapApp() : captureHandler(hmd) { captureHandler.startCapture(); ballCenter = glm::vec3(0, 0, -0.25); } virtual ~LeapApp() { captureHandler.stopCapture(); } void initGl() { RiftApp::initGl(); program = oria::loadProgram(Resource::SHADERS_LIT_VS, Resource::SHADERS_LITCOLORED_FS); sphere = oria::loadSphere({"Position", "Normal"}, program); oria::bindLights(program); } virtual void update() { if (captureHandler.get(latestFrame)) { Leap::HandList hands = latestFrame.frame.hands(); for (int iHand = 0; iHand < hands.count(); iHand++) { Leap::Hand hand = hands[iHand]; Leap::Finger finger = hand.fingers()[1]; // Index only if (hand.isValid() && finger.isExtended()) { moveBall(finger); } } } } void moveBall(Leap::Finger finger) { glm::vec3 riftCoords = leapToRiftPosition(finger.tipPosition()); riftCoords = glm::vec3(latestFrame.leapPose * glm::vec4(riftCoords, 1)); if (glm::length(riftCoords - ballCenter) <= BALL_RADIUS) { ballCenter.x += (riftCoords.x - ballCenter.x) / 4; ballCenter.y += (riftCoords.y - ballCenter.y) / 4; } } virtual void renderScene() { glClear(GL_DEPTH_BUFFER_BIT); oria::renderSkybox(Resource::IMAGES_SKY_CITY_XNEG_PNG); MatrixStack & mv = Stacks::modelview(); mv.withPush([&]{ mv.transform(latestFrame.leapPose); Leap::HandList hands = latestFrame.frame.hands(); for (int iHand = 0; iHand < hands.count(); iHand++) { Leap::Hand hand = hands[iHand]; if (hand.isValid()) { drawHand(hand); } } }); //GlUtils::draw3dLine(glm::vec3(ballCenter.x, -1000, ballCenter.z), glm::vec3(ballCenter.x, 1000, ballCenter.z)); //GlUtils::draw3dLine(glm::vec3(-1000, ballCenter.y, ballCenter.z), glm::vec3(1000, ballCenter.y, ballCenter.z)); drawSphere(ballCenter, BALL_RADIUS); } void drawHand(const Leap::Hand & hand) { drawSphere(leapToRiftPosition(hand.wristPosition()), 0.02f); for (int f = 0; f < hand.fingers().count(); f++) { Leap::Finger finger = hand.fingers()[f]; if (finger.isValid()) { drawFinger(finger, hand.isLeft()); } } } void drawFinger(const Leap::Finger & finger, bool isLeft) { MatrixStack & mv = Stacks::modelview(); for (int b = 0; b < 4; b++) { mv.withPush([&] { Leap::Bone bone = finger.bone((Leap::Bone::Type) b); glm::vec3 riftCoords = leapToRiftPosition(bone.center()); float length = bone.length() / 1000; mv.translate(riftCoords); mv.transform(leapBasisToRiftBasis(bone.basis(), isLeft)); mv.scale(glm::vec3(0.01, 0.01, length)); oria::renderColorCube(); }); } } void drawSphere(glm::vec3 & pos, float radius) { MatrixStack & mv = Stacks::modelview(); mv.withPush([&]{ mv.translate(pos); mv.scale(radius); oria::renderGeometry(sphere, program); }); } glm::mat4 leapBasisToRiftBasis(Leap::Matrix & mat, bool isLeft) { glm::vec3 x = leapToRift(mat.transformDirection(Leap::Vector(isLeft ? -1 : 1, 0, 0))); glm::vec3 y = leapToRift(mat.transformDirection(Leap::Vector(0, 1, 0))); glm::vec3 z = leapToRift(mat.transformDirection(Leap::Vector(0, 0, 1))); return glm::mat4x4(glm::mat3x3(x, y, z)); } glm::vec3 leapToRift(Leap::Vector & vec) { return glm::vec3(-vec.x, -vec.z, -vec.y); } glm::vec3 leapToRiftPosition(Leap::Vector & vec) { return leapToRift(vec) / 1000.0f + glm::vec3(0, 0, -0.070); } }; RUN_OVR_APP(LeapApp); #else MAIN_DECL { SAY("Leap Motion SDK required for this example"); } #endif
26.118483
117
0.640719
[ "vector", "transform" ]
8e7a3f6189655d6a8100940f0beae3326e5277c1
5,403
cpp
C++
TheRayTracerChallenge/tuples.feature.cpp
erosnick/TheRayTracerChallenge
4375b5a5a0222b59107dca1d61f157f1de3e70fc
[ "MIT" ]
null
null
null
TheRayTracerChallenge/tuples.feature.cpp
erosnick/TheRayTracerChallenge
4375b5a5a0222b59107dca1d61f157f1de3e70fc
[ "MIT" ]
null
null
null
TheRayTracerChallenge/tuples.feature.cpp
erosnick/TheRayTracerChallenge
4375b5a5a0222b59107dca1d61f157f1de3e70fc
[ "MIT" ]
null
null
null
#include "catch.hpp" #include "Tuple.h" SCENARIO("A tuple with w = 1.0 is a point", "[Tuple]") { GIVEN("A = tuple(4.3, -4.2, 3.1, 1.0") { auto a = Tuple(4.3, -4.2, 3.1, 1.0); THEN("a.x == 4.3" "a.y == -4.2" "a.z == 3.1" "a.w == 1.0") { REQUIRE(a.x == 4.3); REQUIRE(a.y == -4.2); REQUIRE(a.z == 3.1); REQUIRE(a.w == 1.0); } } } SCENARIO("A tuple with w = 0.0 is a vector", "[Tuple]") { GIVEN("A = tuple(4.3, -4.2, 3.1, 1.0") { auto a = Tuple(4.3, -4.2, 3.1, 0.0); THEN("a.x == 4.3f" "a.y == -4.2f" "a.z == 3.1" "a.w == 0.0") { REQUIRE(a.x == 4.3); REQUIRE(a.y == -4.2); REQUIRE(a.z == 3.1); REQUIRE(a.w == 0.0); } } } SCENARIO("point() creates tuples with w = 1", "[Tuple]") { GIVEN("p = point(4.0, -4.0, 3.0)") { auto p = point(4.0, -4.0, 3.0); THEN("p == tuple(4, -4, 3, 1)") { REQUIRE(p == Tuple(4.0, -4.0, 3.0, 1.0)); } } } SCENARIO("vector() creates tuples with w = 0", "[Tuple]") { GIVEN("v = point(4.0, -4.0, 3.0)") { auto v = vector(4.0, -4.0, 3.0); THEN("v == tuple(4, -4, 3, 1)") { REQUIRE(v == Tuple(4.0, -4.0, 3.0, 0.0)); } } } SCENARIO("Adding two tuples") { GIVEN("a1 = tuple(3.0, -2.0, 5.0, 1.0") { auto a1 = Tuple(3.0, -2.0, 5.0, 1.0); AND_GIVEN("a2 = tuple(-2.0, 3.0, 1.0, 0.0") { auto a2 = Tuple(-2.0, 3.0, 1.0, 0.0); REQUIRE(a1 + a2 == Tuple(1.0, 1.0, 6.0, 1.0)); } } } SCENARIO("Substracting two points", "[Tuple]") { GIVEN("p1 = point(3.0, 2.0, 1.0") { auto p1 = point(3.0, 2.0, 1.0); AND_GIVEN("p2 = point(5.0, 6.0, 7.0") { auto p2 = point(5.0, 6.0, 7.0); REQUIRE(p1 - p2 == vector(-2.0, -4.0, -6.0)); } } } SCENARIO("Substracting a vector from a point", "[Tuple]") { GIVEN("p1 = point(3.0, 2.0, 1.0") { auto p = point(3.0, 2.0, 1.0); AND_GIVEN("p2 = point(5.0, 6.0, 7.0") { auto v = vector(5.0, 6.0, 7.0); REQUIRE(p - v == point(-2.0, -4.0, -6.0)); } } } SCENARIO("Substracting two vectors", "[Tuple]") { GIVEN("v1 = point(3.0, 2.0, 1.0") { auto v1 = point(3.0, 2.0, 1.0); AND_GIVEN("v2 = point(5.0, 6.0, 7.0") { auto v2 = point(5.0, 6.0, 7.0); REQUIRE(v1 - v2 == vector(-2.0, -4.0, -6.0)); } } } SCENARIO("Substracting a vector from the zero vector", "[Tuple]") { GIVEN("zero = vector(0.0, 0.0, 0.0") { auto zero = vector(0.0, 0.0, 0.0); AND_GIVEN("v = vector(1.0, -2.0, 3.0") { auto v = vector(1.0, -2.0, 3.0); REQUIRE(zero - v == vector(-1.0, 2.0, -3.0)); } } } SCENARIO("Negating a tuple", "[Tuple]") { GIVEN("a = tuple(1.0, -2.0, 3.0, -4.0") { auto a = Tuple(1.0, -2.0, 3.0, -4.0); REQUIRE(-a == Tuple(-1.0, 2.0, -3.0, 4.0)); } } SCENARIO("Multiplying a tuple by a scalar", "[Tuple]") { GIVEN("a = tuple(1.0, -2.0, 3.0, -4.0") { auto a = Tuple(1.0, -2.0, 3.0, -4.0); REQUIRE(a * 3.5 == Tuple(3.5, -7.0, 10.5, -14.0)); } } SCENARIO("Multiplying a tuple by a fraction", "[Tuple]") { GIVEN("a = tuple(1.0, -2.0, 3.0, -4.0") { auto a = Tuple(1.0, -2.0, 3.0, -4.0); REQUIRE(a * 0.5 == Tuple(0.5, -1.0, 1.5, -2.0)); } } SCENARIO("Dividing a tuple by a scalar", "[Tuple]") { GIVEN("a = tuple(1.0, -2.0, 3.0, -4.0") { auto a = Tuple(1.0, -2.0, 3.0, -4.0); REQUIRE(a / 2.0 == Tuple(0.5, -1.0, 1.5, -2.0)); } } SCENARIO("Computing the magnitude of vector(1.0, 0.0, 0.0)", "[Tuple]") { GIVEN("v = vector(1.0, 0.0, 0.0)") { auto v = vector(1.0, 0.0, 0.0); REQUIRE(v.magnitude() == 1.0); } } SCENARIO("Computing the magnitude of vector(0.0, 1.0, 0.0)", "[Tuple]") { GIVEN("v = vector(0.0, 1.0, 0.0)") { auto v = vector(0.0, 1.0, 0.0); REQUIRE(v.magnitude() == 1.0); } } SCENARIO("Computing the magnitude of vector(0.0, 0.0, 1.0)", "[Tuple]") { GIVEN("v = vector(0.0, 0.0, 1.0)") { auto v = vector(0.0, 0.0, 1.0); REQUIRE(v.magnitude() == 1.0); } } SCENARIO("Computing the magnitude of vector(1.0, 2.0, 3.0)", "[Tuple]") { GIVEN("v = vector(1.0, 2.0, 3.0)") { auto v = vector(1.0, 2.0, 3.0); REQUIRE(v.magnitude() == std::sqrt(14.0)); } } SCENARIO("Computing the magnitude of vector(-1.0, -2.0, -3.0)", "[Tuple]") { GIVEN("v = vector(-1.0, -2.0, -3.0)") { auto v = vector(-1.0, -2.0, -3.0); REQUIRE(v.magnitude() == std::sqrt(14.0)); } } SCENARIO("Normalizing vector(4.0f, 0.0f, 0.0f) gives (1.0, 0.0, 0.0)", "[Tuple]") { GIVEN("v = vector(4.0, 0.0, 0.0") { auto v = vector(4.0, 0.0, 0.0); REQUIRE(v.normalize() == vector(1.0, 0.0, 0.0)); } } SCENARIO("Normalizing vector(1.0, 2.0, 3.0)", "[Tuple]") { GIVEN("v = vector(1.0, 2.0, 3.0") { auto v = vector(1.0, 2.0, 3.0); REQUIRE(v.normalize() == vector(0.267261, 0.534522, 0.801784)); } } SCENARIO("The magnitude of a normalized vector", "[Tuple]") { GIVEN("v = vector(1.0, 2.0, 3.0") { auto v = vector(4.0, 0.0, 0.0); WHEN("norm == v.normalize()") { auto norm = v.normalize(); REQUIRE(norm.magnitude() == 1.0); } } } SCENARIO("The dot product of two tuples", "[Tuple]") { GIVEN("a = vector(1.0, 2.0, 3.0") { auto a = vector(1.0, 2.0, 3.0); AND_GIVEN("b = vector(2.0, 3.0, 4.0") { auto b = vector(2.0, 3.0, 4.0); REQUIRE(a.dot(b) == 20); } } } SCENARIO("The cross product of two vectors", "[Tuple]") { GIVEN("a = vector(1.0, 2.0, 3.0") { auto a = vector(1.0, 2.0, 3.0); AND_GIVEN("b = vector(2.0, 3.0, 4.0") { auto b = vector(2.0, 3.0, 4.0); REQUIRE(a.cross(b) == vector(-1.0, 2.0, -1.0)); REQUIRE(b.cross(a) == vector(1.0, -2.0, 1.0)); } } }
25.975962
83
0.510642
[ "vector" ]
8e7e2b0f524408e5c1cc5dceda35929a7542b5d8
27,403
cpp
C++
release/common/pathmachine.cpp
CecilHarvey/racc
836568ef7eecde208632571065c69f4b5f1a8d2b
[ "BSD-3-Clause" ]
1
2018-09-24T13:35:46.000Z
2018-09-24T13:35:46.000Z
release/common/pathmachine.cpp
CecilHarvey/racc
836568ef7eecde208632571065c69f4b5f1a8d2b
[ "BSD-3-Clause" ]
null
null
null
release/common/pathmachine.cpp
CecilHarvey/racc
836568ef7eecde208632571065c69f4b5f1a8d2b
[ "BSD-3-Clause" ]
1
2021-01-15T18:46:22.000Z
2021-01-15T18:46:22.000Z
// RACC - AI development project for first-person shooter games // (http://racc.bots-united.com/) // // Rational Autonomous Cybernetic Commandos AI // // pathmachine.cpp // #include "racc.h" void BotInitPathMachine (player_t *pPlayer) { // this function prepare a bot's pathfinding machine, initializing the lists to the number // of nodes the current map has, and cleansing the whole crap out. Local variables have been // declared static to speed the function up a bit. static pathmachine_t *pathmachine; pathmachine = &pPlayer->Bot.BotBrain.PathMachine; // first get a quick access to the bot's pathmachine // make sure the OPEN and PATH lists are empty if (pathmachine->open) free (pathmachine->open); // free the list to have it in a clean state if (pathmachine->path) free (pathmachine->path); // free the list to have it in a clean state // now initialize them so as they can hold pointers to the max number of nodes this map has pathmachine->open = (navnode_t **) malloc (map.walkfaces_count * sizeof (navnode_t *)); pathmachine->path = (navlink_t **) malloc (map.walkfaces_count * sizeof (navlink_t *)); // and clean the whole machine memset (pathmachine->open, 0, map.walkfaces_count * sizeof (navnode_t *)); pathmachine->open_count = 0; memset (pathmachine->path, 0, map.walkfaces_count * sizeof (navlink_t *)); pathmachine->path_count = 0; pathmachine->path_cost = 0; return; // now the lists can be safely considered as valid arrays of pointers } void BotRunPathMachine (player_t *pPlayer) { // this function runs a time-sliced A* path machine belonging to a particular bot. Each bot // has its own pathmachine, allowing several pathfinding sessions to run in parallel. // paths are computed in the REVERSE order, because since a pathfinding process may extend on // several frames, the "start" of the path, which can be where the bot is, is likely to change, // because of the bot being still running, or moving elseway. // In order to compute a path, one must: // 1. wait for the pathmachine to finish a previous task or forcefully reset it // 2. place the GOAL node (the start node for the pathfinder) on the open list // These operations are done automatically upon each call of BotFindPathTo(). // Then the path machine looks for a path, several cycles per frame depending on the value of // the cycles_per_frame variable, and if one path is available, it sets a flag to indicate // it has finished, and builds the path under the form of an array of nodes (in the right // order this time) in the final "path" field of the pathmachine. // Local variables have been declared static to speedup recurrent calls of this function. static char display_string[256]; static int cycles_per_frame; static pathmachine_t *pathmachine; static walkface_t *walkface_at_feet; static navnode_t *pathmemory; static navnode_t *examined_node, *ancestor_node, *goal_node; register int cycle_count, node_index, link_index; static float ancestor_travel_cost; static float debug_update_time = 0; pathmachine = &pPlayer->Bot.BotBrain.PathMachine; // quick access to pathmachine pathmemory = pPlayer->Bot.BotBrain.PathMemory; // quick access to pathmemory // have we NOT been asked to compute a path yet ? if ((pathmachine->open[0] == NULL) || (pathmachine->open_count == 0)) return; // just return when there's nothing to do // looks like a pathfinding session is in progress or has just started... pathmachine->busy = TRUE; // so mark the machine as busy // timeslice duration is inversely adaptative to frame duration, for example: // 100 fps => 100 cycles // 10 fps => 1000 cycles // 1 fps => 10000 cycles (roughly means: do not slice at all) // this is meant to preserve some sort of homogeneity in the bot's reaction time cycles_per_frame = 10 * server.msecval; // compute timeslice cycles quota cycle_count = 0; // reset the pathfinding machine's cycle count // does the bot want to find a path from its current location ? if (pathmachine->should_update_goal) { // find and get the navnode under this bot's feet (by linking a pointer to it). The node // at the bot's feet is the start node of the path from the bot's point of view, but it is // the GOAL node in the search routine since we look for the path in the reverse order. walkface_at_feet = pPlayer->pFaceAtFeet; // reliability check: is the walkface at feet not found ? if (walkface_at_feet == NULL) { if (pPlayer->is_watched && (DebugLevel.navigation > 1)) ServerConsole_printf ("Bot %s can't do pathfinding (can't find walkface at feet)\n", pPlayer->connection_name); return; // if so, don't compute anything this frame (the bot doesn't know where it is) } // with this we can keep the goal node updated dynamically all along the search :) node_index = WalkfaceIndexOf (walkface_at_feet); goal_node = &pathmemory[node_index]; // node indices are the same as walkface indices, btw } else goal_node = pathmachine->goal_node; // else use the goal node the pathmachine was told // who said I would never use A* ? me?? err... okay, I admit. Stop nagging, you there. // while there are nodes on the open list, examine them... while (pathmachine->open_count > 0) { if (cycle_count == cycles_per_frame) return; // break the loop if we've searched for too long (we'll continue next frame) if (debug_update_time > server.time) return; // also break the loop when debug mode and not time to update yet // take the most interesting node among the list of those we haven't examined yet examined_node = PopFromOpenList (pathmachine); // if navigation debug level is VERY high, slow down the pathmachine if (pPlayer->is_watched && (DebugLevel.navigation > 2)) { // and display its progress visually printf ("Examining node %d\n", WalkfaceIndexOf (examined_node->walkface)); UTIL_DrawWalkface (examined_node->walkface, 25, 255, 255, 255); debug_update_time = server.time + 3.0; // next pass in 3 seconds } // is this node the goal node ? if (examined_node == goal_node) { pathmachine->path_count = 0; // we have found the path ! so build it... // while we've not built the entire path... while (examined_node->entrypoint != NULL) { // append this link to the path array of link pointers pathmachine->path[pathmachine->path_count] = examined_node->entrypoint; pathmachine->path_count++; // the path is now one node longer examined_node = examined_node->parent; } // remember the path cost, while we're at it... pathmachine->path_cost = goal_node->total_cost; // if navigation debug level is high, print out the path if (pPlayer->is_watched && (DebugLevel.navigation > 1)) { printf ("PATH FOUND: %d links involved, cost: %.1f\n", pathmachine->path_count, pathmachine->path_cost); for (link_index = 0; link_index < pathmachine->path_count; link_index++) ServerConsole_printf ("Link at (%.0f, %.0f, %.0f): reachability %d\n", pathmachine->path[link_index]->v_origin.x, pathmachine->path[link_index]->v_origin.y, pathmachine->path[link_index]->v_origin.z, pathmachine->path[link_index]->reachability); UTIL_DrawPath (pathmachine); } // clean up the machine and notify the bot that we have finished computing the path memset (pathmachine->open, 0, map.walkfaces_count * sizeof (navnode_t *)); pathmachine->open_count = 0; pathmachine->finished = TRUE; pathmachine->busy = FALSE; return; // and return } // this node is NOT the goal node, but since it might be on the path (we don't know yet) // we have to check for its ancestors in order to know where they lead to... for (link_index = 0; link_index < examined_node->links_count; link_index++) { // get an entrypoint to the node (by linking a pointer to it) ancestor_node = examined_node->links[link_index].node_from; // if navigation debug level is VERY high, display the pathmachine's progress visually if (pPlayer->is_watched && (DebugLevel.navigation > 2)) { printf ("Examining entrypoint %d\n", link_index); UTIL_DrawWalkface (ancestor_node->walkface, 25, 255, 0, 0); } // compute its travel cost by adding this of its parent to its own ancestor_travel_cost = examined_node->travel_cost + BotEstimateTravelCost (pPlayer, examined_node->entrypoint, &examined_node->links[link_index]); // check whether this node is already in the open list AND is cheaper there if (ancestor_node->is_in_open_list && (ancestor_node->travel_cost <= ancestor_travel_cost)) continue; // then skip this node // check whether this node is already in the closed list AND is cheaper there if (ancestor_node->is_in_closed_list && (ancestor_node->travel_cost <= ancestor_travel_cost)) continue; // then skip this node ancestor_node->parent = examined_node; // remember this node's parent ancestor_node->entrypoint = &examined_node->links[link_index]; // remember its entry point ancestor_node->travel_cost = ancestor_travel_cost; // remember its travel cost ancestor_node->remaining_cost = EstimateTravelCostFromTo (ancestor_node, pathmachine->open[0]); ancestor_node->total_cost = ancestor_travel_cost + ancestor_node->remaining_cost; // was this node on the closed list again ? if (ancestor_node->is_in_closed_list) ancestor_node->is_in_closed_list = FALSE; // take it off the list // is this node NOT in the OPEN list yet ? if (!ancestor_node->is_in_open_list) PushToOpenList (pathmachine, ancestor_node); // push it there } examined_node->is_in_closed_list = TRUE; // done examining this node and its entrypoints cycle_count++; // the pathfinding machine has elapsed one cycle more } // if we get there, that's we have explored all the nodes ascending from the start point, // and that none of them has been able to reach the destination point. It just means that // no path exists, so clean up the machine and return. // do we want to debug the navigation ? if (pPlayer->is_watched && (DebugLevel.navigation > 0)) printf ("PATH UNAVAILABLE\n"); // if so, inform us that no path could be found memset (pathmachine->open, 0, map.walkfaces_count * sizeof (navnode_t *)); pathmachine->open_count = 0; memset (pathmachine->path, 0, map.walkfaces_count * sizeof (navlink_t *)); pathmachine->path_count = 0; pathmachine->path_cost = 0; pathmachine->finished = TRUE; pathmachine->busy = FALSE; return; // pathmachine unable to find any path, so return } void BotShutdownPathMachine (player_t *pPlayer) { // this function frees all the memory space that has been allocated for the specified bot's // pathmachine and resets its pointers to zero. Beware NOT to use the machine afterwards !!! // Local variables have been declared static to speed the function up a bit. static pathmachine_t *pathmachine; pathmachine = &pPlayer->Bot.BotBrain.PathMachine; // quick access to the bot's pathmachine // do we need to free this bot's pathmachine ? if (pathmachine->open) free (pathmachine->open); // free the node queue pathmachine->open = NULL; if (pathmachine->path) free (pathmachine->path); // free the path list pathmachine->path = NULL; return; // finished, everything is freed } bool BotFindPathTo (player_t *pPlayer, Vector v_goal, bool urgent) { // the purpose of this function is to setup bot pBot's pathmachine so that it computes a // path to the destination described by the spatial vector v_goal. If additionally the urgent // flag is set, and the pathmachine is already computing another path, the function forcibly // resets the pathmachine and make it compute the new path immediately instead. First the bot // will try to determine if it knows a navnode that would enclose the destination location, // and if one is found, it is put on the pathmachine's open list to tell it to compute a path // to this location. // remember: the startface for the pathmachine is our GOAL face !!! register int index; static pathmachine_t *pathmachine; static walkface_t *startface; static navnode_t *pathmemory, *startnode; if (pPlayer->Bot.findpath_time > server.time) return (FALSE); // cancel if not time to pathmachine = &pPlayer->Bot.BotBrain.PathMachine; // quick access to pathmachine pathmemory = pPlayer->Bot.BotBrain.PathMemory; // quick access to pathmemory // if bot is already computing another path and there's no emergency, give up if (pathmachine->busy && !urgent) { pPlayer->Bot.findpath_time = server.time + 1.0; // try again in one second return (FALSE); // but not now } // try to find the walkface corresponding to the location we want to go to startface = NULL; // don't forget to reset it since it is static startface = WalkfaceAt (v_goal); // if we can't find that walkface, then the bot does not know about its destination if (startface == NULL) { pPlayer->Bot.findpath_time = server.time + 1.0; // try again in one second return (FALSE); // howd'ya want to go anywhere if you didn't knew that place existed ? } // clean up the machine before proceeding memset (pathmachine->open, 0, map.walkfaces_count * sizeof (navnode_t *)); pathmachine->open_count = 0; pathmachine->finished = FALSE; // do not forget to empty all the lists ! for (index = 0; index < map.walkfaces_count; index++) { pathmemory[index].parent = NULL; pathmemory[index].entrypoint = NULL; pathmemory[index].is_in_open_list = FALSE; pathmemory[index].is_in_closed_list = FALSE; pathmemory[index].travel_cost = 0; pathmemory[index].remaining_cost = 0; pathmemory[index].total_cost = 0; } // tell the pathmachine that it should update the goal node dynamically pathmachine->should_update_goal = TRUE; // find the destination node (its index is the same as the destination face index) and put // it on the open list of the pathmachine, setting the open list count to 1 startnode = &pathmemory[WalkfaceIndexOf (startface)]; startnode->parent = NULL; startnode->entrypoint = NULL; startnode->travel_cost = 0; startnode->remaining_cost = (v_goal - pPlayer->v_origin).Length (); startnode->total_cost = startnode->remaining_cost; PushToOpenList (pathmachine, startnode); pPlayer->Bot.findpath_time = server.time + RandomFloat (1.0, 3.0); // next try in a few secs return (TRUE); // and let the pathmachine do its job } bool BotFindPathFromTo (player_t *pPlayer, Vector v_start, Vector v_goal, bool urgent) { // the purpose of this function is to setup bot pBot's pathmachine so that it computes a // path from and to the locations specified by v_start and v_goal. If additionally the urgent // flag is set, and the pathmachine is already computing another path, the function forcibly // resets the pathmachine and make it compute the new path immediately instead. First the bot // will try to determine if it knows a navnode that would enclose the destination location, // and if one is found, it is put on the pathmachine's open list to tell it to compute a path // to this location. register int index; static pathmachine_t *pathmachine; static walkface_t *startface, *goalface; static navnode_t *pathmemory, *startnode; if (pPlayer->Bot.findpath_time > server.time) return (FALSE); // cancel if not time to pathmachine = &pPlayer->Bot.BotBrain.PathMachine; // quick access to pathmachine pathmemory = pPlayer->Bot.BotBrain.PathMemory; // quick access to pathmemory // if bot is already computing another path and there's no emergency, give up if (pathmachine->busy && !urgent) { pPlayer->Bot.findpath_time = server.time + 1.0; // try again in one second return (FALSE); // but not now } // try to find the walkface corresponding to the location we want to go to startface = NULL; // don't forget to reset it since it is static startface = WalkfaceAt (v_goal); // if we can't find that walkface, then the bot does not know about its destination if (startface == NULL) { pPlayer->Bot.findpath_time = server.time + 1.0; // try again in one second return (FALSE); // howd'ya want to go anywhere if you didn't knew that place existed ? } // try to find the walkface corresponding to the location we want to start from goalface = NULL; // don't forget to reset it since it is static goalface = WalkfaceAt (v_start); // if we can't find that walkface, then the bot does not know where the path starts if (goalface == NULL) { pPlayer->Bot.findpath_time = server.time + 1.0; // try again in one second return (FALSE); // howd'ya want to go anywhere if you didn't knew that place existed ? } // clean up the machine before proceeding memset (pathmachine->open, 0, map.walkfaces_count * sizeof (navnode_t *)); pathmachine->open_count = 0; pathmachine->finished = FALSE; // do not forget to empty all the lists ! for (index = 0; index < map.walkfaces_count; index++) { pathmemory[index].parent = NULL; pathmemory[index].entrypoint = NULL; pathmemory[index].is_in_open_list = FALSE; pathmemory[index].is_in_closed_list = FALSE; pathmemory[index].travel_cost = 0; pathmemory[index].remaining_cost = 0; pathmemory[index].total_cost = 0; } // push the goal node (start node for us) onto the pathmachine pathmachine->goal_node = &pathmemory[WalkfaceIndexOf (goalface)]; pathmachine->should_update_goal = FALSE; // this is NOT a goal to update dynamically // find the destination node (its index is the same as the destination face index) and put // it on the open list of the pathmachine, setting the open list count to 1 startnode = &pathmemory[WalkfaceIndexOf (startface)]; startnode->parent = NULL; startnode->entrypoint = NULL; startnode->travel_cost = 0; startnode->remaining_cost = (v_goal - pPlayer->v_origin).Length (); startnode->total_cost = startnode->remaining_cost; PushToOpenList (pathmachine, startnode); pPlayer->Bot.findpath_time = server.time + RandomFloat (1.0, 3.0); // next try in a few secs return (TRUE); // and let the pathmachine do its job } float EstimateTravelCostFromTo (navnode_t *node_from, navnode_t *node_to) { // this function estimates the travel cost between two navigation links. It's a heuristic // used in the pathfinding process. Currently we assume the travel cost is roughly equal // to the straight distance between both nodes (more accurately between the center of the // walkfaces they represent). register int index; static walkface_t *walkface_from, *walkface_to; static Vector v_from, v_to; if ((node_from == NULL) || (node_to == NULL)) return (0); // reliability check // get a quick access to the involved walkfaces walkface_from = node_from->walkface; walkface_to = node_to->walkface; // figure out where the center of the first walkface is v_from = g_vecZero; for (index = 0; index < walkface_from->corner_count; index++) v_from = v_from + walkface_from->v_corners[index]; v_from = v_from / (float) walkface_from->corner_count; // figure out where the center of the second walkface is v_to = g_vecZero; for (index = 0; index < walkface_to->corner_count; index++) v_to = v_to + walkface_to->v_corners[index]; v_to = v_to / (float) walkface_to->corner_count; // and return a base cost according to the distance return ((v_to - v_from).Length ()); } float BotEstimateTravelCost (player_t *pPlayer, navlink_t *link_from, navlink_t *link_to) { // this function returns a weighted measurement of the travel cost between two navnodes // under the estimation the specified personality makes of it (regarding its memories about // either of these nodes). The basis for the estimation is the raw distance between these // two nodes, weighted by the type of reachability between them. At least link_to must point // to a valid navlink that is present in personality's nav memory. If link_from is NULL or // unspecified, the returned cost will be zero. static float f_cost; if (link_to == NULL) return (0); // don't know where we want to go, can't tell how far it is ! if (link_from == NULL) return (0); // don't know where we came from, can't tell how far it is ! // compute a base cost according to the distance f_cost = (link_to->v_origin - link_from->v_origin).Length (); // now given the type of reachability it is, weighten this base cost according to an // overall like/dislike factor (this factor changes when the bot's happiness suddently // changes at these locations, f.ex. when the bot is hurt, when it kills someone or when // it is killed here)... if (link_to->reachability & REACHABILITY_LADDER) f_cost *= pPlayer->Bot.BotBrain.likelevel.ladder; if (link_to->reachability & REACHABILITY_FALLEDGE) f_cost *= pPlayer->Bot.BotBrain.likelevel.falledge; if (link_to->reachability & REACHABILITY_ELEVATOR) f_cost *= pPlayer->Bot.BotBrain.likelevel.elevator; if (link_to->reachability & REACHABILITY_PLATFORM) f_cost *= pPlayer->Bot.BotBrain.likelevel.platform; if (link_to->reachability & REACHABILITY_CONVEYOR) f_cost *= pPlayer->Bot.BotBrain.likelevel.conveyor; if (link_to->reachability & REACHABILITY_TRAIN) f_cost *= pPlayer->Bot.BotBrain.likelevel.train; if (link_to->reachability & REACHABILITY_LONGJUMP) f_cost *= pPlayer->Bot.BotBrain.likelevel.longjump; if (link_to->reachability & REACHABILITY_SWIM) f_cost *= pPlayer->Bot.BotBrain.likelevel.swim; if (link_to->reachability & REACHABILITY_TELEPORTER) f_cost *= pPlayer->Bot.BotBrain.likelevel.teleporter; if (link_to->reachability & REACHABILITY_JUMP) f_cost *= pPlayer->Bot.BotBrain.likelevel.jump; if (link_to->reachability & REACHABILITY_CROUCH) f_cost *= pPlayer->Bot.BotBrain.likelevel.crouch; if (link_to->reachability & REACHABILITY_UNKNOWN1) f_cost *= pPlayer->Bot.BotBrain.likelevel.unknown1; if (link_to->reachability & REACHABILITY_UNKNOWN2) f_cost *= pPlayer->Bot.BotBrain.likelevel.unknown2; if (link_to->reachability & REACHABILITY_UNKNOWN3) f_cost *= pPlayer->Bot.BotBrain.likelevel.unknown3; if (link_to->reachability & REACHABILITY_UNKNOWN4) f_cost *= pPlayer->Bot.BotBrain.likelevel.unknown4; if (link_to->reachability & REACHABILITY_UNKNOWN5) f_cost *= pPlayer->Bot.BotBrain.likelevel.unknown5; // *** TODO *** Make the bot question its individual memory about this link // i.e: this spot is dangerous, it's a weapon spot, a cover passage, etc. return (f_cost); // and return the weightened cost } void PushToOpenList (pathmachine_t *pathmachine, navnode_t *queue_element) { // this function inserts an element in the OPEN priority queue of the specified pathmachine // and rearrange the heap so as to always have the item which has the lower weight at the // root of the heap. register int index; if (pathmachine == NULL) return; // reliability check index = pathmachine->open_count; // first insert position at the trailing end of the heap // while the item is not at the right position in the heap so as to have it sorted... while ((index > 0) && (queue_element->total_cost < pathmachine->open[(index - 1) / 2]->total_cost)) { pathmachine->open[index] = pathmachine->open[(index - 1) / 2]; // shuffle the branch down index = (index - 1) / 2; // proceed to the parent element } queue_element->is_in_open_list = TRUE; // flag this element as a member of the OPEN list queue_element->is_in_closed_list = FALSE; // this element cannot be on the CLOSED list now pathmachine->open[index] = queue_element; // attach the item at this remaining location pathmachine->open_count++; // there is now one element more in the heap return; // done, heap is sorted } navnode_t *PopFromOpenList (pathmachine_t *pathmachine) { // this function takes the element with the lower weight from the OPEN priority queue of the // specified pathmachine and rearrange the heap so as to always have the item which has the // lower weight at the root of the heap. static navnode_t *return_element, *temp_element; register int i, j; if ((pathmachine == NULL) || (pathmachine->open_count == 0)) return (NULL); // reliability check return_element = pathmachine->open[0]; // get the element with highest priority from the top return_element->is_in_open_list = FALSE; // flag this element as NOT a member of the OPEN list pathmachine->open_count--; // there is now one element less in the heap temp_element = pathmachine->open[pathmachine->open_count]; // take the last inserted element i = 0; // start searching for its new position at root level // while we've not found the place to insert this temporary element so as to have the heap // sorted again, shuffle the tree down while (i < (pathmachine->open_count + 1) / 2) { j = (2 * i) + 1; // consider i's first child and name it j if ((j < pathmachine->open_count - 1) && (pathmachine->open[j]->total_cost > pathmachine->open[j + 1]->total_cost)) j++; // now take the lowest weighted of i's two siblings (either j, or its brother) if (pathmachine->open[j]->total_cost >= temp_element->total_cost) break; // stop here when this child is more weighted than the element we want to shuffle pathmachine->open[i] = pathmachine->open[j]; // else shuffle this child one rank up i = j; // reach the position of the lowest weighted child for next pass } pathmachine->open[i] = temp_element; // now here is a good place to dump that element to return (return_element); // done, heap is sorted again. }
46.288851
156
0.679707
[ "vector" ]
8e84ea0684388c92468807169e3c5b25f27b32ef
1,614
cpp
C++
Problems/0137. Single Number II.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0137. Single Number II.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0137. Single Number II.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
class Solution { public: int singleNumber(vector<int>& nums) { int l{0}, h{0}; for(auto i:nums){ l = ~h & (l^i); h = ~l & (h^i); } return l; } }; /* Because every number will appear three times except only one, we need two bits to save the 3 states of all elements. Our goal is to design a logic operation that will be transformed by following this rule: 00 -> 01 -> 10 -> 00. Let’s assume the input is i , the low bit be l, the high bit be h, the new low bit be l’ and the new high bit be h’. We can draw the truth table of the 3 states as follow: h | l | i | h'| l' ------------------- 0 | 0 | 0 | 0 | 0 => no input, no change ------------------- 0 | 1 | 0 | 0 | 1 => no input, no change ------------------- 1 | 0 | 0 | 1 | 0 => no input, no change ------------------- 0 | 0 | 1 | 0 | 1 => 00 -> 01 ------------------- 0 | 1 | 1 | 1 | 0 => 01 -> 10 ------------------- 1 | 0 | 1 | 0 | 0 => 10 -> 00 By above truth table, we can compute h' and l' by h , l and i: h' = h & ~l & ~i | ~h & l & i with third and fifth rows of truth table l' = ~h & l & ~i | ~h & ~l & i with second and forth rows of truth table And the later can further be reduced to: l' = ~h & (l ^ i) — formula 1. Moreover, if we let l' be assigned first, h' can also be computed by l': h' = h & ~i & ~l' | ~h & i & ~l' with third and fifth rows of truth table which is also equal to h' = ~l' & (h ^ i) — formula 2. By formula 1 and 2, we can easily extract the only single one by taking low bit, which means the number whose state still remains 01. */
32.938776
399
0.534077
[ "vector" ]
8e84ed132670798825886f458dbf2adf087f77d8
2,242
cpp
C++
src/core/scene.cpp
yumcyaWiz/LTRE
dd65125bb133c345a10a3cf3d4c2a330b38ee82b
[ "MIT" ]
3
2021-08-15T08:59:21.000Z
2021-11-27T08:23:37.000Z
src/core/scene.cpp
yumcyaWiz/LTRE
dd65125bb133c345a10a3cf3d4c2a330b38ee82b
[ "MIT" ]
null
null
null
src/core/scene.cpp
yumcyaWiz/LTRE
dd65125bb133c345a10a3cf3d4c2a330b38ee82b
[ "MIT" ]
1
2021-12-09T15:43:57.000Z
2021-12-09T15:43:57.000Z
#include "LTRE/core/scene.hpp" namespace LTRE { Scene::Scene() {} Scene::Scene(const std::shared_ptr<Intersector<Primitive>>& intersector, const std::shared_ptr<Light>& sky) : intersector(intersector), sky(sky) {} void Scene::addPrimitive(const Primitive& primitive) { intersector->addPrimitive(primitive); } void Scene::addModel(const Model& model) { // for each meshes for (unsigned int i = 0; i < model.meshes.size(); ++i) { // create Primitive const std::shared_ptr<Mesh> shape = model.meshes[i]; const auto material = model.createMaterial(i); const auto areaLight = model.createAreaLight(i); const Primitive prim = Primitive(shape, material, areaLight); // add Primitive to intersector intersector->addPrimitive(prim); } } void Scene::build() { // build intersector intersector->build(); const AABB sceneAABB = intersector->aabb(); spdlog::info("[Scene] scene bounds: ({0}, {1}, {2}), ({3}, {4}, {5})", sceneAABB.bounds[0][0], sceneAABB.bounds[0][1], sceneAABB.bounds[0][2], sceneAABB.bounds[1][0], sceneAABB.bounds[1][1], sceneAABB.bounds[1][2]); // initialize lights // NOTE: only add lights which has power greater than 0 for (const auto& prim : intersector->getPrimitivesRef()) { if (prim.hasArealight()) { const auto light = prim.getAreaLightPtr(); if (light->power() > Vec3(0)) { lights.push_back(light); } } } // add sky to lights if (sky->power() > Vec3(0)) { lights.push_back(sky); } spdlog::info("[Scene] number of lights: {}", lights.size()); } bool Scene::intersect(const Ray& ray, IntersectInfo& info) const { return intersector->intersect(ray, info); } bool Scene::intersectP(const Ray& ray) const { return intersector->intersectP(ray); } Vec3 Scene::getSkyRadiance(const Ray& ray) const { // TODO: more nice way? SurfaceInfo dummy; return sky->Le(ray.direction, dummy); } std::shared_ptr<Light> Scene::sampleLight(Sampler& sampler, float& pdf) const { unsigned int lightIdx = lights.size() * sampler.getNext1D(); if (lightIdx == lights.size()) lightIdx--; pdf = 1.0f / lights.size(); return lights[lightIdx]; } } // namespace LTRE
29.5
79
0.652096
[ "mesh", "shape", "model" ]
8e8d0c1429a6520b584adc5d411b10fbe3e3ba64
1,293
hpp
C++
include/tinyspv/spirv/unified1/instrs/SPIRV.control-flow.hpp
PENGUINLIONG/tinyspv
508ca5f4e1e4a1c2f4fb4323e0d0c8a367874a03
[ "Apache-2.0", "MIT" ]
null
null
null
include/tinyspv/spirv/unified1/instrs/SPIRV.control-flow.hpp
PENGUINLIONG/tinyspv
508ca5f4e1e4a1c2f4fb4323e0d0c8a367874a03
[ "Apache-2.0", "MIT" ]
null
null
null
include/tinyspv/spirv/unified1/instrs/SPIRV.control-flow.hpp
PENGUINLIONG/tinyspv
508ca5f4e1e4a1c2f4fb4323e0d0c8a367874a03
[ "Apache-2.0", "MIT" ]
1
2021-10-11T01:55:18.000Z
2021-10-11T01:55:18.000Z
// THIS IS A GENERATED SOURCE. MODIFICATION WILL BE OVERWRITTEN. // USING JSON FROM: // PENGUINLIONG/tinyspv @ db18ea116bd8c195ee18714eb9dffab473dfa7da #pragma once #include <vector> #include <string> #include <optional> #include "tinyspv/spirv/unified1/SPIRV.hpp" namespace tinyspv { namespace instrs { typedef uint32_t Id; typedef std::vector<uint32_t> Literal; typedef std::vector<uint32_t> LiteralList; struct OpPhi { Id result_type; Id result_id; std::vector<Id> variable; }; struct OpLoopMerge { Id merge_block; Id continue_target; LoopControl loop_control; LiteralList loop_control_parameters; }; struct OpSelectionMerge { Id merge_block; SelectionControl selection_control; }; struct OpLabel { Id result_id; }; struct OpBranch { Id target_label; }; struct OpBranchConditional { Id condition; Id true_label; Id false_label; LiteralList branch_weights; }; struct OpSwitch { Id selector; Id default; LiteralList target; std::vector<Id> target2; }; struct OpKill { }; struct OpReturn { }; struct OpReturnValue { Id value; }; struct OpUnreachable { }; struct OpLifetimeStart { Id pointer; uint32_t size; }; struct OpLifetimeStop { Id pointer; uint32_t size; }; struct OpTerminateInvocation { }; } // namespace instrs } // namespace tinyspv
19.014706
68
0.747873
[ "vector" ]
8e956a1cf616a7dec317591ec47201a6cc74eb83
1,543
cpp
C++
storage/src/vespa/storage/distributor/clusterinformation.cpp
bowlofstew/vespa
5212c7a5568769eadb5c5d99b6a503a70c82af48
[ "Apache-2.0" ]
null
null
null
storage/src/vespa/storage/distributor/clusterinformation.cpp
bowlofstew/vespa
5212c7a5568769eadb5c5d99b6a503a70c82af48
[ "Apache-2.0" ]
1
2021-01-21T01:37:37.000Z
2021-01-21T01:37:37.000Z
storage/src/vespa/storage/distributor/clusterinformation.cpp
bowlofstew/vespa
5212c7a5568769eadb5c5d99b6a503a70c82af48
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "clusterinformation.h" #include <vespa/vdslib/distribution/distribution.h> #include <vespa/vdslib/state/clusterstate.h> namespace storage::distributor { bool ClusterInformation::ownsBucket(const document::BucketId& bucketId) const { try { uint16_t distributor(getDistribution().getIdealDistributorNode( getClusterState(), bucketId)); return (getDistributorIndex() == distributor); } catch (lib::TooFewBucketBitsInUseException& e) { return false; } catch (lib::NoDistributorsAvailableException& e) { return false; } } bool ClusterInformation::nodeInSameGroupAsSelf(uint16_t otherNode) const { return (getDistribution().getNodeGraph().getGroupForNode(otherNode) == getDistribution().getNodeGraph().getGroupForNode(getDistributorIndex())); } vespalib::string ClusterInformation::getDistributionHash() const { return getDistribution().getNodeGraph().getDistributionConfigHash(); } std::vector<uint16_t> ClusterInformation::getIdealStorageNodesForState( const lib::ClusterState& clusterState, const document::BucketId& bucketId) const { return getDistribution().getIdealStorageNodes( clusterState, bucketId, getStorageUpStates()); } uint16_t ClusterInformation::getStorageNodeCount() const { return getClusterState().getNodeCount(lib::NodeType::STORAGE); } }
28.054545
118
0.724563
[ "vector" ]
8ea59cb7b07bd1a8fa52aba812bf8dad1920b895
24,589
cpp
C++
view/src/custom_chart_view.cpp
Rapprise/b2s-trader
ac8a3c2221d15c4df8df63842d20dafd6801e535
[ "BSD-2-Clause" ]
21
2020-06-07T20:34:47.000Z
2021-08-10T20:19:59.000Z
view/src/custom_chart_view.cpp
Rapprise/b2s-trader
ac8a3c2221d15c4df8df63842d20dafd6801e535
[ "BSD-2-Clause" ]
null
null
null
view/src/custom_chart_view.cpp
Rapprise/b2s-trader
ac8a3c2221d15c4df8df63842d20dafd6801e535
[ "BSD-2-Clause" ]
4
2020-07-13T10:19:44.000Z
2022-03-11T12:15:43.000Z
/* * Copyright (c) 2020, Rapprise. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "include/custom_chart_view.h" #include <common/loggers/file_logger.h> #include <QApplication> #include <QtCharts/QBarCategoryAxis> #include <QtCharts/QCandlestickSet> #include <QtCharts/QDateTimeAxis> #include <QtCharts/QValueAxis> #include <cmath> #include <iomanip> #include <iostream> #include <queue> #include "common/exceptions/undefined_type_exception.h" namespace auto_trader { namespace view { constexpr int MAX_BARS_COUNT = 2000; constexpr int MAX_TICK_COUNT_PER_TIME = 9; constexpr int MIN_TICK_RANGE_ON_SCREEN = 10; CustomChartView::CustomChartView(QWidget *parent) : QtCharts::QChartView(parent), mainChart_(new QtCharts::QChart()), lineSeries_(new QtCharts::QLineSeries(this)), verticalSeries_(new QtCharts::QLineSeries(this)), bottomSeries_(new QtCharts::QLineSeries(this)), mountainSeries_(new QtCharts::QAreaSeries(this)), candleSeries_(new QtCharts::QCandlestickSeries(this)), currentPriceDisplayItem_(nullptr), currentDateDisplayItem_(nullptr), zoomIndex_(0, true) { initialize(); } CustomChartView::~CustomChartView() { delete currentPriceDisplayItem_; delete currentDateDisplayItem_; delete mainChart_; } void CustomChartView::initialize() { marketDates_.resize(MAX_BARS_COUNT); mainChart_->createDefaultAxes(); mainChart_->legend()->hide(); mainChart_->setTitle("No active stock exchange chosen."); mainChart_->setPlotAreaBackgroundBrush(QBrush(QColor("#B7BBC1"))); mainChart_->setPlotAreaBackgroundVisible(true); mainChart_->setBackgroundBrush(QBrush(QColor("#B7BBC1"))); axisX_ = new QtCharts::QDateTimeAxis; axisX_->setTickCount(MAX_TICK_COUNT_PER_TIME); axisX_->setFormat("h:mm:ss"); axisX_->setTitleText("Date"); auto currentDate = common::Date::getCurrentTime(); QDateTime todayDate, oneHourAhead; todayDate.setDate(QDate(currentDate.year_, currentDate.month_, currentDate.day_)); todayDate.setTime(QTime(currentDate.hour_, currentDate.minute_, currentDate.second_)); auto currentHour = currentDate.hour_; auto oneHourFromNow = currentHour == 23 ? 1 : currentHour + 1; oneHourAhead.setDate(QDate(currentDate.year_, currentDate.month_, currentDate.day_)); oneHourAhead.setTime(QTime(oneHourFromNow, currentDate.minute_, currentDate.second_)); marketDates_.push_back(todayDate); marketDates_.push_back(oneHourAhead); marketDatesPrice_[todayDate] = 0.5; marketDatesPrice_[oneHourAhead] = 0.5; lineSeries_->append(todayDate.toMSecsSinceEpoch(), 0.5); lineSeries_->append(oneHourAhead.toMSecsSinceEpoch(), 0.5); bottomSeries_->append(todayDate.toMSecsSinceEpoch(), 0); bottomSeries_->append(oneHourAhead.toMSecsSinceEpoch(), 0); axisY_ = new QtCharts::QValueAxis; axisY_->setLabelFormat("%.6f"); axisY_->setTickCount(MAX_TICK_COUNT_PER_TIME); axisY_->setTitleText("Price"); axisY_->setRange(0, 1); axisX_->setRange(todayDate, oneHourAhead); mainChart_->addAxis(axisX_, Qt::AlignBottom); mainChart_->addAxis(axisY_, Qt::AlignLeft); setupChart(); setChart(mainChart_); currentPriceDisplayItem_ = new QGraphicsSimpleTextItem(mainChart_); currentPriceDisplayItem_->setPos(120, 10); currentPriceDisplayItem_->setText("closed price: "); currentDateDisplayItem_ = new QGraphicsSimpleTextItem(mainChart_); currentDateDisplayItem_->setPos(120, 35); currentDateDisplayItem_->setText("closed date"); setMouseTracking(true); setDragMode(QGraphicsView::NoDrag); setRenderHint(QPainter::Antialiasing); setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); } void CustomChartView::mouseMoveEvent(QMouseEvent *event) { updateVerticalLine(event->pos()); if (event->buttons() & Qt::LeftButton) { auto dPos = event->pos() - lastMousePosition_; auto axisXMin = axisX_->min().toMSecsSinceEpoch() + (-dPos.x()); auto axisXMax = axisX_->max().toMSecsSinceEpoch() + (-dPos.x()); if (marketDates_.empty()) { chart()->scroll(-dPos.x(), 0); lastMousePosition_ = event->pos(); event->accept(); QChartView::mouseMoveEvent(event); return; } auto lowerBound = std::lower_bound(marketDates_.begin(), marketDates_.end(), QDateTime::fromMSecsSinceEpoch(axisXMin)); auto upperBound = std::upper_bound(marketDates_.begin(), marketDates_.end(), QDateTime::fromMSecsSinceEpoch(axisXMax)); if (upperBound == marketDates_.end()) { if (dPos.x() < 0) { lastMousePosition_ = event->pos(); event->accept(); QChartView::mouseMoveEvent(event); axisX_->setMax(marketDates_.back()); return; } } if (lowerBound == marketDates_.begin()) { if (dPos.x() > 0) { lastMousePosition_ = event->pos(); event->accept(); QChartView::mouseMoveEvent(event); axisX_->setMin(marketDates_.front()); return; } } std::vector<QDateTime> range(lowerBound, upperBound); double minValue = INT32_MAX; double maxValue = 0; for (auto &date : range) { double currentValue = marketDatesPrice_[date]; minValue = std::min(minValue, currentValue); maxValue = std::max(maxValue, currentValue); } auto deltaY = (maxValue - minValue) / MAX_TICK_COUNT_PER_TIME; minValue = minValue - deltaY; maxValue = maxValue + deltaY; axisY_->setRange(minValue, maxValue); chart()->scroll(-dPos.x(), 0); lastMousePosition_ = event->pos(); event->accept(); } QChartView::mouseMoveEvent(event); } void CustomChartView::displayMarketData(const QDateTime &dateTime, double price) { std::string dayText = (dateTime.date().day() < 10) ? std::string("0") + std::to_string(dateTime.date().day()) : std::to_string(dateTime.date().day()); std::string monthText = (dateTime.date().month() < 10) ? std::string("0") + std::to_string(dateTime.date().month()) : std::to_string(dateTime.date().month()); std::string hourText = (dateTime.time().hour() < 10) ? std::string("0") + std::to_string(dateTime.time().hour()) : std::to_string(dateTime.time().hour()); std::string minuteText = (dateTime.time().minute() < 10) ? std::string("0") + std::to_string(dateTime.time().minute()) : std::to_string(dateTime.time().minute()); std::string secondText = (dateTime.time().second() < 10) ? std::string("0") + std::to_string(dateTime.time().second()) : std::to_string(dateTime.time().second()); std::string dateText = "closed date : " + dayText + ":" + monthText + "-" + hourText + ":" + minuteText + ":" + secondText; std::ostringstream stream; stream << std::fixed << std::setprecision(8) << price; std::string pp = stream.str(); std::string priceStr = "closed price : " + pp; currentPriceDisplayItem_->setText(QString::fromStdString(priceStr)); currentDateDisplayItem_->setText(QString::fromStdString(dateText)); } void CustomChartView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor)); lastMousePosition_ = event->pos(); event->accept(); } QChartView::mousePressEvent(event); } void CustomChartView::mouseReleaseEvent(QMouseEvent *event) { QApplication::restoreOverrideCursor(); event->accept(); QChartView::mouseReleaseEvent(event); } void CustomChartView::zoomChart(int delta) { if (delta > 0) { auto xMin = axisX_->min().toMSecsSinceEpoch(); auto xMax = axisX_->max().toMSecsSinceEpoch(); auto lowerLocalBound = std::lower_bound(marketDates_.begin(), marketDates_.end(), QDateTime::fromMSecsSinceEpoch(xMin)); auto upperLocalBound = std::upper_bound(marketDates_.begin(), marketDates_.end(), QDateTime::fromMSecsSinceEpoch(xMax)); std::vector<QDateTime> localRange(lowerLocalBound, upperLocalBound); if (localRange.size() < MIN_TICK_RANGE_ON_SCREEN) return; } else { auto frontTimestampLocal = marketDates_.front().toMSecsSinceEpoch(); auto backTimestampLocal = marketDates_.back().toMSecsSinceEpoch(); if (axisX_->min().toMSecsSinceEpoch() <= frontTimestampLocal && axisX_->max().toMSecsSinceEpoch() >= backTimestampLocal) { return; } } double factor = pow((double)2, delta / 240.0); chart()->zoom(factor); QPointF mousePos = mapFromGlobal(QCursor::pos()); auto axisXMin = axisX_->min().toMSecsSinceEpoch(); auto axisXMax = axisX_->max().toMSecsSinceEpoch(); auto frontTimestamp = marketDates_.front().toMSecsSinceEpoch(); auto backTimestamp = marketDates_.back().toMSecsSinceEpoch(); if (axisXMin <= frontTimestamp) { axisX_->setMin(QDateTime::fromMSecsSinceEpoch(frontTimestamp)); } if (axisXMax >= backTimestamp) { axisX_->setMax(QDateTime::fromMSecsSinceEpoch(backTimestamp)); } auto lowerBound = std::lower_bound(marketDates_.begin(), marketDates_.end(), QDateTime::fromMSecsSinceEpoch(axisXMin)); auto upperBound = std::upper_bound(marketDates_.begin(), marketDates_.end(), QDateTime::fromMSecsSinceEpoch(axisXMax)); std::vector<QDateTime> range(lowerBound, upperBound); double minValue = INT32_MAX; double maxValue = 0; for (auto &date : range) { double currentValue = marketDatesPrice_[date]; minValue = std::min(minValue, currentValue); maxValue = std::max(maxValue, currentValue); } auto deltaY = (maxValue - minValue) / MAX_TICK_COUNT_PER_TIME; minValue = minValue - deltaY; maxValue = maxValue + deltaY; axisY_->setRange(minValue, maxValue); lastMousePosition_ = mousePos; updateVerticalLine(mousePos); if (zoomIndex_.second) { zoomIndex_.first += delta; } } void CustomChartView::zoomIndex(int index) { zoomIndex_.first = index; } void CustomChartView::wheelEvent(QWheelEvent *event) { int delta = event->delta(); delta = (delta > 0) ? 120 : -120; zoomChart(delta); event->accept(); } void CustomChartView::updateVerticalLine(QPointF mousePos) { verticalSeries_->clear(); if (currentDateDisplayItem_ && currentPriceDisplayItem_) { auto msEpoch = mainChart_->mapToValue(mousePos).x(); QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(msEpoch); auto price = mainChart_->mapToValue(mousePos).y(); if (marketDates_.empty()) { verticalSeries_->append(dateTime.toMSecsSinceEpoch(), axisY_->min()); verticalSeries_->append(dateTime.toMSecsSinceEpoch(), axisY_->max()); displayMarketData(dateTime, price); } else { auto lowerBound = std::lower_bound(marketDates_.begin(), marketDates_.end(), dateTime); if (lowerBound != marketDates_.end()) { if (lowerBound == marketDates_.begin()) { auto elem = *marketDates_.begin(); verticalSeries_->append(elem.toMSecsSinceEpoch(), axisY_->min()); verticalSeries_->append(elem.toMSecsSinceEpoch(), axisY_->max()); displayMarketData(elem, marketDatesPrice_[elem]); } else { uint64_t previousIndex = lowerBound - marketDates_.begin(); auto prevElement = marketDates_[--previousIndex]; if (dateTime.toMSecsSinceEpoch() - prevElement.toMSecsSinceEpoch() < lowerBound->toMSecsSinceEpoch() - dateTime.toMSecsSinceEpoch()) { verticalSeries_->append(prevElement.toMSecsSinceEpoch(), axisY_->min()); verticalSeries_->append(prevElement.toMSecsSinceEpoch(), axisY_->max()); displayMarketData(prevElement, marketDatesPrice_[prevElement]); } else { verticalSeries_->append(lowerBound->toMSecsSinceEpoch(), axisY_->min()); verticalSeries_->append(lowerBound->toMSecsSinceEpoch(), axisY_->max()); auto &lowerBoundDate = *lowerBound; displayMarketData(lowerBoundDate, marketDatesPrice_[lowerBoundDate]); } } } else { auto lastDate = marketDates_.back(); displayMarketData(lastDate, marketDatesPrice_[lastDate]); verticalSeries_->append(lastDate.toMSecsSinceEpoch(), axisY_->min()); verticalSeries_->append(lastDate.toMSecsSinceEpoch(), axisY_->max()); } } } } void CustomChartView::refreshChartView(common::MarketHistoryPtr marketHistory, common::StockExchangeType stockExchangeType, common::charts::ChartPeriodType::Enum periodType, common::charts::ChartDisplayType::Enum displayType) { switch (displayType) { case common::charts::ChartDisplayType::MOUNTAINS: refreshMountainView(std::move(marketHistory), periodType); break; case common::charts::ChartDisplayType::CANDLES: refreshCandleView(std::move(marketHistory), periodType); break; case common::charts::ChartDisplayType::UNKNOWN: throw common::exceptions::UndefinedTypeException("Chart display type"); } const std::string &chartTitle = common::convertStockExchangeTypeToString(stockExchangeType); mainChart_->setTitle(QString::fromStdString(chartTitle)); } void CustomChartView::refreshMountainView(common::MarketHistoryPtr marketHistory, common::charts::ChartPeriodType::Enum periodType) { if (marketHistory->marketData_.empty()) return; lineSeries_->clear(); bottomSeries_->clear(); candleSeries_->clear(); marketDatesPrice_.clear(); marketDates_.clear(); mainChart_->removeAllSeries(); initializeSeries(); size_t candlesCount = marketHistory->marketData_.size(); double minPrice = marketHistory->marketData_.back().closePrice_; double maxPrice = marketHistory->marketData_.back().closePrice_; auto firstDate = marketHistory->marketData_.back().date_; QDateTime firstDateTime; firstDateTime.setDate(QDate(firstDate.year_, firstDate.month_, firstDate.day_)); firstDateTime.setTime(QTime(firstDate.hour_, firstDate.minute_, firstDate.second_)); QDateTime lastDateTime = firstDateTime; int maxTicksCount = 0; common::Date lastDateTick = getLastTick(periodType); size_t lastCandleIndex = 0; if (candlesCount > MAX_BARS_COUNT) { lastCandleIndex = candlesCount - MAX_BARS_COUNT; } for (size_t index = candlesCount - 1; index >= 0; --index) { auto marketData = marketHistory->marketData_[index]; if (marketData.date_ <= lastDateTick) break; if (index == lastCandleIndex) break; QDateTime todayDate; todayDate.setDate( QDate(marketData.date_.year_, marketData.date_.month_, marketData.date_.day_)); todayDate.setTime( QTime(marketData.date_.hour_, marketData.date_.minute_, marketData.date_.second_)); if (maxTicksCount < MAX_TICK_COUNT_PER_TIME) { minPrice = std::min(minPrice, marketData.closePrice_); maxPrice = std::max(maxPrice, marketData.closePrice_); firstDateTime = std::min(todayDate, firstDateTime); lastDateTime = std::max(todayDate, lastDateTime); maxTicksCount++; } lineSeries_->append(todayDate.toMSecsSinceEpoch(), marketData.closePrice_); bottomSeries_->append(todayDate.toMSecsSinceEpoch(), 0); marketDatesPrice_.insert(std::make_pair<>(todayDate, marketData.closePrice_)); marketDates_.push_front(todayDate); } setupChart(); auto deltaY = (maxPrice - minPrice) / MAX_TICK_COUNT_PER_TIME; minPrice = minPrice - deltaY; maxPrice = maxPrice + deltaY; axisY_->setRange(minPrice, maxPrice); axisX_->setRange(firstDateTime, lastDateTime); zoomIndex_.second = false; zoomChart(zoomIndex_.first); zoomIndex_.second = true; } void CustomChartView::refreshCandleView(common::MarketHistoryPtr marketHistory, common::charts::ChartPeriodType::Enum periodType) { if (marketHistory->marketData_.empty()) return; lineSeries_->clear(); bottomSeries_->clear(); candleSeries_->clear(); marketDatesPrice_.clear(); marketDates_.clear(); mainChart_->removeAllSeries(); initializeSeries(); double minPrice = marketHistory->marketData_.back().closePrice_; double maxPrice = marketHistory->marketData_.back().closePrice_; auto firstDate = marketHistory->marketData_.back().date_; QDateTime firstDateTime; firstDateTime.setDate(QDate(firstDate.year_, firstDate.month_, firstDate.day_)); firstDateTime.setTime(QTime(firstDate.hour_, firstDate.minute_, firstDate.second_)); QDateTime lastDateTime = firstDateTime; size_t candlesCount = marketHistory->marketData_.size(); common::Date latestDate = getLastTick(periodType); size_t lastCandleIndex = 0; if (candlesCount > MAX_BARS_COUNT) { lastCandleIndex = candlesCount - MAX_BARS_COUNT; } int maxTicksCount = 0; for (size_t index = candlesCount - 1; index >= 0; --index) { auto marketData = marketHistory->marketData_[index]; if (marketData.date_ <= latestDate) break; if (index == lastCandleIndex) break; QDateTime todayDate; todayDate.setDate( QDate(marketData.date_.year_, marketData.date_.month_, marketData.date_.day_)); todayDate.setTime( QTime(marketData.date_.hour_, marketData.date_.minute_, marketData.date_.second_)); if (maxTicksCount < MAX_TICK_COUNT_PER_TIME) { minPrice = std::min(minPrice, marketData.closePrice_); maxPrice = std::max(maxPrice, marketData.closePrice_); firstDateTime = std::min(todayDate, firstDateTime); lastDateTime = std::max(todayDate, lastDateTime); maxTicksCount++; } const qreal timestamp = todayDate.toMSecsSinceEpoch(); const qreal open = marketData.openPrice_; const qreal high = marketData.highPrice_; const qreal low = marketData.lowPrice_; const qreal close = marketData.closePrice_; auto candlestickSet = new QtCharts::QCandlestickSet(timestamp); candlestickSet->setOpen(open); candlestickSet->setHigh(high); candlestickSet->setLow(low); candlestickSet->setClose(close); candleSeries_->append(candlestickSet); marketDatesPrice_.insert(std::make_pair<>(todayDate, marketData.closePrice_)); marketDates_.push_back(todayDate); } std::reverse(marketDates_.begin(), marketDates_.end()); setupChart(); auto deltaY = (maxPrice - minPrice) / MAX_TICK_COUNT_PER_TIME; minPrice = minPrice - deltaY; maxPrice = maxPrice + deltaY; axisY_->setRange(minPrice, maxPrice); axisX_->setRange(firstDateTime, lastDateTime); zoomIndex_.second = false; zoomChart(zoomIndex_.first); zoomIndex_.second = true; } common::Date CustomChartView::getLastTick(common::charts::ChartPeriodType::Enum period) { switch (period) { case common::charts::ChartPeriodType::ONE_DAY: { common::Date latestDate = common::Date::getCurrentTime(); latestDate = common::Date::getDayBefore(latestDate, 1); return latestDate; } case common::charts::ChartPeriodType::ONE_WEEK: { common::Date latestDate = common::Date::getCurrentTime(); latestDate = common::Date::getDayBefore(latestDate, 7); return latestDate; } case common::charts::ChartPeriodType::ONE_MONTH: { common::Date latestDate = common::Date::getCurrentTime(); if (latestDate.month_ <= 1) { int difference = 1 - latestDate.month_; latestDate.year_ = latestDate.year_ - 1; latestDate.month_ = 12 - difference; } else { latestDate.month_ = latestDate.month_ - 1; } return latestDate; } case common::charts::ChartPeriodType::THREE_MONTH: { common::Date latestDate = common::Date::getCurrentTime(); if (latestDate.month_ <= 3) { int difference = 3 - latestDate.month_; latestDate.year_ = latestDate.year_ - 1; latestDate.month_ = 12 - difference; } else { latestDate.month_ = latestDate.month_ - 3; } return latestDate; } case common::charts::ChartPeriodType::SIX_MONTH: { common::Date latestDate = common::Date::getCurrentTime(); if (latestDate.month_ <= 6) { int difference = 6 - latestDate.month_; latestDate.year_ = latestDate.year_ - 1; latestDate.month_ = 12 - difference; } else { latestDate.month_ = latestDate.month_ - 6; } return latestDate; } case common::charts::ChartPeriodType::ONE_YEAR: { common::Date latestDate = common::Date::getCurrentTime(); latestDate.year_ = latestDate.year_ - 1; return latestDate; } case common::charts::ChartPeriodType::ALL: { common::Date latestDate{0, 0, 0, 0, 0, 0}; return latestDate; } default: throw common::exceptions::UndefinedTypeException("Chart Period Type"); } } void CustomChartView::resetChart() { lineSeries_->clear(); bottomSeries_->clear(); candleSeries_->clear(); marketDatesPrice_.clear(); marketDates_.clear(); auto currentDate = common::Date::getCurrentTime(); QDateTime todayDate, oneHourAhead; todayDate.setDate(QDate(currentDate.year_, currentDate.month_, currentDate.day_)); todayDate.setTime(QTime(currentDate.hour_, currentDate.minute_, currentDate.second_)); auto currentHour = currentDate.hour_; auto oneHourFromNow = currentHour == 23 ? 1 : currentHour + 1; oneHourAhead.setDate(QDate(currentDate.year_, currentDate.month_, currentDate.day_)); oneHourAhead.setTime(QTime(oneHourFromNow, currentDate.minute_, currentDate.second_)); marketDates_.push_back(todayDate); marketDates_.push_back(oneHourAhead); marketDatesPrice_[todayDate] = 0.5; marketDatesPrice_[oneHourAhead] = 0.5; lineSeries_->append(todayDate.toMSecsSinceEpoch(), 0.5); lineSeries_->append(oneHourAhead.toMSecsSinceEpoch(), 0.5); bottomSeries_->append(todayDate.toMSecsSinceEpoch(), 0); bottomSeries_->append(oneHourAhead.toMSecsSinceEpoch(), 0); mountainSeries_->setUpperSeries(lineSeries_); mountainSeries_->setLowerSeries(bottomSeries_); } void CustomChartView::initializeSeries() { lineSeries_ = new QtCharts::QLineSeries(this); verticalSeries_ = new QtCharts::QLineSeries(this); bottomSeries_ = new QtCharts::QLineSeries(this); mountainSeries_ = new QtCharts::QAreaSeries(this); candleSeries_ = new QtCharts::QCandlestickSeries(this); } void CustomChartView::setupChart() { candleSeries_->setIncreasingColor(QColor("#49974E")); candleSeries_->setDecreasingColor(QColor("#C62B2B")); mountainSeries_->setUpperSeries(lineSeries_); mountainSeries_->setLowerSeries(bottomSeries_); mainChart_->addSeries(mountainSeries_); mainChart_->addSeries(candleSeries_); mainChart_->addSeries(verticalSeries_); mountainSeries_->attachAxis(axisX_); mountainSeries_->attachAxis(axisY_); candleSeries_->attachAxis(axisX_); candleSeries_->attachAxis(axisY_); verticalSeries_->attachAxis(axisX_); verticalSeries_->attachAxis(axisY_); } } // namespace view } // namespace auto_trader
37.655436
94
0.69588
[ "vector" ]
8eb3bca81d2a8a146b84d515e4dd6adcb884c652
3,097
cpp
C++
src/lib/bms/Types.cpp
minium/bitcoin-messaging
74d8431e42718f2104f6f4838a24bc4e3cce1427
[ "Unlicense", "MIT" ]
7
2015-02-19T07:55:01.000Z
2021-04-20T07:50:19.000Z
src/lib/bms/Types.cpp
minium/bitcoin-messaging
74d8431e42718f2104f6f4838a24bc4e3cce1427
[ "Unlicense", "MIT" ]
null
null
null
src/lib/bms/Types.cpp
minium/bitcoin-messaging
74d8431e42718f2104f6f4838a24bc4e3cce1427
[ "Unlicense", "MIT" ]
6
2015-07-09T09:51:05.000Z
2018-05-10T17:30:39.000Z
/** * Types.cpp * * Types module with definitions of various types and * a set of auxiliary type conversion and manipulation operations. * * @author Krzysztof Okupski * @version 1.0 */ #include "Types.h" #include "util.h" #include <stdlib.h> #include <iostream> #include <random> using std::string; using std::vector; using std::stringstream; /** * Pads the binary vector with \p nBits zero's. * @param bits The binary vector to be padded. * @param nBits Number of padding bits. */ void PadBits(DataBits& bits, uint32_t nBits) { bits.insert(bits.end(), nBits, false); } /** * Cuts the first \p nBits bits out of the binary vector and returns them. * @param bits The binary vector to be sliced. * @param nBits Number of leading bits to be cut out. */ DataBits SliceBits(DataBits& bits, uint32_t nBits) { DataBits slice = DataBits(bits.begin(), bits.begin()+nBits); bits.erase(bits.begin(), bits.begin()+nBits); return slice; } /** * Converts a binary vector with exactly 8 elements into a character. * @param Vec Binary vector to be converted into a character. * @result Converted character. */ char BoolVecToChar(const vector<bool>& Vec) { assert(Vec.size() == 8); char c = 0x00; for (unsigned int i = 0; i < 8; i++) { c += (Vec[i] << (7 - i)); } return c; } /** * Converts a character into a binary vector with exactly 8 elements. * @param ch Character to be converted. * @result Converted binary vector. */ vector<bool> CharToBoolVec(char ch) { vector<bool> vec; for (unsigned int i = 0; i < 8; i++) { vec.push_back((ch >> (7 - i)) & 0x01); } return vec; } /** * Converts a vector of unsigned chars into a binary vector. * @param data Unsigned char vector to be converted. * @result Converted binary vector. */ DataBits DataToBits(const Data& data) { DataBits vec, tmp; for(Data::const_iterator it = data.begin(); it != data.end(); it++) { tmp = CharToBoolVec(*it); vec.insert(vec.end(), tmp.begin(), tmp.end()); } return vec; } /** * Converts a binary vector into a vector of unsigned chars. * @param data Binary vector to be converted. * @result Converted unsigned char vector. */ Data BitsToData(const DataBits& data) { assert(data.size() % 8 == 0); Data buf; DataBits slice; unsigned char tmp; for(unsigned int i = 0; i < data.size(); i+=8) { slice = DataBits(data.begin()+i, data.begin()+i+8); tmp = BoolVecToChar(slice); buf.push_back(tmp); } return buf; } /** * Converts a binary vector into an integer. * @param data Binary vector to be converted. * @result Converted integer. */ BigInt DataBitsToInt(const DataBits& data) { BigInt num = 0; for(unsigned int i = 0; i < data.size()-1; i++) { num += data[i] & 0x01; num *= 2; } num += data[data.size()-1] & 0x01; return num; } /** * Converts an integer into a binary vector. * @param num Integer to be converted. * @result Converted binary vector. */ DataBits IntToDataBits(BigInt num) { DataBits dataBits; while(num != 0) { dataBits.insert(dataBits.begin(), (bool)(num & 0x01)); num /= 2; } return dataBits; }
19.726115
74
0.663545
[ "vector" ]
8eb49207c46a9ef628f0410b79dfae4170cb44cf
1,426
cpp
C++
Plugins/org.blueberry.core.runtime/src/internal/berryHandle.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Plugins/org.blueberry.core.runtime/src/internal/berryHandle.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Plugins/org.blueberry.core.runtime/src/internal/berryHandle.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryHandle.h" #include "berryIObjectManager.h" namespace berry { Handle::Handle(const SmartPointer<const IObjectManager> &objectManager, int value) : objectManager(objectManager.GetPointer()) , objectId(value) , isStrongRef(true) { const_cast<IObjectManager*>(this->objectManager)->Register(); } Handle::Handle(const IObjectManager *objectManager, int value) : objectManager(objectManager) , objectId(value) , isStrongRef(false) { } Handle::~Handle() { if (isStrongRef) { const_cast<IObjectManager*>(objectManager)->UnRegister(); } } int Handle::GetId() const { return objectId; } bool Handle::operator==(const Object* object) const { if (const Handle* h = dynamic_cast<const Handle*>(object)) { return objectId == h->objectId; } return false; } uint Handle::HashCode() const { return static_cast<std::size_t>(objectId); } }
20.970588
83
0.629032
[ "object" ]
8ebdedfb8e9826df889c1725c4e6e4c55bf8d177
1,799
hpp
C++
src/components.hpp
Xelonidas/OdysseyGameEngine
f19082f07fbd9b8045e4cf304c656e9965c49d7e
[ "MIT" ]
1
2021-07-04T11:06:05.000Z
2021-07-04T11:06:05.000Z
src/components.hpp
Xelonidas/OdysseyGameEngine
f19082f07fbd9b8045e4cf304c656e9965c49d7e
[ "MIT" ]
null
null
null
src/components.hpp
Xelonidas/OdysseyGameEngine
f19082f07fbd9b8045e4cf304c656e9965c49d7e
[ "MIT" ]
null
null
null
#pragma once namespace oge { class component { public: virtual std::string toString() { return "Empty component"; } virtual void update() {} virtual void intervalUpdate() {} }; class helloWorldComponent : public component { public: std::string toString() override { return "Hello World component"; } void update() override { std::cout<<"Hello World updated"<<std::endl; } void intervalUpdate() override { std::cout<<"Hello World updated"<<std::endl; } }; class gameObject { public: int goId; std::vector<component*> components; float* transform; gameObject(int id) : goId(id), components({}) { transform = new float[4]; for (int i = 0; i < 4; i++) { transform[i] = 0.0; } } void update() { for(component* v : components) { v->update(); } } void intervalUpdate() { for(component* v : components) { v->intervalUpdate(); } } template<class T> T* getComponent() { T* toRet; for(component* comp : components) { if(toRet = dynamic_cast<T*>(comp)) return toRet; } return NULL; } template<class T> std::vector<T*> getComponents() { std::vector<T*> toRet; T* temp; for(component* comp : components) { if(temp = dynamic_cast<T*>(comp)) toRet.push_back(temp); } return toRet; } float getX() { return transform[0]; } float getY() { return transform[1]; } float getZ() { return transform[2]; } void setX(float x) { transform[0] = x; } void setY(float y) { transform[1] = y; } void setZ(float z) { transform[2] = z; } void setPos(float x, float y, float z) { transform[0] = x; transform[1] = y; transform[2] = z; } void setAngle(float ang) { transform[3] = ang; } float getAngle() { return transform[3]; } }; }
20.918605
81
0.599778
[ "vector", "transform" ]
8ec45f37315d734da75143b4f12dff5d42e84514
6,344
cc
C++
lib/base/database/SParDatabaseSource.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
null
null
null
lib/base/database/SParDatabaseSource.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
3
2020-05-06T18:22:40.000Z
2020-05-26T14:00:23.000Z
lib/base/database/SParDatabaseSource.cc
SiFi-CC/sifi-framework
8dba20dcc4dc8b25ca000d58e6eac27b2a94eb55
[ "MIT" ]
4
2021-02-11T10:44:29.000Z
2021-06-17T10:50:23.000Z
// @(#)lib/base:$Id$ // Author: Rafal Lalik 18/11/2017 /************************************************************************* * Copyright (C) 2017-2018, Rafał Lalik. * * All rights reserved. * * * * For the licensing terms see $SiFiSYS/LICENSE. * * For the list of contributors see $SiFiSYS/README/CREDITS. * *************************************************************************/ #include "SParDatabaseSource.h" #include "SContainer.h" #include "SDatabase.h" #include "tabulate/cell.hpp" // for Cell #include "tabulate/color.hpp" // for Color, Color::red, Color::yellow #include "tabulate/column.hpp" // for Column, ColumnFormat::font_align #include "tabulate/column_format.hpp" // for ColumnFormat #include "tabulate/font_align.hpp" // for FontAlign, FontAlign::center #include "tabulate/font_style.hpp" // for FontStyle, FontStyle::bold #include "tabulate/format.hpp" // for Format #include "tabulate/row.hpp" // for Row #include "tabulate/table_internal.hpp" // for Cell::format #include <ctime> #include <cxxabi.h> // for __forced_unwind #include <iomanip> #include <iostream> #include <string_view> #include <utility> // for pair #include <variant> // for variant /** * \class SParDatabaseSource \ingroup lib_base_database Reads parameters from the database file. Parameters in the database are organized in: * releases - collections of paramaters related to given experiment, test, measurement * versions (ranges) - specific value of parameters valid in specific time range * runid - run number (from DAQ) The database interface must provide following interface: 1. Getting data from database: - Read parameater values for given time slice `getContainer(release : string, container_name : string, runid : long) -> SContainer` - Read all paramater ranges for given release `getContainer(release : string, container_name : string) -> std::vector<SContainer>` - Read selected paramater ranges for given release `getContainer(release : string, range : range) -> std::vector<SContainer>` 2. Writing data from database: - Write slice (ascii) to database as range. Returns 0 if succeed, otherwise positive value as error code (e.g. 1 - overlap, etc.) `writeContainer(release : string, container_name : string, range : range, container : SContainer) -> int` */ /** * Constructor. * * \param source ascii source file name */ SParDatabaseSource::SParDatabaseSource() : SParSource() { mysqlcon = std::make_unique<SMysqlInterface>("http://localhost", 1234); parseSource(); } /** * Parse source file. Implemented based on hadd.C from ROOT. * * \return success */ bool SParDatabaseSource::parseSource() { return true; } SContainer* SParDatabaseSource::getContainer(const std::string& name, long runid) { // check if same release std::string_view release = SDatabase::instance()->getRelease(); // TODO if release has name, then check whether it matches the one from file // if (!release.empty() and release != this_release_from_file) return 0; // DB call // DBOBJECT->getContainer(release, name, runid); mysqlcon->setParamRelease(release); mysqlcon->getContainer(name, runid); // check if container is in the source at all auto it = containers.find(name); if (it == containers.end()) { return nullptr; } // if it was the same version like before, return cached one SContainer* last = last_container[name]; if (last and last->validity == runid) return last; // get fresh version, need to set flag reinit! TODO // also runid -> time conversion auto time = runid; auto&& cont_map = containers[name]; auto it2 = cont_map.lower_bound(validity_range_t(time, time)); if (it2 != cont_map.end()) { if (it2->second->validity == time) { // TODO force DB to reinit here return it2->second; } } return nullptr; } bool SParDatabaseSource::setContainer(const std::string& name, SContainer&& cont) { // check if same release std::string_view release = SDatabase::instance()->getRelease(); // TODO if release has name, then check whether it matches the one from file // if (!release.empty() and release != this_release_from_file) return 0; // DB call // DBOBJECT->getContainer(release, name, runid); mysqlcon->setParamRelease(release); return mysqlcon->addContainer(std::move(name), std::move(cont)); } #include "tabulate/table.hpp" using namespace tabulate; void SParDatabaseSource::print() const { std::cout << "=== Daatbase Source Info ===" << std::endl; std::cout << " Database: " << source << std::endl; for (auto& container : containers) { const validity_range_t* cache = nullptr; Table cont_summary; cont_summary.add_row({container.first, "Valid from", "Valid to", "Overlap", "Truncated"}); for (auto& revision : container.second) { std::stringstream s_from; s_from << std::put_time(std::gmtime(&revision.first.from), "%c %Z"); std::stringstream s_to; s_to << std::put_time(std::gmtime(&revision.first.to), "%c %Z"); std::stringstream trunc_from; if (revision.first.truncated > 0) trunc_from << std::put_time(std::gmtime(&revision.first.truncated), "%c %Z"); bool overlap = cache ? revision.first.check_overlap(*cache) : false; cont_summary.add_row( {"", s_from.str(), s_to.str(), std::to_string(overlap), trunc_from.str()}); cache = &revision.first; } cont_summary.column(3).format().font_align(FontAlign::center); cont_summary.column(4).format().font_align(FontAlign::center).font_color(Color::red); for (size_t i = 0; i < 5; ++i) { cont_summary[0][i] .format() .font_color(Color::yellow) .font_align(FontAlign::center) .font_style({FontStyle::bold}); } std::cout << cont_summary << std::endl; } }
33.566138
98
0.618064
[ "vector" ]
8ec4f1bc3b8a47f94cd1c81cde067bd69d46151d
1,548
cpp
C++
prog/potienko/block_2_3/lab_1/calculator.cpp
pashchenkoromak/jParcs
5d91ef6fdd983300e850599d04a469c17238fc65
[ "MIT" ]
2
2019-10-01T09:41:15.000Z
2021-06-06T17:46:13.000Z
prog/potienko/block_2_3/lab_1/calculator.cpp
pashchenkoromak/jParcs
5d91ef6fdd983300e850599d04a469c17238fc65
[ "MIT" ]
1
2018-05-18T18:20:46.000Z
2018-05-18T18:20:46.000Z
prog/potienko/block_2_3/lab_1/calculator.cpp
pashchenkoromak/jParcs
5d91ef6fdd983300e850599d04a469c17238fc65
[ "MIT" ]
8
2017-01-20T15:44:06.000Z
2021-11-28T20:00:49.000Z
// // Created by lionell on 5/13/15. // #include "calculator.h" #include <stack> #include <typeinfo> BigFloat evaluate(const BigFloat &left, const std::string &operation) { BigFloat result; if (operation == "@") result = -left; return result; } BigFloat evaluate(const BigFloat &left, const BigFloat &right, const std::string &operation) { BigFloat result; if (operation == "+") result = left + right; else if (operation == "-") result = left - right; else if (operation == "*") result = left * right; else if (operation == "/") result = left / right; else if (operation == "^") result = left ^ right; return result; } BigFloat calculate(std::vector<Token*> rpn) { std::stack<BigFloat> stack1; for (auto& token: rpn) { if (typeid(*token) == typeid(Number)) { Number *number = static_cast<Number*>(token); stack1.push(number->get_value()); } else if (typeid(*token) == typeid(UnaryOperator)) { UnaryOperator *operation = static_cast<UnaryOperator*>(token); BigFloat left = stack1.top(); stack1.pop(); stack1.push(evaluate(left, operation->get_value())); } else if (typeid(*token) == typeid(BinaryOperator)) { BinaryOperator *operation = static_cast<BinaryOperator*>(token); BigFloat right = stack1.top(); stack1.pop(); BigFloat left = stack1.top(); stack1.pop(); stack1.push(evaluate(left, right, operation->get_value())); } } return stack1.top(); }
36
94
0.607235
[ "vector" ]
8ecca30ac19f465f3605327e995108224df4c5ae
732
cpp
C++
Assignment 4/Assingnment 4/Assingnment 4/HighContrast.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 4/Assingnment 4/Assingnment 4/HighContrast.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 4/Assingnment 4/Assingnment 4/HighContrast.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
/* Assignment: 4 Description: Paycheck Calculator Author: Justin Harper WSU ID: 10696738 Completion Time: 4hrs In completing this program, I received help from the following people: myself version 1.0 (major relese) I am happy with this version! */ #include "HighContrast.h" using namespace std; //class to convert image to highcontrast void HighContrast::processImage(vector<Point>& points) { //follows algorthym oovided in descrpiton for (int i = 0; i < points.size(); i++) { if (points[i].getRed() > (255 / 2)) { points[i].setRed(255); } if (points[i].getGreen() > (255 / 2)) { points[i].setGreen(255); } if (points[i].getBlue() > (255 / 2)) { points[i].setBlue(255); } } return; }
15.913043
70
0.659836
[ "vector" ]
8ed7ffccd59d4ec461a0d6f161ddcfda4ba2ea66
724
cc
C++
algorithm/sort/is_sorted_until.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
1
2015-09-11T00:33:43.000Z
2015-09-11T00:33:43.000Z
algorithm/sort/is_sorted_until.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
null
null
null
algorithm/sort/is_sorted_until.cc
HelloCodeMing/ToySTL
8221688f8674ab214e3e57abe262b02f952c8036
[ "MIT" ]
null
null
null
#include <predef.hpp> template <class Iter, class T = typename std::iterator_traits<Iter>::value_type, class Cmp = std::less<T>> Iter is_sorted_until(Iter first, Iter last, Cmp cmp = Cmp()) { --last; for (; first != last; ++first) { auto next = std::next(first); if (!cmp(*first, *(next))) return next; } ++last; return last; } int main() { { std::vector<int> vec = { 1, 2, 3, 4, -1, 5 }; auto i = ::is_sorted_until(vec.begin(), vec.end()); assert(*i == -1); } { std::vector<int> vec = {1, 2, 3}; auto i = ::is_sorted_until(vec.begin(), vec.end()); assert(i == vec.end()); } return 0; }
23.354839
67
0.498619
[ "vector" ]
8ed88b17bcbaa660b3af44243b10bc1d97859e34
25,921
hpp
C++
src/ratehelpers.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
27
2016-11-19T16:51:21.000Z
2021-09-08T16:44:15.000Z
src/ratehelpers.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
1
2016-12-28T16:38:38.000Z
2017-02-17T05:32:13.000Z
src/ratehelpers.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
10
2016-12-28T02:31:38.000Z
2021-06-15T09:02:07.000Z
/* Copyright (C) 2016 -2017 Jerry Jin */ #ifndef ratehelpers_h #define ratehelpers_h #include <nan.h> #include <string> #include <queue> #include <utility> #include "../quantlibnode.hpp" #include <oh/objecthandler.hpp> using namespace node; using namespace v8; using namespace std; class DepositRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mRate; string mIborIndex; string mReturnValue; string mError; DepositRateHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Rate ,string IborIndex ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mRate(Rate) ,mIborIndex(IborIndex) { }; //~DepositRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DepositRateHelper2Worker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mRate; string mTenor; ObjectHandler::property_t mFixingDays; string mCalendar; string mConvention; bool mEndOfMonth; string mDayCounter; string mReturnValue; string mError; DepositRateHelper2Worker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Rate ,string Tenor ,ObjectHandler::property_t FixingDays ,string Calendar ,string Convention ,bool EndOfMonth ,string DayCounter ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mRate(Rate) ,mTenor(Tenor) ,mFixingDays(FixingDays) ,mCalendar(Calendar) ,mConvention(Convention) ,mEndOfMonth(EndOfMonth) ,mDayCounter(DayCounter) { }; //~DepositRateHelper2Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SwapRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mRate; string mSwapIndex; ObjectHandler::property_t mSpread; string mForwardStart; ObjectHandler::property_t mDiscountingCurve; string mPillarDate; ObjectHandler::property_t mCustomPillarDate; string mReturnValue; string mError; SwapRateHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Rate ,string SwapIndex ,ObjectHandler::property_t Spread ,string ForwardStart ,ObjectHandler::property_t DiscountingCurve ,string PillarDate ,ObjectHandler::property_t CustomPillarDate ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mRate(Rate) ,mSwapIndex(SwapIndex) ,mSpread(Spread) ,mForwardStart(ForwardStart) ,mDiscountingCurve(DiscountingCurve) ,mPillarDate(PillarDate) ,mCustomPillarDate(CustomPillarDate) { }; //~SwapRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SwapRateHelper2Worker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mRate; ObjectHandler::property_t mSettlDays; string mTenor; string mCalendar; string mFixedLegFrequency; string mFixedLegConvention; string mFixedLegDayCounter; string mIborIndex; ObjectHandler::property_t mSpread; string mForwardStart; ObjectHandler::property_t mDiscountingCurve; string mPillarDate; ObjectHandler::property_t mCustomPillarDate; string mReturnValue; string mError; SwapRateHelper2Worker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Rate ,ObjectHandler::property_t SettlDays ,string Tenor ,string Calendar ,string FixedLegFrequency ,string FixedLegConvention ,string FixedLegDayCounter ,string IborIndex ,ObjectHandler::property_t Spread ,string ForwardStart ,ObjectHandler::property_t DiscountingCurve ,string PillarDate ,ObjectHandler::property_t CustomPillarDate ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mRate(Rate) ,mSettlDays(SettlDays) ,mTenor(Tenor) ,mCalendar(Calendar) ,mFixedLegFrequency(FixedLegFrequency) ,mFixedLegConvention(FixedLegConvention) ,mFixedLegDayCounter(FixedLegDayCounter) ,mIborIndex(IborIndex) ,mSpread(Spread) ,mForwardStart(ForwardStart) ,mDiscountingCurve(DiscountingCurve) ,mPillarDate(PillarDate) ,mCustomPillarDate(CustomPillarDate) { }; //~SwapRateHelper2Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class OISRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mSettlDays; string mTenor; ObjectHandler::property_t mFixedRate; string mONIndex; ObjectHandler::property_t mDiscountingCurve; string mReturnValue; string mError; OISRateHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t SettlDays ,string Tenor ,ObjectHandler::property_t FixedRate ,string ONIndex ,ObjectHandler::property_t DiscountingCurve ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mSettlDays(SettlDays) ,mTenor(Tenor) ,mFixedRate(FixedRate) ,mONIndex(ONIndex) ,mDiscountingCurve(DiscountingCurve) { }; //~OISRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class DatedOISRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mStartDate; ObjectHandler::property_t mEndDate; ObjectHandler::property_t mFixedRate; string mONIndex; ObjectHandler::property_t mDiscountingCurve; string mReturnValue; string mError; DatedOISRateHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t StartDate ,ObjectHandler::property_t EndDate ,ObjectHandler::property_t FixedRate ,string ONIndex ,ObjectHandler::property_t DiscountingCurve ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mStartDate(StartDate) ,mEndDate(EndDate) ,mFixedRate(FixedRate) ,mONIndex(ONIndex) ,mDiscountingCurve(DiscountingCurve) { }; //~DatedOISRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FraRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mRate; string mPeriodToStart; string mIborIndex; string mPillarDate; ObjectHandler::property_t mCustomPillarDate; string mReturnValue; string mError; FraRateHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Rate ,string PeriodToStart ,string IborIndex ,string PillarDate ,ObjectHandler::property_t CustomPillarDate ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mRate(Rate) ,mPeriodToStart(PeriodToStart) ,mIborIndex(IborIndex) ,mPillarDate(PillarDate) ,mCustomPillarDate(CustomPillarDate) { }; //~FraRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FraRateHelper2Worker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mRate; string mPeriodToStart; ObjectHandler::property_t mLengthInMonths; ObjectHandler::property_t mFixingDays; string mCalendar; string mConvention; bool mEndOfMonth; string mDayCounter; string mPillarDate; ObjectHandler::property_t mCustomPillarDate; string mReturnValue; string mError; FraRateHelper2Worker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Rate ,string PeriodToStart ,ObjectHandler::property_t LengthInMonths ,ObjectHandler::property_t FixingDays ,string Calendar ,string Convention ,bool EndOfMonth ,string DayCounter ,string PillarDate ,ObjectHandler::property_t CustomPillarDate ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mRate(Rate) ,mPeriodToStart(PeriodToStart) ,mLengthInMonths(LengthInMonths) ,mFixingDays(FixingDays) ,mCalendar(Calendar) ,mConvention(Convention) ,mEndOfMonth(EndOfMonth) ,mDayCounter(DayCounter) ,mPillarDate(PillarDate) ,mCustomPillarDate(CustomPillarDate) { }; //~FraRateHelper2Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class BondHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mPrice; string mBond; bool mUseCleanPrice; string mReturnValue; string mError; BondHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Price ,string Bond ,bool UseCleanPrice ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mPrice(Price) ,mBond(Bond) ,mUseCleanPrice(UseCleanPrice) { }; //~BondHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FixedRateBondHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mPrice; long mSettlementDays; double mFaceAmount; string mScheduleID; std::vector<double> mCoupons; string mDayCounter; string mPaymentBDC; double mRedemption; ObjectHandler::property_t mIssueDate; string mPaymentCalendar; string mExCouponPeriod; string mExCouponCalendar; string mExCouponBDC; bool mExCouponEndOfMonth; bool mUseCleanPrice; string mReturnValue; string mError; FixedRateBondHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Price ,long SettlementDays ,double FaceAmount ,string ScheduleID ,std::vector<double> Coupons ,string DayCounter ,string PaymentBDC ,double Redemption ,ObjectHandler::property_t IssueDate ,string PaymentCalendar ,string ExCouponPeriod ,string ExCouponCalendar ,string ExCouponBDC ,bool ExCouponEndOfMonth ,bool UseCleanPrice ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mPrice(Price) ,mSettlementDays(SettlementDays) ,mFaceAmount(FaceAmount) ,mScheduleID(ScheduleID) ,mCoupons(Coupons) ,mDayCounter(DayCounter) ,mPaymentBDC(PaymentBDC) ,mRedemption(Redemption) ,mIssueDate(IssueDate) ,mPaymentCalendar(PaymentCalendar) ,mExCouponPeriod(ExCouponPeriod) ,mExCouponCalendar(ExCouponCalendar) ,mExCouponBDC(ExCouponBDC) ,mExCouponEndOfMonth(ExCouponEndOfMonth) ,mUseCleanPrice(UseCleanPrice) { }; //~FixedRateBondHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FuturesRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mPrice; string mFuturesType; ObjectHandler::property_t mFuturesDate; string mIborIndex; ObjectHandler::property_t mConvexityAdjQuote; string mReturnValue; string mError; FuturesRateHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Price ,string FuturesType ,ObjectHandler::property_t FuturesDate ,string IborIndex ,ObjectHandler::property_t ConvexityAdjQuote ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mPrice(Price) ,mFuturesType(FuturesType) ,mFuturesDate(FuturesDate) ,mIborIndex(IborIndex) ,mConvexityAdjQuote(ConvexityAdjQuote) { }; //~FuturesRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FuturesRateHelper2Worker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mPrice; string mFuturesType; ObjectHandler::property_t mFuturesDate; long mLengthInMonths; string mCalendar; string mConvention; bool mEndOfMonth; string mDayCounter; ObjectHandler::property_t mConvexityAdjQuote; string mReturnValue; string mError; FuturesRateHelper2Worker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Price ,string FuturesType ,ObjectHandler::property_t FuturesDate ,long LengthInMonths ,string Calendar ,string Convention ,bool EndOfMonth ,string DayCounter ,ObjectHandler::property_t ConvexityAdjQuote ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mPrice(Price) ,mFuturesType(FuturesType) ,mFuturesDate(FuturesDate) ,mLengthInMonths(LengthInMonths) ,mCalendar(Calendar) ,mConvention(Convention) ,mEndOfMonth(EndOfMonth) ,mDayCounter(DayCounter) ,mConvexityAdjQuote(ConvexityAdjQuote) { }; //~FuturesRateHelper2Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FuturesRateHelper3Worker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mPrice; string mFuturesType; ObjectHandler::property_t mFuturesDate; ObjectHandler::property_t mEndDate; string mDayCounter; ObjectHandler::property_t mConvexityAdjQuote; string mReturnValue; string mError; FuturesRateHelper3Worker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t Price ,string FuturesType ,ObjectHandler::property_t FuturesDate ,ObjectHandler::property_t EndDate ,string DayCounter ,ObjectHandler::property_t ConvexityAdjQuote ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mPrice(Price) ,mFuturesType(FuturesType) ,mFuturesDate(FuturesDate) ,mEndDate(EndDate) ,mDayCounter(DayCounter) ,mConvexityAdjQuote(ConvexityAdjQuote) { }; //~FuturesRateHelper3Worker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mFwdPoint; ObjectHandler::property_t mSpotFx; string mTenor; ObjectHandler::property_t mFixingDays; string mCalendar; string mConvention; bool mEndOfMonth; bool mIsFxBaseCurrencyCollateralCurrency; ObjectHandler::property_t mCollateralCurve; string mReturnValue; string mError; FxSwapRateHelperWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t FwdPoint ,ObjectHandler::property_t SpotFx ,string Tenor ,ObjectHandler::property_t FixingDays ,string Calendar ,string Convention ,bool EndOfMonth ,bool IsFxBaseCurrencyCollateralCurrency ,ObjectHandler::property_t CollateralCurve ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mFwdPoint(FwdPoint) ,mSpotFx(SpotFx) ,mTenor(Tenor) ,mFixingDays(FixingDays) ,mCalendar(Calendar) ,mConvention(Convention) ,mEndOfMonth(EndOfMonth) ,mIsFxBaseCurrencyCollateralCurrency(IsFxBaseCurrencyCollateralCurrency) ,mCollateralCurve(CollateralCurve) { }; //~FxSwapRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperEarliestDateWorker : public Nan::AsyncWorker { public: string mObjectID; long mReturnValue; string mError; RateHelperEarliestDateWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperEarliestDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperLatestRelevantDateWorker : public Nan::AsyncWorker { public: string mObjectID; long mReturnValue; string mError; RateHelperLatestRelevantDateWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperLatestRelevantDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperPillarDateWorker : public Nan::AsyncWorker { public: string mObjectID; long mReturnValue; string mError; RateHelperPillarDateWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperPillarDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperMaturityDateWorker : public Nan::AsyncWorker { public: string mObjectID; long mReturnValue; string mError; RateHelperMaturityDateWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperMaturityDateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperQuoteNameWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; RateHelperQuoteNameWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperQuoteNameWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperQuoteValueWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; RateHelperQuoteValueWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperQuoteValueWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperQuoteIsValidWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; RateHelperQuoteIsValidWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperQuoteIsValidWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperImpliedQuoteWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; RateHelperImpliedQuoteWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperImpliedQuoteWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperQuoteErrorWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; RateHelperQuoteErrorWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~RateHelperQuoteErrorWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SwapRateHelperSpreadWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; SwapRateHelperSpreadWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SwapRateHelperSpreadWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class SwapRateHelperForwardStartWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; SwapRateHelperForwardStartWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~SwapRateHelperForwardStartWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FuturesRateHelperConvexityAdjustmentWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; FuturesRateHelperConvexityAdjustmentWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FuturesRateHelperConvexityAdjustmentWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperSpotValueWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; FxSwapRateHelperSpotValueWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FxSwapRateHelperSpotValueWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperTenorWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; FxSwapRateHelperTenorWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FxSwapRateHelperTenorWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperFixingDaysWorker : public Nan::AsyncWorker { public: string mObjectID; long mReturnValue; string mError; FxSwapRateHelperFixingDaysWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FxSwapRateHelperFixingDaysWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperCalendarWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; FxSwapRateHelperCalendarWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FxSwapRateHelperCalendarWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperBDCWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; FxSwapRateHelperBDCWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FxSwapRateHelperBDCWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperEOMWorker : public Nan::AsyncWorker { public: string mObjectID; bool mReturnValue; string mError; FxSwapRateHelperEOMWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FxSwapRateHelperEOMWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class FxSwapRateHelperIsBaseCurrencyCollateralCurrencyWorker : public Nan::AsyncWorker { public: string mObjectID; bool mReturnValue; string mError; FxSwapRateHelperIsBaseCurrencyCollateralCurrencyWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~FxSwapRateHelperIsBaseCurrencyCollateralCurrencyWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperSelectionWorker : public Nan::AsyncWorker { public: std::vector<string> mRateHelpers; std::vector<ObjectHandler::property_t> mPriority; ObjectHandler::property_t mNImmFutures; ObjectHandler::property_t mNSerialFutures; ObjectHandler::property_t mFutureRollDays; string mDepoInclusion; std::vector<ObjectHandler::property_t> mMinDistance; std::vector<string> mReturnValue; string mError; RateHelperSelectionWorker( Nan::Callback *callback ,std::vector<string> RateHelpers ,std::vector<ObjectHandler::property_t> Priority ,ObjectHandler::property_t NImmFutures ,ObjectHandler::property_t NSerialFutures ,ObjectHandler::property_t FutureRollDays ,string DepoInclusion ,std::vector<ObjectHandler::property_t> MinDistance ): Nan::AsyncWorker(callback) ,mRateHelpers(RateHelpers) ,mPriority(Priority) ,mNImmFutures(NImmFutures) ,mNSerialFutures(NSerialFutures) ,mFutureRollDays(FutureRollDays) ,mDepoInclusion(DepoInclusion) ,mMinDistance(MinDistance) { }; //~RateHelperSelectionWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class RateHelperRateWorker : public Nan::AsyncWorker { public: string mRateHelper; double mReturnValue; string mError; RateHelperRateWorker( Nan::Callback *callback ,string RateHelper ): Nan::AsyncWorker(callback) ,mRateHelper(RateHelper) { }; //~RateHelperRateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; #endif
19.592593
88
0.666178
[ "vector" ]
8edef8ac18d5127e04fca47001d190f71f3f4acc
20,976
cpp
C++
sphero_gazebo/src/gazebo_sphero_controller.cpp
ovgu-FINken/SpheroSim
bcdeef58020d531b862d21f7d14a0072ee9f0b1c
[ "MIT" ]
1
2017-11-30T10:36:30.000Z
2017-11-30T10:36:30.000Z
sphero_gazebo/src/gazebo_sphero_controller.cpp
ovgu-FINken/SpheroSim
bcdeef58020d531b862d21f7d14a0072ee9f0b1c
[ "MIT" ]
null
null
null
sphero_gazebo/src/gazebo_sphero_controller.cpp
ovgu-FINken/SpheroSim
bcdeef58020d531b862d21f7d14a0072ee9f0b1c
[ "MIT" ]
null
null
null
/* * \file gazebo_sphero_controller.cpp * * \brief A differential drive plugin for gazebo. Based on the diffdrive plugin * developed for the erratic robot. The original * plugin can be found in the ROS package gazebo_erratic_plugins. * * A modification from the original Differential drive of Gazebo * To make the Sphero simulated robot move using any keyboard teleop * \author Ricardo Tellez <rtellez@theconstructsim.com> * \date 11th of Aug 2016 * * $ Id: 08/11/2016 20:05:40 PM ouroboros $ */ #include <algorithm> #include <assert.h> #include <sphero_gazebo/gazebo_sphero_controller.h> #include <sphero_error_inject/error.h> #include <sphero_error_mapping/error_insert.h> #include <gazebo/math/gzmath.hh> #include <sdf/sdf.hh> #include <ros/ros.h> using namespace sphero_error_mapping; using namespace sphero_error_inject; using namespace std; namespace gazebo { enum { RIGHT, LEFT, }; GazeboSpheroController::GazeboSpheroController() {} // Destructor GazeboSpheroController::~GazeboSpheroController() {} // Load the controller void GazeboSpheroController::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) { this->parent = _parent; gazebo_ros_ = GazeboRosPtr(new GazeboRos(_parent, _sdf, "DiffDrive")); // Make sure the ROS node for Gazebo has already been initialized gazebo_ros_->isInitialized(); gazebo_ros_->getParameter<std::string>(command_topic_, "commandTopic", "sphero/cmd_vel"); gazebo_ros_->getParameter<std::string>(odometry_topic_, "odometryTopic", "odom"); gazebo_ros_->getParameter<std::string>(position_topic_, "positionTopic", "pos"); gazebo_ros_->getParameter<std::string>(odometry_frame_, "odometryFrame", "/odom_frame"); gazebo_ros_->getParameter<std::string>(robot_base_frame_, "robotBaseFrame", "base_footprint"); gazebo_ros_->getParameterBoolean(publishWheelTF_, "publishWheelTF", false); gazebo_ros_->getParameterBoolean(publishWheelJointState_, "publishWheelJointState", false); gazebo_ros_->getParameter<double>(wheel_separation_, "wheelSeparation", 0.34); gazebo_ros_->getParameter<double>(wheel_diameter_, "wheelDiameter", 0.1); gazebo_ros_->getParameter<double>(wheel_accel, "wheelAcceleration", 0.0); gazebo_ros_->getParameter<double>(wheel_torque, "wheelTorque", 0.02); gazebo_ros_->getParameter<double>(update_rate_, "updateRate", 10.0); std::map<std::string, OdomSource> odomOptions; odomOptions["encoder"] = ENCODER; odomOptions["world"] = WORLD; gazebo_ros_->getParameter<OdomSource>(odom_source_, "odometrySource", odomOptions, WORLD); joints_.resize ( 2 ); joints_[LEFT] = gazebo_ros_->getJoint(parent, "leftJoint", "left_joint"); joints_[RIGHT] = gazebo_ros_->getJoint(parent, "rightJoint", "right_joint"); joints_[LEFT]->SetParam("fmax", 0, wheel_torque); joints_[RIGHT]->SetParam("fmax", 0, wheel_torque); this->publish_tf_ = true; if (!_sdf->HasElement("publishTf")) { ROS_WARN("GazeboSpheroController Plugin (ns = %s) missing <publishTf>, defaults to %d", this->robot_namespace_.c_str(), this->publish_tf_); } else { this->publish_tf_ = _sdf->GetElement("publishTf")->Get<bool>(); } // Initialize update rate stuff if ( this->update_rate_ > 0.0 ) this->update_period_ = 1.0 / this->update_rate_; else this->update_period_ = 0.0; last_update_time_ = parent->GetWorld()->GetSimTime(); // Initialize velocity stuff wheel_speed_[RIGHT] = 0; wheel_speed_[LEFT] = 0; x_ = 0; rot_ = 0; alive_ = true; if (this->publishWheelJointState_) { joint_state_publisher_ = gazebo_ros_->node()->advertise<sensor_msgs::JointState>("joint_states", 1000); ROS_INFO("%s: Advertise joint_states!", gazebo_ros_->info()); } transform_broadcaster_ = boost::shared_ptr<tf::TransformBroadcaster>(new tf::TransformBroadcaster()); // ROS: Subscribe to the velocity command topic (usually "cmd_vel") ROS_INFO("%s: Try to subscribe to %s!", gazebo_ros_->info(), command_topic_.c_str()); ros::SubscribeOptions so = ros::SubscribeOptions::create<geometry_msgs::Twist>(command_topic_, 1, boost::bind(&GazeboSpheroController::cmdVelCallback, this, _1), ros::VoidPtr(), &queue_); cmd_vel_subscriber_ = gazebo_ros_->node()->subscribe(so); ROS_INFO("%s: Subscribe to %s!", gazebo_ros_->info(), command_topic_.c_str()); reportClient_ = gazebo_ros_->node()->serviceClient<sphero_error_mapping::error_insert>("/sphero_error_mapping/insert_error"); if (this->publish_tf_) { odometry_publisher_ = gazebo_ros_->node()->advertise<nav_msgs::Odometry>(odometry_topic_, 1); ROS_INFO("%s: Advertise odom on %s !", gazebo_ros_->info(), odometry_topic_.c_str()); position_publisher_ = gazebo_ros_->node()->advertise<geometry_msgs::Pose2D>(position_topic_, 1); ROS_INFO("%s: Advertise position on %s !", gazebo_ros_->info(), position_topic_.c_str()); } errorClient_ = gazebo_ros_->node()->serviceClient<sphero_error_inject::error>("get_position_error"); // start custom queue for diff drive this->callback_queue_thread_ = boost::thread(boost::bind(&GazeboSpheroController::QueueThread, this)); // listen to the update event (broadcast every simulation iteration) this->update_connection_ = event::Events::ConnectWorldUpdateBegin ( boost::bind ( &GazeboSpheroController::UpdateChild, this ) ); // initialize prediction math::Pose world_pose = parent->GetWorldPose(); predict_pose_.x = world_pose.pos.x; predict_pose_.y = world_pose.pos.y; // get the orientation from the simulation double theta = world_pose.rot.GetYaw(); predict_pose_.theta = theta * 180; } void GazeboSpheroController::Reset() { last_update_time_ = parent->GetWorld()->GetSimTime(); pose_encoder_.x = 0; pose_encoder_.y = 0; pose_encoder_.theta = 0; x_ = 0; rot_ = 0; joints_[LEFT]->SetParam ( "fmax", 0, wheel_torque ); joints_[RIGHT]->SetParam ( "fmax", 0, wheel_torque ); } void GazeboSpheroController::publishWheelJointState() { ros::Time current_time = ros::Time::now(); joint_state_.header.stamp = current_time; joint_state_.name.resize ( joints_.size() ); joint_state_.position.resize ( joints_.size() ); for ( int i = 0; i < 2; i++ ) { physics::JointPtr joint = joints_[i]; math::Angle angle = joint->GetAngle ( 0 ); joint_state_.name[i] = joint->GetName(); joint_state_.position[i] = angle.Radian() ; } joint_state_publisher_.publish(joint_state_); } void GazeboSpheroController::publishWheelTF() { ros::Time current_time = ros::Time::now(); for ( int i = 0; i < 2; i++ ) { string wheel_frame = gazebo_ros_->resolveTF(joints_[i]->GetChild()->GetName ()); string wheel_parent_frame = gazebo_ros_->resolveTF(joints_[i]->GetParent()->GetName ()); math::Pose poseWheel = joints_[i]->GetChild()->GetRelativePose(); tf::Quaternion qt ( poseWheel.rot.x, poseWheel.rot.y, poseWheel.rot.z, poseWheel.rot.w ); tf::Vector3 vt ( poseWheel.pos.x, poseWheel.pos.y, poseWheel.pos.z ); tf::Transform tfWheel ( qt, vt ); transform_broadcaster_->sendTransform ( tf::StampedTransform ( tfWheel, current_time, wheel_parent_frame, wheel_frame ) ); } } // Update the controller void GazeboSpheroController::UpdateChild() { /* force reset SetMaxForce since Joint::Reset reset MaxForce to zero at https://bitbucket.org/osrf/gazebo/src/8091da8b3c529a362f39b042095e12c94656a5d1/gazebo/physics/Joint.cc?at=gazebo2_2.2.5#cl-331 (this has been solved in https://bitbucket.org/osrf/gazebo/diff/gazebo/physics/Joint.cc?diff2=b64ff1b7b6ff&at=issue_964 ) and Joint::Reset is called after ModelPlugin::Reset, so we need to set maxForce to wheel_torque other than GazeboSpheroController::Reset (this seems to be solved in https://bitbucket.org/osrf/gazebo/commits/ec8801d8683160eccae22c74bf865d59fac81f1e) */ /* The real sphero takes velocity commands on a scale of 0 - 255. Gazebo (through ros) takes velocity commands in rad/s. At maximum linear velocity (255) of 2m/s and small wheel diameter of 2cm maximum angluar velocity: 200 rad/s ==> scaling factor is 1/1.275 */ for (int i = 0; i < 2; i++) { if (fabs(wheel_torque - joints_[i]->GetParam("fmax", 0)) > 1e-6) { joints_[i]->SetParam("fmax", 0, wheel_torque); } } if (odom_source_ == ENCODER) { UpdateOdometryEncoder(); } common::Time current_time = parent->GetWorld()->GetSimTime(); double seconds_since_last_update = (current_time - last_update_time_).Double(); if (seconds_since_last_update > update_period_) { if (this->publish_tf_) { publishOdometry(); publishPosition(); publishDiff(); updatePrediction(seconds_since_last_update); } if (publishWheelTF_) { publishWheelTF(); } if (publishWheelJointState_) { publishWheelJointState(); } // Update robot in case new velocities have been requested getWheelVelocities(); double current_speed[2]; current_speed[LEFT] = joints_[LEFT]->GetVelocity(0) * (wheel_diameter_ / 2.0); current_speed[RIGHT] = joints_[RIGHT]->GetVelocity(0) * (wheel_diameter_ / 2.0); if (wheel_accel == 0 || (fabs(wheel_speed_[LEFT] - current_speed[LEFT]) < 0.01) || (fabs(wheel_speed_[RIGHT] - current_speed[RIGHT]) < 0.01)) { //if max_accel == 0, or target speed is reached joints_[LEFT]->SetParam("vel", 0, wheel_speed_[LEFT] / (wheel_diameter_ / 2.0)); joints_[RIGHT]->SetParam("vel", 0, wheel_speed_[RIGHT] / (wheel_diameter_ / 2.0)); } else { if ( wheel_speed_[LEFT]>=current_speed[LEFT] ) wheel_speed_instr_[LEFT]+=fmin ( wheel_speed_[LEFT]-current_speed[LEFT], wheel_accel * seconds_since_last_update ); else wheel_speed_instr_[LEFT]+=fmax ( wheel_speed_[LEFT]-current_speed[LEFT], -wheel_accel * seconds_since_last_update ); if ( wheel_speed_[RIGHT]>current_speed[RIGHT] ) wheel_speed_instr_[RIGHT]+=fmin ( wheel_speed_[RIGHT]-current_speed[RIGHT], wheel_accel * seconds_since_last_update ); else wheel_speed_instr_[RIGHT]+=fmax ( wheel_speed_[RIGHT]-current_speed[RIGHT], -wheel_accel * seconds_since_last_update ); joints_[LEFT]->SetParam("vel", 0,wheel_speed_instr_[LEFT] / (wheel_diameter_ / 2.0)); joints_[RIGHT]->SetParam("vel", 0,wheel_speed_instr_[RIGHT] / (wheel_diameter_ / 2.0)); } last_update_time_+= common::Time(update_period_); } } // Finalize the controller void GazeboSpheroController::FiniChild() { alive_ = false; queue_.clear(); queue_.disable(); gazebo_ros_->node()->shutdown(); callback_queue_thread_.join(); } // calculates the factor to apply to a movement command to inject a random error double GazeboSpheroController::getErrorFactor(double limit) { double lower_bound = limit * -1; uniform_real_distribution<double> unif(lower_bound,limit); default_random_engine re; double random = unif(re); return 1 + random; } void GazeboSpheroController::getWheelVelocities() { boost::mutex::scoped_lock scoped_lock ( lock ); // TODO: retrieve error from current position --> errorMap-Service // inject a random error into the next movement instruction double linearLimit = 0.01; double angularLimit = 0.01; double linearFactor = getErrorFactor(linearLimit); double angularFactor = getErrorFactor(angularLimit); sphero_error_inject::error errorService; errorService.request.pose = pose_; errorClient_.call(errorService); linearFactor += errorService.response.linearError; angularFactor += errorService.response.angularError; double vr = x_;// * linearFactor; double va = rot_;// * angularFactor; // hand the movement command over to gazebo wheel_speed_[LEFT] = vr; wheel_speed_[RIGHT] = va * wheel_separation_ / 2.0; } void GazeboSpheroController::cmdVelCallback ( const geometry_msgs::Twist::ConstPtr& cmd_msg ) { boost::mutex::scoped_lock scoped_lock(lock); //ROS_INFO("%s: cmd_vel - linar.x: %g \t| angular.z: %g", gazebo_ros_->info(), cmd_msg->linear.x, cmd_msg->angular.z); x_ = cmd_msg->linear.x; rot_ = cmd_msg->angular.z; } void GazeboSpheroController::QueueThread() { static const double timeout = 0.01; while ( alive_ && gazebo_ros_->node()->ok() ) { queue_.callAvailable ( ros::WallDuration ( timeout ) ); } } /** * Calculates the odometry for the current step based on the current movement and the last known position. * http://www.cs.columbia.edu/~allen/F15/NOTES/icckinematics.pdf */ void GazeboSpheroController::UpdateOdometryEncoder() { common::Time current_time = parent->GetWorld()->GetSimTime(); double seconds_since_last_update = (current_time - last_odom_update_).Double(); last_odom_update_ = current_time; tf::Vector3 vt; tf::Quaternion qt; if(x_ == 0) { // no movement is currently happening, so odom is just the current position vt = tf::Vector3(pose_.x, pose_.y, 0 ); double theta = pose_.theta + (rot_ * seconds_since_last_update); qt.setRPY(0, 0, theta); } else if (rot_ == 0) { // no turning happens, just movement in a straight line double distance = x_ * seconds_since_last_update; vt = tf::Vector3( (distance * cos(pose_.theta)) + pose_.x, (distance * sin(pose_.theta)) + pose_.y, 0 ); qt.setRPY(0, 0, pose_.theta); } else { Eigen::Vector3d odomTarget = this->calculateCurveMovement(seconds_since_last_update, pose_, x_, rot_); vt = tf::Vector3(odomTarget.x(), odomTarget.y(), 0 ); qt.setRPY(0, 0, odomTarget.z()); } odom_.pose.pose.position.x = vt.x(); odom_.pose.pose.position.y = vt.y(); odom_.pose.pose.position.z = vt.z(); odom_.pose.pose.orientation.x = qt.x(); odom_.pose.pose.orientation.y = qt.y(); odom_.pose.pose.orientation.z = qt.z(); odom_.pose.pose.orientation.w = qt.w(); } Eigen::Vector3d GazeboSpheroController::calculateCurveMovement(double timeInSeconds, geometry_msgs::Pose2D pose, double x, double rot) { double currentOrientation = pose.theta; // rot_ specifies how long it will take for a full circle (angular velocity in rad/s) // x_ specifies how fast the robot travels trough the circle (linear velocity in m/s) // x_ / rot_ specifies the radius of the circle double fullTurn = 3.14159265358979323846 * 2; // specifies how long a full circle will take double fullTurnTime = fullTurn / rot; double circumference = fullTurnTime * x; double radius = circumference / fullTurn; // = x_ / rot_; double angle = rot * timeInSeconds; // instantanious center of curvature - the point the current curve revolves around double iccX = pose.x - (radius * sin(currentOrientation)); double iccY = pose.y + (radius * cos(currentOrientation)); Eigen::Matrix3d rotateArountIcc; rotateArountIcc << cos(angle), -1 * sin(angle), 0, sin(angle), cos(angle), 0, 0, 0, 1; Eigen::Vector3d translateIccToOrigin(pose.x - iccX, pose.y - iccY, currentOrientation); Eigen::Vector3d translateIccBack(iccX, iccY, angle); Eigen::Vector3d odomTarget = (rotateArountIcc * translateIccToOrigin) + translateIccBack; return odomTarget; } void GazeboSpheroController::publishDiff() { double distance = sqrt(pow(last_pose_.x - pose_.x, 2) + pow(last_pose_.y - pose_.y, 2)); double planned_distance = sqrt(pow(last_pose_.x - odom_.pose.pose.position.x, 2) + pow(last_pose_.y - odom_.pose.pose.position.y, 2)); double relative_distance_diff = abs((distance / planned_distance) - 1); // the incoming geometry_msgs::Quaternion is transformed to a tf::Quaterion tf::Quaternion quat; tf::quaternionMsgToTF(odom_.pose.pose.orientation, quat); // the tf::Quaternion has a method to acess roll pitch and yaw double roll, pitch, yaw; tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); double theta_diff = abs(last_pose_.theta - pose_.theta); double planned_theta_diff = abs(last_pose_.theta - yaw); double relative_theta_diff = abs((theta_diff / planned_theta_diff) - 1); sphero_error_mapping::error_insert mappingService; mappingService.request.pose.x = pose_.x; mappingService.request.pose.y = pose_.y; mappingService.request.linearError = relative_distance_diff; mappingService.request.angularError = relative_theta_diff; mappingService.request.robotId = '0'; reportClient_.call(mappingService); } void GazeboSpheroController::updatePrediction(double seconds_since_last_update) { if(x_ == 0 && rot_ == 0) { // no movement, no prediction update return; } else if(x_ == 0) { // no linear movement, so odom is just the current position with new orientation predict_pose_.theta = pose_.theta + (rot_ * seconds_since_last_update); predict_pose_.x = pose_.x; predict_pose_.y = pose_.y; } else if (rot_ == 0) { // no turning happens, just movement in a straight line double distance = x_ * seconds_since_last_update; predict_pose_.x = (distance * cos(pose_.theta)) + pose_.x; predict_pose_.y = (distance * sin(pose_.theta)) + pose_.y; predict_pose_.theta = pose_.theta; } else { Eigen::Vector3d predictTarget = this->calculateCurveMovement(seconds_since_last_update, pose_, x_, rot_); predict_pose_.x = predictTarget.x(); predict_pose_.y = predictTarget.y(); predict_pose_.theta = predictTarget.z(); } // ROS_INFO("%s: current: %g, %g | %g", gazebo_ros_->info(), pose_.x, pose_.y, pose_.theta); // ROS_INFO("%s: predict: %g, %g | %g", gazebo_ros_->info(), predict_pose_.x, predict_pose_.y, predict_pose_.theta); } void GazeboSpheroController::publishPosition() { // get the position from the simulation math::Pose world_pose = parent->GetWorldPose(); last_pose_ = pose_; pose_.x = world_pose.pos.x; pose_.y = world_pose.pos.y; // get the orientation from the simulation double theta = world_pose.rot.GetYaw(); pose_.theta = theta * 180; position_publisher_.publish(pose_); } void GazeboSpheroController::publishOdometry() { ros::Time current_time = ros::Time::now(); tf::Quaternion qt; tf::Vector3 vt; math::Pose pose = parent->GetWorldPose(); if (odom_source_ == ENCODER) { // getting data form encoder integration qt = tf::Quaternion(odom_.pose.pose.orientation.x, odom_.pose.pose.orientation.y, odom_.pose.pose.orientation.z, odom_.pose.pose.orientation.w); vt = tf::Vector3(odom_.pose.pose.position.x, odom_.pose.pose.position.y, odom_.pose.pose.position.z); } if ( odom_source_ == WORLD ) { qt = tf::Quaternion(0, 0, 0, 1); vt = tf::Vector3(pose.pos.x, pose.pos.y, pose.pos.z); odom_.pose.pose.position.x = vt.x(); odom_.pose.pose.position.y = vt.y(); odom_.pose.pose.position.z = vt.z(); odom_.pose.pose.orientation.x = qt.x(); odom_.pose.pose.orientation.y = qt.y(); odom_.pose.pose.orientation.z = qt.z(); odom_.pose.pose.orientation.w = qt.w(); } // get velocity in /odom frame odom_.twist.twist.angular.z = parent->GetWorldAngularVel().z; // convert velocity to child_frame_id (aka base_footprint) math::Vector3 linear = parent->GetWorldLinearVel(); float yaw = pose.rot.GetYaw(); odom_.twist.twist.linear.x = cosf ( yaw ) * linear.x + sinf ( yaw ) * linear.y; odom_.twist.twist.linear.y = cosf ( yaw ) * linear.y - sinf ( yaw ) * linear.x; string odom_frame = gazebo_ros_->resolveTF(odometry_frame_); string base_footprint_frame = gazebo_ros_->resolveTF(robot_base_frame_); tf::Transform base_footprint_to_odom(qt, vt); transform_broadcaster_->sendTransform(tf::StampedTransform(base_footprint_to_odom, current_time, odom_frame, base_footprint_frame)); // set covariance odom_.pose.covariance[0] = 0.00001; odom_.pose.covariance[7] = 0.00001; odom_.pose.covariance[14] = 1000000000000.0; odom_.pose.covariance[21] = 1000000000000.0; odom_.pose.covariance[28] = 1000000000000.0; odom_.pose.covariance[35] = 0.001; // set header odom_.header.stamp = current_time; odom_.header.frame_id = odom_frame; odom_.child_frame_id = base_footprint_frame; odometry_publisher_.publish(odom_); } GZ_REGISTER_MODEL_PLUGIN(GazeboSpheroController) }
40.572534
152
0.682065
[ "transform" ]
8ee25b08c5b603254c31965b490ff6cc83e69ce5
3,644
hxx
C++
code/LibEpipolarConsistency/Gui/ComputeRadonIntermediate.hxx
mareikethies/EpipolarConsistency
63d7ca2fd705911a6c93ca4247486fc66a9d31c7
[ "Apache-2.0" ]
2
2020-03-21T16:33:51.000Z
2021-09-12T03:03:00.000Z
code/LibEpipolarConsistency/Gui/ComputeRadonIntermediate.hxx
mareikethies/EpipolarConsistency
63d7ca2fd705911a6c93ca4247486fc66a9d31c7
[ "Apache-2.0" ]
1
2018-06-14T07:48:55.000Z
2018-06-14T07:48:55.000Z
code/LibEpipolarConsistency/Gui/ComputeRadonIntermediate.hxx
mareikethies/EpipolarConsistency
63d7ca2fd705911a6c93ca4247486fc66a9d31c7
[ "Apache-2.0" ]
6
2018-05-15T21:38:35.000Z
2022-01-06T07:20:47.000Z
// Created by A. Aichert on Mon Mar 27st 2017. #ifndef __compute_radon_intermediate #define __compute_radon_intermediate #include <LibProjectiveGeometry/ProjectionMatrix.h> #include <LibEpipolarConsistency/RadonIntermediate.h> #include <GetSet/GetSetObjects.h> #include <GetSet/ProgressInterface.hxx> #include <LibUtilsQt/Figure.hxx> #include <NRRD/nrrd_image_stack.hxx> #include <Utils/Projtable.hxx> #include "PreProccess.h" #include <map> #include <string> ///////////////////////// // JUST FOR TESTING #include <NRRD/nrrd_lowpass.hxx> ///////////////////////// namespace EpipolarConsistency { // // Computing Radon Intermediate and Filter // struct RadonIntermediateFunction : public GetSetGui::Configurable { /// Filter applied to Radon transform. RadonIntermediate::Filter filter=RadonIntermediate::Derivative; /// Function applied to each value in the Radon transform RadonIntermediate::PostProcess post_process=RadonIntermediate::Identity; /// Size of the Radon transform. struct NumberOfBins { int angle=768; //< Size of the Radon transform in angle-direction. int distance=768; //< Size of the Radon transform in distance-direction. } number_of_bins; /// Declare default values. void gui_declare_section (const GetSetGui::Section& section) { // RadonIntermediate GetSet<int> ("Number Of Bins/Angle" , section, number_of_bins.angle ).setDescription("Number of Radon bins in alpha-direction"); GetSet<int> ("Number Of Bins/Distance" , section, number_of_bins.distance ).setDescription("Number of Radon bins in t-direction"); section.subsection("Number Of Bins").setGrouped(); GetSetGui::Enum ("Distance Filter" , section, filter ).setChoices("Derivative;Ramp;None") .setDescription("A homogeneous function of degree two must be applied for the consistency condition to hold. This becomes a Ramp or derivative filter in t-direction."); GetSetGui::Enum ("Post Process" , section, post_process ).setChoices("Identity;sgn(x)*sqrt(abs(x));sgn(x)*log(abs(x)-1)") .setDescription("A function applied to the Radon transform after computation. Function: x, sgn(x)*sqrt(abs(x)) or sgn(x)*log(abs(x)+1)."); } // Retreive current values from GUI void gui_retreive_section(const GetSetGui::Section& section) { post_process =(RadonIntermediate::PostProcess)(GetSet<int>("Post Process" , section).getValue()); filter =(RadonIntermediate::Filter) (GetSet<int>("Distance Filter" , section).getValue()); number_of_bins.angle = GetSet<int>("Number Of Bins/Angle" , section); number_of_bins.distance = GetSet<int>("Number Of Bins/Distance" , section); } /// Load and process Radon Intemediate Functions. RadonIntermediate* compute(NRRD::ImageView<float>& img, Geometry::ProjectionMatrix *P=0x0, double *mm_per_px=0x0) { // Compute Radon Intermediate int n_alpha=number_of_bins.angle; int n_t=number_of_bins.distance; auto * dtr=new EpipolarConsistency::RadonIntermediate( img, n_alpha,n_t, filter, post_process); // Store projection matrix in NRRD header, if provided if (P) img.meta_info["Original Image/Projection Matrix"] = toString(*P); if (mm_per_px) img.meta_info["Original Image/Pixel Spacing" ] = toString(*mm_per_px); return dtr; } }; } // namespace EpipolarConsistency #endif // __compute_radon_intermediate
40.043956
172
0.674808
[ "geometry", "transform" ]
8ee36601581f3c17919a6cf02305f524d75e8adf
807
hpp
C++
src/examples/trading/server/market_data_bus.hpp
jjzhang166/executors
9b42e193b27cc5c3308dd3bc4e52712c2e442c4b
[ "BSL-1.0" ]
406
2015-01-19T06:35:42.000Z
2022-03-30T04:38:12.000Z
src/examples/trading/server/market_data_bus.hpp
rongming-lu/executors
9b42e193b27cc5c3308dd3bc4e52712c2e442c4b
[ "BSL-1.0" ]
1
2018-06-13T03:17:24.000Z
2019-03-05T20:09:47.000Z
src/examples/trading/server/market_data_bus.hpp
rongming-lu/executors
9b42e193b27cc5c3308dd3bc4e52712c2e442c4b
[ "BSL-1.0" ]
66
2015-01-22T09:01:17.000Z
2022-03-30T04:38:13.000Z
// // market_data_bus.hpp // ~~~~~~~~~~~~~~~~~~~ // Bus used to distribute events to all market data feeds. // // Copyright (c) 2014 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef MARKET_DATA_BUS_HPP #define MARKET_DATA_BUS_HPP #include <vector> #include "common/market_data.hpp" #include "market_data_feed.hpp" class market_data_bus { public: // Subscribe a market data feed to the bus. void subscribe(market_data_feed& f); // Dispatch a market data event to the bus. void dispatch_event(market_data::new_order o); void dispatch_event(market_data::trade t); private: std::vector<market_data_feed*> feeds_; }; #endif
23.735294
79
0.729864
[ "vector" ]
8ee3f157537dc7c50e2b2ca26e9b327dea8cc789
10,805
cpp
C++
src/domain.cpp
lujuntuan/dcus
fc9733898dcb79923d25b85a231e793d4adfb8e6
[ "Apache-2.0" ]
null
null
null
src/domain.cpp
lujuntuan/dcus
fc9733898dcb79923d25b85a231e793d4adfb8e6
[ "Apache-2.0" ]
null
null
null
src/domain.cpp
lujuntuan/dcus
fc9733898dcb79923d25b85a231e793d4adfb8e6
[ "Apache-2.0" ]
null
null
null
/********************************************************************************* *Copyright(C): Juntuan.Lu 2021 *Author: Juntuan.Lu *Version: 1.0 *Date: 2021/04/22 *Phone: 15397182986 *Description: *Others: *Function List: *History: **********************************************************************************/ #include "dcus/domain.h" #include "dcus/utils/string.h" #include <algorithm> #include <iostream> DCUS_NAMESPACE_BEGIN std::string Domain::getMrStateStr(ServerState state) noexcept { switch (state) { case MR_UNKNOWN: return "UNKNOWN"; case MR_OFFLINE: return "OFFLINE"; case MR_PENDING: return "PENDING"; case MR_IDLE: return "IDLE"; case MR_READY: return "READY"; case MR_DOWNLOAD: return "DOWNLOAD"; case MR_VERIFY: return "VERIFY"; case MR_DISTRIBUTE: return "DISTRIBUTE"; case MR_WAIT: return "MR_WAIT"; case MR_DEPLOY: return "DEPLOY"; case MR_CANCEL: return "CANCEL"; case MR_DOWNLOAD_ASK: return "DOWNLOAD_ASK"; case MR_DEPLOY_ASK: return "DEPLOY_ASK"; case MR_CANCEL_ASK: return "CANCEL_ASK"; case MR_RESUME_ASK: return "MR_RESUME_ASK"; case MR_DONE_ASK: return "DONE_ASK"; case MR_ERROR_ASK: return "ERROR_ASK"; default: return "UNKNOWN"; } } std::string Domain::getWrStateStr(ClientState state) noexcept { switch (state) { case WR_UNKNOWN: return "UNKNOWN"; case WR_OFFLINE: return "OFFLINE"; case WR_ERROR: return "ERROR"; case WR_IDLE: return "IDLE"; case WR_DOWNLOAD: return "DOWNLOAD"; case WR_VERIFY: return "VERIFY"; case WR_PATCH: return "PATCH"; case WR_WAIT: return "WAIT"; case WR_DEPLOY: return "DEPLOY"; case WR_CANCEL: return "CANCEL"; default: return "UNKNOWN"; } } std::string Domain::getControlStr(Control control) noexcept { switch (control) { case CTL_UNKNOWN: return "UNKNOWN"; case CTL_RESET: return "RESET"; case CTL_DOWNLOAD: return "DOWNLOAD"; case CTL_DEPLOY: return "DEPLOY"; case CTL_CLEAR: return "CLEAR"; default: return "UNKNOWN"; } } std::string Domain::getAnswerStr(Answer answer) noexcept { switch (answer) { case ANS_UNKNOWN: return "UNKNOWN"; case ANS_ACCEPT: return "ACCEPT"; case ANS_REFUSE: return "REFUSE"; default: return "UNKNOWN"; } } bool Domain::mrStateIsBusy(ServerState state) noexcept { if (state == MR_PENDING || state == MR_READY || state == MR_DOWNLOAD || state == MR_VERIFY || state == MR_DISTRIBUTE || state == MR_WAIT || state == MR_DEPLOY || state == MR_CANCEL) { return true; } return false; } bool Domain::wrStateIsBusy(ClientState state) noexcept { if (state == WR_DOWNLOAD || state == WR_VERIFY || state == WR_PATCH || state == WR_WAIT || state == WR_DEPLOY || state == WR_CANCEL) { return true; } return false; } bool Domain::mrStateIsAsk(ServerState state) noexcept { if (state == MR_DOWNLOAD_ASK || state == MR_DEPLOY_ASK || state == MR_CANCEL_ASK || state == MR_RESUME_ASK || state == MR_DONE_ASK || state == MR_ERROR_ASK) { return true; } return false; } void Domain::update(const Domain& domain) noexcept { if (m_name != domain.name()) { return; } m_state = domain.state(); m_last = domain.last(); m_watcher = domain.watcher(); m_error = domain.error(); m_version = domain.version(); m_attribute = domain.attribute(); m_meta = domain.meta(); m_progress = domain.progress(); m_message = domain.message(); m_answer = domain.answer(); } bool Domain::isEqual(const Domain& domain) const noexcept { return m_name == domain.name() //&&guid() == domain.guid() && m_state == domain.state() && m_last == domain.last() && m_watcher == domain.watcher() && m_error == domain.error() && m_version == domain.version() && m_attribute == domain.attribute() && m_meta == domain.meta() && m_progress == domain.progress() && m_message == domain.message() && m_answer == domain.answer(); } bool Domain::operator==(const Domain& domain) const noexcept { return isEqual(domain); } bool Domain::operator!=(const Domain& domain) const noexcept { return !isEqual(domain); } std::ostream& operator<<(std::ostream& ostream, const Domain& domain) noexcept { if (domain.name().empty()) { ostream << "{\n Unavailable domain\n}"; return ostream; } ostream << "{\n"; ostream << " [name]: " << domain.name() << "\n"; if (!domain.guid().empty()) { ostream << " [guid]: " << domain.guid() << "\n"; } ostream << " [state]: " << Domain::getWrStateStr(domain.state()) << "\n"; ostream << " [last]: " << Domain::getWrStateStr(domain.last()) << "\n"; if (domain.watcher()) { ostream << " [watcher]: " << std::string("true") << "\n"; } if (domain.error() != 0) { ostream << " [error]: " << domain.error() << "\n"; } if (!domain.version().empty()) { ostream << " [version]: " << domain.version() << "\n"; } if (!domain.attribute().empty()) { ostream << " [attribute]: " << domain.attribute().toStream() << "\n"; } if (!domain.meta().empty()) { ostream << " [meta]: " << domain.meta().toStream() << "\n"; } if (domain.progress() != 0) { ostream << " [progress]: " << Utils::doubleToString(domain.progress()) << "\n"; } if (!domain.message().empty()) { ostream << " [message]: " << domain.message() << "\n"; } if (domain.answer() != ANS_UNKNOWN) { ostream << " [answer]: " << Domain::getAnswerStr(domain.answer()) << "\n"; } ostream << "}"; return ostream; } std::ostream& operator<<(std::ostream& ostream, const Depends& depends) noexcept { int i = 0; for (const auto& s : depends) { if (i > 0) { ostream << ", "; } ostream << s; i++; } return ostream; } bool Detail::detectVersionEqual() const noexcept { if (m_domain.version().empty()) { return false; } return m_domain.version() == m_package.version(); } bool Detail::detectVersionVaild() const noexcept { if (m_domain.version().empty() || m_package.version().empty()) { return false; } bool numOk = false; const auto currentVersionList = Utils::stringSplit(m_domain.version(), "."); const auto targetVersionList = Utils::stringSplit(m_package.version(), "."); if (currentVersionList.size() != targetVersionList.size()) { return false; } for (unsigned i = 0; i < currentVersionList.size(); i++) { int selfNum = Utils::getNumForString(currentVersionList[i], &numOk); if (numOk == false || selfNum < 0) { return false; } int targetNum = Utils::getNumForString(targetVersionList[i], &numOk); if (numOk == false || targetNum < 0) { return false; } if (targetNum > selfNum) { return true; } } return false; } inline static std::vector<std::string> getDependsNames(const Data& meta) { std::vector<std::string> depends; std::string dependsStr = meta.value("depends").toString(); if (dependsStr.empty()) { return depends; } Utils::stringReplace(dependsStr, "\n", " "); depends = Utils::stringSplit(dependsStr, " "); return depends; } bool Detail::hasDepends(const Depends& depends) const noexcept { const auto& requireNames = getDependsNames(m_package.meta()); for (const auto& str : requireNames) { if (str.empty()) { continue; } for (const auto& name : depends) { if (name == str) { return true; } } } return false; } bool Detail::operator==(const Detail& detail) const noexcept { return m_domain == detail.domain(); } bool Detail::operator!=(const Detail& detail) const noexcept { return m_domain != detail.domain(); } bool Detail::operator<(const Detail& detail) const noexcept { if (m_domain == detail.domain()) { return false; } const auto& requireNames = getDependsNames(detail.package().meta()); for (const auto& str : requireNames) { if (str.empty()) { continue; } if (str == m_domain.name()) { return true; } } return m_domain.name() < detail.domain().name(); } bool Detail::operator>(const Detail& detail) const noexcept { if (m_domain == detail.domain()) { return true; } return !(*this < detail); } std::ostream& operator<<(std::ostream& ostream, const Detail& detail) noexcept { ostream << detail.domain() << "\n"; if (!detail.package().files().empty()) { ostream << " [package-size]: " << detail.package().files().size() << "\n"; } if (!detail.transfers().empty()) { ostream << " [transfers-size]: " << detail.transfers().size() << "\n"; } if (detail.progress() != 0) { ostream << " [progress]: " << Utils::doubleToString(detail.progress()) << "\n"; } if (detail.deploy().active()) { ostream << " [deploy]: " << detail.deploy().get() << std::string(" ms") << "\n"; } if (detail.heartbeat().active()) { ostream << " [heartbeat]: " << detail.heartbeat().get() << std::string(" ms") << "\n"; } return ostream; } Detail* Details::update(Domain&& domain, bool force) noexcept { for (Detail& d : *this) { if (d.domain().name() == domain.name()) { if (force) { d.domain() = domain; } else { d.domain().update(domain); } return &d; } } if (force) { push_back(Detail(std::move(domain))); return &(this->back()); } return nullptr; } void Details::sort() noexcept { std::sort(begin(), end(), [](const Detail& lhs, const Detail& rhs) { return lhs < rhs; }); } Detail* Details::find(const std::string& name) noexcept { for (auto& d : *this) { if (d.domain().name() == name) { return &d; } } return nullptr; } std::ostream& operator<<(std::ostream& ostream, const Details& domains) noexcept { ostream << "[\n"; for (const auto& d : domains) { ostream << d << "\n"; } ostream << "]"; return ostream; } DCUS_NAMESPACE_END
26.162228
110
0.553818
[ "vector" ]
8ee499db7e02d48e49b37edad92f24869b769e34
874
hh
C++
MiniSatExt.hh
MikolasJanota/qesto
7c3c389f5227f3f2867742294152544a0d7e4046
[ "MIT" ]
null
null
null
MiniSatExt.hh
MikolasJanota/qesto
7c3c389f5227f3f2867742294152544a0d7e4046
[ "MIT" ]
null
null
null
MiniSatExt.hh
MikolasJanota/qesto
7c3c389f5227f3f2867742294152544a0d7e4046
[ "MIT" ]
null
null
null
/* * File: MiniSatExt.hh * Author: mikolas * * Created on November 29, 2010, 5:40 PM */ #ifndef MINISATEXT_HH #define MINISATEXT_HH #include "auxiliary.hh" #include "minisat/core/Solver.h" namespace SATSPC { class MiniSatExt : public Solver { public: inline void bump(const Var var) { varBumpActivity(var); } inline void new_variables(Var max_id); inline void new_variables(const std::vector<Var>& variables); }; inline void MiniSatExt::new_variables(Var max_id) { const int target_number = (int)max_id+1; while (nVars() < target_number) newVar(); } inline void MiniSatExt::new_variables(const std::vector<Var>& variables) { Var max_id = 0; FOR_EACH(variable_index, variables) { const Var v = *variable_index; if (max_id < v) max_id = v; } new_variables(max_id); } } #endif /* MINISATEXT_HH */
24.277778
76
0.672769
[ "vector" ]
8eec3b6192b87b31944630acdde67de18f2b0d8f
304
cpp
C++
src/Cpp/1-getting-started/1-1-1-HelloWindow/HelloWindowApplication.cpp
spnda/learnd3d11
83fea43afffca48776521d8f1ae60e9d0bc6dc84
[ "MIT" ]
29
2022-02-19T00:54:51.000Z
2022-03-24T11:05:47.000Z
src/Cpp/1-getting-started/1-1-1-HelloWindow/HelloWindowApplication.cpp
spnda/learnd3d11
83fea43afffca48776521d8f1ae60e9d0bc6dc84
[ "MIT" ]
67
2022-02-19T16:47:40.000Z
2022-03-30T15:09:38.000Z
src/Cpp/1-getting-started/1-1-1-HelloWindow/HelloWindowApplication.cpp
spnda/learnd3d11
83fea43afffca48776521d8f1ae60e9d0bc6dc84
[ "MIT" ]
8
2022-02-15T11:06:31.000Z
2022-03-16T22:34:22.000Z
#include "HelloWindowApplication.hpp" #include <string> HelloWindowApplication::HelloWindowApplication(const std::string& title) : Application(title) { } bool HelloWindowApplication::Load() { return true; } void HelloWindowApplication::Render() { } void HelloWindowApplication::Update() { }
13.818182
72
0.75
[ "render" ]
8ef36ebce7326cd75703b1e6bee12cbad63ed539
842
cpp
C++
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/descriptor_set_layout.cpp
Karamays/karamay_engine
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
[ "MIT" ]
null
null
null
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/descriptor_set_layout.cpp
Karamays/karamay_engine
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
[ "MIT" ]
null
null
null
_KaramayEngine/karamay_engine_graphics_unit_cmake/karamay_engine_graphics_unit/source/graphics/vulkan/device_object/descriptor_set_layout.cpp
Karamays/karamay_engine
858054ea5155d0b690b7cf17d0e6a6266e0b0b9c
[ "MIT" ]
1
2022-01-29T08:24:14.000Z
2022-01-29T08:24:14.000Z
#include "descriptor_set_layout.h" descriptor_set_layout::descriptor_set_layout(device& dev) : device_object(dev) { } descriptor_set_layout::~descriptor_set_layout() { deallocate(); } bool descriptor_set_layout::allocate(const std::vector<VkDescriptorSetLayoutBinding>& bindings) noexcept { VkDescriptorSetLayoutCreateInfo _create_info; _create_info.pBindings = bindings.data(); _create_info.bindingCount = bindings.size(); auto _ret = vkCreateDescriptorSetLayout(_device.handle(), &_create_info, nullptr, &_handle); if (_ret != VkResult::VK_SUCCESS) { return false; } _bindings = bindings; return true; } void descriptor_set_layout::deallocate() noexcept { if (_handle) { vkDestroyDescriptorSetLayout(_device.handle(), _handle, nullptr); _handle = nullptr; } }
24.764706
104
0.72209
[ "vector" ]
f111f64beaeaba36757cb19f0dda2eb6b4e78ffd
2,582
cc
C++
cms/src/model/NodeProcessesResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
cms/src/model/NodeProcessesResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
cms/src/model/NodeProcessesResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cms/model/NodeProcessesResult.h> #include <json/json.h> using namespace AlibabaCloud::Cms; using namespace AlibabaCloud::Cms::Model; NodeProcessesResult::NodeProcessesResult() : ServiceResult() {} NodeProcessesResult::NodeProcessesResult(const std::string &payload) : ServiceResult() { parse(payload); } NodeProcessesResult::~NodeProcessesResult() {} void NodeProcessesResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allNodeProcesses = value["NodeProcesses"]["NodeProcess"]; for (auto value : allNodeProcesses) { NodeProcess nodeProcessesObject; if(!value["Id"].isNull()) nodeProcessesObject.id = std::stol(value["Id"].asString()); if(!value["Name"].isNull()) nodeProcessesObject.name = value["Name"].asString(); if(!value["InstanceId"].isNull()) nodeProcessesObject.instanceId = value["InstanceId"].asString(); if(!value["ProcessName"].isNull()) nodeProcessesObject.processName = value["ProcessName"].asString(); if(!value["ProcessUser"].isNull()) nodeProcessesObject.processUser = value["ProcessUser"].asString(); if(!value["Command"].isNull()) nodeProcessesObject.command = value["Command"].asString(); nodeProcesses_.push_back(nodeProcessesObject); } if(!value["ErrorCode"].isNull()) errorCode_ = std::stoi(value["ErrorCode"].asString()); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } std::vector<NodeProcessesResult::NodeProcess> NodeProcessesResult::getNodeProcesses()const { return nodeProcesses_; } int NodeProcessesResult::getErrorCode()const { return errorCode_; } std::string NodeProcessesResult::getErrorMessage()const { return errorMessage_; } bool NodeProcessesResult::getSuccess()const { return success_; }
28.688889
90
0.738575
[ "vector", "model" ]
47e6530b0fbd521dd52f5319ca32a0b7a771729c
13,706
cpp
C++
Source/EMsoftWorkbench/Workbench/Modules/MonteCarloSimulationModule/MonteCarloSimulationController.cpp
josephtessmer/EMsoft
b6f73c76c52ff7bfa432119b91d3981c8e97fd11
[ "Intel", "Unlicense", "MIT-CMU", "BSD-3-Clause" ]
37
2019-02-11T15:39:55.000Z
2022-03-15T10:37:23.000Z
Source/EMsoftWorkbench/Workbench/Modules/MonteCarloSimulationModule/MonteCarloSimulationController.cpp
hhoward22/EMsoft
97daa26978c42d5f569f4588a9991393c157d509
[ "Intel", "BSD-3-Clause", "MIT-CMU", "Unlicense" ]
83
2018-08-30T10:30:30.000Z
2022-03-31T09:27:33.000Z
Source/EMsoftWorkbench/Workbench/Modules/MonteCarloSimulationModule/MonteCarloSimulationController.cpp
hhoward22/EMsoft
97daa26978c42d5f569f4588a9991393c157d509
[ "Intel", "BSD-3-Clause", "MIT-CMU", "Unlicense" ]
71
2018-08-21T14:19:22.000Z
2022-03-30T19:50:54.000Z
/* ============================================================================ * Copyright (c) 2009-2017 BlueQuartz Software, LLC * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of BlueQuartz Software, the US Air Force, nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The code contained herein was partially funded by the followig contracts: * United States Air Force Prime Contract FA8650-07-D-5800 * United States Air Force Prime Contract FA8650-10-D-5210 * United States Prime Contract Navy N00173-07-C-2068 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "MonteCarloSimulationController.h" #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QTextStream> #include "EMsoftLib/EMsoftStringConstants.h" #include "Workbench/Common/FileIOTools.h" const QString k_ExeName = QString("EMMCOpenCL"); const QString k_NMLName = QString("EMMCOpenCL.nml"); // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MonteCarloSimulationController::MonteCarloSimulationController(QObject* parent) : IProcessController(k_ExeName, k_NMLName, parent) { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MonteCarloSimulationController::~MonteCarloSimulationController() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MonteCarloSimulationController::setData(const InputDataType& data) { m_InputData = data; } // ----------------------------------------------------------------------------- void MonteCarloSimulationController::generateNMLFile(const QString& path) { std::vector<std::string> nml; m_InputData.inputFilePath = FileIOTools::GetAbsolutePath(m_InputData.inputFilePath); m_InputData.outputFilePath = FileIOTools::GetAbsolutePath(m_InputData.outputFilePath); nml.emplace_back(std::string(" &MCCLdata")); nml.emplace_back(std::string("! only bse1, full or Ivol simulation")); if(m_InputData.mcMode == 1) { nml.emplace_back(FileIOTools::CreateNMLEntry("mode", EMsoft::Constants::full, false)); } nml.emplace_back(std::string("! name of the crystal structure file")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::xtalname, m_InputData.inputFilePath)); nml.emplace_back(std::string("! number of pixels along x-direction of square projection [odd number!]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::numsx, m_InputData.numOfPixelsN)); nml.emplace_back(std::string("! for full mode: sample tilt angle from horizontal [degrees]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::sig, static_cast<float>(m_InputData.sampleTiltAngleSig))); nml.emplace_back(std::string("! sample tilt angle around RD axis [degrees]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::omega, static_cast<float>(m_InputData.sampleRotAngleOmega))); nml.emplace_back(std::string("! for bse1 mode: start angle")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::sigstart, static_cast<float>(m_InputData.sampleStartTiltAngle))); nml.emplace_back(std::string("! for bse1 mode: end angle")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::sigend, static_cast<float>(m_InputData.sampleEndTiltAngle))); nml.emplace_back(std::string("! for bse1 mode: sig step size")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::sigstep, static_cast<float>(m_InputData.sampleTiltStepSize))); nml.emplace_back(std::string("! x, y, z number of voxels [odd numbers!]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::ivolx, m_InputData.ivolx)); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::ivoly, m_InputData.ivoly)); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::ivolz, m_InputData.ivolz)); nml.emplace_back(std::string("! x, y, z voxel step sizes [nm]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::ivolstepx, static_cast<float>(m_InputData.ivolstepx))); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::ivolstepy, static_cast<float>(m_InputData.ivolstepy))); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::ivolstepz, static_cast<float>(m_InputData.ivolstepz))); nml.emplace_back(std::string("! number of incident electrons per thread")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::num_el, m_InputData.numOfEPerWorkitem)); nml.emplace_back(std::string("! GPU platform ID selector")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::platid, m_InputData.gpuPlatformID + 1)); nml.emplace_back(std::string("! GPU device ID selector")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::devid, m_InputData.gpuDeviceID + 1)); nml.emplace_back(std::string("! number of work items (depends on GPU card; leave unchanged)")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::globalworkgrpsz, m_InputData.globalWorkGroupSize)); nml.emplace_back(std::string("! total number of incident electrons and multiplier (to get more than 2^(31)-1 electrons)")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::totnumel, m_InputData.totalNumOfEConsidered)); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::multiplier, m_InputData.multiplierForTotalNumOfE)); nml.emplace_back(std::string("! incident beam energy [keV]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::EkeV, m_InputData.acceleratingVoltage)); nml.emplace_back(std::string("! minimum energy to consider [keV]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::Ehistmin, m_InputData.minEnergyConsider)); nml.emplace_back(std::string("! energy binsize [keV]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::Ebinsize, m_InputData.energyBinSize)); nml.emplace_back(std::string("! maximum depth to consider for exit depth statistics [nm]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::depthmax, m_InputData.maxDepthConsider)); nml.emplace_back(std::string("! depth step size [nm]")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::depthstep, m_InputData.depthStepSize)); nml.emplace_back(std::string("! should the user be notified by email or Slack that the program has completed its run?")); nml.emplace_back(FileIOTools::CreateNMLEntry(QString("Notify"), QString("Off"))); nml.emplace_back(std::string("! output data file name; pathname is relative to the EMdatapathname path !!!")); nml.emplace_back(FileIOTools::CreateNMLEntry(EMsoft::Constants::dataname, m_InputData.outputFilePath)); nml.emplace_back(std::string(" /")); QFile outputFile(path); if(outputFile.open(QFile::WriteOnly)) { QTextStream out(&outputFile); for(const auto& entry : nml) { out << QString::fromStdString(entry) << "\n"; } outputFile.close(); // outputFile.copy("/tmp/EMMCOpenCL.nml"); } else { emit errorMessageGenerated(QString("Could not create temp NML file at path %1").arg(path)); } } // ----------------------------------------------------------------------------- void MonteCarloSimulationController::processFinished() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- bool MonteCarloSimulationController::validateInput() const { if(m_InputData.inputFilePath.isEmpty()) { QString ss = QObject::tr("The crystal structure input file path must be set."); emit errorMessageGenerated(ss); return false; } { QString inputFilePath = m_InputData.inputFilePath; QFileInfo fi(inputFilePath); if(fi.completeSuffix() != "xtal") { QString ss = QObject::tr("The crystal structure input file at path '%1' needs a '.xtal' suffix.").arg(inputFilePath); emit errorMessageGenerated(ss); return false; } if(!fi.exists()) { QString ss = QObject::tr("The crystal structure input file at path '%1' does not exist.").arg(inputFilePath); emit errorMessageGenerated(ss); return false; } } if(m_InputData.outputFilePath.isEmpty()) { QString ss = QObject::tr("The monte carlo output file path must be set."); emit errorMessageGenerated(ss); return false; } QString outputFilePath = m_InputData.outputFilePath; QFileInfo fi(outputFilePath); if(fi.completeSuffix() != "h5") { QString ss = QObject::tr("The monte carlo output file at path '%1' needs a '.h5' suffix.").arg(outputFilePath); emit errorMessageGenerated(ss); return false; } if(m_InputData.totalNumOfEConsidered < 0) { QString ss = QObject::tr("The total number of electrons must be > 0. Value = %1").arg(m_InputData.totalNumOfEConsidered); emit errorMessageGenerated(ss); return false; } // test sample tilt angles for EBSD if((m_InputData.sampleTiltAngleSig < 0) || (m_InputData.sampleTiltAngleSig >= 90)) { QString ss = QObject::tr("Sample TD tilt angle must be in interval [0,90["); emit errorMessageGenerated(ss); return false; } if((m_InputData.sampleRotAngleOmega < -45) || (m_InputData.sampleRotAngleOmega > 45)) { QString ss = QObject::tr("Sample RD tilt angle must be in interval [-45,45]"); emit errorMessageGenerated(ss); return false; } // test sample tilt angles for ECP if((m_InputData.sampleStartTiltAngle < 0) || (m_InputData.sampleStartTiltAngle > m_InputData.sampleEndTiltAngle) || (m_InputData.sampleStartTiltAngle > 90)) { QString ss = QObject::tr("Sample start tilt angle must be in interval [0,endangle]"); emit errorMessageGenerated(ss); return false; } if((m_InputData.sampleEndTiltAngle < m_InputData.sampleStartTiltAngle) || (m_InputData.sampleEndTiltAngle > 90)) { QString ss = QObject::tr("Sample end tilt angle must be in interval [startangle,90]"); emit errorMessageGenerated(ss); return false; } if((m_InputData.sampleTiltStepSize < 0) || (m_InputData.sampleTiltStepSize > m_InputData.sampleEndTiltAngle - m_InputData.sampleStartTiltAngle)) { QString ss = QObject::tr("Sample tilt step size must be positive, with at least one step in the [start,end] interval."); emit errorMessageGenerated(ss); return false; } // test voltage and step size if(m_InputData.acceleratingVoltage < 0) { QString ss = QObject::tr("Microscope accelerating voltage must be positive"); emit errorMessageGenerated(ss); return false; } if((m_InputData.minEnergyConsider < 0) || m_InputData.minEnergyConsider > m_InputData.acceleratingVoltage) { QString ss = QObject::tr("Voltage must be positive and less than the accelerating voltage"); emit errorMessageGenerated(ss); return false; } if((m_InputData.energyBinSize < 0) || m_InputData.energyBinSize > m_InputData.acceleratingVoltage - m_InputData.minEnergyConsider) { QString ss = QObject::tr("Voltage step size must be positive, with at least one bin."); emit errorMessageGenerated(ss); return false; } // test depth parameters if(m_InputData.maxDepthConsider <= 0) { QString ss = QObject::tr("Maximum depth must be strictly positive"); emit errorMessageGenerated(ss); return false; } if((m_InputData.depthStepSize <= 0) || (m_InputData.depthStepSize > m_InputData.maxDepthConsider)) { QString ss = QObject::tr("Depth step size must be strictly positive, with at least one bin."); emit errorMessageGenerated(ss); return false; } // numsx must be an odd number ... if((m_InputData.numOfPixelsN % 2) == 0) { QString ss = QObject::tr("Number of points must be odd."); emit errorMessageGenerated(ss); return false; } // make sure the multiplier is strictly positive if(m_InputData.multiplierForTotalNumOfE < 1) { QString ss = QObject::tr("Multiplier must be at least 1"); emit errorMessageGenerated(ss); return false; } return true; }
45.234323
158
0.692106
[ "vector" ]
47ef36e06ecbdcbc229fde9189c7bf8b5646d223
1,523
cpp
C++
tests/sem3d.cpp
Fvergnet/cafes
ac634318980e7b5787ba34a4d6d20eb27be69c9a
[ "BSD-3-Clause" ]
5
2016-07-15T09:34:27.000Z
2021-02-11T21:01:26.000Z
tests/sem3d.cpp
Fvergnet/cafes
ac634318980e7b5787ba34a4d6d20eb27be69c9a
[ "BSD-3-Clause" ]
1
2020-09-11T14:59:58.000Z
2020-09-11T14:59:58.000Z
tests/sem3d.cpp
Fvergnet/cafes
ac634318980e7b5787ba34a4d6d20eb27be69c9a
[ "BSD-3-Clause" ]
2
2016-12-16T09:40:57.000Z
2019-09-03T12:40:40.000Z
#include <cafes.hpp> #include <petsc.h> void zeros(const PetscReal x[], PetscScalar *u){ *u = 0.; } void ones(const PetscReal x[], PetscScalar *u){ *u = 1.; } int main(int argc, char **argv) { PetscErrorCode ierr; std::size_t const dim = 3; ierr = PetscInitialize(&argc, &argv, (char *)0, (char *)0);CHKERRQ(ierr); auto bc = cafes::make_bc<dim>({ {{zeros, zeros, zeros}} , {{zeros, zeros, zeros}} , {{zeros, zeros, zeros}} , {{zeros, zeros, zeros}} , {{zeros, zeros, zeros}} , {{zeros, zeros, zeros}} }); auto rhs = cafes::make_rhs<dim>({{ ones, zeros, zeros }}); auto st = cafes::make_stokes<dim>(bc, rhs); auto se = cafes::make_sphere( {.5, .5, .5}, .1); std::vector<cafes::particle<decltype(se)>> pt{ cafes::make_particle_with_force(se, {0.,150., 1.}, 0.25) }; auto s = cafes::make_SEM(pt, st, {{.1, .1}}); ierr = s.create_Mat_and_Vec();CHKERRQ(ierr); s.setup_RHS(); s.setup_KSP(); s.solve(); // PetscViewer viewer; // ierr = PetscViewerHDF5Open(PETSC_COMM_WORLD, "solution.h5", FILE_MODE_WRITE, &viewer);CHKERRQ(ierr); // ierr = VecView(st.sol, viewer);CHKERRQ(ierr); // ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); ierr = PetscFinalize();CHKERRQ(ierr); return 0; }
33.108696
107
0.508864
[ "vector" ]
47effe33d948cc92a8bcc67ee022b760dfb8bf97
1,365
hpp
C++
dev/Basic/shared/network/ControlManager.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/shared/network/ControlManager.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/shared/network/ControlManager.hpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology //Licensed under the terms of the MIT License, as described in the file: // license.txt (http://opensource.org/licenses/MIT) /* * ControlManager.hpp * * Created on: Nov 24, 2012 * Author: redheli */ #pragma once #include <sys/poll.h> #include <stdio.h> #include <fcntl.h> #include <map> #include <string> #include <boost/thread.hpp> namespace sim_mob { class ConfigParams; enum SIMSTATE { IDLE=0, RUNNING=1, PAUSE=2, STOP=3, NOTREADY=4, READY=5, LOADSCENARIO=6, QUIT }; class ControlManager { public: void start(); void setSimState(int s); int getSimState(); void getLoadScenarioParas(std::map<std::string,std::string> &para) { para=loadScenarioParas; } bool handleInput(std::string& input); void setEndTick(int t); int getEndTick() { return endTick;} private: ControlManager(); struct pollfd fds; int simState; std::map<std::string,std::string> loadScenarioParas; boost::mutex lock; boost::mutex lockEndTick; int endTick; //Again, ControlManager's constructor is private for now (since we need to guarantee only one of these), // but to avoid the singleton pattern, we place the global ControlManager object into ConfigParams. friend class sim_mob::ConfigParams; }; }
22.75
108
0.684982
[ "object" ]
9a0482861c4bee53be460e9b811387c6e8e25f96
4,018
cpp
C++
ros/src/computing/perception/localization/packages/orb_scan_localizer/Thirdparty/g2o/g2o/solvers/csparse/csparse_helper.cpp
yukitsuji/mono_3d_localizer
a3b4f64058482b072c277b5f6e959d485f26868b
[ "BSD-3-Clause" ]
5
2018-06-20T08:29:21.000Z
2018-11-12T06:05:52.000Z
ros/src/computing/perception/localization/packages/orb_scan_localizer/Thirdparty/g2o/g2o/solvers/csparse/csparse_helper.cpp
yukitsuji/mono_3d_localizer
a3b4f64058482b072c277b5f6e959d485f26868b
[ "BSD-3-Clause" ]
null
null
null
ros/src/computing/perception/localization/packages/orb_scan_localizer/Thirdparty/g2o/g2o/solvers/csparse/csparse_helper.cpp
yukitsuji/mono_3d_localizer
a3b4f64058482b072c277b5f6e959d485f26868b
[ "BSD-3-Clause" ]
1
2019-01-21T13:38:45.000Z
2019-01-21T13:38:45.000Z
// g2o - General Graph Optimization // Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "csparse_helper.h" #include "g2o/stuff/macros.h" #include <string> #include <cassert> #include <fstream> #include <cstring> #include <iomanip> #include <iostream> #include <algorithm> #include <vector> using namespace std; namespace g2o { namespace csparse_extension { struct SparseMatrixEntry{ SparseMatrixEntry(int r=-1, int c=-1, double x=0) : _r(r), _c(c), _x(x) { } int _r,_c; double _x; }; struct SparseMatrixEntryColSort { bool operator()(const SparseMatrixEntry& e1, const SparseMatrixEntry& e2) const { return e1._c < e2._c || (e1._c == e2._c && e1._r < e2._r); } }; bool writeCs2Octave(const char* filename, const cs* A, bool upperTriangular) { int cols = A->n; int rows = A->m; string name = filename; std::string::size_type lastDot = name.find_last_of('.'); if (lastDot != std::string::npos) name = name.substr(0, lastDot); vector<SparseMatrixEntry> entries; if (A->nz == -1) { // CCS matrix const int* Ap = A->p; const int* Ai = A->i; const double* Ax = A->x; for (int i=0; i < cols; i++) { const int& rbeg = Ap[i]; const int& rend = Ap[i+1]; for (int j = rbeg; j < rend; j++) { entries.push_back(SparseMatrixEntry(Ai[j], i, Ax[j])); if (upperTriangular && Ai[j] != i) entries.push_back(SparseMatrixEntry(i, Ai[j], Ax[j])); } } } else { // Triplet matrix entries.reserve(A->nz); int *Aj = A->p; // column indeces int *Ai = A->i; // row indices double *Ax = A->x; // values; for (int i = 0; i < A->nz; ++i) { entries.push_back(SparseMatrixEntry(Ai[i], Aj[i], Ax[i])); if (upperTriangular && Ai[i] != Aj[i]) entries.push_back(SparseMatrixEntry(Aj[i], Ai[i], Ax[i])); } } sort(entries.begin(), entries.end(), SparseMatrixEntryColSort()); std::ofstream fout(filename); fout << "# name: " << name << std::endl; fout << "# type: sparse matrix" << std::endl; fout << "# nnz: " << entries.size() << std::endl; fout << "# rows: " << rows << std::endl; fout << "# columns: " << cols << std::endl; //fout << fixed; fout << setprecision(9) << endl; for (vector<SparseMatrixEntry>::const_iterator it = entries.begin(); it != entries.end(); ++it) { const SparseMatrixEntry& entry = *it; fout << entry._r+1 << " " << entry._c+1 << " " << entry._x << std::endl; } return fout.good(); } } // end namespace } // end namespace
34.34188
101
0.630911
[ "vector" ]
9a106bcbee666aa5ea982991e1bc866053b7e41a
16,186
cpp
C++
ui/ddf_bindingeditor.cpp
giuliandenicola1/deconz-rest-plugin
f01c40bcb73f17339216bd3c15af4a6bbc3b54e4
[ "BSD-3-Clause" ]
1,765
2015-06-09T08:10:44.000Z
2022-03-29T16:20:41.000Z
ui/ddf_bindingeditor.cpp
giuliandenicola1/deconz-rest-plugin
f01c40bcb73f17339216bd3c15af4a6bbc3b54e4
[ "BSD-3-Clause" ]
5,354
2015-01-09T21:18:14.000Z
2022-03-31T21:41:56.000Z
ui/ddf_bindingeditor.cpp
giuliandenicola1/deconz-rest-plugin
f01c40bcb73f17339216bd3c15af4a6bbc3b54e4
[ "BSD-3-Clause" ]
506
2015-04-15T14:08:41.000Z
2022-03-28T09:23:35.000Z
#include <QAction> #include <QEvent> #include <QDragEnterEvent> #include <QDropEvent> #include <QFormLayout> #include <QHBoxLayout> #include <QHeaderView> #include <QLabel> #include <QLineEdit> #include <QMimeData> #include <QScrollArea> #include <QSpinBox> #include <QStandardItemModel> #include <QTableView> #include <QUrlQuery> #include <QVBoxLayout> #include "deconz/dbg_trace.h" #include "deconz/zcl.h" #include "ddf_bindingeditor.h" #include "device_descriptions.h" DDF_ZclReportWidget::DDF_ZclReportWidget(QWidget *parent, DDF_ZclReport *rep, const deCONZ::ZclCluster *cl) : QFrame(parent) { Q_ASSERT(rep); Q_ASSERT(cl); cluster = cl; report = rep; attrId = new QLineEdit(this); attrName = new QLabel(this); attrName->setWordWrap(true); QFont smallFont = font(); smallFont.setPointSize(smallFont.pointSize() - 1); mfCode = new QLineEdit(this); mfCode->setPlaceholderText(QLatin1String("0x0000")); dataType = new QLineEdit(this); minInterval = new QSpinBox(this); minInterval->setMinimum(0); minInterval->setMaximum(65535); maxInterval = new QSpinBox(this); maxInterval->setMinimum(0); maxInterval->setMaximum(65535); reportableChange = new QLineEdit(this); const auto dt = deCONZ::ZCL_DataType(rep->dataType); DBG_Assert(dt.isValid()); auto at = std::find_if(cl->attributes().cbegin(), cl->attributes().cend(), [rep](const auto &i) { return i.id() == rep->attributeId; }); attrId->setText(QString("0x%1").arg(rep->attributeId, 4, 16, QLatin1Char('0'))); if (rep->manufacturerCode != 0) { mfCode->setText(QString("0x%1").arg(rep->manufacturerCode, 4, 16, QLatin1Char('0'))); } if (at != cl->attributes().cend()) { attrName->setText(at->name()); } if (dt.isValid()) { dataType->setText(dt.shortname()); } else { dataType->setText(QString("0x%1").arg(rep->dataType, 2, 16, QLatin1Char('0'))); } minInterval->setValue(rep->minInterval); maxInterval->setValue(rep->maxInterval); reportableChange->setText(QString::number(rep->reportableChange)); connect(attrId, &QLineEdit::textChanged, this, &DDF_ZclReportWidget::attributeIdChanged); connect(mfCode, &QLineEdit::textChanged, this, &DDF_ZclReportWidget::mfCodeChanged); connect(dataType, &QLineEdit::textChanged, this, &DDF_ZclReportWidget::dataTypeChanged); connect(reportableChange, &QLineEdit::textChanged, this, &DDF_ZclReportWidget::reportableChangeChanged); connect(minInterval, SIGNAL(valueChanged(int)), this, SLOT(minMaxChanged(int))); connect(maxInterval, SIGNAL(valueChanged(int)), this, SLOT(minMaxChanged(int))); auto *lay = new QFormLayout; lay->addRow(QLatin1String("Attribute"), attrName); lay->addRow(QLatin1String("Attribute ID"), attrId); lay->addRow(QLatin1String("Manufacturer code"), mfCode); lay->addRow(QLatin1String("Datatype ID"), dataType); lay->addRow(QLatin1String("Min interval"), minInterval); lay->addRow(QLatin1String("Max interval"), maxInterval); lay->addRow(QLatin1String("Reportable change"), reportableChange); setLayout(lay); setFrameStyle(QFrame::StyledPanel | QFrame::Raised); QAction *removeAction = new QAction(tr("Remove"), this); addAction(removeAction); setContextMenuPolicy(Qt::ActionsContextMenu); connect(removeAction, &QAction::triggered, this, &DDF_ZclReportWidget::removed); } void DDF_ZclReportWidget::attributeIdChanged() { if (report) { bool ok; uint val = attrId->text().toUShort(&ok, 0); if (ok && report->attributeId != val) { // update attribute name auto at = std::find_if(cluster->attributes().cbegin(), cluster->attributes().cend(), [val](const auto &i) { return i.id() == val; }); if (at != cluster->attributes().cend()) { attrName->setText(at->name()); } else { attrName->clear(); } report->attributeId = val; emit changed(); } } } void DDF_ZclReportWidget::mfCodeChanged() { if (report) { bool ok; uint val = mfCode->text().toUShort(&ok, 0); if (ok) { report->manufacturerCode = val; emit changed(); } } } void DDF_ZclReportWidget::dataTypeChanged() { if (report) { QString text = dataType->text(); if (text.startsWith(QLatin1String("0x"))) { bool ok; uint val = dataType->text().toUShort(&ok, 0); if (ok && val <= UINT8_MAX) { const auto dt = deCONZ::ZCL_DataType(val); if (dt.isValid()) { report->dataType = val; emit changed(); } } } else { const auto dt = deCONZ::ZCL_DataType(text); if (dt.isValid() && report->dataType != dt.id()) { report->dataType = dt.id(); emit changed(); } } } } void DDF_ZclReportWidget::reportableChangeChanged() { if (report) { bool ok; uint val = reportableChange->text().toUInt(&ok, 0); if (ok && val <= UINT32_MAX) { report->reportableChange = val; emit changed(); } } } void DDF_ZclReportWidget::minMaxChanged(int val) { Q_UNUSED(val) if (report) { report->minInterval = minInterval->value(); report->maxInterval = maxInterval->value(); emit changed(); } } class DDF_BindingEditorPrivate { public: DDF_Binding *getSelectedBinding(QModelIndex *index); std::vector<DDF_Binding> bindings; QTableView *bndView = nullptr; QStandardItemModel *bndModel = nullptr; QScrollArea *repScrollArea = nullptr; QWidget *repWidget = nullptr; deCONZ::ZclCluster curCluster; std::vector<DDF_ZclReportWidget*> repReportWidgets; }; DDF_Binding *DDF_BindingEditorPrivate::getSelectedBinding(QModelIndex *index) { const QModelIndexList indexes = bndView->selectionModel()->selectedIndexes(); if (indexes.isEmpty()) { return nullptr; } *index = indexes.first(); if (!index->isValid() || index->row() >= int(bindings.size())) { return nullptr; } return &bindings[index->row()]; } DDF_BindingEditor::DDF_BindingEditor(QWidget *parent) : QWidget(parent), d(new DDF_BindingEditorPrivate) { auto *lay = new QHBoxLayout; setLayout(lay); auto *bndLay = new QVBoxLayout; auto *bndLabel = new QLabel(tr("Bindings")); bndLay->addWidget(bndLabel); d->bndModel = new QStandardItemModel(this); d->bndModel->setColumnCount(3); d->bndView = new QTableView(this); d->bndView->setModel(d->bndModel); d->bndView->horizontalHeader()->setStretchLastSection(true); d->bndView->setMinimumWidth(400); d->bndView->setMaximumWidth(600); d->bndView->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); d->bndView->setSelectionBehavior(QTableView::SelectRows); d->bndView->setSelectionMode(QTableView::SingleSelection); d->bndView->verticalHeader()->hide(); d->bndView->setAcceptDrops(true); d->bndView->installEventFilter(this); connect(d->bndView->selectionModel(), &QItemSelectionModel::currentChanged, this, &DDF_BindingEditor::bindingActivated); QAction *removeAction = new QAction(tr("Remove"), this); d->bndView->addAction(removeAction); d->bndView->setContextMenuPolicy(Qt::ActionsContextMenu); connect(removeAction, &QAction::triggered, this, &DDF_BindingEditor::removeBinding); bndLay->addWidget(d->bndView); lay->addLayout(bndLay); auto *repLay = new QVBoxLayout; auto *repLabel = new QLabel(tr("Reporting configuration")); repLay->addWidget(repLabel); d->repScrollArea = new QScrollArea(this); d->repScrollArea->setMinimumWidth(400); d->repScrollArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); d->repWidget = new QWidget; d->repWidget->installEventFilter(this); d->repWidget->setAcceptDrops(true); auto *scrollLay = new QVBoxLayout; scrollLay->addStretch(); d->repWidget->setLayout(scrollLay); d->repScrollArea->setWidget(d->repWidget); d->repScrollArea->setWidgetResizable(true); repLay->addWidget(d->repScrollArea); lay->addLayout(repLay); lay->addStretch(0); } DDF_BindingEditor::~DDF_BindingEditor() { delete d; } const std::vector<DDF_Binding> &DDF_BindingEditor::bindings() const { return d->bindings; } /* { "bind": "unicast", "src.ep": 2, "cl": "0x0001", "report": [ {"at": "0x0021", "dt": "0x20", "min": 7200, "max": 7200, "change": "0x00" } ] } */ void DDF_BindingEditor::setBindings(const std::vector<DDF_Binding> &bindings) { d->bndModel->clear(); d->bndModel->setHorizontalHeaderLabels({"Type", "Endpoint", "Cluster"}); d->bindings = bindings; for (const auto &bnd : d->bindings) { const auto cl = deCONZ::ZCL_InCluster(HA_PROFILE_ID, bnd.clusterId, 0x0000); QStandardItem *type = new QStandardItem((bnd.isUnicastBinding ? "unicast" : "group")); QStandardItem *srcEp = new QStandardItem(QString("0x%1").arg(bnd.srcEndpoint, 2, 16, QLatin1Char('0'))); QString name; if (cl.isValid()) { name = cl.name(); } else { name = QString("0x%1").arg(bnd.clusterId, 4, 16, QLatin1Char('0')); } QStandardItem *cluster = new QStandardItem(name); d->bndModel->appendRow({type,srcEp,cluster}); } d->bndView->resizeColumnToContents(0); d->bndView->resizeColumnToContents(1); d->bndView->horizontalHeader()->setStretchLastSection(true); bindingActivated(d->bndModel->index(0, 0), QModelIndex()); } bool DDF_BindingEditor::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::DragEnter) { QDragEnterEvent *e = static_cast<QDragEnterEvent*>(event); if (!e->mimeData()->hasUrls()) { return false; } const auto urls = e->mimeData()->urls(); const auto url = urls.first(); if (object == d->bndView) { if (url.scheme() == QLatin1String("cluster") || url.scheme() == QLatin1String("zclattr")) { e->accept(); return true; } } else if (object == d->repWidget) { QModelIndex index; DDF_Binding *bnd = d->getSelectedBinding(&index); if (bnd && url.scheme() == QLatin1String("zclattr")) { QUrlQuery urlQuery(url); bool ok; if (urlQuery.queryItemValue("cid").toUShort(&ok, 16) == bnd->clusterId) { e->accept(); return true; } } } } else if (event->type() == QEvent::Drop) { QDropEvent *e = static_cast<QDropEvent*>(event); if (!e->mimeData()->hasUrls()) { return false; } const auto urls = e->mimeData()->urls(); if (object == d->bndView) { if (urls.first().scheme() == QLatin1String("cluster")) { dropClusterUrl(urls.first()); } else if (urls.first().scheme() == QLatin1String("zclattr")) { dropClusterUrl(urls.first()); // contains also "cid" and "ep" } return true; } else if (object == d->repWidget) { if (urls.first().scheme() == QLatin1String("zclattr")) { dropAttributeUrl(urls.first()); } return true; } } return false; } void DDF_BindingEditor::bindingActivated(const QModelIndex &index, const QModelIndex &prev) { Q_UNUSED(prev) for (auto *w : d->repReportWidgets) { w->report = nullptr; w->hide(); w->deleteLater(); } d->repReportWidgets.clear(); if (!index.isValid() || index.row() >= int(d->bindings.size())) { return; } auto &bnd = d->bindings[index.row()]; d->curCluster = deCONZ::ZCL_InCluster(HA_PROFILE_ID, bnd.clusterId, 0x0000); QVBoxLayout *lay = static_cast<QVBoxLayout*>(d->repWidget->layout()); int i = 0; for (auto &rep : bnd.reporting) { auto *w = new DDF_ZclReportWidget(d->repWidget, &rep, &d->curCluster); d->repReportWidgets.push_back(w); lay->insertWidget(i, w); i++; connect(w, &DDF_ZclReportWidget::changed, this, &DDF_BindingEditor::bindingsChanged); connect(w, &DDF_ZclReportWidget::removed, this, &DDF_BindingEditor::reportRemoved); } } void DDF_BindingEditor::dropClusterUrl(const QUrl &url) { QUrlQuery urlQuery(url); DDF_Binding bnd{}; bool ok; bnd.clusterId = urlQuery.queryItemValue("cid").toUShort(&ok, 16); bnd.srcEndpoint = urlQuery.queryItemValue("ep").toUInt(&ok, 16) & 0xFF; bnd.isUnicastBinding = 1; const auto i = std::find_if(d->bindings.cbegin(), d->bindings.cend(), [&](const auto &i) { return i.clusterId == bnd.clusterId && i.srcEndpoint == bnd.srcEndpoint && i.isUnicastBinding == bnd.isUnicastBinding; }); if (i == d->bindings.cend()) { d->bindings.push_back(bnd); setBindings(d->bindings); d->bndView->selectRow(d->bindings.size() - 1); emit bindingsChanged(); } } void DDF_BindingEditor::dropAttributeUrl(const QUrl &url) { QModelIndex index; DDF_Binding *bnd = d->getSelectedBinding(&index); if (!bnd) { return; } QUrlQuery urlQuery(url); if (!urlQuery.hasQueryItem("a")) { return; } DDF_ZclReport rep{}; bool ok; rep.attributeId = urlQuery.queryItemValue("a").toUShort(&ok, 16); if (urlQuery.hasQueryItem("mf")) { rep.manufacturerCode = urlQuery.queryItemValue("mf").toUShort(&ok, 16); } if (urlQuery.hasQueryItem("dt")) { rep.dataType = urlQuery.queryItemValue("dt").toUShort(&ok, 16) & 0xFF; } if (urlQuery.hasQueryItem("rmin")) { rep.minInterval = urlQuery.queryItemValue("rmin").toUShort(); } if (urlQuery.hasQueryItem("rmax")) { rep.maxInterval = urlQuery.queryItemValue("rmax").toUShort(); } if (urlQuery.queryItemValue("t") == "A" && urlQuery.hasQueryItem("rchange")) { rep.reportableChange = urlQuery.queryItemValue("rchange").toUShort(); } auto i = std::find_if(bnd->reporting.begin(), bnd->reporting.end(), [&](const auto &i) { return i.attributeId == rep.attributeId; }); if (i == bnd->reporting.cend()) { bnd->reporting.push_back(rep); } else { *i = rep; } bindingActivated(index, QModelIndex()); emit bindingsChanged(); } void DDF_BindingEditor::reportRemoved() { DDF_ZclReportWidget *w = static_cast<DDF_ZclReportWidget*>(sender()); if (!w || !w->report) { return; } QModelIndex index; DDF_Binding *bnd = d->getSelectedBinding(&index); if (!bnd) { return; } auto i = std::find_if(bnd->reporting.begin(), bnd->reporting.end(), [&](const auto &i){ return w->report == &i; }); if (i != bnd->reporting.end()) { w->report = nullptr; bnd->reporting.erase(i); bindingActivated(index, QModelIndex()); emit bindingsChanged(); } } void DDF_BindingEditor::removeBinding() { QModelIndex index; auto *bnd = d->getSelectedBinding(&index); if (!bnd || !index.isValid() || index.row() >= int(d->bindings.size())) { return; } d->bindings.erase(d->bindings.begin() + index.row()); setBindings(d->bindings); emit bindingsChanged(); }
27.341216
145
0.599098
[ "object", "vector" ]
9a1372e394c9eae5cc6d4d39ce43223973de6ad0
11,313
cxx
C++
src/extractor/compressed_edge_container.cxx
ambasta/osram
5415b73292e1387fb1dbcab58296ea6fefab9075
[ "BSD-2-Clause" ]
1
2021-01-25T11:07:22.000Z
2021-01-25T11:07:22.000Z
src/extractor/compressed_edge_container.cxx
ambasta/osram
5415b73292e1387fb1dbcab58296ea6fefab9075
[ "BSD-2-Clause" ]
null
null
null
src/extractor/compressed_edge_container.cxx
ambasta/osram
5415b73292e1387fb1dbcab58296ea6fefab9075
[ "BSD-2-Clause" ]
null
null
null
#include "osram/util/typedefs.hxx" #include <algorithm> #include <fmt/core.h> #include <osram/extractor/compressed_edge_container.hxx> namespace osram { namespace extractor { CompressedEdgeContainer::CompressedEdgeContainer() { m_free_list.reserve(100); increase_free_list(); } void CompressedEdgeContainer::increase_free_list() { m_compressed_oneway_geometries.resize(m_compressed_oneway_geometries.size() + 100); for (std::size_t index = 100; index > 0; --index) { m_free_list.emplace_back(free_lis_max); ++free_lis_max; } } bool CompressedEdgeContainer::has_entry_for_id(const EdgeId edge_id) const { auto iter = m_edge_id_to_list_index_map.find(edge_id); return iter != m_edge_id_to_list_index_map.end(); } bool CompressedEdgeContainer::has_zipped_entry_for_forward_id( const EdgeId edge_id) const { auto iter = m_forward_edge_id_to_zipped_index_map.find(edge_id); return iter != m_forward_edge_id_to_zipped_index_map.end(); } bool CompressedEdgeContainer::has_zipped_entry_for_reverse_id( const EdgeId edge_id) const { auto iter = m_reverse_edge_id_to_zipped_index_map.find(edge_id); return iter != m_reverse_edge_id_to_zipped_index_map.end(); } unsigned CompressedEdgeContainer::get_position_for_id(const EdgeId edge_id) const { auto iter = m_edge_id_to_list_index_map.find(edge_id); assert(iter != m_edge_id_to_list_index_map.end()); assert(iter->second < m_compressed_oneway_geometries.size()); return iter->second; } /* unsigned CompressedEdgeContainer::get_zipped_position_for_forward_id( const EdgeId edge_id) const { auto iter = m_forward_edge_id_to_zipped_index_map.find(edge_id); assert(iter != m_forward_edge_id_to_zipped_index_map.end()); assert(iter->second < segment_data->nodes_size()); return iter->second; } unsigned CompressedEdgeContainer::get_zipped_position_for_reverse_id( const EdgeId edge_id) const { auto iter = m_reverse_edge_id_to_zipped_index_map.find(edge_id); assert(iter != m_reverse_edge_id_to_zipped_index_map.end()); assert(iter->second < segment_data->nodes_size()); return iter->second; }*/ SegmentWeight CompressedEdgeContainer::clip_weight(const SegmentWeight weight) { if (weight >= INVALID_SEGMENT_WEIGHT) { clipped_weights++; return MAX_SEGMENT_WEIGHT; } return weight; } SegmentDuration CompressedEdgeContainer::clip_duration(const SegmentDuration duration) { if (duration > INVALID_SEGMENT_DURATION) { clipped_weights++; return MAX_SEGMENT_DURATION; } return duration; } void CompressedEdgeContainer::compress_edge( const EdgeId surviving_edge_id, const EdgeId removed_edge_id, const NodeId via_node_id, const NodeId target_node, const EdgeWeight surviving_edge_weight, const EdgeWeight removed_edge_weight, const EdgeDuration surviving_edge_duration, const EdgeDuration removed_edge_duration, const EdgeWeight node_weight_penalty = INVALID_EDGE_WEIGHT, const EdgeDuration node_duration_penalty = MAXIMAL_EDGE_DURATION) { assert(surviving_edge_id != SPECIAL_EDGEID); assert(removed_edge_id != SPECIAL_EDGEID); assert(via_node_id != SPECIAL_NODEID); assert(target_node != SPECIAL_NODEID); assert(surviving_edge_weight != INVALID_SEGMENT_WEIGHT); assert(removed_edge_weight != INVALID_SEGMENT_WEIGHT); if (!has_entry_for_id(surviving_edge_id)) { if (m_free_list.size() == 0) increase_free_list(); assert(!m_free_list.empty()); m_edge_id_to_list_index_map[surviving_edge_id] = m_free_list.back(); m_free_list.pop_back(); } const auto iter = m_edge_id_to_list_index_map.find(surviving_edge_id); assert(iter != m_edge_id_to_list_index_map.end()); const unsigned surviving_edge_bucket_id = iter->second; assert(surviving_edge_bucket_id == get_position_for_id(surviving_edge_id)); assert(surviving_edge_bucket_id < m_compressed_oneway_geometries.size()); std::vector<OneWayCompressedEdge> &surviving_edge_bucket_list = m_compressed_oneway_geometries[surviving_edge_bucket_id]; if (surviving_edge_bucket_list.empty()) { surviving_edge_bucket_list.emplace_back( OneWayCompressedEdge{via_node_id, clip_weight(surviving_edge_weight), clip_duration(surviving_edge_duration)}); } assert(surviving_edge_bucket_list.size() > 0); assert(!surviving_edge_bucket_list.empty()); if (node_weight_penalty != INVALID_EDGE_WEIGHT and node_duration_penalty != MAXIMAL_EDGE_DURATION) { surviving_edge_bucket_list.emplace_back( OneWayCompressedEdge{via_node_id, clip_weight(node_weight_penalty), clip_duration(node_duration_penalty)}); } if (has_entry_for_id(removed_edge_id)) { const unsigned list_to_remove_index = get_position_for_id(removed_edge_id); assert(list_to_remove_index < m_compressed_oneway_geometries.size()); std::vector<OneWayCompressedEdge> &removed_edge_bucket_list = m_compressed_oneway_geometries[list_to_remove_index]; surviving_edge_bucket_list.insert(surviving_edge_bucket_list.end(), removed_edge_bucket_list.begin(), removed_edge_bucket_list.end()); m_edge_id_to_list_index_map.erase(removed_edge_id); assert(m_edge_id_to_list_index_map.end() == m_edge_id_to_list_index_map.find(removed_edge_id)); removed_edge_bucket_list.clear(); assert(removed_edge_bucket_list.size() == 0); m_free_list.emplace_back(list_to_remove_index); assert(m_free_list.back() == list_to_remove_index); } else { surviving_edge_bucket_list.emplace_back( OneWayCompressedEdge{target_node, clip_weight(removed_edge_weight), clip_duration(removed_edge_duration)}); } } void CompressedEdgeContainer::add_uncompressed_edge( const EdgeId edge_id, const NodeId node_id, const SegmentWeight weight, const SegmentDuration duration) { assert(edge_id != SPECIAL_EDGEID); assert(node_id != SPECIAL_NODEID); assert(weight != INVALID_EDGE_WEIGHT); if (!has_entry_for_id(edge_id)) { if (m_free_list.size() == 0) increase_free_list(); assert(!m_free_list.empty()); m_edge_id_to_list_index_map[edge_id] = m_free_list.back(); m_free_list.pop_back(); } const auto iter = m_edge_id_to_list_index_map.find(edge_id); assert(iter != m_edge_id_to_list_index_map.end()); const unsigned edge_bucket_id = iter->second; assert(edge_bucket_id == get_position_for_id(edge_id)); assert(edge_bucket_id < m_compressed_oneway_geometries.size()); std::vector<OneWayCompressedEdge> &edge_bucket_list = m_compressed_oneway_geometries[edge_bucket_id]; if (edge_bucket_list.empty()) { edge_bucket_list.emplace_back(OneWayCompressedEdge{ node_id, clip_weight(weight), clip_duration(duration)}); } } void CompressedEdgeContainer::initialize_both_way_vector() { segment_data = std::make_unique<SegmentDataContainer>(); segment_data->reserve(m_compressed_oneway_geometries.size()); } unsigned CompressedEdgeContainer::zip_edges(const EdgeId forward_edge_id, const EdgeId reverse_edge_id) { if (!segment_data) initialize_both_way_vector(); const auto &forward_bucket = get_bucket_reference(forward_edge_id); const auto &reverse_bucket = get_bucket_reference(reverse_edge_id); assert(forward_bucket.size() == reverse_bucket.size()); const unsigned zipped_geometry_id = segment_data->index_size(); m_forward_edge_id_to_zipped_index_map[forward_edge_id] = zipped_geometry_id; m_reverse_edge_id_to_zipped_index_map[reverse_edge_id] = zipped_geometry_id; const auto &first_node = reverse_bucket.back(); constexpr DataSourceId LUA_SOURCE = 0; segment_data->emplace_back(segment_data->nodes_size(), first_node.node_id, INVALID_SEGMENT_WEIGHT, first_node.weight, INVALID_SEGMENT_DURATION, first_node.duration, LUA_SOURCE, LUA_SOURCE); for (std::size_t index = 0; index < forward_bucket.size() - 1; ++index) { const auto &fwd_node = forward_bucket.at(index); const auto &rev_node = reverse_bucket.at(reverse_bucket.size() - 2 - index); assert(fwd_node.node_id == rev_node.node_id); segment_data->emplace_back(fwd_node.node_id, fwd_node.weight, rev_node.weight, fwd_node.duration, rev_node.duration, LUA_SOURCE, LUA_SOURCE); } const auto &last_node = forward_bucket.back(); segment_data->emplace_back(last_node.node_id, last_node.weight, INVALID_SEGMENT_WEIGHT, last_node.duration, INVALID_SEGMENT_DURATION, LUA_SOURCE, LUA_SOURCE); return zipped_geometry_id; } void CompressedEdgeContainer::show_statistics() const { const uint64_t compressed_edges = m_compressed_oneway_geometries.size(); assert(compressed_edges % 2 == 0); assert(compressed_edges + m_free_list.size() > 0); uint64_t compressed_geometries = 0, longest_chain_length = 0; for (const auto &current_vector : m_compressed_oneway_geometries) { compressed_geometries += current_vector.size(); longest_chain_length = std::max(longest_chain_length, (uint64_t)current_vector.size()); } if (clipped_weights > 0) fmt::format("Clipped {} segment weight to {}", clipped_weights, INVALID_SEGMENT_WEIGHT - 1); if (clipped_durations > 0) fmt::format("Clipped {} segment duration to {}", clipped_durations, INVALID_SEGMENT_DURATION - 1); fmt::format( "Geometry successfully removed: \n compressed edges: {}\n compressed " "geometries: {}\n longest chain length: {}\n cmpr ratio: {}\n avg chain " "length: {}", compressed_edges, compressed_geometries, longest_chain_length, (float)compressed_edges / std::max(compressed_geometries, (uint64_t)1), (float)(compressed_geometries) / std::max((uint64_t)1, compressed_edges)); } const CompressedEdgeContainer::OnewayEdgeBucket & CompressedEdgeContainer::get_bucket_reference(const EdgeId edge_id) const { const std::size_t index = m_edge_id_to_list_index_map.at(edge_id); return m_compressed_oneway_geometries.at(index); } bool CompressedEdgeContainer::is_trivial(const EdgeId edge_id) const { return get_bucket_reference(edge_id).size() == 1; } NodeId CompressedEdgeContainer::get_first_edge_target_id(const EdgeId edge_id) const { const auto &bucket = get_bucket_reference(edge_id); assert(bucket.size() > 0); return bucket.front().node_id; } NodeId CompressedEdgeContainer::get_last_edge_source_id(const EdgeId edge_id) const { const auto &bucket = get_bucket_reference(edge_id); assert(bucket.size() > 1); return bucket[bucket.size() - 2].node_id; } NodeId CompressedEdgeContainer::get_last_edge_target_id(const EdgeId edge_id) const { const auto &bucket = get_bucket_reference(edge_id); assert(bucket.size() > 0); return bucket.back().node_id; } std::unique_ptr<SegmentDataContainer> CompressedEdgeContainer::to_segment_data() { segment_data->push_back_index(segment_data->nodes_size()); return std::move(segment_data); } } // namespace extractor } // namespace osram
37.336634
80
0.744188
[ "geometry", "vector" ]
9a13e1a93ac17a32c69b9387a834653698f9e904
4,456
cpp
C++
arbor/cable_cell_param.cpp
8Stefan/arbor
89a4fc4335fe433af6758db84990a08ae5a8e3b2
[ "BSD-3-Clause" ]
null
null
null
arbor/cable_cell_param.cpp
8Stefan/arbor
89a4fc4335fe433af6758db84990a08ae5a8e3b2
[ "BSD-3-Clause" ]
null
null
null
arbor/cable_cell_param.cpp
8Stefan/arbor
89a4fc4335fe433af6758db84990a08ae5a8e3b2
[ "BSD-3-Clause" ]
null
null
null
#include <cfloat> #include <cmath> #include <numeric> #include <vector> #include <arbor/cable_cell.hpp> #include <arbor/cable_cell_param.hpp> #include <arbor/morph/locset.hpp> #include "morph/em_morphology.hpp" #include "util/maputil.hpp" namespace arb { void check_global_properties(const cable_cell_global_properties& G) { auto& param = G.default_parameters; if (!param.init_membrane_potential) { throw cable_cell_error("missing global default parameter value: init_membrane_potential"); } if (!param.temperature_K) { throw cable_cell_error("missing global default parameter value: temperature"); } if (!param.axial_resistivity) { throw cable_cell_error("missing global default parameter value: axial_resistivity"); } if (!param.membrane_capacitance) { throw cable_cell_error("missing global default parameter value: membrane_capacitance"); } for (const auto& ion: util::keys(G.ion_species)) { if (!param.ion_data.count(ion)) { throw cable_cell_error("missing ion defaults for ion "+ion); } } for (const auto& kv: param.ion_data) { auto& ion = kv.first; const cable_cell_ion_data& data = kv.second; if (std::isnan(data.init_int_concentration)) { throw cable_cell_error("missing init_int_concentration for ion "+ion); } if (std::isnan(data.init_ext_concentration)) { throw cable_cell_error("missing init_ext_concentration for ion "+ion); } if (std::isnan(data.init_reversal_potential) && !param.reversal_potential_method.count(ion)) { throw cable_cell_error("missing init_reversal_potential or reversal_potential_method for ion "+ion); } } } cable_cell_local_parameter_set neuron_parameter_defaults = { // ion defaults: internal concentration [mM], external concentration [mM], reversal potential [mV] { {"na", {10.0, 140.0, 115 - 65.}}, {"k", {54.4, 2.5, -12 - 65.}}, {"ca", {5e-5, 2.0, 12.5*std::log(2.0/5e-5)}} }, // initial membrane potential [mV] -65.0, // temperatue [K] 6.3 + 273.15, // axial resistivity [Ω·cm] 35.4, // membrane capacitance [F/m²] 0.01 }; // Discretization policy implementations: locset cv_policy_max_extent::cv_boundary_points(const cable_cell& cell) const { const auto& emorph = *cell.morphology(); const unsigned nbranch = emorph.num_branches(); if (!nbranch || max_extent_<=0) return ls::nil(); std::vector<mlocation> points; unsigned bidx = 0; if (flags_&cv_policy_flag::single_root_cv) { points.push_back({0, 0.}); points.push_back({0, 1.}); bidx = 1; } const double oomax_extent = 1./max_extent_; while (bidx<nbranch) { unsigned ncv = std::ceil(emorph.branch_length(bidx)*oomax_extent); double ooncv = 1./ncv; if (flags_&cv_policy_flag::interior_forks) { for (unsigned i = 0; i<ncv; ++i) { points.push_back({bidx, (1+2*i)*ooncv/2}); } } else { for (unsigned i = 0; i<ncv; ++i) { points.push_back({bidx, i*ooncv}); } points.push_back({bidx, 1.}); } ++bidx; } return std::accumulate(points.begin(), points.end(), ls::nil(), [](auto& l, auto& p) { return join(l, ls::location(p)); }); } locset cv_policy_fixed_per_branch::cv_boundary_points(const cable_cell& cell) const { const unsigned nbranch = cell.morphology()->num_branches(); if (!nbranch) return ls::nil(); std::vector<mlocation> points; unsigned bidx = 0; if (flags_&cv_policy_flag::single_root_cv) { points.push_back({0, 0.}); points.push_back({0, 1.}); bidx = 1; } double ooncv = 1./cv_per_branch_; while (bidx<nbranch) { if (flags_&cv_policy_flag::interior_forks) { for (unsigned i = 0; i<cv_per_branch_; ++i) { points.push_back({bidx, (1+2*i)*ooncv/2}); } } else { for (unsigned i = 0; i<cv_per_branch_; ++i) { points.push_back({bidx, i*ooncv}); } points.push_back({bidx, 1.}); } ++bidx; } return std::accumulate(points.begin(), points.end(), ls::nil(), [](auto& l, auto& p) { return join(l, ls::location(p)); }); } } // namespace arb
31.160839
127
0.605925
[ "vector" ]
9a1c93cf3a12cc48afe0d9fd67d10c23f2a0bd60
1,388
cpp
C++
cpp/2020-08-19--zmq-cmd-chat/code/work_outgoing.cpp
Dreamykass/bitsofkass
b43f726b4d12784075eec998ebf5fff908f87c35
[ "MIT" ]
2
2021-09-22T15:04:29.000Z
2021-11-22T06:30:48.000Z
cpp/2020-08-19--zmq-cmd-chat/code/work_outgoing.cpp
Dreamykass/bitsofkass
b43f726b4d12784075eec998ebf5fff908f87c35
[ "MIT" ]
null
null
null
cpp/2020-08-19--zmq-cmd-chat/code/work_outgoing.cpp
Dreamykass/bitsofkass
b43f726b4d12784075eec998ebf5fff908f87c35
[ "MIT" ]
null
null
null
#include "networker.hpp" #include <map> #include <zmq.hpp> namespace { const std::chrono::milliseconds timeout{ 200 }; } void networker_t::outgoing_work() { zmq::context_t context; zmq::poller_t<> poller; std::map<std::string, zmq::socket_t> sockets; std::vector<zmq::poller_event<>> events(100); while (app_running.load() == true) { { auto _ = std::unique_lock(internal_mutex); for (const auto& peer : peers) { if (!sockets.contains(peer)) { sockets[peer] = std::move(zmq::socket_t(context, zmq::socket_type::push)); poller.add(sockets[peer], zmq::event_flags::pollout); sockets[peer].connect(peer); } } } bool outgoing_messages_is_empty; { auto _ = std::unique_lock(internal_mutex); outgoing_messages_is_empty = outgoing_messages.empty(); } if (!outgoing_messages_is_empty) { events.resize(100); const auto event_n = poller.wait_all(events, timeout); auto _ = std::unique_lock(internal_mutex); while (!outgoing_messages.empty()) { for (size_t i = 0; i < event_n; i++) { auto buff = zmq::buffer(outgoing_messages.back()); events[i].socket.send(buff); } outgoing_messages.pop_back(); } } else { std::this_thread::sleep_for(std::chrono::milliseconds{ 1 }); } } }
24.350877
70
0.607349
[ "vector" ]
9a1f75efa05e0bdb9fd864858e7c7a4daaa38165
52,383
cpp
C++
aws-cpp-sdk-accessanalyzer/source/AccessAnalyzerClient.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-accessanalyzer/source/AccessAnalyzerClient.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-accessanalyzer/source/AccessAnalyzerClient.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/accessanalyzer/AccessAnalyzerClient.h> #include <aws/accessanalyzer/AccessAnalyzerEndpoint.h> #include <aws/accessanalyzer/AccessAnalyzerErrorMarshaller.h> #include <aws/accessanalyzer/model/ApplyArchiveRuleRequest.h> #include <aws/accessanalyzer/model/CancelPolicyGenerationRequest.h> #include <aws/accessanalyzer/model/CreateAccessPreviewRequest.h> #include <aws/accessanalyzer/model/CreateAnalyzerRequest.h> #include <aws/accessanalyzer/model/CreateArchiveRuleRequest.h> #include <aws/accessanalyzer/model/DeleteAnalyzerRequest.h> #include <aws/accessanalyzer/model/DeleteArchiveRuleRequest.h> #include <aws/accessanalyzer/model/GetAccessPreviewRequest.h> #include <aws/accessanalyzer/model/GetAnalyzedResourceRequest.h> #include <aws/accessanalyzer/model/GetAnalyzerRequest.h> #include <aws/accessanalyzer/model/GetArchiveRuleRequest.h> #include <aws/accessanalyzer/model/GetFindingRequest.h> #include <aws/accessanalyzer/model/GetGeneratedPolicyRequest.h> #include <aws/accessanalyzer/model/ListAccessPreviewFindingsRequest.h> #include <aws/accessanalyzer/model/ListAccessPreviewsRequest.h> #include <aws/accessanalyzer/model/ListAnalyzedResourcesRequest.h> #include <aws/accessanalyzer/model/ListAnalyzersRequest.h> #include <aws/accessanalyzer/model/ListArchiveRulesRequest.h> #include <aws/accessanalyzer/model/ListFindingsRequest.h> #include <aws/accessanalyzer/model/ListPolicyGenerationsRequest.h> #include <aws/accessanalyzer/model/ListTagsForResourceRequest.h> #include <aws/accessanalyzer/model/StartPolicyGenerationRequest.h> #include <aws/accessanalyzer/model/StartResourceScanRequest.h> #include <aws/accessanalyzer/model/TagResourceRequest.h> #include <aws/accessanalyzer/model/UntagResourceRequest.h> #include <aws/accessanalyzer/model/UpdateArchiveRuleRequest.h> #include <aws/accessanalyzer/model/UpdateFindingsRequest.h> #include <aws/accessanalyzer/model/ValidatePolicyRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::AccessAnalyzer; using namespace Aws::AccessAnalyzer::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "access-analyzer"; static const char* ALLOCATION_TAG = "AccessAnalyzerClient"; AccessAnalyzerClient::AccessAnalyzerClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<AccessAnalyzerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } AccessAnalyzerClient::AccessAnalyzerClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<AccessAnalyzerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } AccessAnalyzerClient::AccessAnalyzerClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<AccessAnalyzerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } AccessAnalyzerClient::~AccessAnalyzerClient() { } void AccessAnalyzerClient::init(const Client::ClientConfiguration& config) { SetServiceClientName("AccessAnalyzer"); m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + AccessAnalyzerEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void AccessAnalyzerClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } ApplyArchiveRuleOutcome AccessAnalyzerClient::ApplyArchiveRule(const ApplyArchiveRuleRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/archive-rule"); return ApplyArchiveRuleOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } ApplyArchiveRuleOutcomeCallable AccessAnalyzerClient::ApplyArchiveRuleCallable(const ApplyArchiveRuleRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ApplyArchiveRuleOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ApplyArchiveRule(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ApplyArchiveRuleAsync(const ApplyArchiveRuleRequest& request, const ApplyArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ApplyArchiveRuleAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ApplyArchiveRuleAsyncHelper(const ApplyArchiveRuleRequest& request, const ApplyArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ApplyArchiveRule(request), context); } CancelPolicyGenerationOutcome AccessAnalyzerClient::CancelPolicyGeneration(const CancelPolicyGenerationRequest& request) const { if (!request.JobIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("CancelPolicyGeneration", "Required field: JobId, is not set"); return CancelPolicyGenerationOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [JobId]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/policy/generation/"); uri.AddPathSegment(request.GetJobId()); return CancelPolicyGenerationOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } CancelPolicyGenerationOutcomeCallable AccessAnalyzerClient::CancelPolicyGenerationCallable(const CancelPolicyGenerationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CancelPolicyGenerationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CancelPolicyGeneration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::CancelPolicyGenerationAsync(const CancelPolicyGenerationRequest& request, const CancelPolicyGenerationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CancelPolicyGenerationAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::CancelPolicyGenerationAsyncHelper(const CancelPolicyGenerationRequest& request, const CancelPolicyGenerationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CancelPolicyGeneration(request), context); } CreateAccessPreviewOutcome AccessAnalyzerClient::CreateAccessPreview(const CreateAccessPreviewRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/access-preview"); return CreateAccessPreviewOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } CreateAccessPreviewOutcomeCallable AccessAnalyzerClient::CreateAccessPreviewCallable(const CreateAccessPreviewRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateAccessPreviewOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateAccessPreview(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::CreateAccessPreviewAsync(const CreateAccessPreviewRequest& request, const CreateAccessPreviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateAccessPreviewAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::CreateAccessPreviewAsyncHelper(const CreateAccessPreviewRequest& request, const CreateAccessPreviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateAccessPreview(request), context); } CreateAnalyzerOutcome AccessAnalyzerClient::CreateAnalyzer(const CreateAnalyzerRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer"); return CreateAnalyzerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } CreateAnalyzerOutcomeCallable AccessAnalyzerClient::CreateAnalyzerCallable(const CreateAnalyzerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateAnalyzerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateAnalyzer(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::CreateAnalyzerAsync(const CreateAnalyzerRequest& request, const CreateAnalyzerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateAnalyzerAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::CreateAnalyzerAsyncHelper(const CreateAnalyzerRequest& request, const CreateAnalyzerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateAnalyzer(request), context); } CreateArchiveRuleOutcome AccessAnalyzerClient::CreateArchiveRule(const CreateArchiveRuleRequest& request) const { if (!request.AnalyzerNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("CreateArchiveRule", "Required field: AnalyzerName, is not set"); return CreateArchiveRuleOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerName]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer/"); uri.AddPathSegment(request.GetAnalyzerName()); uri.AddPathSegments("/archive-rule"); return CreateArchiveRuleOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } CreateArchiveRuleOutcomeCallable AccessAnalyzerClient::CreateArchiveRuleCallable(const CreateArchiveRuleRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateArchiveRuleOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateArchiveRule(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::CreateArchiveRuleAsync(const CreateArchiveRuleRequest& request, const CreateArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateArchiveRuleAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::CreateArchiveRuleAsyncHelper(const CreateArchiveRuleRequest& request, const CreateArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateArchiveRule(request), context); } DeleteAnalyzerOutcome AccessAnalyzerClient::DeleteAnalyzer(const DeleteAnalyzerRequest& request) const { if (!request.AnalyzerNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("DeleteAnalyzer", "Required field: AnalyzerName, is not set"); return DeleteAnalyzerOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerName]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer/"); uri.AddPathSegment(request.GetAnalyzerName()); return DeleteAnalyzerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER)); } DeleteAnalyzerOutcomeCallable AccessAnalyzerClient::DeleteAnalyzerCallable(const DeleteAnalyzerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteAnalyzerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteAnalyzer(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::DeleteAnalyzerAsync(const DeleteAnalyzerRequest& request, const DeleteAnalyzerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteAnalyzerAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::DeleteAnalyzerAsyncHelper(const DeleteAnalyzerRequest& request, const DeleteAnalyzerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteAnalyzer(request), context); } DeleteArchiveRuleOutcome AccessAnalyzerClient::DeleteArchiveRule(const DeleteArchiveRuleRequest& request) const { if (!request.AnalyzerNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("DeleteArchiveRule", "Required field: AnalyzerName, is not set"); return DeleteArchiveRuleOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerName]", false)); } if (!request.RuleNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("DeleteArchiveRule", "Required field: RuleName, is not set"); return DeleteArchiveRuleOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [RuleName]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer/"); uri.AddPathSegment(request.GetAnalyzerName()); uri.AddPathSegments("/archive-rule/"); uri.AddPathSegment(request.GetRuleName()); return DeleteArchiveRuleOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER)); } DeleteArchiveRuleOutcomeCallable AccessAnalyzerClient::DeleteArchiveRuleCallable(const DeleteArchiveRuleRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteArchiveRuleOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteArchiveRule(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::DeleteArchiveRuleAsync(const DeleteArchiveRuleRequest& request, const DeleteArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteArchiveRuleAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::DeleteArchiveRuleAsyncHelper(const DeleteArchiveRuleRequest& request, const DeleteArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteArchiveRule(request), context); } GetAccessPreviewOutcome AccessAnalyzerClient::GetAccessPreview(const GetAccessPreviewRequest& request) const { if (!request.AccessPreviewIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetAccessPreview", "Required field: AccessPreviewId, is not set"); return GetAccessPreviewOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AccessPreviewId]", false)); } if (!request.AnalyzerArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetAccessPreview", "Required field: AnalyzerArn, is not set"); return GetAccessPreviewOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/access-preview/"); uri.AddPathSegment(request.GetAccessPreviewId()); return GetAccessPreviewOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } GetAccessPreviewOutcomeCallable AccessAnalyzerClient::GetAccessPreviewCallable(const GetAccessPreviewRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetAccessPreviewOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetAccessPreview(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::GetAccessPreviewAsync(const GetAccessPreviewRequest& request, const GetAccessPreviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetAccessPreviewAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::GetAccessPreviewAsyncHelper(const GetAccessPreviewRequest& request, const GetAccessPreviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetAccessPreview(request), context); } GetAnalyzedResourceOutcome AccessAnalyzerClient::GetAnalyzedResource(const GetAnalyzedResourceRequest& request) const { if (!request.AnalyzerArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetAnalyzedResource", "Required field: AnalyzerArn, is not set"); return GetAnalyzedResourceOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerArn]", false)); } if (!request.ResourceArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetAnalyzedResource", "Required field: ResourceArn, is not set"); return GetAnalyzedResourceOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ResourceArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzed-resource"); return GetAnalyzedResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } GetAnalyzedResourceOutcomeCallable AccessAnalyzerClient::GetAnalyzedResourceCallable(const GetAnalyzedResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetAnalyzedResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetAnalyzedResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::GetAnalyzedResourceAsync(const GetAnalyzedResourceRequest& request, const GetAnalyzedResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetAnalyzedResourceAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::GetAnalyzedResourceAsyncHelper(const GetAnalyzedResourceRequest& request, const GetAnalyzedResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetAnalyzedResource(request), context); } GetAnalyzerOutcome AccessAnalyzerClient::GetAnalyzer(const GetAnalyzerRequest& request) const { if (!request.AnalyzerNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetAnalyzer", "Required field: AnalyzerName, is not set"); return GetAnalyzerOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerName]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer/"); uri.AddPathSegment(request.GetAnalyzerName()); return GetAnalyzerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } GetAnalyzerOutcomeCallable AccessAnalyzerClient::GetAnalyzerCallable(const GetAnalyzerRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetAnalyzerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetAnalyzer(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::GetAnalyzerAsync(const GetAnalyzerRequest& request, const GetAnalyzerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetAnalyzerAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::GetAnalyzerAsyncHelper(const GetAnalyzerRequest& request, const GetAnalyzerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetAnalyzer(request), context); } GetArchiveRuleOutcome AccessAnalyzerClient::GetArchiveRule(const GetArchiveRuleRequest& request) const { if (!request.AnalyzerNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetArchiveRule", "Required field: AnalyzerName, is not set"); return GetArchiveRuleOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerName]", false)); } if (!request.RuleNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetArchiveRule", "Required field: RuleName, is not set"); return GetArchiveRuleOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [RuleName]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer/"); uri.AddPathSegment(request.GetAnalyzerName()); uri.AddPathSegments("/archive-rule/"); uri.AddPathSegment(request.GetRuleName()); return GetArchiveRuleOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } GetArchiveRuleOutcomeCallable AccessAnalyzerClient::GetArchiveRuleCallable(const GetArchiveRuleRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetArchiveRuleOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetArchiveRule(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::GetArchiveRuleAsync(const GetArchiveRuleRequest& request, const GetArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetArchiveRuleAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::GetArchiveRuleAsyncHelper(const GetArchiveRuleRequest& request, const GetArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetArchiveRule(request), context); } GetFindingOutcome AccessAnalyzerClient::GetFinding(const GetFindingRequest& request) const { if (!request.AnalyzerArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetFinding", "Required field: AnalyzerArn, is not set"); return GetFindingOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerArn]", false)); } if (!request.IdHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetFinding", "Required field: Id, is not set"); return GetFindingOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [Id]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/finding/"); uri.AddPathSegment(request.GetId()); return GetFindingOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } GetFindingOutcomeCallable AccessAnalyzerClient::GetFindingCallable(const GetFindingRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetFindingOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetFinding(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::GetFindingAsync(const GetFindingRequest& request, const GetFindingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetFindingAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::GetFindingAsyncHelper(const GetFindingRequest& request, const GetFindingResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetFinding(request), context); } GetGeneratedPolicyOutcome AccessAnalyzerClient::GetGeneratedPolicy(const GetGeneratedPolicyRequest& request) const { if (!request.JobIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetGeneratedPolicy", "Required field: JobId, is not set"); return GetGeneratedPolicyOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [JobId]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/policy/generation/"); uri.AddPathSegment(request.GetJobId()); return GetGeneratedPolicyOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } GetGeneratedPolicyOutcomeCallable AccessAnalyzerClient::GetGeneratedPolicyCallable(const GetGeneratedPolicyRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetGeneratedPolicyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetGeneratedPolicy(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::GetGeneratedPolicyAsync(const GetGeneratedPolicyRequest& request, const GetGeneratedPolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetGeneratedPolicyAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::GetGeneratedPolicyAsyncHelper(const GetGeneratedPolicyRequest& request, const GetGeneratedPolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetGeneratedPolicy(request), context); } ListAccessPreviewFindingsOutcome AccessAnalyzerClient::ListAccessPreviewFindings(const ListAccessPreviewFindingsRequest& request) const { if (!request.AccessPreviewIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListAccessPreviewFindings", "Required field: AccessPreviewId, is not set"); return ListAccessPreviewFindingsOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AccessPreviewId]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/access-preview/"); uri.AddPathSegment(request.GetAccessPreviewId()); return ListAccessPreviewFindingsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListAccessPreviewFindingsOutcomeCallable AccessAnalyzerClient::ListAccessPreviewFindingsCallable(const ListAccessPreviewFindingsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListAccessPreviewFindingsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListAccessPreviewFindings(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListAccessPreviewFindingsAsync(const ListAccessPreviewFindingsRequest& request, const ListAccessPreviewFindingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListAccessPreviewFindingsAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListAccessPreviewFindingsAsyncHelper(const ListAccessPreviewFindingsRequest& request, const ListAccessPreviewFindingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListAccessPreviewFindings(request), context); } ListAccessPreviewsOutcome AccessAnalyzerClient::ListAccessPreviews(const ListAccessPreviewsRequest& request) const { if (!request.AnalyzerArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListAccessPreviews", "Required field: AnalyzerArn, is not set"); return ListAccessPreviewsOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/access-preview"); return ListAccessPreviewsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListAccessPreviewsOutcomeCallable AccessAnalyzerClient::ListAccessPreviewsCallable(const ListAccessPreviewsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListAccessPreviewsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListAccessPreviews(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListAccessPreviewsAsync(const ListAccessPreviewsRequest& request, const ListAccessPreviewsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListAccessPreviewsAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListAccessPreviewsAsyncHelper(const ListAccessPreviewsRequest& request, const ListAccessPreviewsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListAccessPreviews(request), context); } ListAnalyzedResourcesOutcome AccessAnalyzerClient::ListAnalyzedResources(const ListAnalyzedResourcesRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzed-resource"); return ListAnalyzedResourcesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListAnalyzedResourcesOutcomeCallable AccessAnalyzerClient::ListAnalyzedResourcesCallable(const ListAnalyzedResourcesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListAnalyzedResourcesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListAnalyzedResources(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListAnalyzedResourcesAsync(const ListAnalyzedResourcesRequest& request, const ListAnalyzedResourcesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListAnalyzedResourcesAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListAnalyzedResourcesAsyncHelper(const ListAnalyzedResourcesRequest& request, const ListAnalyzedResourcesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListAnalyzedResources(request), context); } ListAnalyzersOutcome AccessAnalyzerClient::ListAnalyzers(const ListAnalyzersRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer"); return ListAnalyzersOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListAnalyzersOutcomeCallable AccessAnalyzerClient::ListAnalyzersCallable(const ListAnalyzersRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListAnalyzersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListAnalyzers(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListAnalyzersAsync(const ListAnalyzersRequest& request, const ListAnalyzersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListAnalyzersAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListAnalyzersAsyncHelper(const ListAnalyzersRequest& request, const ListAnalyzersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListAnalyzers(request), context); } ListArchiveRulesOutcome AccessAnalyzerClient::ListArchiveRules(const ListArchiveRulesRequest& request) const { if (!request.AnalyzerNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListArchiveRules", "Required field: AnalyzerName, is not set"); return ListArchiveRulesOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerName]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer/"); uri.AddPathSegment(request.GetAnalyzerName()); uri.AddPathSegments("/archive-rule"); return ListArchiveRulesOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListArchiveRulesOutcomeCallable AccessAnalyzerClient::ListArchiveRulesCallable(const ListArchiveRulesRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListArchiveRulesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListArchiveRules(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListArchiveRulesAsync(const ListArchiveRulesRequest& request, const ListArchiveRulesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListArchiveRulesAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListArchiveRulesAsyncHelper(const ListArchiveRulesRequest& request, const ListArchiveRulesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListArchiveRules(request), context); } ListFindingsOutcome AccessAnalyzerClient::ListFindings(const ListFindingsRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/finding"); return ListFindingsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ListFindingsOutcomeCallable AccessAnalyzerClient::ListFindingsCallable(const ListFindingsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListFindingsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListFindings(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListFindingsAsync(const ListFindingsRequest& request, const ListFindingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListFindingsAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListFindingsAsyncHelper(const ListFindingsRequest& request, const ListFindingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListFindings(request), context); } ListPolicyGenerationsOutcome AccessAnalyzerClient::ListPolicyGenerations(const ListPolicyGenerationsRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/policy/generation"); return ListPolicyGenerationsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListPolicyGenerationsOutcomeCallable AccessAnalyzerClient::ListPolicyGenerationsCallable(const ListPolicyGenerationsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListPolicyGenerationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListPolicyGenerations(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListPolicyGenerationsAsync(const ListPolicyGenerationsRequest& request, const ListPolicyGenerationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListPolicyGenerationsAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListPolicyGenerationsAsyncHelper(const ListPolicyGenerationsRequest& request, const ListPolicyGenerationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListPolicyGenerations(request), context); } ListTagsForResourceOutcome AccessAnalyzerClient::ListTagsForResource(const ListTagsForResourceRequest& request) const { if (!request.ResourceArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListTagsForResource", "Required field: ResourceArn, is not set"); return ListTagsForResourceOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ResourceArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/tags/"); uri.AddPathSegment(request.GetResourceArn()); return ListTagsForResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListTagsForResourceOutcomeCallable AccessAnalyzerClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTagsForResource(request), context); } StartPolicyGenerationOutcome AccessAnalyzerClient::StartPolicyGeneration(const StartPolicyGenerationRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/policy/generation"); return StartPolicyGenerationOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } StartPolicyGenerationOutcomeCallable AccessAnalyzerClient::StartPolicyGenerationCallable(const StartPolicyGenerationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< StartPolicyGenerationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StartPolicyGeneration(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::StartPolicyGenerationAsync(const StartPolicyGenerationRequest& request, const StartPolicyGenerationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->StartPolicyGenerationAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::StartPolicyGenerationAsyncHelper(const StartPolicyGenerationRequest& request, const StartPolicyGenerationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, StartPolicyGeneration(request), context); } StartResourceScanOutcome AccessAnalyzerClient::StartResourceScan(const StartResourceScanRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/resource/scan"); return StartResourceScanOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } StartResourceScanOutcomeCallable AccessAnalyzerClient::StartResourceScanCallable(const StartResourceScanRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< StartResourceScanOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StartResourceScan(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::StartResourceScanAsync(const StartResourceScanRequest& request, const StartResourceScanResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->StartResourceScanAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::StartResourceScanAsyncHelper(const StartResourceScanRequest& request, const StartResourceScanResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, StartResourceScan(request), context); } TagResourceOutcome AccessAnalyzerClient::TagResource(const TagResourceRequest& request) const { if (!request.ResourceArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("TagResource", "Required field: ResourceArn, is not set"); return TagResourceOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ResourceArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/tags/"); uri.AddPathSegment(request.GetResourceArn()); return TagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } TagResourceOutcomeCallable AccessAnalyzerClient::TagResourceCallable(const TagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, TagResource(request), context); } UntagResourceOutcome AccessAnalyzerClient::UntagResource(const UntagResourceRequest& request) const { if (!request.ResourceArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("UntagResource", "Required field: ResourceArn, is not set"); return UntagResourceOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ResourceArn]", false)); } if (!request.TagKeysHasBeenSet()) { AWS_LOGSTREAM_ERROR("UntagResource", "Required field: TagKeys, is not set"); return UntagResourceOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [TagKeys]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/tags/"); uri.AddPathSegment(request.GetResourceArn()); return UntagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER)); } UntagResourceOutcomeCallable AccessAnalyzerClient::UntagResourceCallable(const UntagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UntagResource(request), context); } UpdateArchiveRuleOutcome AccessAnalyzerClient::UpdateArchiveRule(const UpdateArchiveRuleRequest& request) const { if (!request.AnalyzerNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("UpdateArchiveRule", "Required field: AnalyzerName, is not set"); return UpdateArchiveRuleOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AnalyzerName]", false)); } if (!request.RuleNameHasBeenSet()) { AWS_LOGSTREAM_ERROR("UpdateArchiveRule", "Required field: RuleName, is not set"); return UpdateArchiveRuleOutcome(Aws::Client::AWSError<AccessAnalyzerErrors>(AccessAnalyzerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [RuleName]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/analyzer/"); uri.AddPathSegment(request.GetAnalyzerName()); uri.AddPathSegments("/archive-rule/"); uri.AddPathSegment(request.GetRuleName()); return UpdateArchiveRuleOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } UpdateArchiveRuleOutcomeCallable AccessAnalyzerClient::UpdateArchiveRuleCallable(const UpdateArchiveRuleRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateArchiveRuleOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateArchiveRule(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::UpdateArchiveRuleAsync(const UpdateArchiveRuleRequest& request, const UpdateArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateArchiveRuleAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::UpdateArchiveRuleAsyncHelper(const UpdateArchiveRuleRequest& request, const UpdateArchiveRuleResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateArchiveRule(request), context); } UpdateFindingsOutcome AccessAnalyzerClient::UpdateFindings(const UpdateFindingsRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/finding"); return UpdateFindingsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } UpdateFindingsOutcomeCallable AccessAnalyzerClient::UpdateFindingsCallable(const UpdateFindingsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UpdateFindingsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateFindings(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::UpdateFindingsAsync(const UpdateFindingsRequest& request, const UpdateFindingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UpdateFindingsAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::UpdateFindingsAsyncHelper(const UpdateFindingsRequest& request, const UpdateFindingsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UpdateFindings(request), context); } ValidatePolicyOutcome AccessAnalyzerClient::ValidatePolicy(const ValidatePolicyRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/policy/validation"); return ValidatePolicyOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } ValidatePolicyOutcomeCallable AccessAnalyzerClient::ValidatePolicyCallable(const ValidatePolicyRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ValidatePolicyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ValidatePolicy(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void AccessAnalyzerClient::ValidatePolicyAsync(const ValidatePolicyRequest& request, const ValidatePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ValidatePolicyAsyncHelper( request, handler, context ); } ); } void AccessAnalyzerClient::ValidatePolicyAsyncHelper(const ValidatePolicyRequest& request, const ValidatePolicyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ValidatePolicy(request), context); }
54.114669
254
0.794074
[ "model" ]
9a27f7568d77bcbd048cdce8c0e02d351ca41aca
1,164
cpp
C++
leetcode/1391. Check if There is a Valid Path in a Grid/s2.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/1391. Check if There is a Valid Path in a Grid/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/1391. Check if There is a Valid Path in a Grid/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/ // Author: github.com/lzl124631x // Time: O(MN) // Space: O(MN) // Ref: https://www.youtube.com/watch?v=SpMez87v0O8 class Solution { int M, N; vector<vector<int>> A; vector<vector<bool>> vis; int h(int x, int y) { return x * N + y; } int dx[4] = {1,-1,0,0}, dy[4] = {0,0,1,-1}, t[6] = {4|8, 1|2, 8|1, 4|1, 8|2, 4|2}; bool dfs(int i, int j) { if (i == M - 1 && j == N - 1) return 1; vis[i][j] = 1; for (int k = 0; k < 4; ++k) { if (t[A[i][j] - 1] >> k & 1 ^ 1) continue; // If A[i][j] can't extend to this direction, skip int x = i + dx[k], y = j + dy[k]; if (x < 0 || x >= M || y < 0 || y >= N || vis[x][y]) continue; int rk = k ^ 1; if (t[A[x][y] - 1] >> rk & 1 ^ 1) continue; // If A[x][y] can't extend back, skip if (dfs(x, y)) return 1; } return 0; } public: bool hasValidPath(vector<vector<int>>& A) { M = A.size(), N = A[0].size(); this->A = A; vis.assign(M, vector<bool>(N)); return dfs(0, 0); } };
36.375
105
0.458763
[ "vector" ]
9a284166dbfc99b7354906a6723f069b105ff30c
1,342
cpp
C++
NumberofStudents/main.cpp
khalidHsoliman/Problem-Solving
532a63833f982472a82c358a7c5827da73680a6f
[ "MIT" ]
5
2020-06-30T18:37:16.000Z
2020-07-22T09:23:58.000Z
NumberofStudents/main.cpp
khalidHsoliman/Problem-Solving
532a63833f982472a82c358a7c5827da73680a6f
[ "MIT" ]
null
null
null
NumberofStudents/main.cpp
khalidHsoliman/Problem-Solving
532a63833f982472a82c358a7c5827da73680a6f
[ "MIT" ]
null
null
null
// Problem Link : https://leetcode.com/contest/weekly-contest-189 #include <bits/stdc++.h> using namespace std; int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime); int main() { int t; cin >> t; while(t--) { vector<int> startTime; vector<int> endTime; int queryTime; int n; int element; cin >> n; for(int i = 0; i < n; i++) { cin >> element; startTime.push_back(element); } for(int i = 0; i < n; i++) { cin >> element; endTime.push_back(element); } cin >> queryTime; cout << startTime[0] << endl << endTime[0] << endl << queryTime; int num = busyStudent(startTime, endTime, queryTime); cout << num << endl; } return 0; } int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) { int num = 0; int n = startTime.size(); vector< pair <int,int> > vect; for(int i = 0; i < n; i++) { vect.push_back( make_pair(startTime[i],endTime[i])); } sort(vect.begin(), vect.end()); if((queryTime < vect[0].first)) return num; for(int i = 0; i < n; i++) { if((queryTime >= vect[i].first) && (queryTime <= vect[i].second)) num++; } return num; }
21.301587
86
0.520119
[ "vector" ]
9a28ae75e6330a027c1eeca8de8769a3c28ff0e8
963
cpp
C++
qtcreator-templates/wizards/simpleqt/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
54
2015-09-13T07:29:52.000Z
2022-03-16T07:43:50.000Z
qtcreator-templates/wizards/simpleqt/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
null
null
null
qtcreator-templates/wizards/simpleqt/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
31
2016-08-26T13:35:01.000Z
2022-03-13T16:43:12.000Z
@if "%GITHUBLINK%" == "true" // %GITHUBURL%/%ProjectName% @endif @if "%QT%" == "true" @if "%CONSOLE%" == "false" @if "%QT4SUPPORT%" == "false" #include <QtWidgets> @else #include <QtGui> #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) #include <QtWidgets> #endif @endif @else #include <QtCore> @endif @if "%OBJECT%" != "" class %OBJECT% : public QObject { Q_OBJECT public: @if "%CPP11INITS%" == "true" %OBJECT%(QObject * parent = 0) : QObject{parent} {} @else %OBJECT%(QObject * parent = 0) : QObject(parent) {} @endif }; @endif int main(int argc, char ** argv) { @if "%CONSOLE%" == "false" @if "%CPP11INITS%" == "true" QApplication app{argc, argv}; @else QApplication app(argc, argv); @endif @else @if "%CPP11INITS%" == "true" QCoreApplication app{argc, argv}; @else QCoreApplication app(argc, argv); @endif @endif return app.exec(); } @if "%OBJECT%" != "" #include "main.moc" @endif @else #include <iostream> int main() { } @endif
16.894737
55
0.622015
[ "object" ]
9a2a4bcad905f19d6c753137d5d8e72f40eaa915
4,954
cpp
C++
solutions/LeetCode/C++/1034.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/1034.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/1034.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 48 ms submission static const auto _ = []() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return nullptr; }(); class Solution { public: bool visited[50][50]; int connect[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; void DFS(vector <vector <int>>& grid, int r, int c, int target) { visited[r][c] = true; for(int i = 0; i < 4; i++) { int next_r = r + connect[i][0], next_c = c + connect[i][1]; if(next_r != grid.size() && next_r != -1 && next_c != grid[0].size() && next_c != -1 && grid[next_r][next_c] == target && !visited[next_r][next_c]) DFS(grid, next_r, next_c, target); } } vector<vector<int>> colorBorder(vector<vector<int>>& grid, int r0, int c0, int color) { memset(visited, 0, 50 * 50 * sizeof(bool)); DFS(grid, r0, c0, grid[r0][c0]); for(int r = 0; r < grid.size(); r++) { for(int c = 0; c < grid[0].size(); c++) { if(visited[r][c]) { if(r == 0 || r == grid.size() - 1 || c == 0 || c == grid[0].size() - 1) grid[r][c] = color; for(int i = 0; i < 4; i++) { int next_r = r + connect[i][0], next_c = c + connect[i][1]; if(next_r != grid.size() && next_r != -1 && next_c != grid[0].size() && next_c != -1 && !visited[next_r][next_c]) grid[r][c] = color; } } } } return grid; } }; __________________________________________________________________________________________________ sample 52 ms submission class Solution { public: vector<vector<int>> colorBorder(vector<vector<int>>& grid, int r0, int c0, int color) { dfs(grid,r0,c0,grid[r0][c0]); for(int i=0;i<grid.size();i++) for(int j=0;j<grid[0].size();j++) grid[i][j]=(grid[i][j]<0?color:grid[i][j]); return grid; } void dfs(vector<vector<int> > &g,int r,int c,int cl){ if(r>=g.size()||r<0||c>=g[0].size()||c<0||g[r][c]!=cl) return ; g[r][c]=-cl; dfs(g,r-1,c,cl); dfs(g,r+1,c,cl); dfs(g,r,c-1,cl); dfs(g,r,c+1,cl); if(r>0&&r<g.size()-1&&c>0&&c<g[0].size()-1&&abs(g[r-1][c])==cl&&abs(g[r][c-1])==cl&&abs(g[r+1][c])==cl&&abs(g[r][c+1])==cl) g[r][c]=cl; } }; __________________________________________________________________________________________________ sample 56 ms submission class Solution { public: bool isValid(int i,int j,int m,int n){ return i>=0 && j>=0 && j<m && i<n; } bool isCorner(int i,int j,int m,int n){ return i==0 || j==0 || j==m-1 || i==n-1; } bool isDiff(int r,int c, vector<vector<int>>& grid) { int dx[]={-1,0,0,1}; int dy[]={0,-1,1,0}; for(int i=0;i<4;++i){ int r1=r+dx[i]; int c1=c+dy[i]; if(isValid(r1,c1,grid[0].size(),grid.size()) && grid[r][c]!=grid[r1][c1]){ return true; } } return false; } void dfs(int r,int c,vector<vector<int>>& grid, vector<vector<bool>>& visited,int color){ int dx[]={-1,0,0,1}; int dy[]={0,-1,1,0}; for(int i=0;i<4;++i){ int r1=r+dx[i]; int c1=c+dy[i]; if(isValid(r1,c1,grid[0].size(),grid.size()) && !visited[r1][c1]){ if(grid[r1][c1]==color){ // cout<<r1<<" "<<c1<<endl; visited[r1][c1]=true; dfs(r1,c1,grid,visited,color); } } } } vector<vector<int>> colorBorder(vector<vector<int>>& grid, int r0, int c0, int color) { vector<vector<bool>> visited(grid.size(),vector<bool>(grid[0].size(),false)); vector<vector<bool>> change(grid.size(),vector<bool>(grid[0].size(),false)); int c=grid[r0][c0]; visited[r0][c0]=true; dfs(r0,c0,grid,visited,c); for(int i=0;i<grid.size();++i){ for(int j=0;j<grid[i].size();++j){ if(visited[i][j] && grid[i][j]==c && (isCorner(i,j,grid[0].size(),grid.size()) || isDiff(i,j,grid))){ change[i][j]=true; } } } for(int i=0;i<grid.size();++i){ for(int j=0;j<grid[i].size();++j){ if(change[i][j]){ grid[i][j]=color; } } } return grid; } };
35.385714
159
0.450343
[ "vector" ]
9a2eceb753972cf7c4c5c683fefd67afd8021feb
3,735
cpp
C++
cpp/src/longest_common_subsequence.cpp
CarnaViire/training
5a01a022167a88a9c90bc6db4e14347ad60ee9e4
[ "Unlicense" ]
3
2017-07-08T05:18:33.000Z
2021-06-11T13:49:37.000Z
cpp/src/longest_common_subsequence.cpp
kondratyev-nv/training
ed28507694bc2026867b67c26dc9c4a955b24fb4
[ "Unlicense" ]
44
2017-10-05T20:23:03.000Z
2022-02-10T19:50:21.000Z
cpp/src/longest_common_subsequence.cpp
CarnaViire/training
5a01a022167a88a9c90bc6db4e14347ad60ee9e4
[ "Unlicense" ]
4
2017-10-06T19:29:55.000Z
2022-01-04T23:25:18.000Z
/** * Compute the longest common subsequence of two or three sequences. */ #include "longest_common_subsequence.hpp" #include <unordered_map> using namespace std; int longest_common_subsequence(vector<int> const& x, vector<int> const& y, int xi, int yi, unordered_map<int, unordered_map<int, int>>& cache) { if (xi < 0 || yi < 0) { return 0; } if (cache.find(xi) != cache.end() && cache[xi].find(yi) != cache[xi].end()) { return cache[xi][yi]; } if (x[xi] == y[yi]) { cache[xi][yi] = 1 + longest_common_subsequence(x, y, xi - 1, yi - 1, cache); } else { cache[xi][yi] = max(longest_common_subsequence(x, y, xi - 1, yi, cache), longest_common_subsequence(x, y, xi, yi - 1, cache)); } return cache[xi][yi]; } int longest_common_subsequence(vector<int> const& x, vector<int> const& y, vector<int> const& z, int xi, int yi, int zi, unordered_map<int, unordered_map<int, unordered_map<int, int>>>& cache) { if (xi < 0 || yi < 0 || zi < 0) { return 0; } if (cache.find(xi) != cache.end() && cache[xi].find(yi) != cache[xi].end() && cache[xi][yi].find(zi) != cache[xi][yi].end()) { return cache[xi][yi][zi]; } if (x[xi] == y[yi] && y[yi] == z[zi]) { cache[xi][yi][zi] = 1 + longest_common_subsequence(x, y, z, xi - 1, yi - 1, zi - 1, cache); } else { cache[xi][yi][zi] = max(max(longest_common_subsequence(x, y, z, xi - 1, yi, zi, cache), longest_common_subsequence(x, y, z, xi, yi - 1, zi, cache)), longest_common_subsequence(x, y, z, xi, yi, zi - 1, cache)); } return cache[xi][yi][zi]; } vector<int> longest_common_subsequence(vector<int> const& x, vector<int> const& y) { unordered_map<int, unordered_map<int, int>> cache; int max_length = longest_common_subsequence(x, y, x.size() - 1, y.size() - 1, cache); vector<int> lcs(max_length); int xi = x.size() - 1, yi = y.size() - 1; int lcsi = cache[xi][yi]; while (xi >= 0 && yi >= 0) { if (x[xi] == y[yi]) { lcs[lcsi - 1] = x[xi]; xi--; yi--; lcsi--; } else if (cache[xi - 1][yi] > cache[xi][yi - 1]) { xi--; } else { yi--; } } return lcs; } vector<int> longest_common_subsequence(std::vector<int> const& x, std::vector<int> const& y, std::vector<int> const& z) { unordered_map<int, unordered_map<int, unordered_map<int, int>>> cache; int max_length = longest_common_subsequence(x, y, z, x.size() - 1, y.size() - 1, z.size() - 1, cache); vector<int> lcs(max_length); int xi = x.size() - 1, yi = y.size() - 1, zi = z.size() - 1; int lcsi = cache[xi][yi][zi]; while (xi >= 0 && yi >= 0 && zi >= 0) { if (x[xi] == y[yi] && y[yi] == z[zi]) { lcs[lcsi - 1] = x[xi]; xi--; yi--; zi--; lcsi--; } else if (cache[xi - 1][yi][zi] >= cache[xi][yi - 1][zi] && cache[xi - 1][yi][zi] >= cache[xi][yi][zi - 1]) { xi--; } else if (cache[xi][yi - 1][zi] >= cache[xi - 1][yi][zi] && cache[xi][yi - 1][zi] >= cache[xi][yi][zi - 1]) { yi--; } else { zi--; } } return lcs; }
36.262136
118
0.457831
[ "vector" ]