Exemple #1
0
	bool dfs(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) {
		if (not root) return true;
		if ((minNode and root->val<=minNode->val) or (maxNode and root->val>=maxNode->val)) return false;
		return dfs(root->left, minNode, root) and dfs(root->right, root, maxNode);
	}
Exemple #2
0
/* Ip2_ViscElMat_ViscElMat_ViscElPhys */
void Ip2_ViscElMat_ViscElMat_ViscElPhys::go(const shared_ptr<Material>& b1, const shared_ptr<Material>& b2, const shared_ptr<Interaction>& interaction) {

	// no updates of an existing contact 
	if(interaction->phys) return;
	ViscElMat* mat1 = static_cast<ViscElMat*>(b1.get());
	ViscElMat* mat2 = static_cast<ViscElMat*>(b2.get());
	Real mass1 = 1.0;
	Real mass2 = 1.0;
	
	if (mat1->massMultiply and mat2->massMultiply) {
		mass1 = Body::byId(interaction->getId1())->state->mass;
		mass2 = Body::byId(interaction->getId2())->state->mass;
		if (mass1 == 0.0 and mass2 > 0.0) {
			mass1 = mass2;
		} else if (mass2 == 0.0 and mass1 > 0.0) {
			mass2 = mass1;
		}
	}
	
	GenericSpheresContact* sphCont=YADE_CAST<GenericSpheresContact*>(interaction->geom.get());
	Real R1=sphCont->refR1>0?sphCont->refR1:sphCont->refR2;
	Real R2=sphCont->refR2>0?sphCont->refR2:sphCont->refR1;
	
	const Real kn1 = isnan(mat1->kn)?2*mat1->young*R1:mat1->kn*mass1;
	const Real cn1 = mat1->cn*mass1;
	const Real ks1 = isnan(mat1->ks)?kn1*mat1->poisson:mat1->ks*mass1;
	const Real cs1 = mat1->cs*mass1;
	
	const Real mR1 = mat1->mR;      const Real mR2 = mat2->mR; 
	const int mRtype1 = mat1->mRtype; const int mRtype2 = mat2->mRtype;
	
	const Real kn2 = isnan(mat2->kn)?2*mat2->young*R2:mat2->kn*mass2;
	const Real cn2 = mat2->cn*mass2;
	const Real ks2 = isnan(mat2->ks)?kn2*mat2->poisson:mat2->ks*mass2;
	const Real cs2 = mat2->cs*mass2;
		
	ViscElPhys* phys = new ViscElPhys();

	phys->kn = contactParameterCalculation(kn1,kn2, mat1->massMultiply&&mat2->massMultiply);
	phys->ks = contactParameterCalculation(ks1,ks2, mat1->massMultiply&&mat2->massMultiply);
	phys->cn = contactParameterCalculation(cn1,cn2, mat1->massMultiply&&mat2->massMultiply);
	phys->cs = contactParameterCalculation(cs1,cs2, mat1->massMultiply&&mat2->massMultiply);

 	if ((mR1>0) or (mR2>0)) {
		phys->mR = 2.0/( ((mR1>0)?1/mR1:0) + ((mR2>0)?1/mR2:0) );
	} else {
		phys->mR = 0;
	}

	phys->tangensOfFrictionAngle = std::tan(std::min(mat1->frictionAngle, mat2->frictionAngle)); 
	phys->shearForce = Vector3r(0,0,0);
	
	if ((mRtype1 != mRtype2) or (mRtype1>2) or (mRtype2>2) or (mRtype1<1) or (mRtype2<1) ) {
		throw runtime_error("mRtype should be equal for both materials and have the values 1 or 2!");
	} else {
		phys->mRtype = mRtype1;
	}
	
	if (mat1->Capillar and mat2->Capillar)  {
		if (mat1->Vb == mat2->Vb) {
			phys->Vb = mat1->Vb;
		} else {
			throw runtime_error("Vb should be equal for both particles!.");
		}
		
		if (mat1->gamma == mat2->gamma) {
			phys->gamma = mat1->gamma;
		} else {
			throw runtime_error("Gamma should be equal for both particles!.");
		}
	
		if (mat1->theta == mat2->theta) {
			phys->theta = (mat1->theta*M_PI/180.0);
		} else {
			throw runtime_error("Theta should be equal for both particles!.");
		}
		
		if (mat1->CapillarType == mat2->CapillarType and mat2->CapillarType != ""){
			
			if      (mat1->CapillarType == "Willett_numeric")  phys->CapillarType = Willett_numeric;
			else if (mat1->CapillarType == "Willett_analytic") phys->CapillarType = Willett_analytic;
			else if (mat1->CapillarType == "Weigert")          phys->CapillarType = Weigert;
			else if (mat1->CapillarType == "Rabinovich")       phys->CapillarType = Rabinovich;
			else if (mat1->CapillarType == "Lambert")          phys->CapillarType = Lambert;
			else                                               phys->CapillarType = None_Capillar;
		} else {
			throw runtime_error("CapillarType should be equal for both particles!.");
		}
		phys->Capillar=true;
	}
	
	interaction->phys = shared_ptr<ViscElPhys>(phys);
}
int main(int argc, char *argv[]){
    /**
     EXPLANATION:
     This function computes the average of the (projected) deltas as a function of redshift
     Note that this program should work with typical ini file developed to pass to correlation.run but that not all options are used here.
     This program should be run for each set of the paramenters z_min_interpolation, z_max_interpolation, num_points_interpolation, 
     or pixel_separation
          
     INPUTS:
     input_file[optional] - a file containing the input settings
     
     OUTPUTS:
     NONE
          
     CLASSES USED:
     AstroObjectDataset
     Input
     PlateNeighbours
     LyaSpectraDataset
     
     FUNCITONS USED:
     ComputePlateNeighbours
     */
    
    // load time control variables
    time_t start_time,end_time;
    time(&start_time);

    // load global variables and plot object
    std::cout << "Initializing variables" << std::endl;
    string input_filename = "";
    if (argc > 1){
        input_filename += argv[1];
    }
    Input input(input_filename);
    size_t flag_verbose_main = input.flag_verbose_main();
    const PlotsObject kPlots(input);

    // check whether or not this comuputation is necessary
    if (not input.flag_project_deltas()){
        std::cout << "Deltas are not projected, correction unnecessary" << std::endl;
        return 0;
    }
    
    // check whether or not the plate list needs to be computed
    if (input.flag_compute_plate_neighbours()){
        ComputePlateNeighbours(input);
    }
    // load plate list
    const PlateNeighbours kPlateNeighbours(input);
    
    // load spectra dataset
    std::auto_ptr<SpectraDataset> spectra_list;
    if (input.dataset2_type() == "lya"){
        spectra_list.reset(new LyaSpectraDataset(input));
    }
    else if (input.dataset2_type() == "civ"){
        spectra_list.reset(new CIVSpectraDataset(input));
    }
    else{
        std::cout << "Error : The selected type for dataset2 is not enabled. Current options are: " << input.dataset2_type_options() << std::endl;
        return 1;
    }
    if (input.flag_plot_catalog_info()){
        if (flag_verbose_main >= 2){
            std::cout << "Plotting spectra dataset information" << std::endl;
        }
        kPlots.PlotRADECDispersion(*spectra_list, true);
        kPlots.PlotZHistogram(*spectra_list, true);
        if (flag_verbose_main >= 2){
            std::cout << "done" << std::endl;
        }
    }
    
    // define vectors to store the average projected delta as a function of redshift
    size_t num_points_interpolation = input.num_points_interpolation();
    std::vector<double> z_mean_delta(num_points_interpolation, 0.0);
    double z_step = (input.z_max_interpolation() - input.z_min_interpolation())/float(z_mean_delta.size());
    for (size_t index = 0; index < z_mean_delta.size(); index++){
        z_mean_delta[index] = input.z_min_interpolation() + z_step*float(index);
    }
    std::vector<double> mean_delta(num_points_interpolation, 0.0);
    std::vector<double> total_weight(num_points_interpolation, 0.0);
    
    // define copies of mean_delta and total_weight for each of the threads
    int num_threads = atoi(std::getenv("OMP_NUM_THREADS"));
    std::vector<std::vector<double> > mean_delta_thread;
    mean_delta_thread.resize(num_threads, mean_delta);
    std::vector<std::vector<double> > total_weight_thread;
    total_weight_thread.resize(num_threads, total_weight);
    
    // load list of plates
    PlatesMapVector<LyaSpectrum>::map plates_list = (*spectra_list).list();
    
    // compute the average of projected deltas
    std::cout << "Computing the average of projected deltas" << std::endl;
    // loop over plates
    for (PlatesMapVector<LyaSpectrum>::map::iterator it = plates_list.begin(); it != plates_list.end(); it ++){
        
        std::vector<LyaSpectrum> spec_list = (*it).second;
        // loop over spectra
        #pragma omp parallel for schedule(dynamic)
        for (size_t spectrum_number = 0; spectrum_number < spec_list.size(); spectrum_number ++){
            // get the thread number
            int thread_num = omp_get_thread_num();
            double weight;
            
            std::vector<LyaPixel> spectrum = spec_list[spectrum_number].spectrum();
            // loop over pixel
            for (size_t pixel_number = 0; pixel_number < spectrum.size(); pixel_number++){
                // locate the bin in z the pixel belongs to
                int z_index = int((spectrum[pixel_number].z() - input.z_min_interpolation())/z_step);
                if ((z_index < 0) or (z_index > z_mean_delta.size())){
                    #pragma omp critical (cerr)
                    {
                        std::cerr << "Bad index, z_index = " << z_index << std::endl;
                    }
                }
                else{
                    weight = spectrum[pixel_number].weight();
                    mean_delta_thread[thread_num][z_index] += spectrum[pixel_number].delta()*weight;
                    total_weight_thread[thread_num][z_index] += weight;
                }
            }
        }
    }
    
    // combine the measurements from the different threads
    for (size_t index = 0; index < num_points_interpolation; index ++){
        for (size_t thread_num = 0; thread_num < mean_delta_thread.size(); thread_num ++){
            mean_delta[index] += mean_delta_thread[thread_num][index];
            total_weight[index] += total_weight_thread[thread_num][index];
        }
    }
    
    // normalize the correlation
    for (int index =  0; index < num_points_interpolation; index ++){
        // check that the weight is not zero
        if (total_weight[index] == 0.0){
            std::cerr << "Warning : In compute_projection_correction : Index " << index;
            std::cerr << " shows zero weight. Consider reducing num_points_interpolation." << std::endl;
        }
        else{
            mean_delta[index] /= total_weight[index];
        }
    }
    
    // save results
    std::string filename = input.lya_projection_correction();
    std::cout << "Saving results to " << filename << std::endl;
    std::ofstream file;
    file.open(filename.c_str(),std::ofstream::trunc); // opens the file erasing the previous contents
    if (file.is_open()){
        // print header
        file << "z mean_delta" << std::endl;
        // print results
        for (size_t index = 0; index < z_mean_delta.size(); index ++){
            file << z_mean_delta[index] << " " << mean_delta[index] <<  std::endl;
        }
        
        file.close();
    }
    else{
        std::cerr << "Error : In compute_projection_correction : Unable to open file:" << std::endl << filename << std::endl;
    }
    
    
    // display time required to run the program
    if (flag_verbose_main >= 1){
        std::cout << "End of program" << std::endl;
    }
    time(&end_time);
    double time_spent = difftime(end_time, start_time);
    if (flag_verbose_main >= 1){
        if (time_spent < 60.0){
            std::cout << "Program lasted " << time_spent << " seconds" << std::endl;
        }
        else if (time_spent < 3600.0){
            std::cout << "Program lasted " << time_spent/60.0 << " minutes" << std::endl;
        }
        else{
            std::cout << "Program lasted " << time_spent/3600.0 << " hours" << std::endl;
        }
    }
    return 0;
}
Exemple #4
0
void read_file(char * filename)
{
	fp = fopen(filename, "r");

    char * line = malloc(sizeof(char) * 255);
   	while (fgets(line,255,fp) != NULL) 
  	{

      char * buf[] = {" "," "," "," "};
      char * check = strtok(line, " ");
      int i = 0;
      while (check != NULL)
      {

        if (check != NULL)
        {
          buf[i] = malloc(strlen(check) + 1);
          strcpy(buf[i],check);
        }
        check = strtok(NULL, " ");
        i++;
      } 


  		if(strcmp(buf[0],"addu") == 0)
  		{
  			addu(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		} 
  		else if (strcmp(buf[0],"subu") == 0)
  		{
  			subu(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"slt") ==0)
  		{
  			slt(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"and") == 0)
  		{
  			and(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"or") == 0)
  		{
  			or(trim(buf[2], ','),trim(buf[3], ','),trim(buf[1], '\n'));
  		}
  		else if(strcmp(buf[0],"lw") == 0)
  		{
  			lw(rs_I(buf[2]), trim(buf[1], ','), trim(buf[2], '('));
  		}
  		else if (strcmp(buf[0],"sw") == 0)
  		{
  			sw(rs_I(buf[2]), trim(buf[1], ','), trim(buf[2], '('));
  		}
  		else if(strcmp(buf[0],"bne") == 0)
  		{
  			bne(trim(buf[2], ','),trim(buf[1], ','),trim(buf[3], 'j'));
  		}
  		else if(strcmp(buf[0],"j")== 0)
  		{
  			j(trim(buf[1], 'j'));
  		}

  		
  	}
    fclose(fp);
  	printf("End Scan\n");
}
void UTFT::InitLCD(byte orientation)
{
	orient=orientation;
	_hw_special_init();

	pinMode(__p1,OUTPUT);
	pinMode(__p2,OUTPUT);
	pinMode(__p3,OUTPUT);
	if (__p4 != NOTINUSE)
		pinMode(__p4,OUTPUT);
	if ((display_transfer_mode==LATCHED_16) or ((display_transfer_mode==1) and (display_serial_mode==SERIAL_5PIN)))
		pinMode(__p5,OUTPUT);
	if (display_transfer_mode!=1)
		_set_direction_registers(display_transfer_mode);

	sbi(P_RST, B_RST);
	delay(5); 
	cbi(P_RST, B_RST);
	delay(15);
	sbi(P_RST, B_RST);
	delay(15);

	cbi(P_CS, B_CS);

	switch(display_model)
	{
#ifndef DISABLE_HX8347A
	#include "tft_drivers/hx8347a/initlcd.h"
#endif
#ifndef DISABLE_ILI9327
	#include "tft_drivers/ili9327/initlcd.h"
#endif
#ifndef DISABLE_SSD1289
	#include "tft_drivers/ssd1289/initlcd.h"
#endif
#ifndef DISABLE_ILI9325C
	#include "tft_drivers/ili9325c/initlcd.h"
#endif
#ifndef DISABLE_ILI9325D
	#include "tft_drivers/ili9325d/default/initlcd.h"
#endif
#ifndef DISABLE_ILI9325D_ALT
	#include "tft_drivers/ili9325d/alt/initlcd.h"
#endif
#ifndef DISABLE_HX8340B_8
	#include "tft_drivers/hx8340b/8/initlcd.h"
#endif
#ifndef DISABLE_HX8340B_S
	#include "tft_drivers/hx8340b/s/initlcd.h"
#endif
#ifndef DISABLE_ST7735
	#include "tft_drivers/st7735/std/initlcd.h"
#endif
#ifndef DISABLE_ST7735_ALT
	#include "tft_drivers/st7735/alt/initlcd.h"
#endif
#ifndef DISABLE_PCF8833
	#include "tft_drivers/pcf8833/initlcd.h"
#endif
#ifndef DISABLE_S1D19122
	#include "tft_drivers/s1d19122/initlcd.h"
#endif
#ifndef DISABLE_HX8352A
	#include "tft_drivers/hx8352a/initlcd.h"
#endif
#ifndef DISABLE_SSD1963_480
	#include "tft_drivers/ssd1963/480/initlcd.h"
#endif
#ifndef DISABLE_SSD1963_800
	#include "tft_drivers/ssd1963/800/initlcd.h"
#endif
#ifndef DISABLE_SSD1963_800_ALT
	#include "tft_drivers/ssd1963/800alt/initlcd.h"
#endif
#ifndef DISABLE_S6D1121
	#include "tft_drivers/s6d1121/initlcd.h"
#endif
#ifndef DISABLE_ILI9481
	#include "tft_drivers/ili9481/initlcd.h"
#endif
#ifndef DISABLE_S6D0164
	#include "tft_drivers/s6d0164/initlcd.h"
#endif
#ifndef DISABLE_ST7735S
	#include "tft_drivers/st7735s/initlcd.h"
#endif
#ifndef DISABLE_ILI9341_S4P
	#include "tft_drivers/ili9341/s4p/initlcd.h"
#endif
#ifndef DISABLE_ILI9341_S5P
	#include "tft_drivers/ili9341/s5p/initlcd.h"
#endif
#ifndef DISABLE_R61581
	#include "tft_drivers/r61581/initlcd.h"
#endif
#ifndef DISABLE_ILI9486
	#include "tft_drivers/ili9486/initlcd.h"
#endif
#ifndef DISABLE_CPLD
	#include "tft_drivers/cpld/initlcd.h"
#endif
#ifndef DISABLE_HX8353C
	#include "tft_drivers/hx8353c/initlcd.h"
#endif
	}

	sbi (P_CS, B_CS); 

	setColor(255, 255, 255);
	setBackColor(0, 0, 0);
	cfont.font=0;
	_transparent = false;
}
Exemple #6
0
/*! Check if \p a lies beside \p b. */
template<class T, std::size_t N> inline pure bool beside(const cring<T>& a,
                                                          const vec<T,N>& b){
    return ((dist(a.c(), b) <  a.ri()) or
            (dist(a.c(), b) >= a.ro()));
}
Exemple #7
0
	bool is_hex_digit(char c)
	{
		return (c >= 'a' and c <= 'f') or (c >= 'A' and c <= 'f') or is_number(c);
	}
 /**
  * Since UICoord path specifications may contain gaps and wildcards, we may attempt
  * to fill in these missing parts by matching against the topological structure of an actual UI.
  * In the general case, finding a solution requires a depth-first exponential brute-force search
  * over the whole structure tree, since we have to try every possible branch until we can disprove
  * the possibility of a match. Implemented as depth-first search with backtracking, this scanning
  * pass produces a list of possible matches, from which we pick the first one with maximum
  * coverage, to yield a single solution.
  * @remark the search and matching is based on an iterator pipeline builder, with the special ability
  *         to expand and recurse into the children of the current element on demand: when `expandChildren()`
  *         was invoked, the next iteration will continue with the first child element; there is a stack of
  *         such "child expansions" -- meaning that the search will backtrack and explore further possibilities
  *         later on. Each position where the pattern matches the actual tree is marked as possible solution.
  *         As a sideeffect, a new coordinate spec to reflect the actual coverage is built and re-written,
  *         while the algorithm proceeds. Thus, at any point marked as solution, the current (partial)
  *         solution can be retrieved and copied from this PathManipulator buffer.
  *         An additional filter layer discriminates the first maximal solutions seen thus far.
  */
 bool
 UICoordResolver::pathResolution()
 {
   // Helper to detect a wildcard match
   auto wildMatch = [&](Literal patt, Literal curr, size_t depth)
                       {
                         return patt == Symbol::ANY
                             or patt == Symbol::EMPTY
                             or patt == UIC_ELIDED // "existentially quantified"
                             or (isAnchored() and curr == res_.anchor and depth == UIC_WINDOW);
                       };    // transitive argument: assuming res_.anchor was computed for
                            //  the same coordinate pattern used here for patch resolution
   // algorithm state
   size_t maxDepth = 0;
   PathManipulator coverage;
   const size_t coordDepth = this->uic_.size();
   const size_t minSolutionDepth = find_wildcardFree_suffix (uic_);
   
   auto searchAlgo = query_.getChildren (uic_, 0)
                           .expandOnIteration()
                           .filter ([&](auto& iter)
                                       {
                                          size_t depth = iter.depth();     // we are at that depth in target tree
                                          if (depth >= coordDepth)         // search pattern exhausted without match...
                                            return false;
                                          Literal patt = uic_[depth];      // pick search pattern component at that depth
                                          Literal curr = *iter;            // iterator points at current tree position (ID)
                                          if (patt == curr or              // if either direct match
                                              wildMatch(patt,curr,depth))  // or wildcard match
                                            {
                                              coverage.setAt (depth,curr); // record match rsp. interpolate wildcard into output
                                              iter.expandChildren();       // next iteration will match one level down into the tree
                                            }
                                          return patt == curr              // direct match counts as (partial) solution
                                              or patt == UIC_ELIDED;       // existentially quantified elements also accepted
                                       })
                           .filter ([&](auto& iter)
                                       {
                                          if (iter.depth() < minSolutionDepth)
                                            return false;                  // filter solutions which did not bind all wildcards
                                          if (iter.depth()+1 <= maxDepth)  // filter for maximum solution length
                                            return false;
                                          maxDepth = 1 + iter.depth();
                                          return true;
                                       })
                           .transform ([&](auto&) -> UICoord const&
                                       {
                                          return coverage.retrieveResult();
                                       });
    // is (partial) coverage possible?
   //  search computes definitive answer!
   res_.isResolved = true;
   
   // perform the matching
   if (isnil (searchAlgo))
     return false;     // no solution found
   
   while (searchAlgo)  // pull first maximal solution
     {
       if (not res_.covfefe)
         res_.covfefe.reset (new UICoord {*searchAlgo});
       else
         *res_.covfefe = *searchAlgo;
       ++searchAlgo;
     }
   
   ENSURE (res_.covfefe and res_.covfefe->size() >= 1);
   res_.anchor = res_.covfefe->getWindow();
   
   // but depth reflects only that part coverable without wildcards
   if (res_.depth == 0)
     res_.depth = query_.determineCoverage(uic_);
   if (res_.depth == 0 and res_.anchor)
     res_.depth = 1;
   
   // signal success only when total coverage is possible
   return res_.covfefe->size() == uic_.size();
 }
/*
 * getPacket
 *     description: retrieve data from the provides (input) port
 *
 *  timeout: the amount of time to wait for data before a NULL is returned.
 *           Use 0.0 for non-blocking and -1 for blocking.
 */
BULKIO_dataOctet_In_i::dataTransfer *BULKIO_dataOctet_In_i::getPacket(float timeout, std::string streamID )
{
    if (breakBlock) {
        return NULL;
    }
    //if (workQueue.size() == 0) {
    if ( (workQueue.size() == 0 ) or (( workQueue.size() != 0 ) and ( workQueue.size() == lastQueueSize )) ){
        if (timeout == 0.0) {
            lastQueueSize = workQueue.size();
            return NULL;
        } else if (timeout > 0){
             uint64_t secs = (unsigned long)(trunc(timeout));
            uint64_t msecs = (unsigned long)((timeout - secs) * 1e6);
            boost::system_time to_time  = boost::get_system_time() + boost::posix_time::seconds(secs) + boost::posix_time::microseconds(msecs);
            boost::unique_lock< boost::mutex > lock(dataAvailableMutex);
            if ( dataAvailable.timed_wait( lock, to_time) == false ) {
                return NULL;
            }

            if (breakBlock) {
                return NULL;
            }
        } else {
            boost::unique_lock< boost::mutex > lock(dataAvailableMutex);
            dataAvailable.wait(lock);
            if (breakBlock) {
                return NULL;
            }
        }       
        
    }
    boost::mutex::scoped_lock lock1(dataBufferLock);
    BULKIO_dataOctet_In_i::dataTransfer *tmp = NULL;
    if ( streamID == "" ){
        tmp = workQueue.front();
        workQueue.pop_front();
    } else {
        std::deque< dataTransfer * >::iterator p = workQueue.begin();
        while ( p != workQueue.end() ) {
            if ( (*p)->streamID == streamID ) {
                tmp = *p;
                workQueue.erase(p);
                break;
            }
            p++;
       }
    
    }
    
    if ( tmp == NULL ) {
        lastQueueSize = workQueue.size();
        return NULL;
    }
    
    boost::mutex::scoped_lock lock2(sriUpdateLock);
    if (tmp->EOS) {
	    RH_SRIMap::iterator target = currentHs.find(std::string(tmp->streamID));
        if (target != currentHs.end()) {
            if (target->second.first.blocking) {
                RH_SRIMap::iterator currH;
                bool keepBlocking = false;
                for (currH = currentHs.begin(); currH != currentHs.end(); currH++) {
                    if (currH->second.first.blocking) {
                        keepBlocking = true;
                        break;
                    }
                }

                if (!keepBlocking) {
                    queueSem->setCurrValue(0);
                    blocking = false;
                }
            }
            currentHs.erase(target);
        }
    }

    if (blocking) {
        queueSem->decr();
    }
    
    lastQueueSize=0;
    return tmp;
}
Exemple #10
0
	bool is_letter(char c)
	{
		return (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z');
	}
int Coordinate::operator<=(const Coordinate &rhs) const
{
    return (*this < rhs) or (x == rhs.x && y == rhs.y);
}
Exemple #12
0
interpMEdata doublestratmatch::equityInterpFn( const gameProbabilities& probs, int perspective, int cube, int cubeOwner, bool isDead, int nOverride, int mOverride )
{
    if( currMatch == 0 ) throw string( "Set the match first" );
    
    // look at the match to figure out the score
    
    int n, m; // n is the # of games away for this guy, m for the other
    
    if( nOverride == 0 )
        n = perspective == 0 ? currMatch->getTarget() - currMatch->playerScore() : currMatch->getTarget() - currMatch->opponentScore();
    else
        n = nOverride;
    if( mOverride == 0 )
        m = perspective == 0 ? currMatch->getTarget() - currMatch->opponentScore() : currMatch->getTarget() - currMatch->playerScore();
    else
        m = mOverride;
    
    bool noDoubleAllowed=false;
    
    // Crawford game - no doubling allowed
    
    if( ( n == 1 or m == 1 ) and !currMatch->doneCrawford ) noDoubleAllowed = true;
    
    // cube already at max
    
    if( ( perspective == cubeOwner and n-cube<=0 ) or ( perspective != cubeOwner and m-cube<=0 ) ) noDoubleAllowed = true;
    
    // if this is an automatic double, return that equity (regardless of whether it's dead or live). If the player owns the cube
    // and the cube is such that the opponent will win the match on any kind of win, the player will always double. If he loses
    // doubled he still just loses the match; but if he wins doubled he's twice as close to the target.
    
    if( !noDoubleAllowed and ( ( cubeOwner != perspective and n-cube<=0 and m-cube>0 ) or ( cubeOwner == perspective and m-cube<=0 and n-cube>0 ) ) )
        return equityInterpFn( probs, perspective, 2*cube, 1-cubeOwner, isDead );
    
    // figure out the match equities on different kinds of wins and losses if we
    // do take/cash. Respect the Crawford rule.
    
    double singleWinME, gammonWinME, bgWinME, singleLossME, gammonLossME, bgLossME;
    
    if( n==1 )
    {
        singleWinME  = 1;
        gammonWinME  = 1;
        bgWinME      = 1;
        singleLossME = MET.matchEquityPostCrawford(m-cube);
        gammonLossME = MET.matchEquityPostCrawford(m-2*cube);
        bgLossME     = MET.matchEquityPostCrawford(m-3*cube);
    }
    else if( m == 1 )
    {
        singleWinME  = -MET.matchEquityPostCrawford(n-cube);
        gammonWinME  = -MET.matchEquityPostCrawford(n-2*cube);
        bgWinME      = -MET.matchEquityPostCrawford(n-3*cube);
        singleLossME = -1;
        gammonLossME = -1;
        bgLossME     = -1;
    }
    else
    {
        singleWinME  = MET.matchEquity(n-1*cube, m);
        gammonWinME  = MET.matchEquity(n-2*cube, m);
        bgWinME      = MET.matchEquity(n-3*cube, m);
        singleLossME = MET.matchEquity(n, m-1*cube);
        gammonLossME = MET.matchEquity(n, m-2*cube);
        bgLossME     = MET.matchEquity(n, m-3*cube);
    }
    
    // we'll get equity as a fn of prob of win by assuming that the ratios of gammon and backgammon
    // probs to the relevant winning/losing prob stay fixed.
    
    double W = probs.probWin == 0 ? 1 : ( ( probs.probWin - probs.probGammonWin ) * singleWinME + ( probs.probGammonWin - probs.probBgWin ) * gammonWinME + probs.probBgWin * bgWinME ) / probs.probWin;
    double L = 1-probs.probWin == 0 ? 1 : -( ( 1 - probs.probWin - probs.probGammonLoss ) * singleLossME + ( probs.probGammonLoss - probs.probBgLoss ) * gammonLossME + probs.probBgLoss * bgLossME ) / ( 1 - probs.probWin );
    
    // if we're calculating the dead cube limit, or the cube is legitimately dead because we can't double
    // anymore, return the dead cube equity.
    
    bool returnDead = noDoubleAllowed or isDead;
    
    if( returnDead )
        return interpMEdata( 0, 1, -L, W, W, L );
    
    // if the cube is centered or the player here owns the cube and still can double, the upper end of the
    // range is the cash point; otherwise the cash point is 100% prob and cash equity
    // is the appropriately-weighted win equity
    
    double cashPoint, cashME;
    
    if( ( cube == 1 or perspective == cubeOwner ) and n-cube > 0 )
    {
        if( n == 1 )
            cashME = 1;
        else if( m == 1 )
            cashME = -MET.matchEquityPostCrawford(n-cube);
        else
            cashME = MET.matchEquity(n-cube, m);
        
        // need to get the match equity fn for a state where the cube is doubled and owned by the 
        // opponent; find where that matches the cash match equity.
        
        interpMEdata data2( equityInterpFn( probs, perspective, cube*2, 1-perspective, isDead ) );
        cashPoint = data2.solve( cashME );
    }
    else
    {
        cashPoint = 1.;
        cashME    = W;
    }
    
    // if the cube is centered or the opponent owns the cube and can still double, the lower end of the range is
    // the take point; otherwise the take point is 0% prob and take equity is the 
    // appropriately-weighted loss equity
    
    double takePoint, takeME;
    
    if( ( cube == 1 or perspective != cubeOwner ) and m-cube>0 )
    {
        if( n == 1 )
            takeME = MET.matchEquityPostCrawford(m-cube);
        else if( m == 1 )
            takeME = -1;
        else
            takeME = MET.matchEquity(n, m-cube);
        
        // find the prob such that the match equity equals the take equity in a state 
        // where the cube is doubled and the player owns it
        
        interpMEdata data2( equityInterpFn( probs, perspective, cube*2, perspective, isDead ) );
        takePoint = data2.solve( takeME );
    }
    else
    {
        takePoint = 0;
        takeME    = -L;
    }
    
    return interpMEdata( takePoint, cashPoint, takeME, cashME, W, L );
}
void CUnitManager::process_ai()
{
    for(unsigned int i = 0 ; i < units.size(); i++)
    {
        if(units[i].health > 0)
        {
            units[i].lx = units[i].x;
            units[i].ly = units[i].y;


            SUnit* trg = NULL;
            unsigned int range = 0;

            switch(units[i].r)
            {
            case 1:


                for(unsigned int r = 1; r < 5; r++)
                {
                    range = r;
                    trg = getUnitByPos(units[i].x,units[i].y+r);
                    if(!Map->getMapTile(units[i].x,units[i].y+r)->passable or trg)
                        break;
                }
                if(trg)
                {
                    unit_shot(&units[i],trg,range);
                    continue;
                }
                break;

            case 2:
                for(unsigned int r = 1; r < 5; r++)
                {
                    range = r;
                    trg = getUnitByPos(units[i].x+r,units[i].y);
                    if(!Map->getMapTile(units[i].x+r,units[i].y)->passable or trg)
                        break;
                }
                if(trg)
                {
                    unit_shot(&units[i],trg,range);
                    continue;
                }
                break;

            case 3:
                for(unsigned int r = 1; r < 5; r++)
                {
                    range = r;
                    trg = getUnitByPos(units[i].x,units[i].y-r);
                    if(!Map->getMapTile(units[i].x,units[i].y-r)->passable or trg)
                        break;
                }
                if(trg)
                {
                    unit_shot(&units[i],trg,range);
                    continue;
                }
                break;

            case 4:
                for(unsigned int r = 1; r < 5; r++)
                {
                    range = r;
                    trg = getUnitByPos(units[i].x-r,units[i].y);
                    if(!Map->getMapTile(units[i].x-r,units[i].y)->passable or trg)
                        break;
                }
                if(trg)
                {
                    unit_shot(&units[i],trg,range);
                    continue;
                }
                break;
            }

            switch(units[i].r)
            {
            case 1:
                if(units[i].fm or (Map->getMapTile(units[i].x,units[i].y+1)->passable and not Map->getMapTile(units[i].x-1,units[i].y)->passable) )
                {
                    units[i].y++;
                    units[i].fm = 0;
                    break;
                }
                else
                {
                    if(Map->getMapTile(units[i].x-1,units[i].y)->passable)
                    {
                        units[i].r = 4;
                        units[i].fm = 1;
                        break;
                    }
                    if(not Map->getMapTile(units[i].x-1,units[i].y)->passable)
                    {
                        units[i].r = 2;
                        break;
                    }
                }

                break;
            case 2:
                if(units[i].fm or (Map->getMapTile(units[i].x+1,units[i].y)->passable and not Map->getMapTile(units[i].x,units[i].y+1)->passable))
                {
                    units[i].x++;
                    units[i].fm = 0;
                    break;
                }
                else
                {
                    if( Map->getMapTile(units[i].x,units[i].y+1)->passable)
                    {
                        units[i].r = 1;
                        units[i].fm = 1;
                        break;
                    }
                    if( not Map->getMapTile(units[i].x,units[i].y+1)->passable)
                    {
                        units[i].r = 3;
                        break;
                    }
                }

                break;
            case 3:
                if(units[i].fm or (Map->getMapTile(units[i].x,units[i].y-1)->passable and not Map->getMapTile(units[i].x+1,units[i].y)->passable))
                {
                    units[i].y--;
                    units[i].fm = 0;
                    break;
                }
                else
                {
                    if(Map->getMapTile(units[i].x+1,units[i].y)->passable)
                    {
                        units[i].r = 2;
                        units[i].fm = 1;
                        break;
                    }
                    if(not Map->getMapTile(units[i].x+1,units[i].y)->passable)
                    {
                        units[i].r = 4;
                        break;
                    }
                }

                break;
            case 4:

                if(units[i].fm or (Map->getMapTile(units[i].x-1,units[i].y)->passable and not Map->getMapTile(units[i].x,units[i].y-1)->passable))
                {
                    units[i].x--;
                    units[i].fm = 0;
                    break;
                }
                else
                {
                    if(Map->getMapTile(units[i].x,units[i].y-1)->passable)
                    {
                        units[i].r = 3;
                        units[i].fm = 1;
                        break;
                    }
                    if(not Map->getMapTile(units[i].x,units[i].y-1)->passable)
                    {
                        units[i].r = 1;
                        break;
                    }
                }

            default:
                units[i].r = (rand()%4)+1;
                break;
            }
            if(units[i].r == 5)
                units[i].r = 1;
        }
        else
        {
            units.erase(units.begin() + i);
            createUnit();
        }


    }

}
Exemple #14
0
void AnalyzeFDStates(std::vector<CIWaveFunc*>  roots, int state_num)
{
	CIWaveFunc* root=roots.at(state_num);
	//Print state
	int __ff =0;
	int __dd =0;
	int __s =0;
	int __fs =0;
	int __ds =0;
	int __fd =0;

	for(int i=0; i<root->conf.size();i++)
	{
		int c_f=0;
		int c_d=0;
		int c_s=0;
		std::cout<<(i+1)<<":" ;
		for(int q=0; q<root->conf.at(i)->conf_space.size();q++)
		{
			int state_val = root->conf.at(i)->conf_space.at(q);
			switch(state_val)
			{
			case(SPIN_UP):
				std::cout<<"u";
				break;
			case(SPIN_DOWN):
				std::cout<<"d";
				break;
			case(SPIN_FULL):
				std::cout<<"2";
				break;
			case(SPIN_HOLE):
				std::cout<<"0";
				break;
			default:
				break;
			}

			//f state
			if((q>=0)&&(q<7)&&((state_val==SPIN_DOWN)or(state_val==SPIN_UP))) c_f+=1;
			if((q>=0)&&(q<7)&&(state_val==SPIN_FULL)) c_f+=2;

			//d state
			if((q>=7)&&(q<12)&&((state_val==SPIN_DOWN)or(state_val==SPIN_UP))) c_d+=1;
			if((q>=7)&&(q<12)&&(state_val==SPIN_FULL)) c_d+=2;

			//s state
			if((q==12)&&((state_val==SPIN_DOWN)or(state_val==SPIN_UP))) c_s+=1;
			if((q==12)&&(state_val==SPIN_FULL)) c_s+=2;
			
			root->conf.at(i)->_f=c_f;
			root->conf.at(i)->_d=c_d;
			root->conf.at(i)->_s=c_s;

		}

		if((c_f>0)and(c_d>0))__fd+=1;
		if((c_f>0)and(c_d>0))__fd+=1;

		std::cout<<"  f("<<c_f<<"),d("<<c_d<<"),s("<<c_s<<")";

		std::cout<<std::endl;
	}
//
	std::cout<<std::endl;

}
void StoreNonOverlappingIndices(std::vector<T_MatchPos> &lis, 
    std::vector<T_MatchPos> &noOvpLis) {
	unsigned int i;

	//
	// Greedily add lis matches according to weight.  A match may be added
	// as long as it does not overlap with any other matches.
	//
 
	// do nothing on empty lists
	if (lis.empty()) return;

	//
	// First build a list of matches sorted by weight.
	SortMatchPosListByWeight(lis);

	//
	// The first match is guaranteed to not overlap.
	noOvpLis.push_back(lis[0]);

	//
	// Nothing is overlapping, and everything is sorted when there is 
	// just one value.
	if (lis.size() == 1) return;

	//
	// Next, add matches as long as they do not overlap.
	for (i = 1; i < lis.size(); i++ ){
		VectorIndex j;
		int lts = lis[i].t;
		int lte = lis[i].t + lis[i].GetLength();
		int lqs = lis[i].q;
		int lqe = lis[i].q + lis[i].GetLength();

		int ovpFound = 0;
		for (j =0; j < noOvpLis.size(); j++ ){
			int tIntvStart = noOvpLis[j].t;
			int tIntvEnd   = noOvpLis[j].t + noOvpLis[j].GetLength();
			int qIntvStart = noOvpLis[j].q;
			int qIntvEnd   = noOvpLis[j].q + noOvpLis[j].GetLength();
			if ((lts >= tIntvStart and lts < tIntvEnd) or 
					(lte >  tIntvStart and lte <= tIntvEnd) or
					(lqs >= qIntvStart and lqs < qIntvEnd) or
					(lqe >  qIntvStart and lqe <= qIntvEnd)) {
				ovpFound = 1;
				break;
			}
		}
		if (!ovpFound) {
			noOvpLis.push_back(lis[i]);
		}
	}
	
	//
	// Now, the matches are found in order of size, but they need to
	// be stored in order of text.
	//
	SortMatchPosList(noOvpLis);

	//
	// The match pos list was sorted in order of weight. 
	// Just in case it causes problems down the line, re-sort it 
	// according to query pos.
	//
	lis = noOvpLis;
	SortMatchPosList(lis);
}
Exemple #16
0
void ScaleHMM::EM(int* maxiter, int* maxtime, double* eps)
{
	//FILE_LOG(logDEBUG2) << __PRETTY_FUNCTION__;

	double logPold = -INFINITY;
	double logPnew;
	double** gammaold = CallocDoubleMatrix(this->N, this->T);

	// Parallelization settings
// 	omp_set_nested(1);
	
	// measuring the time
	this->EMStartTime_sec = time(NULL);

	// Print some initial information
	if (this->xvariate == UNIVARIATE)
	{
		//FILE_LOG(logINFO) << "";
		//FILE_LOG(logINFO) << "INITIAL PARAMETERS";
// 		this->print_uni_params();
		this->print_uni_iteration(0);
	}
	else if (this->xvariate == MULTIVARIATE)
	{
		this->print_multi_iteration(0);
	}

	R_CheckUserInterrupt();

	// Do the Baum-Welch and updates
	int iteration = 0;
	while (((this->EMTime_real < *maxtime) or (*maxtime < 0)) and ((iteration < *maxiter) or (*maxiter < 0)))
	{

		iteration++;
		
		try { this->baumWelch(); } catch(...) { throw; }
		logPnew = this->logP;
		this->dlogP = logPnew - logPold;

		if (this->xvariate == UNIVARIATE)
		{
// 			clock_t clocktime = clock(), dtime;
			// difference in posterior
			//FILE_LOG(logDEBUG1) << "Calculating differences in posterior in EM()";
			double postsum = 0.0;
			for (int t=0; t<this->T; t++)
			{
				for (int iN=0; iN<this->N; iN++)
				{
					postsum += fabs(this->gamma[iN][t] - gammaold[iN][t]);
					gammaold[iN][t] = this->gamma[iN][t];
				}
			}
			this->sumdiff_posterior = postsum;
// 			dtime = clock() - clocktime;
// 			//FILE_LOG(logDEBUG) << "differences in posterior: " << dtime << " clicks";
		}

		R_CheckUserInterrupt();

		// Print information about current iteration
		if (this->xvariate == UNIVARIATE)
		{
			this->print_uni_iteration(iteration);
		}
		else if (this->xvariate == MULTIVARIATE)
		{
			this->print_multi_iteration(iteration);
		}

		// Check convergence
		if((fabs(this->dlogP) < *eps) && (this->dlogP < INFINITY)) //it has converged
		{
			//FILE_LOG(logINFO) << "Convergence reached!\n";
			Rprintf("Convergence reached!\n");
			break;
		}
		else
		{ // not converged
			this->EMTime_real = difftime(time(NULL),this->EMStartTime_sec);
			if (iteration == *maxiter)
			{
				//FILE_LOG(logINFO) << "Maximum number of iterations reached!";
				Rprintf("Maximum number of iterations reached!\n");
				break;
			}
			else if ((this->EMTime_real >= *maxtime) and (*maxtime >= 0))
			{
				//FILE_LOG(logINFO) << "Exceeded maximum time!";
				Rprintf("Exceeded maximum time!\n");
				break;
			}
			logPold = logPnew;
		}
		
// 		// Check weights
// 		double weights [this->N];
// 		double sumweights=0;
// 		this->calc_weights(weights);
// 		for (int iN=0; iN<this->N; iN++)
// 		{
// 			//FILE_LOG(logERROR) << "weights["<<iN<<"] = " << weights[iN];
// 			sumweights += weights[iN];
// 		}
// 		//FILE_LOG(logERROR) << "sumweights = " << sumweights;
// 		

		// Updating initial probabilities proba and transition matrix A
		for (int iN=0; iN<this->N; iN++)
		{
			this->proba[iN] = this->gamma[iN][0];
			//FILE_LOG(logDEBUG4) << "sumgamma["<<iN<<"] = " << sumgamma[iN];
			if (this->sumgamma[iN] == 0)
			{
				//FILE_LOG(logINFO) << "Not reestimating A["<<iN<<"][x] because sumgamma["<<iN<<"] = 0";
// 				Rprintf("Not reestimating A[%d][x] because sumgamma[%d] = 0\n", iN, iN);
			}
			else
			{
				for (int jN=0; jN<this->N; jN++)
				{
					//FILE_LOG(logDEBUG4) << "sumxi["<<iN<<"]["<<jN<<"] = " << sumxi[iN][jN];
					this->A[iN][jN] = this->sumxi[iN][jN] / this->sumgamma[iN];
					if (std::isnan(this->A[iN][jN]))
					{
						//FILE_LOG(logERROR) << "updating transition probabilities";
						//FILE_LOG(logERROR) << "A["<<iN<<"]["<<jN<<"] = " << A[iN][jN];
						//FILE_LOG(logERROR) << "sumxi["<<iN<<"]["<<jN<<"] = " << sumxi[iN][jN];
						//FILE_LOG(logERROR) << "sumgamma["<<iN<<"] = " << sumgamma[iN];
						throw nan_detected;
					}
				}
			}
		}

		if (this->xvariate == UNIVARIATE)
		{
// 			clock_t clocktime = clock(), dtime;
// 
// 			// Update all distributions independently
// 			for (int iN=0; iN<this->N; iN++)
// 			{
// 				this->densityFunctions[iN]->update(this->gamma[iN]);
// 			}

			// Update distribution of independent states first, set others as multiples of 'monosomy'
			// This loop assumes that the dependent negative binomial states come last and are consecutive
			int xsomy = 1;
			for (int iN=0; iN<this->N; iN++)
			{
				if (this->densityFunctions[iN]->get_name() == ZERO_INFLATION) {}
				if (this->densityFunctions[iN]->get_name() == GEOMETRIC)
				{
					this->densityFunctions[iN]->update(this->gamma[iN]);
				}
				if (this->densityFunctions[iN]->get_name() == NEGATIVE_BINOMIAL)
				{
					if (xsomy==1)
					{
						//FILE_LOG(logDEBUG1) << "mean(state="<<iN<<") = " << this->densityFunctions[iN]->get_mean() << ", var(state="<<iN<<") = " << this->densityFunctions[iN]->get_variance();
						this->densityFunctions[iN]->update_constrained(this->gamma, iN, this->N);
						double mean1 = this->densityFunctions[iN]->get_mean();
						double variance1 = this->densityFunctions[iN]->get_variance();
						//FILE_LOG(logDEBUG1) << "mean(state="<<iN<<") = " << this->densityFunctions[iN]->get_mean() << ", var(state="<<iN<<") = " << this->densityFunctions[iN]->get_variance();
						// Set others as multiples
						for (int jN=iN+1; jN<this->N; jN++)
						{
							this->densityFunctions[jN]->set_mean(mean1 * (jN-iN+1));
							this->densityFunctions[jN]->set_variance(variance1 * (jN-iN+1));
							//FILE_LOG(logDEBUG1) << "mean(state="<<jN<<") = " << this->densityFunctions[jN]->get_mean() << ", var(state="<<jN<<") = " << this->densityFunctions[jN]->get_variance();
						}
						break;
					}
					xsomy++;
				}
			}
// 			dtime = clock() - clocktime;
// 			//FILE_LOG(logDEBUG) << "updating distributions: " << dtime << " clicks";
			R_CheckUserInterrupt();
		}

	} /* main loop end */
    
    
	//Print the last results
	//FILE_LOG(logINFO) << "";
	//FILE_LOG(logINFO) << "FINAL ESTIMATION RESULTS";
// 	this->print_uni_params();

	// free memory
	FreeDoubleMatrix(gammaold, this->N);

	// Return values
	*maxiter = iteration;
	*eps = this->dlogP;
	this->EMTime_real = difftime(time(NULL),this->EMStartTime_sec);
	*maxtime = this->EMTime_real;
}
Exemple #17
0
// checks basic properties of the convolution result
void Dip2::test_spatialConvolution(void){

   Mat input = Mat::ones(9,9, CV_32FC1);
   input.at<float>(4,4) = 255;
   Mat kernel = Mat(3,3, CV_32FC1, 1./9.);

   Mat output = spatialConvolution(input, kernel);
   
   if ( (input.cols != output.cols) || (input.rows != output.rows) ){
      cout << "ERROR: Dip2::spatialConvolution(): input.size != output.size --> Wrong border handling?" << endl;
      return;
   }
  if ( (sum(output.row(0) < 0).val[0] > 0) or
           (sum(output.row(0) > 255).val[0] > 0) or
           (sum(output.row(8) < 0).val[0] > 0) or
           (sum(output.row(8) > 255).val[0] > 0) or
           (sum(output.col(0) < 0).val[0] > 0) or
           (sum(output.col(0) > 255).val[0] > 0) or
           (sum(output.col(8) < 0).val[0] > 0) or
           (sum(output.col(8) > 255).val[0] > 0) ){
         cout << "ERROR: Dip2::spatialConvolution(): Border of convolution result contains too large/small values --> Wrong border handling?" << endl;
         return;
   }else{
      if ( (sum(output < 0).val[0] > 0) or
         (sum(output > 255).val[0] > 0) ){
            cout << "ERROR: Dip2::spatialConvolution(): Convolution result contains too large/small values!" << endl;
            return;
      }
   }
   float ref[9][9] = {{0, 0, 0, 0, 0, 0, 0, 0, 0},
                      {0, 1, 1, 1, 1, 1, 1, 1, 0},
                      {0, 1, 1, 1, 1, 1, 1, 1, 0},
                      {0, 1, 1, (8+255)/9., (8+255)/9., (8+255)/9., 1, 1, 0},
                      {0, 1, 1, (8+255)/9., (8+255)/9., (8+255)/9., 1, 1, 0},
                      {0, 1, 1, (8+255)/9., (8+255)/9., (8+255)/9., 1, 1, 0},
                      {0, 1, 1, 1, 1, 1, 1, 1, 0},
                      {0, 1, 1, 1, 1, 1, 1, 1, 0},
                      {0, 0, 0, 0, 0, 0, 0, 0, 0}};
   for(int y=1; y<8; y++){
      for(int x=1; x<8; x++){
         if (abs(output.at<float>(y,x) - ref[y][x]) > 0.0001){
            cout << "ERROR: Dip2::spatialConvolution(): Convolution result contains wrong values!" << endl;
            return;
         }
      }
   }
   input.setTo(0);
   input.at<float>(4,4) = 255;
   kernel.setTo(0);
   kernel.at<float>(0,0) = -1;
   output = spatialConvolution(input, kernel);
   if ( abs(output.at<float>(5,5) + 255.) < 0.0001 ){
      cout << "ERROR: Dip2::spatialConvolution(): Is filter kernel \"flipped\" during convolution? (Check lecture/exercise slides)" << endl;
      return;
   }
   if ( ( abs(output.at<float>(2,2) + 255.) < 0.0001 ) || ( abs(output.at<float>(4,4) + 255.) < 0.0001 ) ){
      cout << "ERROR: Dip2::spatialConvolution(): Is anchor point of convolution the centre of the filter kernel? (Check lecture/exercise slides)" << endl;
      return;
   }
   cout << "Message: Dip2::spatialConvolution() seems to be correct" << endl;
}
void log_stepping_movie_data(FILE* data_file, void* dyn, State s, long long iteration) {
  static int buffer_position = 0;
  if (!am_only_writing_on_crash or (am_debugging_onebound and s != BOTHBOUND)) {
    if (--num_movie_writes > 0) {
      if (num_movie_writes == 1) printf("about to exceed movie printing line #\n");
      const char *format = "%d\t"
	"%.10g\t"
	"%.2g\t%.2g\t%.2g\t%.2g\t%.2g\t"
	"%g\t%g\t%g\t%g\t"
	"%g\t%g\t%g\t%g\t"
	"%g\t%g\t"
	"%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g"
	"\n";
      if (s == NEARBOUND or s == FARBOUND) {
	Dynein_onebound* dyn_ob = (Dynein_onebound*) dyn;
	onebound_forces dyn_ob_f = dyn_ob->get_internal();
	fprintf(data_file, format,
		dyn_ob->get_state(),
		iteration*dt,
		dyn_ob->PE_bba, dyn_ob->PE_bma, dyn_ob->PE_ta, dyn_ob->PE_uma, 0.0,
		dyn_ob->get_bbx(), dyn_ob->get_bby(), dyn_ob->get_bmx(), dyn_ob->get_bmy(),
		dyn_ob->get_tx(), dyn_ob->get_ty(), dyn_ob->get_umx(), dyn_ob->get_umy(),
		dyn_ob->get_ubx(), dyn_ob->get_uby(),
		dyn_ob_f.bbx, dyn_ob_f.bby, dyn_ob_f.bmx, dyn_ob_f.bmy, dyn_ob_f.tx,
		dyn_ob_f.ty, dyn_ob_f.umx, dyn_ob_f.umy, dyn_ob_f.ubx, dyn_ob_f.uby);
      }
      else if (s == BOTHBOUND) {
	Dynein_bothbound* dyn_bb = (Dynein_bothbound*) dyn;
	bothbound_forces dyn_bb_f = dyn_bb->get_internal();
	fprintf(data_file, format,
		BOTHBOUND,
		iteration*dt,
		dyn_bb->PE_nba, dyn_bb->PE_nma, dyn_bb->PE_ta, dyn_bb->PE_fma, dyn_bb->PE_fba,
		dyn_bb->get_nbx(), dyn_bb->get_nby(), dyn_bb->get_nmx(), dyn_bb->get_nmy(),
		dyn_bb->get_tx(), dyn_bb->get_ty(), dyn_bb->get_fmx(), dyn_bb->get_fmy(),
		dyn_bb->get_fbx(), dyn_bb->get_fby(),
		dyn_bb_f.nbx, dyn_bb_f.nby, dyn_bb_f.nmx, dyn_bb_f.nmy, dyn_bb_f.tx,
		dyn_bb_f.ty, dyn_bb_f.fmx, dyn_bb_f.fmy, dyn_bb_f.fbx, dyn_bb_f.fby);
      }
      else if (s != UNBOUND){
	printf("Unhandled state in stepping movie data generation!\n");
	exit(1);
      }
    }
  }
  else { // else write to on-crash-print buffer structs
    if (buffer_position == MOVIE_BUFFER_SIZE) {
      movie_data_struct* temp_ptr;
      temp_ptr = on_crash_old_movie_data_global_ptr;
      on_crash_old_movie_data_global_ptr = on_crash_new_movie_data_global_ptr;
      on_crash_new_movie_data_global_ptr = temp_ptr;
      zero_movie_struct(on_crash_new_movie_data_global_ptr);
      buffer_position = 0;
    }

    movie_data_struct* new_movie_buffer = on_crash_new_movie_data_global_ptr;

    if (s == NEARBOUND or s == FARBOUND) {
      Dynein_onebound* dyn_ob = (Dynein_onebound*) dyn;
      onebound_forces dyn_ob_f = dyn_ob->get_internal();
      new_movie_buffer[buffer_position].state = dyn_ob->get_state();
      new_movie_buffer[buffer_position].time = iteration*dt;
      new_movie_buffer[buffer_position].PE_1 = dyn_ob->PE_bba;
      new_movie_buffer[buffer_position].PE_2 = dyn_ob->PE_bma;
      new_movie_buffer[buffer_position].PE_3 = dyn_ob->PE_uma;
      new_movie_buffer[buffer_position].PE_4 = 0.0;

      new_movie_buffer[buffer_position].x_1 = dyn_ob->get_bbx();
      new_movie_buffer[buffer_position].x_2 = dyn_ob->get_bmx();
      new_movie_buffer[buffer_position].x_3 = dyn_ob->get_tx();
      new_movie_buffer[buffer_position].x_4 = dyn_ob->get_umx();
      new_movie_buffer[buffer_position].x_5 = dyn_ob->get_ubx();
      new_movie_buffer[buffer_position].y_1 = dyn_ob->get_bby();
      new_movie_buffer[buffer_position].y_2 = dyn_ob->get_bmy();
      new_movie_buffer[buffer_position].y_3 = dyn_ob->get_ty();
      new_movie_buffer[buffer_position].y_4 = dyn_ob->get_umy();
      new_movie_buffer[buffer_position].y_5 = dyn_ob->get_uby();

      new_movie_buffer[buffer_position].fx_1 = dyn_ob_f.bbx;
      new_movie_buffer[buffer_position].fx_2 = dyn_ob_f.bmx;
      new_movie_buffer[buffer_position].fx_3 = dyn_ob_f.tx;
      new_movie_buffer[buffer_position].fx_4 = dyn_ob_f.umx;
      new_movie_buffer[buffer_position].fx_5 = dyn_ob_f.ubx;
      new_movie_buffer[buffer_position].fy_1 = dyn_ob_f.bby;
      new_movie_buffer[buffer_position].fy_2 = dyn_ob_f.bmy;
      new_movie_buffer[buffer_position].fy_3 = dyn_ob_f.ty;
      new_movie_buffer[buffer_position].fy_4 = dyn_ob_f.umy;
      new_movie_buffer[buffer_position].fy_5 = dyn_ob_f.uby;
    }
    else if (s == BOTHBOUND) {
      Dynein_bothbound* dyn_bb = (Dynein_bothbound*) dyn;
      bothbound_forces dyn_bb_f = dyn_bb->get_internal();
      new_movie_buffer[buffer_position].state = BOTHBOUND;
      new_movie_buffer[buffer_position].time = iteration*dt;
      new_movie_buffer[buffer_position].PE_1 = dyn_bb->PE_nba;
      new_movie_buffer[buffer_position].PE_2 = dyn_bb->PE_nma;
      new_movie_buffer[buffer_position].PE_3 = dyn_bb->PE_fma;
      new_movie_buffer[buffer_position].PE_4 = dyn_bb->PE_fba;

      new_movie_buffer[buffer_position].x_1 = dyn_bb->get_nbx();
      new_movie_buffer[buffer_position].x_2 = dyn_bb->get_nmx();
      new_movie_buffer[buffer_position].x_3 = dyn_bb->get_tx();
      new_movie_buffer[buffer_position].x_4 = dyn_bb->get_fmx();
      new_movie_buffer[buffer_position].x_5 = dyn_bb->get_fbx();
      new_movie_buffer[buffer_position].y_1 = dyn_bb->get_nby();
      new_movie_buffer[buffer_position].y_2 = dyn_bb->get_nmy();
      new_movie_buffer[buffer_position].y_3 = dyn_bb->get_ty();
      new_movie_buffer[buffer_position].y_4 = dyn_bb->get_fmy();
      new_movie_buffer[buffer_position].y_5 = dyn_bb->get_fby();

      new_movie_buffer[buffer_position].fx_1 = dyn_bb_f.nbx;
      new_movie_buffer[buffer_position].fx_2 = dyn_bb_f.nmx;
      new_movie_buffer[buffer_position].fx_3 = dyn_bb_f.tx;
      new_movie_buffer[buffer_position].fx_4 = dyn_bb_f.fmx;
      new_movie_buffer[buffer_position].fx_5 = dyn_bb_f.fbx;
      new_movie_buffer[buffer_position].fy_1 = dyn_bb_f.nby;
      new_movie_buffer[buffer_position].fy_2 = dyn_bb_f.nmy;
      new_movie_buffer[buffer_position].fy_3 = dyn_bb_f.ty;
      new_movie_buffer[buffer_position].fy_4 = dyn_bb_f.fmy;
      new_movie_buffer[buffer_position].fy_5 = dyn_bb_f.fby;
    }
    buffer_position++;
  }
}
Exemple #19
0
static gboolean
calf_vumeter_expose (GtkWidget *widget, GdkEventExpose *event)
{
    g_assert(CALF_IS_VUMETER(widget));

    CalfVUMeter *vu = CALF_VUMETER(widget);
    cairo_t *c = gdk_cairo_create(GDK_DRAWABLE(widget->window));

    float r, g, b;

    int x = widget->allocation.x;
    int y = widget->allocation.y;
    int width = widget->allocation.width;
    int height = widget->allocation.height;
    int border_x = widget->style->xthickness;
    int border_y = widget->style->ythickness;
    int space_x = 1;
    int space_y = 1; // inner border around led bar
    int led = 2; // single LED size
    int led_m = 1; // margin between LED
    int led_s = led + led_m; // size of LED with margin
    int led_x = widget->style->xthickness;
    int led_y = widget->style->ythickness; // position of first LED
    int led_w = width - 2 * led_x + led_m; // width of LED bar w/o text calc (additional led margin, is removed later; used for filling the led bar completely w/o margin gap)
    int led_h = height - 2 * led_y; // height of LED bar w/o text calc
    int text_x = 0;
    int text_y = 0;
    int text_w = 0;
    int text_h = 0;

    // only valid if vumeter is enabled
    cairo_text_extents_t extents;

    if(vu->vumeter_position) {
        cairo_select_font_face(c, "cairo:sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
        cairo_set_font_size(c, 8);

        cairo_text_extents(c, "-88.88", &extents);
        text_w = extents.width;
        text_h = extents.height;
        switch(vu->vumeter_position) {
        case 1:
            text_x = width / 2 - text_w / 2;
            text_y = border_y + led_y - extents.y_bearing;
            led_y += text_h + led_y;
            led_h -= text_h + led_y;
            break;
        case 2:
            text_x = width - border_x - led_x - text_w;
            text_y = height / 2 - text_h / 2 - extents.y_bearing;
            led_w -= led_x + text_w;
            break;
        case 3:
            text_x = width / 2 - text_w / 2;
            text_y = height - border_y - led_y - text_h - extents.y_bearing;
            led_h -= led_y + text_h;
            break;
        case 4:
            text_x = border_x + led_x;
            text_y = height / 2 - text_h / 2 - extents.y_bearing;
            led_x += led_x + text_w;
            led_w -= led_x + text_w;
            break;
        }
    }

    led_w -= led_w % led_s + led_m; //round LED width to LED size and remove margin gap, width is filled with LED without margin gap now

    if( vu->cache_surface == NULL ) {
        // looks like its either first call or the widget has been resized.
        // create the cache_surface.
        vu->cache_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height );
        cairo_t *cache_cr = cairo_create( vu->cache_surface );

        float radius, bevel;
        get_bg_color(widget, NULL, &r, &g, &b);
        gtk_widget_style_get(widget, "border-radius", &radius, "bevel",  &bevel, NULL);
        create_rectangle(cache_cr, 0, 0, width, height, radius);
        cairo_set_source_rgb(cache_cr, r, g, b);
        cairo_fill(cache_cr);
        draw_bevel(cache_cr, 0, 0, width, height, radius, bevel);

        // border around LED
        cairo_rectangle(cache_cr, led_x, led_y, led_w, led_h);
        cairo_set_source_rgb (cache_cr, 0, 0, 0);
        cairo_fill(cache_cr);

        led_x += space_x;
        led_y += space_y;
        led_w -= 2 * space_x;
        led_h -= 2 * space_y;

        // LED bases
        cairo_set_line_width(cache_cr, 1);
        for (int x = led_x; x + led <= led_x + led_w; x += led_s)
        {
            float ts = (x - led_x) * 1.0 / led_w;
            float r = 0.f, g = 0.f, b = 0.f;
            switch(vu->mode)
            {
            case VU_STANDARD:
            default:
                if (ts < 0.75)
                    r = ts / 0.75, g = 0.5 + ts * 0.66, b = 1 - ts / 0.75;
                else
                    r = 1, g = 1 - (ts - 0.75) / 0.25, b = 0;
                //                if (vu->value < ts || vu->value <= 0)
                //                    r *= 0.5, g *= 0.5, b *= 0.5;
                break;
            case VU_STANDARD_CENTER:
                if (ts < 0.25)
                    // 0.0 -> 0.25
                    // green: 0.f -> 1.f
                    r = 1, g = (ts) / 0.25, b = 0;
                else if (ts > 0.75)
                    // 0.75 -> 1.0
                    // green: 1.f -> 0.f
                    r = 1, g = 1 - (ts - 0.75) / 0.25, b = 0;
                else if (ts > 0.5)
                    // 0.5 -> 0.75
                    // red: 0.f -> 1.f
                    // green: 0.5 -> 1.f
                    // blue: 1.f -> 0.f
                    r = (ts - 0.5) / 0.25, g = 0.5 + (ts - 0.5) * 2.f, b = 1 - (ts - 0.5) / 0.25;
                else
                    // 0.25 -> 0.5
                    // red: 1.f -> 0.f
                    // green: 1.f -> 0.5
                    // blue: 0.f -> 1.f
                    r = 1 - (ts - 0.25) / 0.25, g = 1.f - (ts * 2.f - .5f), b = (ts - 0.25) / 0.25;
                //                if (vu->value < ts || vu->value <= 0)
                //                    r *= 0.5, g *= 0.5, b *= 0.5;
                break;
            case VU_MONOCHROME_REVERSE:
                r = 0, g = 170.0 / 255.0, b = 1;
                //                if (!(vu->value < ts) || vu->value >= 1.0)
                //                    r *= 0.5, g *= 0.5, b *= 0.5;
                break;
            case VU_MONOCHROME:
                r = 0, g = 170.0 / 255.0, b = 1;
                //                if (vu->value < ts || vu->value <= 0)
                //                    r *= 0.5, g *= 0.5, b *= 0.5;
                break;
            case VU_MONOCHROME_CENTER:
                r = 0, g = 170.0 / 255.0, b = 1;
                //                if (vu->value < ts || vu->value <= 0)
                //                    r *= 0.5, g *= 0.5, b *= 0.5;
                break;
            }
            GdkColor sc2 = { 0, (guint16)(65535 * r + 0.2), (guint16)(65535 * g), (guint16)(65535 * b) };
            GdkColor sc3 = { 0, (guint16)(65535 * r * 0.7), (guint16)(65535 * g * 0.7), (guint16)(65535 * b * 0.7) };
            gdk_cairo_set_source_color(cache_cr, &sc2);
            cairo_move_to(cache_cr, x + 0.5, led_y);
            cairo_line_to(cache_cr, x + 0.5, led_y + led_h);
            cairo_stroke(cache_cr);
            gdk_cairo_set_source_color(cache_cr, &sc3);
            cairo_move_to(cache_cr, x + 1.5, led_y + led_h);
            cairo_line_to(cache_cr, x + 1.5, led_y);
            cairo_stroke(cache_cr);
        }
        // create blinder pattern
        cairo_pattern_t *pat = cairo_pattern_create_linear (led_x, led_y, led_x, led_y + led_h);
        cairo_pattern_add_color_stop_rgba (pat, 0, 1, 1, 1, 0.25);
        cairo_pattern_add_color_stop_rgba (pat, 0.5, 0.5, 0.5, 0.5, 0.0);
        cairo_pattern_add_color_stop_rgba (pat, 1, 0.0, 0.0, 0.0, 0.25);
        cairo_rectangle(cache_cr, led_x, led_y, led_w, led_h);
        cairo_set_source(cache_cr, pat);
        cairo_fill(cache_cr);

        // create overlay
        vu->cache_overlay = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
        cairo_t *over_cr = cairo_create(vu->cache_overlay);

        // copy surface to overlay
        cairo_set_source_surface(over_cr, vu->cache_surface, 0, 0);
        cairo_rectangle(over_cr, 0, 0, width, height);
        cairo_fill(over_cr);

        // create blinder pattern
        pat = cairo_pattern_create_linear (led_x, led_y, led_x, led_y + led_h);
        cairo_pattern_add_color_stop_rgba (pat, 0, 0.2, 0.2, 0.2, 0.7);
        cairo_pattern_add_color_stop_rgba (pat, 0.4, 0.05, 0.05, 0.05, 0.7);
        cairo_pattern_add_color_stop_rgba (pat, 0.401, 0.05, 0.05, 0.05, 0.9);
        cairo_pattern_add_color_stop_rgba (pat, 1, 0.05, 0.05, 0.05, 0.75);

        // draw on top of overlay
        cairo_set_source(over_cr, pat);
        cairo_rectangle(over_cr, 0, 0, width, height);
        cairo_paint(over_cr);

        // clean up
        cairo_destroy(cache_cr);
        cairo_destroy(over_cr);
    } else {
        led_x += space_x;
        led_y += space_y;
        led_w -= 2 * space_x;
        led_h -= 2 * space_y;
    }
    led_x += x;
    led_y += y;
    text_x += x;
    text_y += y;
    // draw LED blinder
    cairo_set_source_surface( c, vu->cache_surface, x, y );
    cairo_paint( c );
    cairo_set_source_surface( c, vu->cache_overlay, x, y );

    // get microseconds
    timeval tv;
    gettimeofday(&tv, 0);
    long time = tv.tv_sec * 1000 * 1000 + tv.tv_usec;

    // limit to 1.f
    float value_orig = std::max(std::min(vu->value, 1.f), 0.f);
    float value = 0.f;

    // falloff?
    if(vu->vumeter_falloff > 0.f and vu->mode != VU_MONOCHROME_REVERSE) {
        // fall off a bit
        float s = ((float)(time - vu->last_falltime) / 1000000.0);
        float m = vu->last_falloff * s * vu->vumeter_falloff;
        vu->last_falloff -= m;
        // new max value?
        if(value_orig > vu->last_falloff) {
            vu->last_falloff = value_orig;
        }
        value = vu->last_falloff;
        vu->last_falltime = time;
        vu->falling = vu->last_falloff > 0.00000001;
    } else {
        // falloff disabled
        vu->last_falloff = 0.f;
        vu->last_falltime = 0.f;
        value = value_orig;
        vu->falling = false;
    }

    float draw = 0.f;
    float draw_last = 0.f;

    if(vu->vumeter_hold > 0.0) {
        // peak hold timer
        if(time - (long)(vu->vumeter_hold * 1000 * 1000) > vu->last_hold) {
            // time's up, reset
            vu->last_value = value;
            vu->last_hold = time;
            vu->holding = false;
            vu->disp_value = value_orig;
        }
        if( vu->mode == VU_MONOCHROME_REVERSE ) {
            if(value < vu->last_value) {
                // value is above peak hold
                vu->last_value = value;
                vu->last_hold = time;
                vu->holding = true;
            }
            draw = log10(1 + value * 9);
            draw_last = log10(1 + vu->last_value * 9);

            // blinder left -> hold LED
            int hold_x = round((draw_last) * (led_w + led_m)); // add last led_m removed earlier
            hold_x -= hold_x % led_s + led_m;
            hold_x = std::max(0, hold_x);
            cairo_rectangle( c, led_x, led_y, hold_x, led_h);

            // blinder hold LED -> value
            int val_x = round((1 - draw) * (led_w + led_m)); // add last led_m removed earlier
            val_x -= val_x % led_s;
            int blind_x = std::min(hold_x + led_s, led_w);
            int blind_w = std::min(std::max(led_w - val_x - hold_x - led_s, 0), led_w);
            cairo_rectangle(c, led_x + blind_x, led_y, blind_w, led_h);
        } else  if( vu->mode == VU_STANDARD_CENTER ) {
            if(value > vu->last_value) {
                // value is above peak hold
                vu->last_value = value;
                vu->last_hold = time;
                vu->holding = true;
            }
            draw = log10(1 + value * 9);
            int val_x = round((1 - draw) / 2.f * (led_w + led_m)); // add last led_m removed earlier
            cairo_rectangle(c, led_x, led_y, val_x, led_h);
            cairo_rectangle(c, led_x + led_w - val_x, led_y, val_x, led_h);

        } else {
            if(value > vu->last_value) {
                // value is above peak hold
                vu->last_value = value;
                vu->last_hold = time;
                vu->holding = true;
            }
            draw = log10(1 + value * 9);
            draw_last = log10(1 + vu->last_value * 9);

            int hold_x = round((1 - draw_last) * (led_w + led_m)); // add last led_m removed earlier
            hold_x -= hold_x % led_s;
            int val_x = round(draw * (led_w + led_m)); // add last led_m removed earlier
            val_x -= val_x % led_s;
            int blind_w = led_w - hold_x - led_s - val_x;
            blind_w = std::min(std::max(blind_w, 0), led_w);
            cairo_rectangle(c, led_x + val_x, led_y, blind_w, led_h);
            cairo_rectangle( c, led_x + led_w - hold_x, led_y, hold_x, led_h);
        }
    } else {
        // darken normally
        float draw = log10(1 + value * 9);
        if( vu->mode == VU_MONOCHROME_REVERSE )
            cairo_rectangle( c, led_x, led_y, draw * led_w, led_h);
        else if( vu->mode == VU_STANDARD_CENTER ) {
            int val_x = round((1 - draw) / 2.f * (led_w + led_m)); // add last led_m removed earlier
            cairo_rectangle(c, led_x, led_y, val_x, led_h);
            cairo_rectangle(c, led_x + led_w - val_x, led_y, val_x, led_h);
        } else
            cairo_rectangle( c, led_x + draw * led_w, led_y, led_w * (1 - draw), led_h);
    }
    cairo_fill( c );

    if (vu->vumeter_position)
    {
        char str[32];
        if((vu->value > vu->disp_value and vu->mode != VU_MONOCHROME_REVERSE)
                or (vu->value < vu->disp_value and vu->mode == VU_MONOCHROME_REVERSE))
            vu->disp_value = vu->value;
        if (vu->disp_value < 1.0 / 32768.0)
            snprintf(str, sizeof(str), "-inf");
        else
            snprintf(str, sizeof(str), "%0.2f", dsp::amp2dB(vu->disp_value));
        // draw value as number
        cairo_text_extents(c, str, &extents);
        cairo_move_to(c, text_x + (text_w - extents.width) / 2.0, text_y);
        GtkStateType state;
        if(vu->disp_value > 1.f and vu->mode != VU_MONOCHROME_REVERSE)
            state = GTK_STATE_ACTIVE;
        else
            state = GTK_STATE_NORMAL;
        get_fg_color(widget, &state, &r, &g, &b);
        cairo_set_source_rgba (c, r, g, b, 1);
        cairo_show_text(c, str);
        cairo_fill(c);
    }
    cairo_destroy(c);
    //gtk_paint_shadow(widget->style, widget->window, GTK_STATE_NORMAL, GTK_SHADOW_IN, NULL, widget, NULL, ox - 2, oy - 2, sx + 4, sy + 4);
    //printf("exposed %p %d+%d\n", widget->window, widget->allocation.x, widget->allocation.y);

    return TRUE;
}
Exemple #20
0
void RandomForest::recAssignNode(Node* pNode, vector<pair<int,int> >& idx_orig, string pre, int depth, int& node_cnt, double& tree_gini) {
   double best_ig=-1;
   int best_attr=-1;
   bool rand_best_f = false;
   double best_cutVal=0.5;
   vector<vector<int> > best_a_l_cnt(2,vector<int>(2,0));
   vector<pair<int,int> > idx0, idx1;
   idx0.empty();
   idx1.empty();
   pNode->node0 = NULL;
   pNode->node1 = NULL;

   vector<int> features;
   int feature_sample_cnt = (int)((double)base_feature_sample_cnt_ * pow(progressive_factor_,depth));
   if(feature_sample_cnt > good_features_.size()) feature_sample_cnt = good_features_.size();
   create_feature_list(features, feature_sample_cnt, good_features_);
   if(debug && 0) {
      int last=-1;
      for(int i=0; i<features.size(); i++) {
         if(features[i] == last) cerr << endl << "ERROR: repeat feature" << endl;
         last = features[i];
         cerr << features[i] << ",";
      }
      cerr << endl;
   }
   vector<vector<int> > a_l_cnt(2,vector<int>(2,0));
   double cutVal;
   double ig=-1;
   int approach = 1;
   vector<f_ig_cut> vBestF;
   int step_size = (int)(0.01*(double)idx_orig.size());
   if(step_size < 1) step_size = 1;
   for(int attr_idx = 0; attr_idx < feature_sample_cnt; attr_idx++) {
      //double cutVal = (double)((rand() % 1000)+1)/(double)(1001);
      //cerr << features[attr_idx] << ":" << pXD_->attr_class[features[attr_idx]] << ":" << pXD_->attr_class.size() << endl;
      if(pXD_->attr_class[features[attr_idx]] == 1 and approach == 1) {
         double best_ig = -1;
         vector<pair<int,double> > attr_sort_idx(idx_orig.size(),pair<int,double>(0,0.0));
         a_l_cnt.assign(2,vector<int>(2,0));
         for(int exi = 0; exi < idx_orig.size(); exi++) {
            attr_sort_idx[exi] = pair<int,double>(exi,pXD_->trn_attr[idx_orig[exi].first][features[attr_idx]]);
            a_l_cnt[1][(int)pXD_->trn_labl[idx_orig[exi].first]] += idx_orig[exi].second;
         }
         sort(attr_sort_idx.begin(),attr_sort_idx.end(),idx_double_sort);
         int ex_id, ex_id_next, ex_cnt, labl;
         double attr_val;
         for(int exii = 0; exii < (attr_sort_idx.size()-step_size); exii++) {
            ex_id = idx_orig[attr_sort_idx[exii].first].first;
            ex_id_next = idx_orig[attr_sort_idx[exii+step_size].first].first;
            ex_cnt = idx_orig[attr_sort_idx[exii].first].second;
            labl = (int)pXD_->trn_labl[ex_id];
            attr_val = pXD_->trn_attr[ex_id][features[attr_idx]];
            a_l_cnt[0][labl] += ex_cnt;
            a_l_cnt[1][labl] -= ex_cnt;
            if (pXD_->trn_attr[ex_id_next][features[attr_idx]] == attr_val || (exii % step_size) != 0) continue;
            ig = infoGain(a_l_cnt);
            if(ig>best_ig) {
               best_ig = ig;
               cutVal = attr_val;  //be sure to cut at <= cutVal or > cutVal
            }
         }
         ig = best_ig;
      } else {
         a_l_cnt.assign(2,vector<int>(2,0));
         if(approach == 1 || approach == 2) {
            cutVal = pXD_->attr_avg[features[attr_idx]];
         } else {
            cutVal = (double)((rand() % 1000)+1)/(double)(1001);
         }
         int attr_split;
         for(int exi = 0; exi < idx_orig.size(); exi++) {
            attr_split = (pXD_->trn_attr[idx_orig[exi].first][features[attr_idx]] > cutVal) ? 1 : 0;
            a_l_cnt[attr_split][(int)pXD_->trn_labl[idx_orig[exi].first]] += idx_orig[exi].second;
         }
         ig = infoGain(a_l_cnt);
      }

      if(rand_best_f) {
         f_ig_cut newcut;
         newcut.ig = ig;
         newcut.attr = features[attr_idx];
         newcut.cutVal = cutVal;
         newcut.a_l_cnt = a_l_cnt;
         vBestF.push_back(newcut);
      }

      if(ig > best_ig) {
         best_ig = ig;
         best_attr = features[attr_idx];
         best_cutVal = cutVal;
         best_a_l_cnt = a_l_cnt;
      }
      //cerr << features[attr_idx] << "," << pXD_->attr_class[features[attr_idx]] << "," << ig << endl;
   }
   if(rand_best_f) {
      sort(vBestF.begin(), vBestF.end(), f_ig_cut_sort);
      int id = (int)(pow((double)(rand() % 1000)/1000.0,11) * 3 /*vBestF.size()*/); 
      //cerr << id << endl;
      //cerr << vBestF[0].ig << "," << best_ig << endl;
      best_ig = vBestF[id].ig;
      best_attr = vBestF[id].attr;
      best_cutVal = vBestF[id].cutVal;
      best_a_l_cnt = vBestF[id].a_l_cnt;
   }

   pNode->ig = best_ig;
   pNode->attr_id = best_attr;
   pNode->cutVal = best_cutVal;
   pNode->a_l_cnt = best_a_l_cnt;

   int cnt_a1=0, cnt_a0=0, onesCnt_a1=0, onesCnt_a0=0;
   for(int exi = 0; exi < idx_orig.size(); exi++) {
      if(pXD_->trn_attr[idx_orig[exi].first][best_attr] > best_cutVal) {
         idx1.push_back(idx_orig[exi]);
         onesCnt_a1 += (pXD_->trn_labl[idx_orig[exi].first] > 0.5) ? idx_orig[exi].second : 0;
         cnt_a1 += idx_orig[exi].second;
      } else {
         idx0.push_back(idx_orig[exi]);
         onesCnt_a0 += (pXD_->trn_labl[idx_orig[exi].first] > 0.5) ? idx_orig[exi].second : 0;
         cnt_a0 += idx_orig[exi].second;
      }
   }
   //double ls1=1, ls2=2; // laplace smoothing to avoid infinite values
   double ls1=0, ls2=0; // laplace smoothing to avoid infinite values
   if(cnt_a0 > 0) pNode->class_a0 = ((double)onesCnt_a0 + ls1)/((double)cnt_a0 + ls2);
   else pNode->class_a0 = 0.5;
   if(cnt_a1 > 0) pNode->class_a1 = ((double)onesCnt_a1 + ls1)/((double)cnt_a1 + ls2);
   else pNode->class_a1 = 0.5;
   pNode->exCnt = cnt_a0 + cnt_a1;
   /*
   cerr << pre << idx_orig.size() << "," << best_attr << "(" << pXD_->attr_class[best_attr] << ")," << best_ig << "," 
        << idx0.size() << "," << pNode->class_a0 << "," 
        << idx1.size() << "," << pNode->class_a1 << endl;
   */
   {
   int ls1=0, ls2=0;
   if(best_ig > 0 or (feature_sample_cnt < good_features_.size() and progressive_factor_ > 1)) {
      if(idx0.size() > 1 and onesCnt_a0 != 0 and onesCnt_a0 != cnt_a0) {
         pNode->node0 = new Node;
         recAssignNode(pNode->node0, idx0, pre + "  ", depth+1, node_cnt, tree_gini);
      } else {
         if(cnt_a0 > 0) {
            node_cnt++;
            tree_gini += (double)(cnt_a0*2*(cnt_a0-onesCnt_a0+ls1)*(onesCnt_a0+ls1)) / (double)((cnt_a0 + ls2)*(cnt_a0 + ls2));
         }
      }
      if(idx1.size() > 1 and onesCnt_a1 != 0 and onesCnt_a1 != cnt_a1) {
         pNode->node1 = new Node;
         recAssignNode(pNode->node1, idx1, pre + "  ", depth+1, node_cnt, tree_gini);
      } else {
         if(cnt_a1 > 0) {
            node_cnt++;
            tree_gini += (double)(cnt_a1*2*(cnt_a1-onesCnt_a1+ls1)*(onesCnt_a1+ls1)) / (double)((cnt_a1 + ls2)*(cnt_a1+ls2));
         }
      }
   } else {
      if(cnt_a0 > 0) {
         node_cnt += 1;
         tree_gini += (double)(cnt_a0*2*(cnt_a0-onesCnt_a0+ls1)*(onesCnt_a0+ls1)) / (double)((cnt_a0 + ls2)*(cnt_a0+ls2));
      }
      if(cnt_a1 > 0) {
         node_cnt += 1;
         tree_gini += (double)(cnt_a1*2*(cnt_a1-onesCnt_a1+ls1)*(onesCnt_a1+ls1)) / (double)((cnt_a1 + ls2)*(cnt_a1+ls2));
      }
   }
   }
}
	void WString::prepareWString(const AnyString& string, bool uncprefix)
	{
		if (string.empty())
		{
			if (uncprefix)
			{
				pSize = 4;
				pWString = (wchar_t*)::realloc(pWString, sizeof(wchar_t) * 5);
				pWString[0] = L'\\';
				pWString[1] = L'\\';
				pWString[2] = L'?';
				pWString[3] = L'\\';
				pWString[4] = L'\0';
			}
			else
				clear();
			return;
		}

		if (string.size() > INT_MAX)
		{
			clear();
			return;
		}

		// Offset according to the presence of the UNC prefix
		const uint offset = (not uncprefix) ? 0 : 4;

		#ifdef YUNI_OS_WINDOWS
		{
			// Allocate and convert the C-String. Several iterations may be required
			// for allocating enough room for the conversion.
			const int sizeRequired = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), string.size(), nullptr, 0);
			if (sizeRequired <= 0)
			{
				clear();
				return;
			}

			pSize = sizeRequired + offset;

			pWString = (wchar_t*) realloc(pWString, sizeof(wchar_t) * (pSize + 1));
			if (nullptr == pWString) // Impossible to allocate the buffer. Aborting.
			{
				clear();
				return;
			}

			// Converting into Wide String
			const int n = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), static_cast<int>(string.size()), pWString + offset, static_cast<int>(pSize - offset));
			if (n != sizeRequired)
			{
				assert(false and "most likely an error");
				clear();
				return;
			}
		}
		#else
		{
			const char* wcstr = string.c_str();

			mbstate_t state;
			memset (&state, '\0', sizeof (state));

			size_t sizeRequired = mbsnrtowcs(nullptr, &wcstr, string.size(), 0, &state);
			if (0 == sizeRequired or (size_t) -1 == sizeRequired)
			{
				clear();
				return;
			}

			pSize = sizeRequired + offset;

			pWString = (wchar_t*) realloc(pWString, sizeof(wchar_t) * (pSize + 1));
			if (nullptr == pWString) // Impossible to allocate the buffer. Aborting.
			{
				clear();
				return;
			}

			memset (&state, '\0', sizeof (state));
			size_t written = mbsnrtowcs(pWString + offset, &wcstr, string.size(), pSize - offset, &state);
			if (0 == written or (size_t) -1 == written)
			{
				clear();
				return;
			}
		}
		#endif


		// prepend the Windows UNC prefix
		if (uncprefix)
		{
			pWString[0] = L'\\';
			pWString[1] = L'\\';
			pWString[2] = L'?';
			pWString[3] = L'\\';
		}

		// always ensure that the string is zero terminated
		pWString[pSize] = L'\0';
	}
