Ejemplo n.º 1
0
void Evnav::makeGraph(Graph &g, EvnavRequest &req, VertexId srcId, VertexId dstId)
{
    Trip trip;
    // FIXME: move to EvnavRequest?
    double SOC_dyn = req.m_SOC_max - req.m_SOC_min;
    double batt_act = req.m_battery * req.m_SOC_act; // kWh
    double batt_dyn = req.m_battery * SOC_dyn;

    // Add edge from the source to all chargers
    // FIXME: create waypoint class with chargers that extends it

    for (Charger &a : m_provider->chargers()) {
        if (computeTrip(req.m_src, a.loc(), trip) == Status::Ok) {
            double e = computeEnergy(trip, req.m_efficiency);
            if (e < batt_act) {
                Edge edge(srcId, a.id(), (double)trip.time_s);
                edge.m_travel_time = trip.time_s;
                edge.m_dist = trip.dist_m;
                edge.m_energy = e;
                g.addEdge(edge);
            }
        }
    }

    // Add all intermediate chargers
    chargerMatrix([&](Charger &a, Charger &b, Trip &t) {
        // do not add edges between chargers that are too close
        if (t.dist_m < 1000) {
            return;
        }
        double e = computeEnergy(t, req.m_efficiency);
        if (e < batt_dyn) {
            double total_time = computeTripTimeWithCharging(t, e, req.m_power_avg);
            Edge edge(a.id(), b.id(), total_time);
            edge.m_energy = e;
            edge.m_charge_time = computeChargingTime(e, req.m_power_avg);
            edge.m_dist = t.dist_m;
            edge.m_travel_time = t.time_s;
            g.addEdge(edge);
        }
    });

    // Add edge from all chargers to the destination
    for (Charger &a : m_provider->chargers()) {
        if (computeTrip(a.loc(), req.m_dst, trip) == Status::Ok) {
            double e = computeEnergy(trip, req.m_efficiency);
            if (e < batt_dyn) {
                double total_time = computeTripTimeWithCharging(trip, e, req.m_power_avg);
                Edge edge(a.id(), dstId, total_time);
                edge.m_energy = e;
                edge.m_charge_time = computeChargingTime(e, req.m_power_avg);
                edge.m_dist = trip.dist_m;
                edge.m_travel_time = trip.time_s;
                g.addEdge(edge);
            }
        }
    }
}
Ejemplo n.º 2
0
double Model::getEnergy()
{
    double energy = 0;

    for (unsigned int i=0;i<particles.size();i++)
#ifndef ISOTROPIC
        energy += computeEnergy(i, &particles[i].position[0], &particles[i].orientation[0]);
#else
        energy += computeEnergy(i, &particles[i].position[0]);
#endif

    return energy/(2*particles.size());
}
Ejemplo n.º 3
0
Real
AuxChem::computeValue()
{
  Real matrix_energy(0.0);
  Real precip_energy(0.0);
  Real differential(0.0);

  matrix_energy = computeEnergy(_coupled_cons[_qp], _coupled_noncons[_qp], true);
  precip_energy = computeEnergy(_precip_conserved, _precip_nonconserved, false);
  differential = computeDifferential(_coupled_cons[_qp], _coupled_noncons[_qp]);

  return (matrix_energy - precip_energy + differential);
}
 inline real
 AngularUniquePotentialTemplate< Derived >::
 computeEnergy(const Particle &p1, const Particle &p2, const Particle &p3, real theta0) const {
   Real3D r12 = p1.position() - p2.position();
   Real3D r32 = p3.position() - p2.position();
   return computeEnergy(r12, r32, theta0);
 }
 inline real
 AngularUniquePotentialTemplate< Derived >::
 computeEnergy(const Real3D& r12, const Real3D& r32, real theta0) const {
   real dist12Sqr = r12.sqr();
   real dist32Sqr = r32.sqr();
   real cos_theta = r12 * r32 / (sqrt(dist12Sqr) * sqrt(dist32Sqr));
   return computeEnergy(acos(cos_theta), theta0);
 }
