ClassifierEngine::ResultVector ClassifierEngine::runOnBatch(const Bundle& input)
{
    auto network = getAggregateNetwork();

    network->setIsTraining(false);

    auto bundle = network->runInputs(input);

    auto& result = bundle["outputActivations"].get<matrix::MatrixVector>().front();

    auto labels = convertActivationsToLabels(std::move(result), *getModel());

    ClassifierEngine::ResultVector results;

    if(_shouldUseLabeledData)
    {
        bundle = network->getCost(input);

        auto cost = bundle["cost"].get<double>();

        results = compareWithReference(cost * labels.size(), getIteration(), labels,
            getReferenceLabels(bundle, *getModel()));
    }
    else
    {
        results = recordLabels(labels);
    }

    restoreAggregateNetwork();

    return results;
}
Example #2
0
static void getProgressPerSecond(int *iterationsPerSec, double *timePerSec)
{
	static int ips = 0;
	static double tps = 0;
	static long prevIterations = 0;
	static double prevTime = 0;
	static long tock = 0;

	long tick = SDL_GetTicks(); /* milliseconds */

	if (tick - tock > 1000) {
		int dt = tick - tock;
		tock = tick;

		long currIterations = getIteration();
		long deltaIterations = currIterations - prevIterations;
		prevIterations = currIterations;
		ips = deltaIterations * 1000 / dt;

		double currTime = getTime();
		double deltaTime = currTime - prevTime;
		prevTime = currTime;
		tps = deltaTime * 1000 / dt;
	}
	*iterationsPerSec = ips;
	*timePerSec = tps;
}
Example #3
0
void rSdpaLib::solve()
{
  if (CheckMatrix) {
    rTimeStart(FILE_CHECK_START1);
      int i=0,j=0,k=0,l=0;
    // this method needs long time
    checkData(k,l,i,j);
    if (i>0 || j>0) {
      rError("checkData stops");
      cout << "constraint " << k <<":"
	   << "block " << l <<":"
	   << "row " << i <<":"
	   << "column " << j << endl;
    }
    rTimeEnd(FILE_CHECK_END1);
    com.FileCheck += rTimeCal(FILE_CHECK_START1,
			      FILE_CHECK_END1);
  }
#if 1
  rTimeStart(FILE_CHANGE_START1);
  // if possible, change C and A to Dense type matrices.
  C.changeToDense();
  for (int k=0; k<m; ++k) {
    A[k].changeToDense();
  }
  rTimeEnd(FILE_CHANGE_END1);
  com.FileChange += rTimeCal(FILE_CHANGE_START1,
			     FILE_CHANGE_END1);
#endif

  if (InitialPoint) {
    initPt.initializeResetup(m,nBlock,blockStruct,com);
    currentPt.copyFrom(initPt);
    // rMessage("initialize? ");
  } else {
    currentPt.initialize(m,nBlock,blockStruct,pARAM.lambdaStar,com);
  }
  // rMessage("initPt = ");
  // initPt.display();
  // rMessage("currentPt = ");
  // currentPt.display();
  initRes.initialize(m, nBlock, blockStruct, b, C, A, currentPt);
  currentRes.copyFrom(initRes);
  // rMessage("initial currentRes = ");
  // currentRes.display();

  newton.initialize(m, nBlock, blockStruct);
  newton.computeFormula(m,A,0.0,KAPPA);

  alpha.initialize(1.0,1.0,nBlock, blockStruct);
  beta.initialize(pARAM.betaStar);
  reduction.initialize(rSwitch::ON);
  mu.initialize(pARAM.lambdaStar);
  lanczos.initialize(nBlock,blockStruct);

  if (InitialPoint) {
    mu.initialize(nDim,initPt);
  }

  theta.initialize(pARAM,initRes);
  solveInfo.initialize(nDim, b, C, A, initPt, mu.initial,
		       pARAM.omegaStar);
  phase.initialize(initRes, solveInfo, pARAM, nDim);

  rIO::printHeader(OutputFile,DisplayInformation);
  
  int pIteration = 0;

  // -----------------------------------------------------
  // Here is MAINLOOP
  // -----------------------------------------------------

  rTimeStart(MAIN_LOOP_START1);

  // explisit maxIteration
  // pARAM.maxIteration = 100;
  while (phase.updateCheck(currentRes, solveInfo, pARAM)
	 && pIteration < pARAM.maxIteration) {
    // rMessage(" turn hajimari " << pIteration );

    #if 0
    if (alpha.primal<1.0e-5 && alpha.dual<1.0e-5) {
      break;
    }
    #endif

    // Mehrotra's Predictor
    rTimeStart(MEHROTRA_PREDICTOR_START1);

    // calculate variables of Mehrotra
    reduction.MehrotraPredictor(phase);
    beta.MehrotraPredictor(phase, reduction, pARAM);
    // rMessage("reduction = ");
    // reduction.display();
    // rMessage("phase = ");
    // phase.display();
    // rMessage("beta.predictor.value = " << beta.value);
    
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage(" mu = " << mu.current);

    bool isSuccessCholesky;
    isSuccessCholesky = newton.Mehrotra(rNewton::PREDICTOR,
					m, A, C, mu,
					beta, reduction,
					phase, currentPt,
					currentRes, com);
    if (isSuccessCholesky == false) {
      break;
    }
      
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("newton Dy predictor = ");
    // newton.DyVec.display();
    // newton.bMat.display();
    rTimeEnd(MEHROTRA_PREDICTOR_END1);
    com.Predictor += rTimeCal(MEHROTRA_PREDICTOR_START1,
			      MEHROTRA_PREDICTOR_END1);
    
    rTimeStart(STEP_PRE_START1);
    alpha.MehrotraPredictor(b,C,A, currentPt, phase,
			    newton, lanczos, com);
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage("alpha predictor = ");
    // alpha.display();
    // phase.display();
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("currentPt = ");
    // currentPt.display();
    rTimeStart(STEP_PRE_END1);
    com.StepPredictor += rTimeCal(STEP_PRE_START1,STEP_PRE_END1);

    // rMessage("alphaStar = " << pARAM.alphaStar);
    // Mehrotra's Corrector
    // rMessage(" Corrector ");
    rTimeStart(CORRECTOR_START1);
    beta.MehrotraCorrector(nDim,phase,alpha,currentPt,
			   newton,mu,pARAM);
    // rMessage("beta corrector = " << beta.value);
    newton.Mehrotra(rNewton::CORRECTOR,m,A,C,mu,beta,reduction,
		    phase, currentPt, currentRes, com);
    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton corrector = ");
    // newton.display();
    // rMessage("newton Dy corrector = ");
    // newton.DyVec.display();

    rTimeEnd(CORRECTOR_END1);
    com.Corrector += rTimeCal(CORRECTOR_START1,
			      CORRECTOR_END1);
      
    rTimeStart(CORRECTOR_STEP_START1);
    alpha.MehrotraCorrector(nDim, b, C, A, currentPt, phase,
			    reduction, newton, mu, theta,
			    lanczos, pARAM, com);
    // rMessage("alpha corrector = ");
    // alpha.display();
    rTimeEnd(CORRECTOR_STEP_END1);
    com.StepCorrector += rTimeCal(CORRECTOR_STEP_START1,
				  CORRECTOR_STEP_END1);
    // the end of Corrector
    
    rIO::printOneIteration(pIteration, mu, theta, solveInfo,
			   alpha, beta, currentRes, OutputFile,
			   DisplayInformation);

    if (currentPt.update(alpha,newton,com)==false) {
      // if step length is too short,
      // the algorithm ends.
      // rMessage("cannot move");
      pIteration++;
      break;
    }

    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton = ");
    // newton.display();

    // rMessage("updated");
    theta.update(reduction,alpha);
    mu.update(nDim,currentPt);
    currentRes.update(m,nBlock,blockStruct,b,C,A,
		      initRes, theta, currentPt, phase, mu,com);
    
    theta.update_exact(initRes,currentRes);
    solveInfo.update(nDim, b, C, initPt, currentPt,
		     currentRes, mu, theta, pARAM);
    pIteration++;

  } // end of MAIN_LOOP

  rTimeEnd(MAIN_LOOP_END1);

  com.MainLoop = rTimeCal(MAIN_LOOP_START1,
			  MAIN_LOOP_END1);
  currentPt.update_last(com);
  currentRes.compute(m,nBlock,blockStruct,b,C,A,currentPt,mu);
  rIO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		     currentRes, phase, currentPt, com.TotalTime,
		     nDim,b,C,A,com,pARAM, OutputFile,
		     DisplayInformation,false);

  #if REVERSE_PRIMAL_DUAL
  // reverse the sign of y and phase
  rAl::let(currentPt.yVec,'=',currentPt.yVec,'*',&DMONE);
  phase.reverse();
  #endif
  
  iteration = pIteration;

  // for compability SDPA
  PrimalObj    = getPrimalObj();
  DualObj      = getDualObj();
  PrimalError  = getPrimalError();
  DualError    = getDualError();
  Iteration    = getIteration();
  switch (phase.value) {
  case rSolveInfo::noINFO    : Value = ::noINFO;      break;
  case rSolveInfo::pFEAS     : Value = ::pFEAS;       break;
  case rSolveInfo::dFEAS     : Value = ::dFEAS;       break;
  case rSolveInfo::pdFEAS    : Value = ::pdFEAS;      break;
  case rSolveInfo::pdINF     : Value = ::pdINF;       break;
  case rSolveInfo::pFEAS_dINF: Value = ::pFEAS_dINF;  break;
  case rSolveInfo::pINF_dFEAS: Value = ::pINF_dFEAS;  break;
  case rSolveInfo::pdOPT     : Value = ::pdOPT;       break;
  case rSolveInfo::pUNBD     : Value = ::pUNBD;       break;
  case rSolveInfo::dUNBD     : Value = ::dUNBD;       break;
  }
}
Example #4
0
static TaskSignal measTick(void *state)
{
	if (state == NULL)
		return TASK_OK;

	MeasTaskState *measState = (MeasTaskState*) state;
	MeasurementConf *measConf = &measState->measConf;
	long measWait     = measConf->measureWait;
	long measInterval = measConf->measureInterval;
	long measTime     = measConf->measureTime;
	long endTime      = measTime + measWait;
	bool verbose      = measConf->verbose;
	long time         = getIteration();

	SamplerSignal samplerSignal = SAMPLER_OK;

	if (measInterval < 0)
		return TASK_OK;


	switch (measState->measStatus) {
	case RELAXING:
		if (verbose && (time % MAX(measWait/100, 1)) == 0 ) {
			printf("\rRelax time %ld of %ld", time, measWait);
			fflush(stdout);
		}
		if (time >= measWait) {
			measState->intervalTime = time - measWait;
			if (verbose)
				printf("\nStarting measurement.\n");

			/* Start the sampler */
			measState->samplerState = samplerStart(measState);

			measState->measStatus = SAMPLING;
			/* bit of a hack to start sampling immediately: */
			measState->intervalTime = measInterval;
		}
		break;
	case SAMPLING:
		measState->intervalTime++;

		if (measState->intervalTime < measInterval)
			break;

		if (verbose) {
			if (measTime > 0)
				printf("\rSampling at iteration %ld of %ld", 
						time, endTime);
			else
				printf("\rSampling at iteration %ld", time);
			fflush(stdout);
		}

		measState->intervalTime -= measInterval;
		samplerSignal = samplerSample(measState);
		measState->samplerData.sample++;
		
		if (measTime < 0)
			break; /* Go on indefinitely, don't print anything */

		fflush(stdout);
		if (time >= endTime) {
			if (verbose)
				printf("\nFinished sampling period!\n");
			return TASK_STOP;
		}
		break;
	default:
		fprintf(stderr, "Unknown measurement status!\n");
		assert(false);
	}

	switch(samplerSignal) {
		case SAMPLER_OK:
			return TASK_OK;
		case SAMPLER_STOP:
			if (verbose)
				printf("\nSampler requested polite quit.\n");
			return TASK_STOP;
		case SAMPLER_ERROR:
			if (verbose)
				printf("\nSampler encountered error!\n");
			return TASK_ERROR;
		default:
			fprintf(stderr, "Received unknown sampler signal!");
			assert(false);
			return TASK_ERROR;
	}
}
Example #5
0
void Simulation::draw(render::Context& context)
{
    context.setStencilBuffer(getWorldSize().getWidth().value(), getWorldSize().getHeight().value());

    // Render modules
    m_modules.draw(*this, context);

    // Draw objects
    for (auto& obj : m_objects)
    {
        Assert(obj);
        if (obj->isVisible())
            obj->draw(context);
    }

#if defined(CECE_ENABLE_RENDER) && defined(CECE_ENABLE_BOX2D_PHYSICS) && defined(CECE_ENABLE_BOX2D_PHYSICS_DEBUG)
    if (isDrawPhysics())
        m_world.DrawDebugData();
#endif

#if CONFIG_RENDER_TEXT_ENABLE
    context.disableStencilBuffer();

    if (isSimulationTimeRender())
    {
        if (!m_font)
        {
            m_font.create(context, g_fontData);
            m_font->setSize(getFontSize());
        }

        OutStringStream oss;
        {
            auto time = getTotalTime().value();
            unsigned int seconds = time;
            unsigned int milliseconds = static_cast<unsigned int>(time * 1000) % 1000;

            const unsigned int hours = seconds / (60 * 60);
            seconds %= (60 * 60);
            const unsigned int minutes = seconds / 60;
            seconds %= 60;

            if (hours)
            {
                oss << std::setw(2) << std::setfill('0') << hours << ":";
                oss << std::setw(2) << std::setfill('0') << minutes << ":";
            }
            else if (minutes)
            {
                oss << std::setw(2) << std::setfill('0') << minutes << ":";
            }

            oss << std::setw(2) << std::setfill('0') << seconds << ".";
            oss << std::setw(3) << std::setfill('0') << milliseconds;
        }

        if (hasUnlimitedIterations())
        {
            oss << " (" << getIteration() << " / -)";
        }
        else
        {
            oss << " (" << getIteration() << " / " << getIterations() << ")";
        }

        m_font->draw(context, oss.str(), getFontColor());
    }
#endif
}
Example #6
0
bool Simulation::update(units::Duration dt)
{
    // Initialize simulation
    if (!isInitialized())
        initialize();

    // Increase step number
    m_iteration++;
    m_totalTime += dt;

    // Clear all stored forces
    for (auto& obj : m_objects)
        obj->setForce(Zero);

    // Update modules
    updateModules(dt);

    // Update objects
    updateObjects(dt);

    // Detect object that leaved the scene
    detectDeserters();

    // Delete unused objects
    deleteObjects();

    // Store data
    if (m_dataOutObjects)
    {
        for (const auto& object : m_objects)
        {
            const auto pos = object->getPosition();
            const auto vel = object->getVelocity();

            *m_dataOutObjects <<
                // iteration
                getIteration() << ";" <<
                // totalTime
                getTotalTime() << ";" <<
                // id
                object->getId() << ";" <<
                // typeName
                object->getTypeName() << ";" <<
                // posX
                pos.getX() << ";" <<
                // posY
                pos.getY() << ";" <<
                // velX
                vel.getX() << ";" <<
                // velY
                vel.getY() << "\n"
            ;
        }
    }

#ifdef CECE_ENABLE_BOX2D_PHYSICS
    {
        auto _ = measure_time("sim.physics", TimeMeasurementIterationOutput(this));

        m_world.Step(getPhysicsEngineTimeStep().value(), 10, 10);
    }
#endif

    return (hasUnlimitedIterations() || getIteration() <= getIterations());
}