Exemple #22
0
bool ReadPairFilterQuality::useThisCycle(int cycleNum){
  return ( _useEveryCycle or (cycleNum >= _firstCycle and cycleNum < _lastCycleP1));
}
int main(int argc, char **argv)
{
  std::set<std::string> files;

  enum SHAHashType { htUnspecified, htSHA1, htSHA224, htSHA256, htSHA384, htSHA512 };

  SHAHashType hashType = htUnspecified;

  if ((argc>1) and (argv!=NULL))
  {
    int i=1;
    while (i<argc)
    {
      if (argv[i]!=NULL)
      {
        const std::string param = std::string(argv[i]);
        //help parameter
        if ((param=="--help") or (param=="-?") or (param=="/?"))
        {
          showHelp();
          return 0;
        }//if help wanted
        //version information requested?
        else if ((param=="--version") or (param=="-v"))
        {
          showVersion();
          return 0;
        }//version
        else if ((param=="--sha1") or (param=="--sha-1") or (param=="--sha160")
              or (param=="--sha-160"))
        {
          if (hashType==htSHA1)
          {
            std::cout << "Error: parameter "<<param<<" must not occur more than once!\n";
            return rcInvalidParameter;
          }
          if (hashType!=htUnspecified)
          {
            std::cout << "Error: parameter "<<param<<" must not occur after "
                      << "hash type has already been set!\n";
            return rcInvalidParameter;
          }
          hashType = htSHA1;
        }//sha-1
        else if ((param=="--sha224") or (param=="--sha-224"))
        {
          if (hashType==htSHA224)
          {
            std::cout << "Error: parameter " << param << " must not occur more than once!\n";
            return rcInvalidParameter;
          }
          if (hashType!=htUnspecified)
          {
            std::cout << "Error: parameter " << param << " must not occur "
                      << "after hash type has already been set!\n";
            return rcInvalidParameter;
          }
          hashType = htSHA224;
        }//sha-224
        else if ((param=="--sha256") or (param=="--sha-256"))
        {
          if (hashType==htSHA256)
          {
            std::cout << "Error: parameter "<<param<<" must not occur more than once!\n";
            return rcInvalidParameter;
          }
          if (hashType!=htUnspecified)
          {
            std::cout << "Error: parameter "<<param<<" must not occur after "
                      << "hash type has already been set!\n";
            return rcInvalidParameter;
          }
          hashType = htSHA256;
        }//sha-256
        else if ((param=="--sha384") or (param=="--sha-384"))
        {
          if (hashType==htSHA384)
          {
            std::cout << "Error: parameter " << param << " must not occur more than once!\n";
            return rcInvalidParameter;
          }
          if (hashType!=htUnspecified)
          {
            std::cout << "Error: parameter " << param << " must not occur "
                      << "after hash type has already been set!\n";
            return rcInvalidParameter;
          }
          hashType = htSHA384;
        }//sha-384
        else if ((param=="--sha512") or (param=="--sha-512"))
        {
          if (hashType==htSHA512)
          {
            std::cout << "Error: parameter " << param << " must not occur more than once!\n";
            return rcInvalidParameter;
          }
          if (hashType!=htUnspecified)
          {
            std::cout << "Error: parameter " << param << " must not occur "
                      << "after hash type has already been set!\n";
            return rcInvalidParameter;
          }
          hashType = htSHA512;
        }//sha-512
        else
        {
          //should be filename
          if (libstriezel::filesystem::file::exists(param))
          {
            //add file to list
            files.insert(param);
          }
          else
          {
            std::cout << "Invalid parameter/filename given: \""<<param
                      << "\" does not name an existing file!\n"
                      << "Use --help to get a list of valid parameters.\n";
            return rcInvalidParameter;
          }
        }
      }//parameter exists
      else
      {
        std::cout << "Parameter at index "<<i<<" is NULL.\n";
        return rcInvalidParameter;
      }
      ++i;//on to next parameter
    }//while
  }//if arguments present
  else
  {
    std::cout << "You have to specify certain parameters for this program to run properly.\n"
              << "Use --help to get a list of valid parameters.\n";
    return rcInvalidParameter;
  }

  if (files.empty())
  {
    std::cout << "You have to specify certain parameters for this program to run properly.\n"
              << "Use --help to get a list of valid parameters.\n";
    return rcInvalidParameter;
  }

  // Set default hash algorithm, if no choice was made.
  if (hashType==htUnspecified)
    hashType = htSHA256;

  std::cout << "Hashing file(s), this may take a while..." << std::endl;

  std::set<std::string>::const_iterator iter = files.begin();
  SHA512::MessageDigest hash512;
  SHA384::MessageDigest hash384;
  SHA256::MessageDigest hash256;
  SHA224::MessageDigest hash224;
  SHA1::MessageDigest hash160;
  while (iter!=files.end())
  {
    switch (hashType)
    {
      case htSHA1:
           hash160 = SHA1::computeFromFile(*iter);
           std::cout << hash160.toHexString() << "  " << *iter << std::endl;
           break;
      case htSHA224:
           hash224 = SHA224::computeFromFile(*iter);
           std::cout << hash224.toHexString() << "  " << *iter << std::endl;
           break;
      case htSHA384:
           hash384 = SHA384::computeFromFile(*iter);
           std::cout << hash384.toHexString() << "  " << *iter << std::endl;
           break;
      case htSHA512:
           hash512 = SHA512::computeFromFile(*iter);
           std::cout << hash512.toHexString() << "  " << *iter << std::endl;
           break;
      default:
           hash256 = SHA256::computeFromFile(*iter);
           std::cout << hash256.toHexString() << "  " << *iter << std::endl;
           break;
    }//swi
    ++iter;
  }//while

  return 0;
}