Ejemplo n.º 6
0
 int SimulationIsingModel::attemptFlip(int i)
 {
     double old_e = computeEnergy(i);
     _spin[i] *= -1.0;
     double new_e = computeEnergy(i);
     
     //std::cerr << old_e << "\t" << new_e << "\t" << exp(-_beta*(new_e - old_e)) << std::endl;
     
     if (new_e < old_e) {
         //std::cerr << 1 << std::endl;
         return 1;
     }
     else if (_rng.randDouble() < exp(-_beta*(new_e - old_e))) {
         //std::cerr << 1 << std::endl;
         return 1;
     }
     else {
         //std::cerr << 0 << std::endl;
         _spin[i] *= -1.0;
         return 0;
     }
     
 }
Ejemplo n.º 7
0
void PisdWdF<EvalT, Traits>::
evaluateFields(typename Traits::EvalData workset)
{
    ScalarT kappa;
    ScalarT mu;

    // Leading dimension of 1 added so we can use Intrepid::det
    Intrepid::FieldContainer<EnergyFadType> F(1,numDims,numDims);

    // Allocate F ( = defgrad of derivative types) and seed with identity derivs
    for (std::size_t i=0; i < numDims; ++i)
    {
        for (std::size_t j=0; j < numDims; ++j)
        {
            F(0,i,j) = EnergyFadType(numDims*numDims, 0.0); // 0.0 will be overwriten below
            F(0,i,j).fastAccessDx(i*numDims + j) = 1.0;
        }
    }

    for (std::size_t cell=0; cell < workset.numCells; ++cell) {
        for (std::size_t qp=0; qp < numQPs; ++qp) {
            kappa = elasticModulus(cell,qp) / ( 3. * ( 1. - 2. * poissonsRatio(cell,qp) ) );
            mu    = elasticModulus(cell,qp) / ( 2. * ( 1. + poissonsRatio(cell,qp) ) );

            // Fill F with defgrad for value. Derivs already seeded with identity.
            for (std::size_t i=0; i < numDims; ++i)
                for (std::size_t j=0; j < numDims; ++j)
                    F(0,i,j).val() = defgrad(cell, qp, i, j);

            // Call energy funtional (can make a library of these)
            EnergyFadType W = computeEnergy(kappa, mu, F);

            // Extract stress from derivs of energy
            for (std::size_t i=0; i < numDims; ++i)
                for (std::size_t j=0; j < numDims; ++j)
                    P(cell, qp, i, j) = W.fastAccessDx(i*numDims + j);

        }
    }
}
double GI_MF::run(labelType* inferredLabels,
                   int id,
                   size_t maxiter,
                   labelType* nodeLabelsGroundTruth,
                   bool computenergyAtEachIteration,
                   double* _loss)
{
  bool useLossFunction = lossPerLabel!=0;
  string paramMSRC;
  Config::Instance()->getParameter("msrc", paramMSRC);
  bool useMSRC = paramMSRC.c_str()[0] == '1';
  bool replaceVoidMSRC = false;
  labelType voidLabel = 0;
  labelType moutainLabel = 0;
  labelType horseLabel = 0;
  if(!useLossFunction && useMSRC) {
    Config::Instance()->getParameter("msrc_replace_void", paramMSRC);
    replaceVoidMSRC = paramMSRC.c_str()[0] == '1';
    voidLabel = classIdxToLabel[0];
    moutainLabel = classIdxToLabel[4161600];
    horseLabel = classIdxToLabel[8323328];
    printf("[GI_MF] MSRC void=%d, moutain=%d, horse=%d\n",
           (int)voidLabel, (int)moutainLabel, (int)horseLabel);
  } else {
    printf("[GI_MF] Do not replace void labels\n");
  }

  int sid = 0;
  double maxScore = 0;
  double totalScore_old = 0;
  double totalScore = 10;
  supernode *s;

  const map<int, supernode* >& _supernodes = slice->getSupernodes();
  ulong nSupernodes = slice->getNbSupernodes();  

  // check if memory was already allocated for believes
  if(!believes) {
    believes = new double*[nSupernodes];
    for (uint k = 0; k < nSupernodes; ++k) {
      believes[k] = new double[param->nClasses];
    }
  }

  double maxPotential;
  computeNodePotentials(believes, maxPotential);
    
  double scale = 1.0;
  if (fabs(maxPotential) > 1e-30) {
    scale = MAX_POTENTIAL/maxPotential;
  }
  INFERENCE_PRINT("[gi_MF] maxPotential=%g, scale=%g\n", maxPotential, scale);

#if EXP_DOMAIN
  INFERENCE_PRINT("[gi_MF] Computing in exp domain\n");
  // go to exponential domain
  for (uint sid = 0; sid < nSupernodes; ++sid) {
    for(int c = 0; c < param->nClasses; ++c) {
      believes[sid][c] = std::exp(believes[sid][c]*scale);
    }
  }
#else
  INFERENCE_PRINT("[gi_MF] Computing in log domain\n");
  // stay in log domain
  for (uint sid = 0; sid < nSupernodes; ++sid) {
    for(int c = 0; c < param->nClasses; ++c) {
      believes[sid][c] *= scale;
    }
  }
#endif

  //exportBelieves("believes0");

  for(map<int, supernode* >::const_iterator its = _supernodes.begin();
      its != _supernodes.end(); its++) {
    sid = its->first;
    inferredLabels[sid] = 0;
  }

  // random selection
  for(uint iter = 0; iter < maxiter && (totalScore - totalScore_old) > 1.0; ++iter) {
    
    printf("[GI_MF] Iteration %d/%ld\n", iter, maxiter);

    totalScore_old = totalScore;
    totalScore = 0;

    // Select a pixel at random
    //int sid = gsl_rng_uniform_int(r, nSupernodes);

    int nLabelsChanged = 0;
    double* bs = 0;
    double maxBelief = 0;

    for(map<int, supernode* >::const_iterator its = _supernodes.begin();
        its != _supernodes.end(); its++) {
      sid = its->first;
      s = its->second;
      bs = believes[sid];

      if(param->nClasses != 2) {

        for(int c = 0; c < (int)param->nClasses; c++) {
          double unaryPotential = computeUnaryPotential(slice, sid, c) * scale;

          double pairwiseBelief = 0;
          if(param->includeLocalEdges) {
            vector < supernode* >* lNeighbors = &(s->neighbors);
            for(vector < supernode* >::iterator itN = lNeighbors->begin();
                itN != lNeighbors->end(); itN++) {

              // set edges once
              if(its->first < (*itN)->id) {
                continue;
              }

#if USE_LONG_RANGE_EDGES
               double pairwisePotential = computePairwisePotential_distance(slice, s, (*itN),
                                                                            c, inferredLabels[(*itN)->id]);
#else
               double pairwisePotential = computePairwisePotential(slice, s, (*itN),
                                                                   c, inferredLabels[(*itN)->id]);
#endif
               pairwisePotential *= scale;
               pairwiseBelief += believes[(*itN)->id][c] * pairwisePotential;
            }
          }
#if EXP_DOMAIN
        bs[c] = exp(unaryPotential)*exp(pairwiseBelief);
#else
        bs[c] = unaryPotential + pairwiseBelief;
#endif
          if(maxBelief < bs[c]) {
            maxBelief = bs[c];
          }
        }
      } else {
        int c = T_FOREGROUND;
#if EXP_DOMAIN
        bs[T_FOREGROUND] = 1;
#else
        bs[T_FOREGROUND] = 0;
#endif

        c = T_BACKGROUND;
        double unaryPotential = computeUnaryPotential(slice, sid, c) * scale;
        //printf("unaryPotential %d %g\n", sid, unaryPotential);

        double pairwiseBelief = 0;
        if(param->includeLocalEdges) {
          vector < supernode* >* lNeighbors = &(s->neighbors);
          for(vector < supernode* >::iterator itN = lNeighbors->begin();
              itN != lNeighbors->end(); itN++) {

            // set edges once
            if(its->first < (*itN)->id) {
              continue;
            }

#if USE_LONG_RANGE_EDGES
            double pairwisePotential = computePairwisePotential_distance(slice, s, (*itN),
                                                                         c, inferredLabels[(*itN)->id]);
#else
            double pairwisePotential = computePairwisePotential(slice, s, (*itN),
                                                                c, inferredLabels[(*itN)->id]);
#endif
            pairwisePotential *= scale;
            pairwiseBelief += believes[(*itN)->id][c] * pairwisePotential;
            //printf("pairwisePotential %d %d %d %g %g %g\n", sid, (*itN)->id, c, pairwisePotential, believes[(*itN)->id][c], pairwiseBelief);
          }
        }
#if EXP_DOMAIN
        bs[c] = exp(unaryPotential)*exp(pairwiseBelief);
#else
        bs[c] = unaryPotential + pairwiseBelief;
#endif
        //printf("bs[%d] %g\n",c,bs[c]);
        if(maxBelief < bs[c]) {
          maxBelief = bs[c];
        }
      }

      if(useLossFunction) {
        // loss function
        for(int c = 0; c < (int)param->nClasses; c++) {
          if(c != groundTruthLabels[sid]) {
            double _loss = lossPerLabel[groundTruthLabels[sid]] * scale;
            // add loss of the ground truth label
#if EXP_DOMAIN
            bs[c] *= exp(_loss);
#else
            bs[c] += _loss;
#endif

            if(maxBelief < bs[c]) {
              maxBelief = bs[c];
            }
          }
        }
      }

      // pick max
      maxScore = bs[inferredLabels[sid]];
      for(int c = 0; c < (int)param->nClasses; c++) {
        if(!replaceVoidMSRC || (c != voidLabel && c != moutainLabel && c != horseLabel)) {
          if(maxScore < bs[c]) {
            maxScore = bs[c];
            inferredLabels[sid] = c;
            ++nLabelsChanged;
          }
        }
      }
      totalScore += maxScore;
    }
    printf("[GI_MF] Iteration %d/%ld. Total score = %g. nLabelsChanged = %d\n", iter, maxiter,
           totalScore, nLabelsChanged);

    if(maxBelief > MAX_POTENTIAL) {
      // normalize believes
      printf("[GI_MF] Normalizing believes. maxBelief = %g\n", maxBelief);
      for (uint sid = 0; sid < nSupernodes; ++sid) {
        for(int c = 0; c < param->nClasses; ++c) {
          believes[sid][c] /= maxBelief;
        }
      }
    }
    //exportBelieves("believes_last");

  }

  // cleaning
  return computeEnergy(inferredLabels);
}
Ejemplo n.º 9
0
jdoubleArray Java_edu_cornell_audioProbe_AudioManager_features(JNIEnv* env, jobject javaThis, jshortArray array) {
//void Java_edu_cornell_audioProbe_AudioManager_features(JNIEnv* env, jobject javaThis, jshortArray array) {

	(*env)->GetShortArrayRegion(env, array, 0, FRAME_LENGTH, buf);

	normalize_data();

	// apply window
	computeHamming();

	// computeFwdFFT
	kiss_fftr(cfgFwd, normalizedData, fftx);

	//compute power spectrum
	computePowerSpec(fftx, powerSpec, FFT_LENGTH);

	//compute magnitude spectrum
	computeMagnitudeSpec(powerSpec, magnitudeSpec, FFT_LENGTH);

	// compute total energy
	energy = computeEnergy(powerSpec, FFT_LENGTH) / FFT_LENGTH;

	//compute Spectral Entropy
	computeSpectralEntropy2(magnitudeSpec, FFT_LENGTH);


	//compute auto-correlation peaks
	computeAutoCorrelationPeaks2(powerSpec, powerSpecCpx, NOISE_LEVEL, FFT_LENGTH);

	//data output
	////return data as variable size array caused by variable autocorrelation information.
	jdoubleArray featureVector = (*env)->NewDoubleArray(env,6 + 2*numAcorrPeaks + 2 + LOOK_BACK_LENGTH);
	//jdoubleArray featureVector = (*env)->NewDoubleArray(env,6 + 2*numAcorrPeaks + 2 + LOOK_BACK_LENGTH + FFT_LENGTH);
	featuresValuesTemp[0] = numAcorrPeaks; //autocorrelation values
	featuresValuesTemp[1] = maxAcorrPeakVal;
	featuresValuesTemp[2] = maxAcorrPeakLag;
	featuresValuesTemp[3] = spectral_entropy;
	featuresValuesTemp[4] = rel_spectral_entropy;
	featuresValuesTemp[5] = energy;

	//gaussian distribution
	//test the gaussian distribution with some dummy values first
	x[0] = maxAcorrPeakVal;
	x[1] = numAcorrPeaks;
	x[2] = rel_spectral_entropy;
	/*
	emissionVoiced = computeMvnPdf(x,mean_voiced, inv_cov_voiced, denom_gauss_voiced);
	emissionUnvoiced = computeMvnPdf(x,mean_unvoiced, inv_cov_unvoiced, denom_gauss_unvoiced);
	 */
	 
	inferenceResult = getViterbiInference(x,featureAndInference);
	memcpy( featuresValuesTemp+6, featureAndInference, (2+LOOK_BACK_LENGTH)*sizeof(double) ); //observation probabilities, inferences
	
	
	
	//put auto correlation values in the string
	memcpy( featuresValuesTemp+6+2+LOOK_BACK_LENGTH, acorrPeakValueArray, numAcorrPeaks*sizeof(double) );
	memcpy( featuresValuesTemp+6+numAcorrPeaks+2+LOOK_BACK_LENGTH, acorrPeakLagValueArray, numAcorrPeaks*sizeof(double) );
	//memcpy( featuresValuesTemp+6+numAcorrPeaks+numAcorrPeaks+2+LOOK_BACK_LENGTH, magnSpect, FFT_LENGTH*sizeof(double) );
	(*env)->SetDoubleArrayRegion( env, featureVector, 0, 6 + numAcorrPeaks*2 + 2 + LOOK_BACK_LENGTH, (const jdouble*)featuresValuesTemp );
	//(*env)->SetDoubleArrayRegion( env, featureVector, 0, 6 + numAcorrPeaks*2 + 2 + LOOK_BACK_LENGTH + FFT_LENGTH, (const jdouble*)featuresValuesTemp );


	return featureVector;


}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
    printf("%s Starting...\n\n", argv[0]);

    try
    {
        std::string sFilename;
        char *filePath = sdkFindFilePath("person.txt", argv[0]);

        if (filePath)
        {
            sFilename = filePath;
        }
        else
        {
            printf("Error %s was unable to find person.txt\n", argv[0]);
            exit(EXIT_FAILURE);
        }

        cudaDeviceInit(argc, (const char **)argv);

        printfNPPinfo(argc, argv);

        if (g_bQATest == false && (g_nDevice == -1) && argc > 1)
        {
            sFilename = argv[1];
        }

        // if we specify the filename at the command line, then we only test sFilename
        int file_errors = 0;

        std::ifstream infile(sFilename.data(), std::ifstream::in);

        if (infile.good())
        {
            std::cout << "imageSegmentationNPP opened: <" << sFilename.data() << "> successfully!" << std::endl;
            file_errors = 0;
            infile.close();
        }
        else
        {
            std::cout << "imageSegmentationNPP unable to open: <" << sFilename.data() << ">" << std::endl;
            file_errors++;
            infile.close();
        }

        if (file_errors > 0)
        {
            exit(EXIT_FAILURE);
        }

        std::string sResultFilename = sFilename;

        std::string::size_type dot = sResultFilename.rfind('.');

        if (dot != std::string::npos)
        {
            sResultFilename = sResultFilename.substr(0, dot);
        }

        sResultFilename += "_segmentation.pgm";

        if (argc >= 3 && !g_bQATest)
        {
            sResultFilename = argv[2];
        }

        // load MRF declaration
        int width, height, nLabels;
        int *hCue, *vCue, *dataCostArray;

        loadMiddleburyMRFData(sFilename, dataCostArray, hCue, vCue, width, height, nLabels);
        NPP_ASSERT(nLabels == 2);

        std::cout << "Dataset: " << sFilename << std::endl;
        std::cout << "Size: " << width << "x" << height << std::endl;

        NppiSize size;
        size.width = width;
        size.height = height;

        NppiRect roi;
        roi.x=0;
        roi.y=0;
        roi.width=width;
        roi.height=height;

        // Setup flow network
        int step, transposed_step;
        Npp32s *d_source, *d_sink, *d_terminals, *d_left_transposed, *d_right_transposed, *d_top, *d_bottom;

        // Setup terminal capacities
        d_source = nppiMalloc_32s_C1(width, height, &step);
        cudaMemcpy2D(d_source, step, dataCostArray, width * sizeof(int), width*sizeof(int), height, cudaMemcpyHostToDevice);
        d_sink = nppiMalloc_32s_C1(width, height, &step);
        cudaMemcpy2D(d_sink, step, &dataCostArray[width*height], width * sizeof(int), width*sizeof(int), height, cudaMemcpyHostToDevice);

        d_terminals = nppiMalloc_32s_C1(width, height, &step);

        nppiSub_32s_C1RSfs(d_sink, step, d_source, step, d_terminals, step, size, 0);

        // Setup edge capacities
        NppiSize edgeTranposedSize;
        edgeTranposedSize.width = height;
        edgeTranposedSize.height = width-1;

        NppiSize oneRowTranposedSize;
        oneRowTranposedSize.width = height;
        oneRowTranposedSize.height = 1;

        d_right_transposed = nppiMalloc_32s_C1(height, width, &transposed_step);
        cudaMemcpy2D(d_right_transposed, transposed_step, hCue, height * sizeof(int), height * sizeof(int), width, cudaMemcpyHostToDevice);

        d_left_transposed = nppiMalloc_32s_C1(height, width, &transposed_step);
        nppiSet_32s_C1R(0, d_left_transposed, transposed_step, oneRowTranposedSize);
        nppiCopy_32s_C1R(d_right_transposed, transposed_step, d_left_transposed + transposed_step/sizeof(int), transposed_step, edgeTranposedSize);

        NppiSize edgeSize;
        edgeSize.width = width;
        edgeSize.height = height-1;

        NppiSize oneRowSize;
        oneRowSize.width = width;
        oneRowSize.height = 1;

        d_bottom = nppiMalloc_32s_C1(width, height, &step);
        cudaMemcpy2D(d_bottom, step, vCue, width * sizeof(int), width*sizeof(int), height, cudaMemcpyHostToDevice);

        d_top = nppiMalloc_32s_C1(width, height, &step);
        nppiSet_32s_C1R(0, d_top, step, oneRowSize);
        nppiCopy_32s_C1R(d_bottom, step, d_top + step/sizeof(int), step, edgeSize);

        // Allocate temp storage for graphcut computation
        Npp8u *pBuffer;
        int bufferSize;
        nppiGraphcutGetSize(size, &bufferSize);
        cudaMalloc(&pBuffer, bufferSize);

        NppiGraphcutState *pGraphcutState;
        nppiGraphcutInitAlloc(size, &pGraphcutState, pBuffer);

        // Allocate label storage
        npp::ImageNPP_8u_C1 oDeviceDst(width, height);

        cudaEvent_t start, stop;
        cudaEventCreate(&start);
        cudaEventCreate(&stop);

        // Compute the graphcut, result is 0 / !=0
        cudaEventRecord(start,0);

        nppiGraphcut_32s8u(d_terminals, d_left_transposed, d_right_transposed,
                           d_top, d_bottom, step, transposed_step,
                           size, oDeviceDst.data(), oDeviceDst.pitch(), pGraphcutState);

        cudaEventRecord(stop,0);
        cudaEventSynchronize(stop);

        float time;
        cudaEventElapsedTime(&time, start, stop);
        std::cout << "Elapsed Time: " << time << " ms" << std::endl;

        // declare a host image object for an 8-bit grayscale image
        npp::ImageCPU_8u_C1 oHostAlpha(width, height);

        // convert graphcut result to 0/255 alpha image using new nppiCompareC_8u_C1R primitive (CUDA 5.0)
        npp::ImageNPP_8u_C1 oDeviceAlpha(width, height);
        nppiCompareC_8u_C1R(oDeviceDst.data(), oDeviceDst.pitch(), 0, oDeviceAlpha.data(), oDeviceAlpha.pitch(), size,
                            NPP_CMP_GREATER);

        // and copy the result to host
        oDeviceAlpha.copyTo(oHostAlpha.data(), oHostAlpha.pitch());

        int E_d, E_s;
        std::cout << "Graphcut Cost: " << computeEnergy(E_d, E_s, oHostAlpha.data(), oHostAlpha.pitch(), hCue, vCue, dataCostArray, width, height) << std::endl;
        std::cout << "(E_d = " << E_d << ", E_s = " << E_s << ")" << std::endl;

        std::cout << "Saving segmentation result as " << sResultFilename << std::endl;
        saveImage(sResultFilename, oHostAlpha);

        nppiGraphcutFree(pGraphcutState);
        cudaFree(pBuffer);
        cudaFree(d_top);
        cudaFree(d_bottom);
        cudaFree(d_left_transposed);
        cudaFree(d_right_transposed);
        cudaFree(d_source);
        cudaFree(d_sink);
        cudaFree(d_terminals);

        exit(EXIT_SUCCESS);
    }
    catch (npp::Exception &rException)
    {
        std::cerr << "Program error! The following exception occurred: \n";
        std::cerr << rException << std::endl;
        std::cerr << "Aborting." << std::endl;
        exit(EXIT_FAILURE);
    }
    catch (...)
    {
        std::cerr << "Program error! An unknow type of exception occurred. \n";
        std::cerr << "Aborting." << std::endl;
        exit(EXIT_FAILURE);
    }

    return 0;
}
Ejemplo n.º 11
0
int main()
{
	int timer = 0,step,solution=0, useNew, accepted;
	
	float temp = INIT_TEMP;
	memberType current,working,best;
	
	FILE *fp;
	
	fp=fopen("stats.txt", "w");
	
	srand(time(NULL));
	
	initSolution(&current);
	computeEnergy(&current);
	
	best.energy=100.0;
	
	copySolution(&working, &current);
	
	while( temp > FIN_TEMP )
	{
		printf("\n Temperature = %f", temp);
		
		accepted = 0;
		
		/* Monte Carlo step*/
		
		for( step = 0; step < STEPS; step++);
		{
			useNew=0;
			
			tweakSolution(&working);
			computeEnergy(&working);
			
			if(working.energy <= current.energy)
			{
				useNew = 1;
			}
			else
			{
				float test = rand() % 1;
				float delta = working.energy - current.energy;
				float calc = exp(-delta/temp);
				
				if(calc > test)
				{
					accepted++;
					useNew = 1;
				}
			}
		}
		
		if(useNew)
		{
			useNew = 0;
			copySolution(&current, &working);
			
			if(current.energy < best.energy)
			{
				copySolution(&best, &current);
				solution = 1;
			}
			
			else
			{
				copySolution(&working, &current);
			}
			
		}
	
	
	fprintf(fp, "%d %f %f %d \n", timer++, temp, best.energy, accepted);
	printf("Best Energy = %f\n", best.energy);
	
	temp *= ALPHA;
	}
	
	fclose(fp);
	
	if(solution)
	{
		emitSolution(&best);
	}
	
	return 0;
}
Ejemplo n.º 12
0
void Evnav::route(EvnavRequest &req, QJsonObject &json)
{
    Trip trip;
    Graph g;

    VertexId srcId = -1;
    VertexId dstId = -2;

    double SOC_dyn = req.m_SOC_max - req.m_SOC_min;
    double batt_act = req.m_battery * req.m_SOC_act; // kWh
    double batt_dyn = req.m_battery * SOC_dyn;

    if (computeTrip(req.m_src, req.m_dst, trip) == Status::Ok) {
        double e = computeEnergy(trip, req.m_efficiency);
        double e_otw = 0; // kWh
        if (e > batt_act) {
            e_otw = e - batt_act;
        }
        qDebug() << "energy required  : " << e << "kWh";
        qDebug() << "energy start     : " << batt_act << "kWh";
        qDebug() << "energy on the way: " << e_otw << "kWh";
        if (e < batt_act) {
            qDebug() << "reaching destination without charging";

            // FIXME: collect result processing
            json["code"] = "Ok";
            json["message"] = "reachable";

            QJsonObject summary;
            summary["distance"] = trip.dist_m;
            summary["duration"] = trip.time_s;
            summary["energy"] = e;
            summary["driving_duration"] = trip.time_s;
            summary["charging_duration"] = 0;
            summary["charging_cost"] = 0;
            json["route_summary"] = summary;
            json["charging_steps"] = QJsonArray{};
            return;
        } else {
            int min_stops = std::ceil(e_otw / batt_dyn);
            double charging_time = computeChargingTime(e_otw, req.m_power_avg);
            qDebug() << "charging min_stops:" << min_stops;
            qDebug() << "charging min_time :" << formatTime(charging_time);
        }
    }


    makeGraph(g, req, srcId, dstId);
    qDebug() << "graph size:" << g.E();
    // TODO: write the graph as Json

    ShortestPath sp(g, srcId);
    if (sp.hasPathTo(dstId)) {
        QVector<Edge> path = sp.pathTo(dstId).toVector();
        write(path, json);
    } else {
        json["code"] = "Ok";
        json["message"] = "unreachable";
        qDebug() << "cannot reach destination with this electric car";
    }

}