Beispiel #1
0
//-----------------------------------------------------------------------
void Animator::Impl::CrossFade(std::string const& stateName, Duration const& transitionDuration)
{
    if (nextAnimation) {
        return;
    }

    POMDOG_ASSERT(transitionDuration > Duration::zero());
    POMDOG_ASSERT(!std::isnan(transitionDuration.count()));

    auto iter = FindState(animationGraph->States, stateName);
    POMDOG_ASSERT(iter != std::end(animationGraph->States));

    if (iter == std::end(animationGraph->States)) {
        // Error: Cannot find the state
        return;
    }

    POMDOG_ASSERT(iter->Tree);
    nextAnimation = SkeletonAnimationState{};
    nextAnimation->Node = std::shared_ptr<AnimationNode>(animationGraph, iter->Tree.get());
    nextAnimation->Name = stateName;

    auto crossFade = std::make_shared<AnimationCrossFadeNode>(currentAnimation, *nextAnimation, transitionDuration, time);

    currentAnimation.Node = crossFade;
    time = AnimationTimeInterval::zero();
}
Beispiel #2
0
int main( int argc, char *argv[] )
{
	const Clock::time_point start = Clock::now();

	std::cout << "called with: " << std::endl << "\t";
	for ( int i = 0; i < argc; ++i ) {
		std::cout << argv[i] << " ";
	}
	std::cout << std::endl;

	po::options_description desc( "testRDIS options" );

	try {
		addOptions( desc );

		po::variables_map options;
		po::store( po::parse_command_line( argc, argv, desc ), options );

		po::notify( options );

		if ( options.count( "help" ) ) {
			std::cout << desc << std::endl;

		} else {
			std::vector<string> files;

			if ( options.count( "file" ) ) {
				// get the set of files to optimize
				const std::vector<string> tmpf =
						options["file"].as< std::vector<string> >();
				files.assign( tmpf.begin(), tmpf.end() );
			}

			if ( files.empty() ) {
				// run the pre-defined debug tests
				run_debug_test( options );

			} else {
				// optimize each input polynomial
				for ( string file : files ) {
					optimize_poly( file, options );
				}
			}
		}

	} catch ( const std::exception & e ) {
		std::cerr << "Exception occurred in main: \n\t" << e.what() << std::endl;
	} catch ( const std::string & s ) {
		std::cerr << "Exception occurred in main: \n\t" << s << std::endl;
	} catch ( const char * c ) {
		std::cerr << "Exception occurred in main: \n\t" << c << std::endl;
	}

	const Duration elapsed = Clock::now() - start;
	std::cout << "total elapsed time: " << elapsed.count() << " seconds" << std::endl;

	return 0;
}
Beispiel #3
0
int main( int argc, const char * const argv[] )
{
	BOOSTNS::random::mt19937 rng( 834725927 );
	const Clock::time_point start = Clock::now();

	std::cout << "called with: " << std::endl << "\t";
	for ( int i = 0; i < argc; ++i ) {
		std::cout << argv[i] << " ";
	}
	std::cout << std::endl;

	po::options_description desc( "Bundle Adjustment options" );

	try {
		addOptions( desc );

		po::variables_map options;
		po::store( po::parse_command_line( argc, argv, desc ), options );

//		po::parsed_options parsed =
//				po::command_line_parser( argc, argv ).options( desc ).allow_unregistered().run();
//		po::store( parsed, vm );
//		std::vector< string > to_pass_further =
//				po::collect_unrecognized( parsed.options, po::exclude_positional );

		po::notify( options );

		if ( options.count( "help" ) ) {
			std::cout << desc << std::endl;

		} else if ( !options.count( "file" ) ) {
			std::cout << "\nat least one input BA file must be specified\n" << std::endl;
			std::cout << desc << std::endl;

		} else {
			// get the set of files to optimize
			const std::vector< string > files =
					options[ "file" ].as< std::vector< string > >();

			// optimize each one
			for ( string file : files ) {
				optimize_BA( rng, options, file );
			}
		}

	} catch ( po::error & e) {
		  std::cerr << "\nCommand line error: " << e.what() << std::endl << std::endl;
		  std::cerr << desc << std::endl;
	} catch ( std::exception & e ) {
		std::cerr << "\nException occurred in main (B.A. opt): \n\t" << e.what()
				<< ", application will now exit. Goodbye!" << std::endl;
	}

	const Duration elapsed = Clock::now() - start;
	std::cout << "total elapsed time: " << elapsed.count() << " seconds" << std::endl;
}
RttEstimator::RttEstimator(uint16_t maxMultiplier, Duration minRto, double gain)
    : m_maxMultiplier(maxMultiplier)
    , m_minRto(minRto.count())
    , m_rtt(RttEstimator::getInitialRtt().count())
    , m_gain(gain)
    , m_variance(0)
    , m_multiplier(1)
    , m_nSamples(0)
{
}
void
RttEstimator::addMeasurement(Duration measure)
{
    double m = static_cast<double>(measure.count());
    if (m_nSamples > 0) {
        double err = m - m_rtt;
        double gErr = err * m_gain;
        m_rtt += gErr;
        double difference = std::abs(err) - m_variance;
        m_variance += difference * m_gain;
    } else {
        m_rtt = m;
        m_variance = m;
    }
    ++m_nSamples;
    m_multiplier = 1;
}
Beispiel #6
0
void ScenePanel::UpdateAnimation(const Duration& frameDuration)
{
    timer = std::max(timer - frameDuration, Duration::zero());

    if (timer <= Duration::zero()) {
        scrollAcceleration = 1.0f;
        return;
    }

    const auto duration = std::min<double>(frameDuration.count(), 1.0);
    const auto scroll = duration
        * normalizedScrollDirection
        * scrollAcceleration
        * (timer.count() / ZoomAnimationInterval.count());

    POMDOG_ASSERT(cameraZoom > 0);
    cameraZoom = MathHelper::Saturate(cameraZoom + (cameraZoom * scroll * 1000));
}
Beispiel #7
0
int main( int argc, const char * const argv[] )
{
	BOOSTNS::random::mt19937 rng( 834725927 );
	const Clock::time_point start = Clock::now();

	std::cout << "called with: " << std::endl << "\t";
	for ( int i = 0; i < argc; ++i ) {
		std::cout << argv[i] << " ";
	}
	std::cout << std::endl;

	po::options_description desc( "Sinusoid optimization options" );

	try {
		addOptions( desc );

		po::variables_map options;
		po::store( po::parse_command_line( argc, argv, desc ), options );

		po::notify( options );

		if ( options.count( "help" ) ) {
			std::cout << desc << std::endl;
		} else {
			optimize_sinusoid( rng, options );
		}

	} catch ( po::error & e) {
		  std::cerr << "\nCommand line error: " << e.what() << std::endl << std::endl;
		  std::cerr << desc << std::endl;
	} catch ( std::exception & e ) {
		std::cerr << "\nException occurred in main (p.f. opt): \n\t" << e.what()
				<< ", application will now exit. Goodbye!" << std::endl;
//	} catch ( utility::excn::EXCN_Base & e ) {
//		std::cerr << "\nCaught rosetta exception: " << e.msg() <<
//				", application will now exit. Goodbye!" << std::endl;
	}

	const Duration elapsed = Clock::now() - start;
	std::cout << "total elapsed time: " << elapsed.count() << " seconds" << std::endl;
}
Beispiel #8
0
void optimize_sinusoid( BOOSTNS::random::mt19937 & rng,
						const po::variables_map & options ) {

	Numeric regionwidth = 1.0;
	Numeric eps = 0.1, lipsch = 20;
	RDISOptimizer * popt = NULL;

	const string domain =
			BOOSTNS::str( BOOSTNS::format( "%1%:%2%" ) %
					( -regionwidth/2.0 ) % ( regionwidth/2.0 ) );
//					( regionwidth / 4.0 ) % ( 5.0*regionwidth/4.0 ) );

	eps = options.count( "epsilon" ) ? options[ "epsilon" ].as< Numeric >() : eps;
	lipsch = options.count( "lipschitz" ) ? options[ "lipschitz" ].as< Numeric >() : lipsch;

	if ( options.count( "timeAsSeed" ) && options[ "timeAsSeed" ].as< bool >() ) {
		rng.seed( std::time(NULL) + getpid() );
		if ( options[ "sampleOffset"].as< size_t >() > 0 ) {
			std::cout << "WARNING: sampleOffset and timeAsSeed should not both be set" << std::endl;
		}
	}

	const bool isBCD = ( options.count( "opttype" ) &&
			options[ "opttype" ].as< string >() == "bcd" );

	size_t h = options[ "sinHeight" ].as< size_t >();
	size_t bf = options[ "sinBF" ].as< size_t >();
	size_t arity = options[ "sinArity" ].as< size_t >();
	bool oddArity = options[ "sinOddArity" ].as< bool >();

	OptimizableFunctionSP funcsp =
			OptimizableFunctionGenerator::makeHighDimSinusoid( h, bf, arity, oddArity );

	OptimizableFunction & fsinusoid = *funcsp;

	std::cout << fsinusoid << std::endl;

	CGDSubspaceOptimizer ssopt( fsinusoid );
	ssopt.setParameters( options );

	// create the optimizer
	popt = new RDISOptimizer( fsinusoid, ssopt, options );

	RDISOptimizer & opt = *popt;
	setSignalHandler( &opt );

	opt.setApproxFactors( options[ "approxfactors" ].as< bool >() );
	opt.setUseCache( false );
//	opt.setUseExactCaching( false );

	const Numeric MaxVal = std::numeric_limits< Numeric >::max();

	size_t sampleOffset = options[ "sampleOffset" ].as< size_t >();
	size_t nsamples = options[ "nsamples" ].as< size_t >() + sampleOffset;

	const NumericInterval dom = fsinusoid.getVariables()[0]->getDomain().interval();

	BOOSTNS::random::uniform_real_distribution<> unif( dom.lower(), dom.upper() );
	std::vector< State > initialStates( nsamples );

	// create all the random initial states up front (so they're consistent
	// across runs if the seed doesn't change)
	for ( size_t i = 0; i < nsamples; ++i ) {
		for ( VariableID vid = 0; vid < fsinusoid.getNumVars(); ++vid ) {
			initialStates[i].push_back( unif( rng ) );
		}
	}

	const Clock::time_point start = Clock::now();
	Clock::time_point timeout = Clock::time_point::max();

	if ( options.count( "timeout" ) ) {
		size_t ms = 1000.0 * options[ "timeout" ].as< Numeric >();
		timeout = Clock::now() + bc::milliseconds( ms );
	}

	Numeric bestfopt = NumericMAX;
	State bestx;

	size_t i = sampleOffset;
	for ( ; i < nsamples; ) {

		Numeric finit = MaxVal;
		const State & xinit = initialStates[i];

		std::cout << "[" << i << "] optimization starting -- bounds: " <<
				fsinusoid.computeBounds() << std::endl;
		std::cout << "eps: " << eps << ", lipschitz: " << lipsch <<
				", step: " << eps / lipsch <<
				", finit: " << finit << std::endl << "xinit: " << xinit << std::endl;

		std::cout << "initial eval: " << eval( fsinusoid, xinit ) << std::endl;

		++i;

		if ( options.count( "useDA" ) ) {
			throw "deterministic annealing not yet supported";
		} else if ( options.count( "useCP" ) ) {
			throw "cutting plane not yet supported";
		}

		State xopt;
		Numeric result = MaxVal;
		bool timedOut = false;

		if ( !isBCD ) {
			result = opt.optimize( &xinit, finit, timeout, true, start );
			xopt = opt.getOptState();
			opt.printStats();
			timedOut = ( opt.wasStopped() || opt.timedOut() );
		} else {
			timedOut = doBCDOpt( fsinusoid, ssopt, options, xinit, timeout, start,
					xopt, result );
		}

		const Duration elapsed = Clock::now() - start;

		assert( !xopt.empty() );
		std::cout << "sinusoid opt. result: " << result << std::endl <<
					"\tat " << xopt << std::endl;
		Numeric actual = eval( fsinusoid, xopt );
		std::cout << "actual eval: " << actual << " after " << elapsed.count()
				<< " seconds " << std::endl;

		if ( actual < bestfopt ) {
			bestfopt = actual;
			bestx = xopt;
		}

		if ( timedOut ) {
			std::cout << "timeout detected..." << std::endl;
			break; break;
		}
	}
}
Beispiel #9
0
void ParticleSystem::Simulate(Entity & entity, Duration const& duration)
{
    if (state != ParticleSystemState::Playing) {
        return;
    }

    Transform emitterTransform;
    if (auto transform = entity.GetComponent<Transform>()) {
        emitterTransform = *transform;
    }

    erapsedTime += duration;

    if (emitter.Looping && erapsedTime > clip->Duration)
    {
        erapsedTime = Duration::zero();
    }

    if (emitter.Looping || erapsedTime <= clip->Duration)
    {
        emissionTimer += duration;

        POMDOG_ASSERT(emitter.EmissionRate > 0);
        auto emissionInterval = std::max(std::numeric_limits<Duration>::epsilon(),
            Duration(1) / emitter.EmissionRate);

        POMDOG_ASSERT(emissionInterval.count() > 0);

        POMDOG_ASSERT(clip->Duration.count() > 0);
        float normalizedTime = erapsedTime / clip->Duration;

        while ((particles.size() < emitter.MaxParticles) && (emissionTimer >= emissionInterval))
        {
            emissionTimer -= emissionInterval;

            auto particle = CreateParticle(random, *clip, emitter, normalizedTime, emitterTransform);
            particles.push_back(std::move(particle));
        }
    }
    {
        for (auto & particle: particles)
        {
            auto oldTimeToLive = particle.TimeToLive;
            particle.TimeToLive -= duration.count();
            if (particle.TimeToLive <= 0.0f) {
                continue;
            }

            auto deltaTime = oldTimeToLive - particle.TimeToLive;

            Vector2 particleAcceleration {1, 1};
            Vector2 gravityAcceleration {0, -emitter.GravityModifier};
            particle.Velocity += (particleAcceleration * gravityAcceleration * deltaTime);
            particle.Position += (particle.Velocity * deltaTime);

            float normalizedTime = 1.0f - particle.TimeToLive / emitter.StartLifetime;

            POMDOG_ASSERT(clip->ColorOverLifetime);
            particle.Color = Color::Multiply(particle.StartColor,
                clip->ColorOverLifetime->Compute(normalizedTime, particle.ColorVariance));

            // Rotation
            POMDOG_ASSERT(clip->RotationOverLifetime);
            particle.Rotation = particle.Rotation
                + deltaTime * clip->RotationOverLifetime->Compute(normalizedTime, particle.RotationVariance);

            // Size
            POMDOG_ASSERT(clip->SizeOverLifetime);
            particle.Size = particle.StartSize * clip->SizeOverLifetime->Compute(normalizedTime, particle.SizeVariance);
        }

        particles.erase(std::remove_if(std::begin(particles), std::end(particles),
            [](Particle const& p){ return p.TimeToLive <= 0; }), std::end(particles));
    }
}
bool SocketCommunicationDevice::awaitConnection(Duration timeout) {
    if (isServer) {
        return server.waitForNewConnection(timeout.count());
    }
    return socket->waitForConnected(timeout.count());
}
Beispiel #11
0
float StopWatch::ToSeconds(Duration val)
{
	return val.count()*0.000000001f;
}
Beispiel #12
0
void optimize_BA( BOOSTNS::random::mt19937 & rng,
		const po::variables_map & options, const string & bafile ) {

	// get optimization type from command line
	const string opttype = options[ "opttype" ].as< string >();

	const bool isRDIS = ( opttype == "rdis" );
	const bool isBCD = ( opttype == "bcd" );
//	const bool isDisc = ( opttype == "discrete" );
//	const bool isGrid = ( opttype == "grid" );

	Numeric eps = 1.0, lipsch = 20;
	RDISOptimizer * popt = NULL;

	assert( isRDIS || isBCD /*|| isDisc || isGrid*/ );

	eps = options.count( "epsilon" ) ? options[ "epsilon" ].as< Numeric >() : eps;
	lipsch = options.count( "lipschitz" ) ? options[ "lipschitz" ].as< Numeric >() : lipsch;

	if ( options.count( "timeAsSeed" ) && options[ "timeAsSeed" ].as< bool >() ) {
		rng.seed( std::time(NULL) + getpid() );
		if ( options[ "sampleOffset"].as< size_t >() > 0 ) {
			std::cout << "WARNING: sampleOffset and timeAsSeed should not both be set" << std::endl;
		}
	}

	VariableCount ncams = options.count( "ncams" ) ?
						  options["ncams"].as< size_t >() : 0;
	VariableCount npts = options.count( "npts" ) ?
						 options["npts"].as< size_t >() : 0;

	// load and initialize the BA problem we'll optimize
	BundleAdjustmentFunction bafunc;
	if ( !bafunc.load( bafile, ncams, npts ) ) {
		std::cout << "loading file " << bafile << " failed -- exiting" << std::endl;
		return;
	}

	SubspaceOptimizer * pssopt;
	if ( options["useCGD"].as< bool >() ) {
		pssopt = new CGDSubspaceOptimizer( bafunc );
	} else {
		pssopt = new LMSubspaceOptimizer( bafunc );
	}
	SubspaceOptimizer & ssopt = *pssopt;
////	CGDSubspaceOptimizer ssopt( bafunc );
//	LMSubspaceOptimizer ssopt( bafunc );
	ssopt.setParameters( options );

	// create the optimizer and initialize it properly
//	popt = ( isRDIS ?
//			new OptimizerISGD( bafunc, ssopt, options ) :
//			new OptimizerDG( bafunc, options ) );
	popt = new RDISOptimizer( bafunc, ssopt, options );

	RDISOptimizer & opt = *popt;
	setSignalHandler( &opt );

//	opt.setOptType( 3 );
//	opt.setUseFiniteDiffs( true );
//	opt.setUseLinearLB( false );

	opt.setApproxFactors( options[ "approxfactors" ].as< bool >() );
	opt.setUseCache( !isRDIS );
//	opt.setUseExactCaching( isDisc );

	const Numeric MaxVal = std::numeric_limits< Numeric >::max();

	size_t sampleOffset = options[ "sampleOffset" ].as< size_t >();
	size_t nsamples = options[ "nsamples" ].as< size_t >() + sampleOffset;

	std::vector< State > initialStates( nsamples );

	if ( options.count( "randinit" ) && !options["randinit"].as< bool >() ) {
		sampleOffset = 0;
		nsamples = 1;
		initialStates.clear();
		initialStates.push_back( bafunc.getInitialState() );

	} else {
		// create all the random initial states up front (so they're consistent
		// across runs if the seed doesn't change)
		for ( size_t i = 0; i < nsamples; ++i ) {
			for ( VariableID vid = 0; vid < bafunc.getNumVars(); ++vid ) {
				NumericInterval si =
						bafunc.getVariables()[vid]->getDomain().getSamplingInterval();
				BOOSTNS::random::uniform_real_distribution<> unif(
						si.lower(), si.upper() );
				initialStates[i].push_back( unif( rng ) );
			}

//			if ( i >= sampleOffset ) {
//				std::cout << "state " << i << ": " << initialStates[i] << std::endl;
//			}
		}
	}

	const Clock::time_point start = Clock::now();
	Clock::time_point timeout = Clock::time_point::max();

	if ( options.count( "timeout" ) ) {
		size_t ms = 1000.0 * options[ "timeout" ].as< Numeric >();
		timeout = Clock::now() + bc::milliseconds( ms );
	}

	Numeric bestfopt = NumericMAX;
	State bestx;

	size_t i = sampleOffset;
	for ( ; i < nsamples; ) {

		Numeric finit = MaxVal;
		const State & xinit = initialStates[i];

		std::cout << "[" << i << "] optimization starting -- bounds: " <<
				bafunc.computeBounds() << std::endl;
		std::cout << "eps: " << eps << ", lipschitz: " << lipsch <<
				", step: " << eps / lipsch <<
				", finit: " << finit << std::endl << "xinit: " << xinit << std::endl;

		std::cout << "initial eval: " << bafunc.eval( xinit ) << std::endl;

		if ( options.count( "useDA" ) ) {
			throw "deterministic annealing not yet supported";
		} else if ( options.count( "useCP" ) ) {
			throw "cutting plane not yet supported";
		}

		++i;

		State xopt;
		Numeric result = MaxVal;
		bool timedOut = false;

		if ( !isBCD ) {
			if ( options["ignoreCamVars"].as< bool >() ) {
				for ( Variable * v : bafunc.getVariables() ) {
					if ( bafunc.getVarType( v->getID() ) == BundleAdjust::CAM_FOCAL ||
							bafunc.getVarType( v->getID() ) == BundleAdjust::CAM_RDL_K1 ||
							bafunc.getVarType( v->getID() ) == BundleAdjust::CAM_RDL_K2 ) {
						bafunc.getVariables()[i]->assign( bafunc.getInitialState()[i] );
					}
				}
			}
			result = opt.optimize( &xinit, finit, timeout, true, start );
			xopt = opt.getOptState();
			opt.printStats();
			timedOut = ( opt.wasStopped() || opt.timedOut() );
		} else {
			if ( options["ignoreCamVars"].as< bool >() ) {
				std::cout << "IGNORECAMVARS OPTION NOT SUPPORTED FOR BCD" << std::endl;
			}
			timedOut = doBCDOpt( bafunc, ssopt, options, xinit, timeout, start,
					xopt, result );
		}

		assert( !xopt.empty() );

		const Duration elapsed = Clock::now() - start;

		std::cout << "bundle adjustment opt. result: " << result << std::endl
				<< "\tat " << xopt << std::endl;
		Numeric actual = bafunc.eval( xopt );
		std::cout << "actual eval: " << actual << " after "
				<< elapsed.count() << " seconds" << std::endl;

		if ( actual < bestfopt ) {
			bestfopt = actual;
			bestx = xopt;
		}

		if ( timedOut ) {
			std::cout << "timeout detected..." << std::endl;
			break;
		}
	}

	const Duration elapsed = Clock::now() - start;
	std::cout << "----------------" << std::endl;
	std::cout << "best: " << bestfopt << " in " << ( i - sampleOffset ) <<
			" samples after " << elapsed.count() << " seconds at state " <<
			std::endl << bestx << std::endl;
}
Beispiel #13
0
Numeric LMSubspaceOptimizer::optimize( const VariablePtrVec & vars,
		const FactorPtrVec & factors, NumericVec & xval,
		Numeric & deltaFval, const bool printdbg ) {

//	// box-constrained minimization
//	extern int dlevmar_bc_der(
//	   void (*func)(double *p, double *hx, int m, int n, void *adata),
//	   void (*jacf)(double *p, double *j, int m, int n, void *adata),
//	   double *p, double *x, int m, int n, double *lb, double *ub, double *dscl,
//	   int itmax, double *opts, double *info, double *work, double *covar,
//	   void *adata);

//#define USE_LEVMAR
#ifdef USE_LEVMAR
	const Clock::time_point starttime = Clock::now();

//	initstate.assign( xval.begin(), xval.end() );
	LMSSOpt::AuxData aux( vars, factors, f, pgtemp );

	const int m = vars.size();
	const int n = std::max( factors.size(), (size_t) m );

	initeval.resize( n );
	finaleval.resize( n );

//	double lb[ m ];
//	double ub[ m ];
//
//	for ( size_t i = 0; i < vars.size(); ++i ) {
//		NumericInterval dom = vars[i]->getDomain().interval();
//		lb[i] = ( dom.lower() <= -DBL_MAX ? DBL_MAX : dom.lower() );
//		ub[i] = ( dom.upper() >= DBL_MAX ? DBL_MAX : dom.upper() );
//	}

	double * dscl = NULL;

	double opts[ LM_OPTS_SZ ];
//	double * opts = NULL;

	double info[ LM_INFO_SZ ];
	double * work = new double[ LM_BC_DER_WORKSZ( m, n ) ];

	double * covar = NULL;

	if ( printdbg ) {
		std::cout << "LM SS opt m=" << m << ", n=" << n << " (" << vars.size()
				<< " vars, " << factors.size() << " factors)" << std::endl;
	}

//	LMSSOpt::evalFunc( xval.data(), initeval.data(), m, n, &aux );
//	const Numeric ival = NumericVecOps::dot( initeval, initeval ) / 2.0;
	Numeric ferr = 0.0;
	const Numeric ival = f.evalFactors( factors, ferr );

	opts[0] = 1e-3; 	// initial \mu scale factor
	opts[1] = 1e-15;	// stopping thresh. for ||J^T e||_inf
	opts[2] = 1e-15;	// stopping thresh. for ||Dp||_2
	opts[3] = ftol; 	// stopping thresh. for ||e||_2

//	int niters = dlevmar_bc_der(
//			&LMSSOpt::evalFunc,
//			&LMSSOpt::evalJacf,
//			xval.data(), NULL, xval.size(), n, lb, ub,
//			NULL, maxiters, opts, info, work, covar, &aux );

	int niters = dlevmar_der(
			&LMSSOpt::evalFunc,
			&LMSSOpt::evalJacf,
			xval.data(), NULL, xval.size(), n,
			maxiters, opts, info, work, covar, &aux );

	// sanitize values to be within the domain of this variable (note that they
	// are sanitized in quickAssign(), so just copy them out after)
	LMSSOpt::quickAssignVals( aux, m, xval.data() );
	for ( size_t i = 0; i < vars.size(); ++i ) {
		xval[i] = vars[i]->eval();
	}

//	LMSSOpt::evalFunc( xval.data(), finaleval.data(), m, n, &aux );
//	const Numeric fval = NumericVecOps::dot( finaleval, finaleval ) / 2.0;

	Numeric fval = f.evalFactors( factors, ferr );

//	Numeric asdf = 0;
//	for ( size_t i = 0; i < factors.size(); ++i ) {
//		asdf += factors[i]->evalNoCache();
//		std::cout << i << ": f " << factors[i]->getID() << " diff " <<
//				( finaleval[i]*finaleval[i]/2.0 - factors[i]->eval() ) << " ("
//				<< factors[i]->eval() << ")" << std::endl;
//	}
//	std::cout << "asdf: " << asdf << std::endl;
//
//	std::cout << "f.eval " << f.eval() << std::endl;
//	Numeric ferr = 0.0;
//	std::cout << "f fact eval " << f.evalFactors( factors, ferr ) << std::endl;
//
//	std::cout << "xval: " << xval << std::endl;

//	double err[n];
//	dlevmar_chkjac( &LMSSOpt::evalFunc, &LMSSOpt::evalJacf, xval.data(), m, n,
//			&aux, err );
//
//	for ( size_t i = 0; i < m; ++i ) {
//		if ( err[i] < 0.5 ) {
//			std::cout << i << ": var " << vars[i]->getID() << " has jac err "
//					<< err[i] << std::endl;
//		}
//	}

	delete work;

	deltaFval = ( fval - ival);
	const Duration dur = ( Clock::now() - starttime );

	if ( printdbg ) {
		std::cout << "LM SS opt returned " << fval << " (init " << ival
				<< ", diff " << deltaFval << ") after " << niters <<
				" iterations in " << dur.count() << " seconds" << std::endl;

		std::cout << "LM SS opt info -- termination: " << info[6] <<
				", #fevals: " << info[7] << ", #jevals: " << info[8] <<
				", #linsolves" << info[9] << std::endl;
	}

//	if ( deltaFval > 0 ) {
//		fval = ival;
//		xval.assign( initstate.begin(), initstate.end() );
//		deltaFval = 0;
//		std::cout << "LM SS made no progress -- returning initial state" << std::endl;
//	}

	return fval;

#else // USE_LEVMAR

	std::cout << "ERROR: Cannot use LM subspace optimizer without levmar.h." <<
			" Rebuild with -DUSE_LEVMAR and link to liblevmar." << std::endl;

	std::exit( -1 );

	return 0;
#endif // USE_LEVMAR
}
Beispiel #14
0
Numeric EMSubspaceOptimizer::optimize( const VariablePtrVec & vars,
		const FactorPtrVec & facs, NumericVec & xval, Numeric & deltaFval,
		const bool printdbg ) {

	bool result = true;
	Numeric curval( 0 ), prevval( std::numeric_limits< Numeric >::max() );

	const Clock::time_point starttime( Clock::now() );

	quickAssignVals( vars, xval, sanitizeVals );

	Numeric ferr = 0.0;
	Numeric initval = f.evalFactors( facs, ferr );
	prevval = curval = initval;

	VariableCount iter = 0;

	for ( ; ; ) {
//		if ( printdbg && iter == 0 ) {
//			std::clog << "iteration " << iter << ": log likelihood: " <<
//					curval << std::endl;
//		}

		// take an EM step (changes the var assignments)
		result = f.EMStep( vars, facs, sanitizeVals, useFactorCaching );

		// compute the new log likelihood
		prevval = curval;
		curval = f.evalFactors( facs, ferr, useFactorCaching );

		if ( !result ) {
			std::cout << "EM subspace opt. failed on iteration " << iter <<
					", log likelihood: " << curval << std::endl;
			break;
		}

		// if we've converged, get the final state and unassign all vars
		if ( ++iter >= (VariableCount) maxiters && maxiters > 0 ) break;
//		if ( !approxleq( curval, prevval, ftol ) ) break;
		if ( ( prevval - curval ) < ftol ) break;

//		break;
	}

	for ( size_t i = 0; i < vars.size(); ++i ) {
		xval[i] = vars[i]->eval();
	}

//	std::cout << "prevval " << prevval << ", curval " << curval << ", diff " << curval-prevval << std::endl;

	deltaFval = curval - initval;
	Duration runtime = ( Clock::now() - starttime );

	if ( printdbg ) {
	std::cout << "EM ss opt. (iters "<< iter << "): " << curval <<
			" (init: " << initval << ", diff: " << deltaFval << ") in " <<
			runtime.count() << " seconds" << std::endl;
	}

	return curval;
}
Beispiel #15
0
		/// <summary>
		/// 指定したミリ秒だけ処理を停止します。
		/// </summary>
		/// <param name="duration">
		/// 処理を停止する時間
		/// </param>
		/// <returns>
		/// なし
		/// </returns>
		inline void Sleep(const Duration& duration)
		{
			Sleep(static_cast<int32>(duration.count() * 1000));
		}