Example #1
0
FreeModule *FreeModule::tensor(const FreeModule *G) const
// tensor product
{
    if (get_ring() != G->get_ring())
    {
        ERROR("expected free modules over the same ring");
        return 0;
    }
    FreeModule *result = new_free();
    int *deg = degree_monoid()->make_one();

    for (int i=0; i<rank(); i++)
        for (int j=0; j<G->rank(); j++)
        {
            degree_monoid()->mult(degree(i), G->degree(j), deg);
            result->append(deg);
        }

    degree_monoid()->remove(deg);
    if (schreyer != NULL && G->schreyer != NULL)
        result->schreyer = schreyer->tensor(G->schreyer);
    return result;
}
Example #2
0
void print_embedding(const planar_embedding_t & planar_embedding, const Graph & G, std::vector<std::vector<Vertex> > & embedding_as_vertex_order)
{
	Graph::vertex_iterator vertexIt,vertexEnd;
	tie(vertexIt, vertexEnd) = vertices(G);
	embedding_as_vertex_order = std::vector<std::vector<Vertex> >(num_vertices(G));
	unsigned int i = 0, j = 0;
	for( ;vertexIt != vertexEnd; ++vertexIt, i++ )
	{
		j=0;
		embedding_as_vertex_order[i] = std::vector<Vertex>(degree(*vertexIt, G));
		boost::property_traits<planar_embedding_t>::value_type::iterator I = planar_embedding[*vertexIt].begin();
		std::cout<<"cyclic order of nodes around vertex " <<*vertexIt<<": ";
		for( ; I != planar_embedding[*vertexIt].end(); I++, j++)
		{
			//std::cout<<" "<<((*vertexIt == I->m_source) ? I->m_target : I->m_source);

			embedding_as_vertex_order[i][j] = ((*vertexIt == I->m_source) ? I->m_target : I->m_source);
			std::cout<<" "<<embedding_as_vertex_order[i][j];
		}
		std::cout<<std::endl;
	}
	return;
}
// doesn't return a remainder
// N.B. this function will break if there is a remainder
const Polynomial Polynomial::div( const Polynomial& rhs ) const {
  Polynomial retVal;

  if( degree() < rhs.degree() )
    {
      return retVal; // return 0
    }

  Polynomial rSide( *this );
  int rDeg = rhs.degree();
  double rCoeff = rhs._list.begin().getData().coeff;
  
  itr_t it = rSide._list.begin();
  while( 1 )
    {
      if( it == rSide._list.end() ) break;
      int deg_diff = it.getData().degree() - rDeg;
      if( deg_diff < 0 ) break; // TODO: check this condition, maybe need to put rest into remainder?
      
      double coeff = it.getData().coeff / rCoeff;
      Polynomial tmp;
      Term multiplier( coeff, deg_diff );
      retVal.addTerm( multiplier );
      
      for( itr_t itt = rhs._list.begin(); itt != rhs._list.end(); ++itt )
	{
	  Term res = itt.getData() * multiplier;
	  tmp.addTerm( res );
	}

      rSide = rSide.sub( tmp );
      it = rSide._list.begin();
    }
  
  return retVal;
}
Example #4
0
float *traffic_dist(town t, road_construction c, int n)
{
    float *dist = malloc(n*n*sizeof(float));
    t.n=n;
   // int *importance = t.importances;
    int *degrees = degree(c);
    
    for(int i = 0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            if(c.roads[n*i+j])
            {
                //printf("%d and %d also %d plus %d", t.importances[i],degrees[i], t.importances[j], degrees[j]);
                dist[n*i+j]= t.distances[n*i+j]*(1+((float)t.importances[j]/(float)degrees[j]) + ((float)t.importances[i]/degrees[i]));
                //printf("%f", dist[n*i+j]);
            }
            else
                dist[n*i+j]=INFTY;
        }
    }
   
   return dist;
}
Example #5
0
FreeModule *FreeModule::exterior(int p) const
     // p th exterior power
{
  FreeModule *result;

  int rk = rank();

  if (p == 0)
    return get_ring()->make_FreeModule(1);
  else
    result = new_free();
  if (p > rk || p < 0) return result;

  int *a = newarray_atomic(int,p);
  for (int i=0; i<p; i++)
    a[i] = i;

  int *deg = degree_monoid()->make_one();
  do
    {
      degree_monoid()->one(deg);

      for (int r=0; r<p; r++)
        degree_monoid()->mult(deg, degree(a[r]), deg);

      result->append(deg);
    }
  while (comb::increment(p, rk, a));

  degree_monoid()->remove(deg);
  deletearray(a);

  if (schreyer != NULL)
    result->schreyer = schreyer->exterior(p);
  return result;
}
Example #6
0
std::vector<GaloisFieldDict> GaloisFieldDict::gf_frobenius_monomial_base() const
{
    auto n = degree();
    std::vector<GaloisFieldDict> b;
    if (n == 0)
        return b;
    b.resize(n);
    b[0] = GaloisFieldDict::from_vec({1_z}, modulo_);
    GaloisFieldDict temp_out;
    if (mp_get_si(modulo_) < n) {
        for (unsigned i = 1; i < n; ++i) {
            b[i] = b[i - 1].gf_lshift(modulo_);
            b[i] %= (*this);
        }
    } else if (n > 1) {
        b[1] = gf_pow_mod(GaloisFieldDict::from_vec({0_z, 1_z}, modulo_),
                          modulo_);
        for (unsigned i = 2; i < n; ++i) {
            b[i] = b[i - 1] * b[1];
            b[i] %= (*this);
        }
    }
    return b;
}
Example #7
0
int main(int argc, char ** argv) {
	if (argc<3) {
		fprintf(stderr, "usage: pagerank [path] [iterations] [memory budget in GB]\n");
		exit(-1);
	}
	std::string path = argv[1];
	int iterations = atoi(argv[2]);
	long memory_bytes = (argc>=4)?atol(argv[3])*1024l*1024l*1024l:8l*1024l*1024l*1024l;

	Graph graph(path,atoi(argv[4]));
	graph.set_memory_bytes(memory_bytes);
	BigVector<VertexId> degree(graph.path+"/degree", graph.vertices);
	BigVector<float> pagerank(graph.path+"/pagerank", graph.vertices);
	BigVector<float> sum(graph.path+"/sum", graph.vertices);

	long vertex_data_bytes = (long)graph.vertices * ( sizeof(VertexId) + sizeof(float) + sizeof(float) );
	graph.set_vertex_data_bytes(vertex_data_bytes);

	double begin_time = get_time();

	degree.fill(0);
	graph.stream_edges<VertexId>(
		[&](Edge & e){
			write_add(&degree[e.source], 1);
			return 0;
		}, nullptr, 0, 0
	);
	printf("degree calculation used %.2f seconds\n", get_time() - begin_time);
	fflush(stdout);

	graph.hint(pagerank, sum);
	graph.stream_vertices<VertexId>(
		[&](VertexId i){
			pagerank[i] = 1.f / degree[i];
			sum[i] = 0;
			return 0;
		}, nullptr, 0,
		[&](std::pair<VertexId,VertexId> vid_range){
			pagerank.load(vid_range.first, vid_range.second);
			sum.load(vid_range.first, vid_range.second);
		},
		[&](std::pair<VertexId,VertexId> vid_range){
			pagerank.save();
			sum.save();
		}
	);

	for (int iter=0;iter<iterations;iter++) {
		graph.hint(pagerank);
		graph.stream_edges<VertexId>(
			[&](Edge & e){
				write_add(&sum[e.target], pagerank[e.source]);
				return 0;
			}, nullptr, 0, 1,
			[&](std::pair<VertexId,VertexId> source_vid_range){
				pagerank.lock(source_vid_range.first, source_vid_range.second);
			},
			[&](std::pair<VertexId,VertexId> source_vid_range){
				pagerank.unlock(source_vid_range.first, source_vid_range.second);
			}
		);
		graph.hint(pagerank, sum);
		if (iter==iterations-1) {
			graph.stream_vertices<VertexId>(
				[&](VertexId i){
					pagerank[i] = 0.15f + 0.85f * sum[i];
					return 0;
				}, nullptr, 0,
				[&](std::pair<VertexId,VertexId> vid_range){
					pagerank.load(vid_range.first, vid_range.second);
				},
				[&](std::pair<VertexId,VertexId> vid_range){
					pagerank.save();
				}
			);
		} else {
			graph.stream_vertices<float>(
				[&](VertexId i){
					pagerank[i] = (0.15f + 0.85f * sum[i]) / degree[i];
					sum[i] = 0;
					return 0;
				}, nullptr, 0,
				[&](std::pair<VertexId,VertexId> vid_range){
					pagerank.load(vid_range.first, vid_range.second);
					sum.load(vid_range.first, vid_range.second);
				},
				[&](std::pair<VertexId,VertexId> vid_range){
					pagerank.save();
					sum.save();
				}
			);
		}
	}

	double end_time = get_time();
	printf("%d iterations of pagerank took %.2f seconds\n", iterations, end_time - begin_time);

}
Example #8
0
        void Fibre::Tractlet::Tensor::add_section_hessian(
                const Tractlet& tractlet, const Tractlet::Section& section,
                const Strand::BasicSection& gradient, const Strand::BasicSection::Tensor& hessian) {
            
            Fibre::Tractlet d2_intensity = get_template();
            
            Strand pos_gradient = Strand::outer_product(section.position_coeffs,
                    gradient.position() / section.intensity());
            
            if (has_var_acs())
                d2_intensity.set_acs(0.0);
            
//      d2_intensity.set_base_width(0.0);
            
//Add position gradient.
            d2_intensity[0] += pos_gradient;
            d2_intensity[1] += pos_gradient * section.ax1_fraction;
            d2_intensity[2] += pos_gradient * section.ax2_fraction;
            
            //Add tangent gradient.
            
            Strand tang_gradient = Strand::outer_product(section.tangent_coeffs,
                    gradient.tangent() * (section.length_fraction / section.intensity()));
            
            d2_intensity[0] += tang_gradient;
            d2_intensity[1] += tang_gradient * section.ax1_fraction;
            d2_intensity[2] += tang_gradient * section.ax2_fraction;
            
            Fibre::Tractlet acs_gradient = d2_intensity * section.intensity();
            
            if (true) {    //Needs some serious rewriting.
            
                throw Exception(
                        "tied_width hessian needs to be adjusted after accounting for tractlet sheer.");
                
                double norm1 = tractlet[1][0].norm();
                double norm2 = tractlet[2][0].norm();
                
                Coord d_intensity_d1 = tractlet.acs()
                        * ((norm2 / norm1) * tractlet(1, 0) - tractlet(2, 0));
                Coord d_intensity_d2 = tractlet.acs()
                        * ((norm1 / norm2) * tractlet(2, 0) - tractlet(1, 0));
                
                for (size_t dim_i1 = 0; dim_i1 < 3; dim_i1++) {
                    
                    operator()(1, 0, dim_i1, 2, 0, dim_i1) -= gradient.intensity() * tractlet.acs();
                    operator()(2, 0, dim_i1, 1, 0, dim_i1) -= gradient.intensity() * tractlet.acs();
                    
                    operator()(1, 0, dim_i1, 1, 0, dim_i1) += gradient.intensity() * tractlet.acs()
                                                              * norm2
                                                              / norm1;
                    operator()(2, 0, dim_i1, 2, 0, dim_i1) += gradient.intensity() * tractlet.acs()
                                                              * norm1
                                                              / norm2;
                    
                    for (size_t dim_i2 = 0; dim_i2 < 3; dim_i2++) {
                        
                        operator()(1, 0, dim_i1, 1, 0, dim_i2) -= tractlet.acs()
                                * gradient.intensity() * tractlet[1][0][dim_i1]
                                * tractlet[1][0][dim_i2] * (norm2 / MR::Math::pow3(norm1));
                        operator()(2, 0, dim_i1, 2, 0, dim_i2) -= tractlet.acs()
                                * gradient.intensity() * tractlet[2][0][dim_i1]
                                * tractlet[2][0][dim_i2] * (norm1 / MR::Math::pow3(norm2));
                        
                        operator()(1, 0, dim_i1, 2, 0, dim_i2) += tractlet.acs()
                                * gradient.intensity() * tractlet[2][0][dim_i2]
                                * tractlet[1][0][dim_i1]
                                                                  / (norm1 * norm2);
                        operator()(2, 0, dim_i1, 1, 0, dim_i2) += tractlet.acs()
                                * gradient.intensity() * tractlet[1][0][dim_i2]
                                * tractlet[2][0][dim_i1]
                                                                  / (norm2 * norm1);
                        
                        for (size_t ax_i = 0; ax_i < 3; ++ax_i)
                            for (size_t degree_i = 0; degree_i < tractlet.degree(); ++degree_i) {
                                
                                operator()(ax_i, degree_i, dim_i1, 1, 0, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i1]
                                        * d_intensity_d1[dim_i2];
                                operator()(ax_i, degree_i, dim_i1, 2, 0, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i1]
                                        * d_intensity_d2[dim_i2];
                                
                                operator()(1, 0, dim_i1, ax_i, degree_i, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i2]
                                        * d_intensity_d1[dim_i1];
                                operator()(2, 0, dim_i1, ax_i, degree_i, dim_i2) += tractlet.acs()
                                        * d2_intensity(ax_i, degree_i)[dim_i2]
                                        * d_intensity_d2[dim_i1];
                                
                            }
                        
                    }
                    
                }
                
                if (has_var_acs()) {
                    acs_gradient(1, 0) += gradient.intensity() * d_intensity_d1;
                    acs_gradient(2, 0) += gradient.intensity() * d_intensity_d2;
                }
                
            }
            
            if (has_var_acs())
                acs() += acs_gradient;
            
            for (size_t degree_i1 = 0; degree_i1 < degree(); degree_i1++)
                for (size_t dim_i1 = 0; dim_i1 < 3; dim_i1++) {
                    
                    Fibre::Tractlet ax0 = row(0, degree_i1, dim_i1);
                    Fibre::Tractlet ax1 = row(1, degree_i1, dim_i1);
                    Fibre::Tractlet ax2 = row(2, degree_i1, dim_i1);
                    
                    if (has_var_acs()) {
                        ax0.alpha() += acs_gradient.operator()(0, degree_i1)[dim_i1];
                        ax1.alpha() += acs_gradient.operator()(1, degree_i1)[dim_i1];
                        ax2.alpha() += acs_gradient.operator()(2, degree_i1)[dim_i1];
                    }
                    
                    for (size_t degree_i2 = 0; degree_i2 < degree(); degree_i2++)
                        for (size_t dim_i2 = 0; dim_i2 < 3; dim_i2++) {
                            
                            double ax0_ax0 =
                                    section.position_coeffs[degree_i1] * section.position_coeffs[degree_i2]
                                    * hessian.position(dim_i1).position(dim_i2)
                                    + section.position_coeffs[degree_i1] * section.tangent_coeffs[degree_i2]
                                      * hessian.position(dim_i1).tangent(dim_i2)
                                      * section.length_fraction
                                    + section.tangent_coeffs[degree_i1] * section.position_coeffs[degree_i2]
                                      * hessian.tangent(dim_i1).position(dim_i2)
                                      * section.length_fraction
                                    + section.tangent_coeffs[degree_i1] * section.tangent_coeffs[degree_i2]
                                      * hessian.tangent(dim_i1).tangent(dim_i2)
                                      * MR::Math::pow2(section.length_fraction);
                            
                            ax0[0][degree_i2][dim_i2] += ax0_ax0;
                            ax0[1][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction;
                            ax1[0][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction;
                            ax0[2][degree_i2][dim_i2] += ax0_ax0 * section.ax2_fraction;
                            ax2[0][degree_i2][dim_i2] += ax0_ax0 * section.ax2_fraction;
                            
                            ax1[1][degree_i2][dim_i2] += ax0_ax0
                                    * MR::Math::pow2(section.ax1_fraction);
                            ax1[2][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction
                                                         * section.ax2_fraction;
                            ax2[1][degree_i2][dim_i2] += ax0_ax0 * section.ax1_fraction
                                                         * section.ax2_fraction;
                            
                            ax2[2][degree_i2][dim_i2] += ax0_ax0
                                    * MR::Math::pow2(section.ax2_fraction);
                            
                        }
                    
                }
            
        }
Example #9
0
bspline::bspline(unsigned int _degree, Type _type)
    : bspline()
{
    degree(_degree);
    type(_type);
}
Example #10
0
Vector Graph::degree(const VertexSelector& vids, NeighborMode mode, bool loops) const {
    Vector result;
    degree(&result, vids, mode, loops);
    return result;
}
Example #11
0
int QilexDoc::writeXML_kineelement(const char *buffer, size_t size, int tipus, ct_new_kinematic_chain *data, Rchain *kinechain)
{
   bool error=false;
   double scale;
   size_t pos;
   
   QFile file( filename );
   error = file.open(IO_ReadWrite);
   pos = file.size();
   
   if (error && pos == 0)
   {
      file.close();
      error = writeXMLheader();
   }

   if(!error)
   {
      if ( file.open(IO_ReadWrite))
      {
         pos = file.size();
         pos = pos - 13;

         file.at(pos);  //remove </qilexfile>

         QTextStream stream( &file );
        
         stream <<"<kineelement name=\"" << data->QsName.ascii() << "\"" ;
         stream <<" pos_x=\"" << data->x <<"\"";
         stream <<" pos_y=\"" << data->y <<"\"";
         stream <<" pos_z=\"" << data->z <<"\"";
         stream <<" pos_rx=\"" << data->axeX <<"\"";
         stream <<" pos_ry=\"" << data->axeY <<"\"";
         stream <<" pos_rz=\"" << data->axeZ <<"\"";
         stream <<" pos_angle=\"" << data->angle <<"\"" << ">" << endl;
         stream <<"<model3d format=\"";

         if(tipus==0)
         {
            stream << "vrml1\" size=\"" << size << "\">";
            stream << buffer ;

         }
         else{
            stream << "vrml2\" size=\"" << size << "\">";
            stream << buffer;

         }
         stream <<"</model3d>" << endl;
         stream <<"<kinechain name=\"" << kinechain->name << "\"";
         stream << " dof=\"" << kinechain->dof << "\">" << "\n";
         stream <<"  <manufacturer>" << kinechain->manufacturer <<"</manufacturer>" <<"\n";

         scale = kinechain->scale();
         
         for(int i=1;i<=kinechain->dof;i++)
         {
            stream <<"<joint id=\"" << i << "\"" << " sigma=\"" << kinechain->dh_parameters[i].sigma << "\"";
            stream <<" theta=\"" << degree(kinechain->dh_parameters[i].theta) << "\"";
            stream <<" alpha=\"" << degree(atan2(kinechain->dh_parameters[i].salpha,kinechain->dh_parameters[i].calpha)) << "\"";
            stream <<" ai=\"" << kinechain->dh_parameters[i].ai / scale << "\"";
            stream <<" di=\"" << kinechain->dh_parameters[i].di / scale << "\"";

            if (kinechain->dh_parameters[i].sigma == 1)
            {
               stream <<" low_rank=\"" << degree(kinechain->dh_parameters[i].lower_value) << "\"";
               stream <<" up_rank=\""  << degree(kinechain->dh_parameters[i].upper_value) << "\"";
               stream << " home=\"" << degree(kinechain->home[i]) << "\"" ;
					stream << " max_speed=\"" << degree(kinechain->dh_parameters[i].m_speed) << "\"";
            	stream << " max_acc=\"" << degree(kinechain->dh_parameters[i].m_acc) << "\"";
            
            }
            else{             
              stream <<" low_rank=\"" << kinechain->dh_parameters[i].lower_value << "\"";
              stream <<" up_rank=\""  << kinechain->dh_parameters[i].upper_value << "\"";
              stream << " home=\"" << kinechain->home[i] << "\"" << ">" << endl;
				  stream << " max_speed=\"" << kinechain->dh_parameters[i].m_speed << "\"";
              stream << " max_acc=\"" << kinechain->dh_parameters[i].m_acc << "\"";
            
            }
            stream << ">" << endl;
            stream << "</joint>" << endl;
         }
         stream <<"</kinechain>" << endl;
         stream <<"</kineelement>" << "\n";
         stream <<"</qilexfile>" << "\n";
         file.close();
      }

   }
   else
   {
      return 1;
   }
   return 0; 
}
Example #12
0
 int  stressed_degree() const { return degree(StressedEdgeFilter()); }
Example #13
0
 int  polyline_degree() const { return degree(PolylineEdgeFilter()); }
Example #14
0
 int  border_degree()   const { return degree(BorderEdgeFilter()); }
Example #15
0
 int  crease_degree()   const { return degree(CreaseEdgeFilter()); }
Example #16
0
 double min_dot() const {
    double ret = 1;
    for (int i=0; i < degree(); i++)
       ret = min(ret, e(i)->dot());
    return ret;
 }   
int main(int argc, char* argv[])
{
// store the invoking program name
   char* prg_name = argv[0];

// create an object of cpuClock and start it
   cpuClock clock;
   clock.Start();

// want to mark lines
   positionMarker pm;

//   pm << plume::off;

// open a file
   std::ofstream out("MyTestFile.txt");

   channel1.ResetStream(out);
//   channel1.Off();
   channel2.Off();

//   channel1.ResetStream(channel2);

// invoke a function
   Function1();
 
   pm << "About to test anAngle class";// << plume::pause;
// test out the degree, angle etc.
   anAngle alpha;
   alpha = degree(45);
   std::cout << "sin of 45 dgrees is: " << sin(alpha) << std::endl;

   pm << "alpha = degree(45) is over" << plume::ends;
   alpha = degree(90);
   std::cout << "sin of 90 dgrees is: " << sin(alpha) << std::endl;

   alpha = radian(45.0);
//   sin( degree(45) );  // error
//   sin( radian(1.0) ); // error
   std::cout << sin( anAngle( degree(45) ) ) << std::endl
             << sin( anAngle( radian(1) ) )  << std::endl;

// insert a position marker here
//**   pm << plume::off;
   pm << " I am here." << plume::pause;

   pm << "******** Testing aStream object ***********" << plume::ends;

   int i=5;
   pm << " the value of i is: " << i << plume::ends;

   plume::aStream my_s;

   my_s << "~~~~~~~~~Inserted this into the stream." << std::endl << std::ends;
   std::cout << my_s;

   my_s << "~~~~*****Now the string is different" << std::endl << std::endl;
   my_s << std::ends;
   std::cout << my_s;
   my_s << std::ends;
   std::cout << my_s;


// is the new traceable class, traceable??
#if 1
   pm << plume::ends;
   pm << "checking anotherTraceableClass **** " << plume::ends;

   anotherTraceableClass atc;

   pm << plume::pause;
#endif

#if 1
   pm << plume::ends;
   pm << "checking yetAnotherTraceableClass **** " << plume::ends;

   yetAnotherTraceableClass yatc;
   yetAnotherTraceableClass yatc1;
   yetAnotherTraceableClass yatc2;
 
   pm << plume::pause;
#endif


#if 0 // turn off object tracing for the moment
// now let us test object tracing
   traceableClass tc;
   traceableClass* ptc = new traceableClass;
   traceableClass* ptca = new traceableClass[2];
   delete ptc;
   delete [] ptca;
#endif


// stop the clock and display cpu time
   clock.Stop();
   clock.Display();

// write a closure message and finish the program
   std::cout << "Program " << prg_name
             << " completed successfully :-)" << std::endl;

   return 0;
}
Example #18
0
 int  multi_degree()    const { return degree(MultiEdgeFilter()); }
Example #19
0
    void doc_manager::populate(void)
    {
        
        add_class_descriptor(ml::k_base);
        
        add_class_descriptors(ml::k_base, {
            ml::k_classification,
            ml::k_regression
        });
        
        add_class_descriptors(ml::k_regression, {
            ml::k_ann,
            ml::k_linreg,
            ml::k_logreg
        });
        
        add_class_descriptors(ml::k_classification, {
            ml::k_svm,
            ml::k_adaboost,
            ml::k_anbc,
            ml::k_dtw,
            ml::k_hmmc,
            ml::k_softmax,
            ml::k_randforest,
            ml::k_mindist,
            ml::k_knn,
            ml::k_gmm,
            ml::k_dtree
        });
        
        add_class_descriptors(ml::k_feature_extraction, {
            ml::k_peak,
            ml::k_minmax,
            ml::k_zerox
        });
        
        descriptors[ml::k_ann].desc("Artificial Neural Network").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MLP");
        descriptors[ml::k_linreg].desc("Linear Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LinearRegression");
        descriptors[ml::k_logreg].desc("Logistic Regression").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/LogisticRegression");
        descriptors[ml::k_peak].desc("Peak Detection").url("").num_outlets(1);
        descriptors[ml::k_minmax].desc("Minimum / Maximum Detection").url("").num_outlets(1);
        descriptors[ml::k_zerox].desc("Zero Crossings Detection").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ZeroCrossingCounter");
        descriptors[ml::k_svm].desc("Support Vector Machine").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/SVM");
        descriptors[ml::k_adaboost].desc("Adaptive Boosting").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/AdaBoost");
        descriptors[ml::k_anbc].desc("Adaptive Naive Bayes Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/ANBC");
        descriptors[ml::k_dtw].desc("Dynamic Time Warping").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DTW");
        descriptors[ml::k_hmmc].desc("Continuous Hidden Markov Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/HMM");
        descriptors[ml::k_softmax].desc("Softmax Classifier").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/Softmax");
        descriptors[ml::k_randforest].desc("Random Forests").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/RandomForests");
        descriptors[ml::k_mindist].desc("Minimum Distance").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/MinDist");
        descriptors[ml::k_knn].desc("K Nearest Neighbour").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/KNN");
        descriptors[ml::k_gmm].desc("Gaussian Mixture Model").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/GMMClassifier");
        descriptors[ml::k_dtree].desc("Decision Trees").url("http://www.nickgillian.com/wiki/pmwiki.php/GRT/DecisionTree");
        
        for (auto& desc : {&descriptors[ml::k_hmmc], &descriptors[ml::k_dtw]})
        {
            desc->notes(
                        "add and map messages for time series should be delimited with record messages, e.g. record 1, add 1 40 50, add 1 41 50, record 0"
            );
        }
        
        // base descriptor
        message_descriptor add(
                              "add",
                              "list comprising a class id followed by n features, <class> <feature 1> <feature 2> etc",
                               "1 0.2 0.7 0.3 0.1"
                              );

        
        message_descriptor train(
                                "train",
                                "train the model based on vectors added with 'add'"
                                );
        
        message_descriptor map(
                              "map",
                              "generate the output value(s) for the input feature vector",
                               "0.2 0.7 0.3 0.1"
                              );
        
        message_descriptor write(
                                 "write",
                                 "write training data and / or model, first argument gives path to write file",
                                 "/path/to/my_ml-lib_data"
                                 );
        
        message_descriptor read(
                                "read",
                                "read training data and / or model, first argument gives path to the read file",
                                "/path/to/my_ml-lib_data"
                                );
        
        message_descriptor clear(
                                 "clear",
                                 "clear the stored training data and model"
                                 );
        
        message_descriptor help(
                               "help",
                               "post usage statement to the console"
                               );
        
        valued_message_descriptor<int> scaling(
                                               "scaling",
                                               "sets whether values are automatically scaled",
                                               {0, 1},
                                               1
                                               );
        
        valued_message_descriptor<int> record(
                                              "record",
                                              "start or stop time series recording for a single example of a given class",
                                              {0, 1},
                                              0
                                              );
        
        ranged_message_descriptor<float> training_rate(
                                                       "training_rate",
                                                       "set the learning rate, used to update the weights at each step of learning algorithms such as stochastic gradient descent.",
                                                       0.01,
                                                       1.0,
                                                       0.1
                                                       );
        
        ranged_message_descriptor<float> min_change(
                                                    "min_change",
                                                    "set the minimum change that must be achieved between two training epochs for the training to continue",
                                                    0.0,
                                                    1.0,
                                                    1.0e-5
                                                    );
        
        ranged_message_descriptor<int> max_iterations(
                                                      "max_iterations",
                                                      "set the maximum number of training iterations",
                                                      0,
                                                      1000,
                                                      100
                                                      );
        
        record.insert_before = "add";
        descriptors[ml::k_base].add_message_descriptor(add, write, read, train, clear, map, help, scaling, training_rate, min_change, max_iterations);

        // generic classification descriptor
        valued_message_descriptor<bool> null_rejection(
                                                       "null_rejection",
                                                       "toggle NULL rejection off or on, when 'on' classification results below the NULL-rejection threshold will be discarded",
                                                       {false, true},
                                                       true
                                                       );
        
        ranged_message_descriptor<float> null_rejection_coeff(
                                                              "null_rejection_coeff",
                                                              "set a multiplier for the NULL-rejection threshold ",
                                                              0.1,
                                                              1.0,
                                                              0.9
                                                              );
        
        valued_message_descriptor<int> probs(
                                             "probs",
                                             "determines whether probabilities are sent from the right outlet",
                                             {0, 1},
                                             0
                                             );
        
        descriptors[ml::k_classification].add_message_descriptor(null_rejection_coeff, probs, null_rejection);
        
        // generic feature extraction descriptor
//        descriptors[ml::k_feature_extraction].add_message_descriptor(null_rejection_coeff, null_rejection);

        // generic regression descriptor
       
        
//        descriptors[ml::k_regression].add_message_descriptor(training_rate, min_change, max_iterations);
        
        // Object-specific descriptors
        //-- Regressifiers
        //---- ann
        valued_message_descriptor<ml::data_type> mode("mode",
                                                      "set the mode of the ANN, " + std::to_string(ml::LABELLED_CLASSIFICATION) + " for classification, " + std::to_string(ml::LABELLED_REGRESSION) + " for regression",
                                                      {ml::LABELLED_CLASSIFICATION, ml::LABELLED_REGRESSION, ml::LABELLED_TIME_SERIES_CLASSIFICATION},
                                                      ml::defaults::data_type
                                                      );
        
        
        message_descriptor add_ann(
                              "add",
                              "class id followed by n features, <class> <feature 1> <feature 2> etc when in classification mode or N output values followed by M input values when in regression mode (N = num_outputs)",
                                   "1 0.2 0.7 0.3 0.1"

                              );
      
        ranged_message_descriptor<int> num_outputs(
                                                   "num_outputs",
                                                   "set the number of neurons in the output layer",
                                                   1,
                                                   1000,
                                                   ml::defaults::num_output_dimensions
                                                   );
        
        ranged_message_descriptor<int> num_hidden(
                                                  "num_hidden",
                                                  "set the number of neurons in the hidden layer",
                                                  1,
                                                  1000,
                                                  ml::defaults::num_hidden_neurons
                                                  );
        
        ranged_message_descriptor<int> min_epochs(
                                                  "min_epochs",
                                                  "setting the minimum number of training iterations",
                                                  1,
                                                  1000,
                                                  10
                                                  );
        
        // TODO: check if the "epochs" are still needed or if we can use "iterations" as inherited from ml_regression
        ranged_message_descriptor<int> max_epochs(
                                                  "max_epochs",
                                                  "setting the maximum number of training iterations",
                                                  1,
                                                  10000,
                                                  100
                                                  );

        ranged_message_descriptor<float> momentum(
                                                  "momentum",
                                                  "set the momentum",
                                                  0.0,
                                                  1.0,
                                                  0.5
                                                  );
        
        ranged_message_descriptor<float> gamma(
                                                  "gamma",
                                                  "set the gamma",
                                                  0.0,
                                                  10.0,
                                                  2.0
                                                  );
        
        // TODO: have optional value_labels for value labels
        valued_message_descriptor<int> input_activation_function(
                                                                 "input_activation_function",
                                                                 "set the activation function for the input layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );
        
        valued_message_descriptor<int> hidden_activation_function(
                                                                 "hidden_activation_function",
                                                                 "set the activation function for the hidden layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );
        
        valued_message_descriptor<int> output_activation_function(
                                                                 "output_activation_function",
                                                                 "set the activation function for the output layer, 0:LINEAR, 1:SIGMOID, 2:BIPOLAR_SIGMOID",
                                                                 {0, 1, 2},
                                                                 0
                                                                 );

                                                                 
        ranged_message_descriptor<int> rand_training_iterations(
                                                                 "rand_training_iterations",
                                                                 "set the number of random training iterations",
                                                                 0,
                                                                 1000,
                                                                 10
                                                                 );

        valued_message_descriptor<bool> use_validation_set(
                                                           "use_validation_set",
                                                           "set whether to use a validation training set",
                                                           {false, true},
                                                           true
                                                           );
        
        ranged_message_descriptor<int> validation_set_size(
                                                           "validation_set_size",
                                                           "set the size of the validation set",
                                                           1,
                                                           100,
                                                           20
                                                           );
        
        valued_message_descriptor<bool> randomize_training_order(
                                                           "randomize_training_order",
                                                           "sets whether to randomize the training order",
                                                           {false, true},
                                                           false
                                                           );
        
        
        descriptors[ml::k_ann].add_message_descriptor(add_ann, probs, mode, null_rejection, null_rejection_coeff, num_outputs, num_hidden, min_epochs, max_epochs, momentum, gamma, input_activation_function, hidden_activation_function, output_activation_function, rand_training_iterations, use_validation_set, validation_set_size, randomize_training_order);
        
        
        //-- Classifiers
        //---- ml.svm
        ranged_message_descriptor<int> type(
                                            "type",
                                            "set SVM type,"
                                            " 0:C-SVC (multi-class),"
                                            " 1:nu-SVC (multi-class),"
                                            " 2:one-class SVM,"
                                           // " 3:epsilon-SVR (regression),"
                                           // " 4:nu-SVR (regression)"
                                            ,
                                            0,
                                            2,
                                            0
                                            //        "	0 -- C-SVC		(multi-class classification)\n"
                                            //        "	1 -- nu-SVC		(multi-class classification)\n"
                                            //        "	2 -- one-class SVM\n"
                                            //        "	3 -- epsilon-SVR	(regression)\n"
                                            //        "	4 -- nu-SVR		(regression)\n"

                                            );
        
        ranged_message_descriptor<int> kernel(
                                              "kernel",
                                              "set type of kernel function, "
                                              "0:linear, " // (u'*v),"
                                              "1:polynomial, " // (gamma*u'*v + coef0)^degree,"
                                              "2:radial basis function, " //: exp(-gamma*|u-v|^2),"
                                              "3:sigmoid, " //  tanh(gamma*u'*v + coef0),"
                                              "4:precomputed kernel (kernel values in training_set_file)",
                                              0,
                                              4,
                                              0
                                              //        "	0 -- linear: u'*v\n"
                                              //        "	1 -- polynomial: (gamma*u'*v + coef0)^degree\n"
                                              //        "	2 -- radial basis function: exp(-gamma*|u-v|^2)\n"
                                              //        "	3 -- sigmoid: tanh(gamma*u'*v + coef0)\n"
                                              //        "	4 -- precomputed kernel (kernel values in training_set_file)\n"
                                              );
        
        ranged_message_descriptor<float> degree(
                                              "degree",
                                              "set degree in kernel function",
                                              0,
                                              20,
                                              3
                                              );
        
        ranged_message_descriptor<float> svm_gamma(
                                              "gamma",
                                              "set gamma in kernel function",
                                              0.0,
                                              1.0,
                                              0.5
                                              );
        
        ranged_message_descriptor<float> coef0(
                                               "coef0",
                                               "coef0 in kernel function",
                                               INFINITY * -1.f, INFINITY,
                                               0.0
                                               );
        
        ranged_message_descriptor<float> cost(
                                               "cost",
                                               "set the parameter C of C-SVC, epsilon-SVR, and nu-SVR",
                                               INFINITY * -1.f, INFINITY,
                                               1.0
                                               );
        
        ranged_message_descriptor<float> nu(
                                              "nu",
                                              "set the parameter nu of nu-SVC, one-class SVM, and nu-SVR",
                                              INFINITY * -1.f, INFINITY,
                                              0.5
                                              );
        
        message_descriptor cross_validation(
                                            "cross_validation",
                                            "perform cross validation"
                                            );
        
        ranged_message_descriptor<int> num_folds(
                                                 "num_folds",
                                                 "set the number of folds used for cross validation",
                                                 1, 100,
                                                 10
                                                 );
        
        descriptors[ml::k_svm].add_message_descriptor(cross_validation, num_folds, type, kernel, degree, svm_gamma, coef0, cost, nu);
        
        //---- ml.adaboost        
        ranged_message_descriptor<int> num_boosting_iterations(
                                                                "num_boosting_iterations",
                                                               "set the number of boosting iterations that should be used when training the model",
                                                               0,
                                                               200,
                                                               20
                                                               );
        
        valued_message_descriptor<int> prediction_method(
                                                        "prediction_method",
                                                         "set the Adaboost prediction method, 0:MAX_VALUE, 1:MAX_POSITIVE_VALUE",
                                                         {GRT::AdaBoost::MAX_VALUE, GRT::AdaBoost::MAX_POSITIVE_VALUE},
                                                         GRT::AdaBoost::MAX_VALUE
                                                         
        );
        
        valued_message_descriptor<int> set_weak_classifier(
                                                           "set_weak_classifier",
                                                           "sets the weak classifier to be used by Adaboost, 0:DECISION_STUMP, 1:RADIAL_BASIS_FUNCTION",
                                                           {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION},
                                                           ml::weak_classifiers::DECISION_STUMP
                                                           );
        
        valued_message_descriptor<int> add_weak_classifier(
                                                           "add_weak_classifier",
                                                           "add a weak classifier to the list of classifiers used by Adaboost",
                                                           {ml::weak_classifiers::DECISION_STUMP, ml::weak_classifiers::RADIAL_BASIS_FUNCTION},
                                                           ml::weak_classifiers::DECISION_STUMP
                                                           );

        descriptors[ml::k_adaboost].add_message_descriptor(num_boosting_iterations, prediction_method, set_weak_classifier, add_weak_classifier);
        
        //---- ml.anbc
        message_descriptor weights("weights",
                                   "vector of 1 integer and N floating point values where the integer is a class label and the floats are the weights for that class. Sending weights with a vector size of zero clears all weights"
                                   );
        
        descriptors[ml::k_anbc].add_message_descriptor(weights);
        
        //---- ml.dtw
        valued_message_descriptor<int> rejection_mode(
                                                      "rejection_mode",
                                                      "sets the method used for null rejection, 0:TEMPLATE_THRESHOLDS, 1:CLASS_LIKELIHOODS, 2:THRESHOLDS_AND_LIKELIHOODS",
                                                      {GRT::DTW::TEMPLATE_THRESHOLDS, GRT::DTW::CLASS_LIKELIHOODS, GRT::DTW::THRESHOLDS_AND_LIKELIHOODS},
                                                      GRT::DTW::TEMPLATE_THRESHOLDS
                                                      );
        
        ranged_message_descriptor<float> warping_radius(
                                                        "warping_radius",
                                                        "sets the radius of the warping path, which is used if the constrain_warping_path is set to 1",
                                                        0.0,
                                                        1.0,
                                                        0.2
                                                        );
        
        valued_message_descriptor<bool> offset_time_series(
                                                           "offset_time_series",
                                                           "set if each timeseries should be offset by the first sample in the time series",
                                                           {false, true},
                                                           false
                                                           );
        
        valued_message_descriptor<bool> constrain_warping_path(
                                                           "constrain_warping_path",
                                                           "sets the warping path should be constrained to within a specific radius from the main diagonal of the cost matrix",
                                                           {false, true},
                                                           true
                                                           );
        
        valued_message_descriptor<bool> enable_z_normalization(
                                                               "enable_z_normalization",
                                                               "turn z-normalization on or off for training and prediction",
                                                               {false, true},
                                                               false
                                                               );
        
        valued_message_descriptor<bool> enable_trim_training_data(
                                                               "enable_trim_training_data",
                                                               "enabling data trimming prior to training",
                                                               {false, true},
                                                               false
                                                               );
  
        descriptors[ml::k_dtw].insert_message_descriptor(record);
        descriptors[ml::k_dtw].add_message_descriptor(rejection_mode, warping_radius, offset_time_series, constrain_warping_path, enable_z_normalization, enable_trim_training_data);
        
        //---- ml.hmmc
        valued_message_descriptor<int> model_type(
                                                  "model_type",
                                                  "set the model type used, 0:ERGODIC, 1:LEFTRIGHT",
                                                  {HMM_ERGODIC, HMM_LEFTRIGHT},
                                                  HMM_LEFTRIGHT
                                                  );
        
        ranged_message_descriptor<int> delta(
                                             "delta",
                                             "control how many states a model can transition to if the LEFTRIGHT model type is used",
                                             1,
                                             100,
                                             11
                                             );
        
        ranged_message_descriptor<int> max_num_iterations(
                                                          "max_num_iterations",
                                                          "set the maximum number of training iterations",
                                                          1,
                                                          1000,
                                                          100
                                                          );
        
        ranged_message_descriptor<int> committee_size(
                                                      "committee_size",
                                                      "set the committee size for the number of votes combined to make a prediction",
                                                      1,
                                                      1000,
                                                      5
                                                      );
        
        ranged_message_descriptor<int> downsample_factor(
                                                      "downsample_factor",
                                                         "set the downsample factor for the resampling of each training time series. A factor of 5 will result in each time series being resized (smaller) by a factor of 5",
                                                      1,
                                                      1000,
                                                      5
                                                      );
        
        descriptors[ml::k_hmmc].insert_message_descriptor(record);
        descriptors[ml::k_hmmc].add_message_descriptor(model_type, delta, max_num_iterations, committee_size, downsample_factor);
        
        //---- ml.softmax
        
        //---- ml.randforest
        ranged_message_descriptor<int> num_random_splits(
                                                         "num_random_splits",
                                                         "set the number of steps that will be used to search for the best spliting value for each node",
                                                         1,
                                                         1000,
                                                         100
                                                         );
        
        ranged_message_descriptor<int> min_samples_per_node2(
                                                            "min_samples_per_node",
                                                            "set the minimum number of samples that are allowed per node",
                                                            1,
                                                            100,
                                                            5
                                                            );
        
        ranged_message_descriptor<int> max_depth(
                                                 "max_depth",
                                                 "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node",
                                                 1,
                                                 100,
                                                 10
                                                 );

        descriptors[ml::k_randforest].add_message_descriptor(num_random_splits, min_samples_per_node2, max_depth);
        
        //----ml.mindist
        ranged_message_descriptor<int> num_clusters(
                                                    "num_clusters",
                                                    "set how many clusters each model will try to find during the training phase",
                                                    1,
                                                    100,
                                                    10
                                                    );

        descriptors[ml::k_mindist].add_message_descriptor(num_clusters);
                
        //---- ml.knn
//        "best_k_value_search:\tbool (0 or 1) set whether k value search is enabled or not (default 0)\n";

        ranged_message_descriptor<int> k(
                                         "k",
                                         "sets the K nearest neighbours that will be searched for by the algorithm during prediction",
                                         1,
                                         500,
                                         10
                                         );
        
        ranged_message_descriptor<int> min_k_search_value(
                                         "min_k_search_value",
                                         "set the minimum K value to use when searching for the best K value",
                                         1,
                                         500,
                                         1
                                         );
        
        ranged_message_descriptor<int> max_k_search_value(
                                                          "max_k_search_value",
                                                          "set the maximum K value to use when searching for the best K value",
                                                          1,
                                                          500,
                                                          10
                                                          );
        
        valued_message_descriptor<bool> best_k_value_search(
                                                            "best_k_value_search",
                                                            "set whether k value search is enabled or not",
                                                            {false, true},
                                                            false
                                                            );
        
        descriptors[ml::k_knn].add_message_descriptor(k, min_k_search_value, max_k_search_value, best_k_value_search);
        
        //---- ml.gmm
        ranged_message_descriptor<int> num_mixture_models(
                                                          "num_mixture_models",
                                                          "sets the number of mixture models used for class",
                                                          1,
                                                          20,
                                                          2
                                                          );

        descriptors[ml::k_gmm].add_message_descriptor(num_mixture_models);

        //---- ml.dtree
        valued_message_descriptor<bool> training_mode(
                                                      "training_mode",
                                                      "set the training mode",
                                                      {GRT::Tree::BEST_ITERATIVE_SPILT, GRT::Tree::BEST_RANDOM_SPLIT},
                                                      GRT::Tree::BEST_ITERATIVE_SPILT
                                                      );
        
        ranged_message_descriptor<int> num_splitting_steps(
                                                          "num_splitting_steps",
                                                          "set the number of steps that will be used to search for the best spliting value for each node",
                                                          1,
                                                          500,
                                                          100
                                                          );
        
        ranged_message_descriptor<int> min_samples_per_node(
                                                          "min_samples_per_node",
                                                          "sets the minimum number of samples that are allowed per node, if the number of samples at a node is below this value then the node will automatically become a leaf node",
                                                          1,
                                                          100,
                                                          5
                                                          );
        
        ranged_message_descriptor<int> dtree_max_depth(
                                                 "max_depth",
                                                 "sets the maximum depth of the tree, any node that reaches this depth will automatically become a leaf node",
                                                 1,
                                                 100,
                                                 10
                                                 );
        
        valued_message_descriptor<bool> remove_features_at_each_split(
                                                               "remove_features_at_each_split",
                                                               "set if a feature is removed at each spilt so it can not be used again",
                                                               {false, true},
                                                               false
                                                               );
        descriptors[ml::k_dtree].add_message_descriptor(training_mode, num_splitting_steps, min_samples_per_node, dtree_max_depth, remove_features_at_each_split);

        //-- Feature extraction
        
        //---- ml.peak
        ranged_message_descriptor<int> search_window_size(
                                                          "search_window_size",
                                                          "set the search window size in values",
                                                          1,
                                                          500,
                                                          5
                                                          );
        
        ranged_message_descriptor<float> peak(
                                              "float",
                                              "set the current value of the peak detector, a bang will be output when a peak is detected",
                                              INFINITY * -1.f, INFINITY,
                                              1
                                              );
        
        message_descriptor reset(
                                "reset",
                                "reset the peak detector"
                                );
        
        message_descriptor peak_help(
                                 "help",
                                 "post usage statement to the console"
                                 );


        descriptors[ml::k_peak].add_message_descriptor(peak, reset, search_window_size, peak_help);
        
        //---- ml.minmax
        
        message_descriptor input(
                                 "list",
                                 "list of float values in which to find minima and maxima",
                                 "0.1 0.5 -0.3 0.1 0.2 -0.1 0.7 0.1 0.3"
                                 );
        
        ranged_message_descriptor<float> minmax_delta(
                                                      "delta",
                                                      "setting the minmax delta. Input values will be considered to be peaks if they are greater than the previous and next value by at least the delta value",
                                                      0,
                                                      1,
                                                      0.1
                                                      );
        
        descriptors[ml::k_minmax].add_message_descriptor(input, minmax_delta);
        
        //---- ml.zerox
        
        valued_message_descriptor<float> zerox_map(
                                                   "map",
                                                   "a stream of input values in which to detect zero crossings",
                                                   0.5
                                                   );
        
        ranged_message_descriptor<float> dead_zone_threshold(
                                                             "dead_zone_threshold",
                                                             "set the dead zone threshold",
                                                             0.f,
                                                             1.f,
                                                             0.01f
                                                             );
        
        ranged_message_descriptor<int> zerox_search_window_size(
                                                          "search_window_size",
                                                          "set the search window size in values",
                                                          1,
                                                          500,
                                                          20
                                                          );
        
        descriptors[ml::k_zerox].add_message_descriptor(zerox_map, dead_zone_threshold, zerox_search_window_size);
    }
Example #20
0
void createHeadersFly(BucketFLY *bucket,
                      unsigned int newHeadersToGenerate,	// Number of symbols to be retrieved
                      unsigned int offset) {

    double sel;
    unsigned int genDeg;
    unsigned int i, j;

    unsigned int w = bucket->w;
    double *cumulative = bucket->cumulative;

    if (newHeadersToGenerate<1)
        return;

    if ((bucket->genSymbs == 0)&&(bucket->symbols == NULL))
        bucket->symbols = (Symbol *) chk_calloc(newHeadersToGenerate, sizeof(Symbol));
    else {
        bucket->symbols = (Symbol *) chk_realloc(bucket->symbols,
                          bucket->genSymbs + newHeadersToGenerate,
                          sizeof(Symbol));
        for (i=0; i<newHeadersToGenerate; i++) {
            bucket->symbols[bucket->genSymbs+i].info = NULL;
            bucket->symbols[bucket->genSymbs+i].header = NULL;
            bucket->symbols[bucket->genSymbs+i].deg = 0;
            bucket->symbols[bucket->genSymbs+i].symbLen = bucket->symbLen;
        }
    }
    unsigned int *selectedSymbols = NULL;
    selectedSymbols = (unsigned int*) chk_malloc(w, sizeof(unsigned int));

    for (i=0; i<newHeadersToGenerate; i++) {
        // Create header (the symbols are chosen between 0 and w)
        //  therefore shifting is needed.
        genDeg = degree(cumulative, w, real(&bucket->buckRan));
        if (genDeg > w)
            genDeg = w;
        if (genDeg == w) {
            chooseAllInWindowCore(w, offset, selectedSymbols, genDeg);
        } else {
            for (j=0; j<genDeg; j++) {
                sel	= real(&bucket->buckRan);
                selectedSymbols[j]	= rand2windowCore(w, offset, sel);

                if (verifySelectedSymbol(selectedSymbols, j) == False) {
                    j--;		// Doesn't repeat encoding symbols
                }
            }
//			sort(selectedSymbols, 0, genDeg-1);	// Sort the chosen encoding symbols' list
        }

#ifdef DEBUGdecoderPrintHeaders
        int deb_index;
        printf("BUCKET[%d] - symb[%d]\t: deg=%3d\t -> ",
               bucket->nameBucket, bucket->genSymbs, genDeg);
        for (deb_index=0; deb_index<genDeg; deb_index++)
            printf("%3d ", selectedSymbols[deb_index]);
        printf("\n");
#endif

        bucket->symbols[bucket->genSymbs].header =
            (unsigned int *) chk_malloc(genDeg, sizeof(unsigned int *));

        memcpy(bucket->symbols[bucket->genSymbs].header,
               selectedSymbols,
               genDeg*sizeof(unsigned int));
        bucket->symbols[bucket->genSymbs].deg = genDeg;
        bucket->symbols[bucket->genSymbs].symbLen = bucket->symbLen;

        bucket->genSymbs++;
    }

#ifdef DEBUGdecoderPrintHeaders
    printf("\n");
#endif

    free(selectedSymbols);
    selectedSymbols = NULL;
    return;
}
void panel_control_hand::enviarDatoAlServidorSlot()    
{
    // Detener el timer del Socket
    //timerSocket->stop();
    
    // Velocidad y aceleraciĆ³n
    QTextOStream( &str ) << 1000.0 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << 1000.0 << " # " ;
    s.append( str );
    str = ' \0 ';
    
    
    // Convertir el float a string para enviarlo por el socket
    QTextOStream( &str ) << degree(kinechain->list_plug[14].pval) - 90.0 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[15].pval) + 7.5 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[16].pval) << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[17].pval) + 16.65 << " # " ;
    s.append( str );
    str = ' \0 ';
    
    QTextOStream( &str ) << degree(kinechain->list_plug[10].pval) - 90.0 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[11].pval) + 7.5 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[12].pval) << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[13].pval) + 16.65 << " # " ;
    s.append( str );
    str = ' \0 ';

    QTextOStream( &str ) << degree(kinechain->list_plug[6].pval) - 90.0 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[7].pval) + 7.5 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[8].pval) << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[9].pval) + 16.65 << " # " ;
    s.append( str );
    str = ' \0 ';
    
    QTextOStream( &str ) << degree(kinechain->list_plug[18].pval) - 45.44<< " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[19].pval) + 7.5 << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[20].pval) << " # " ;
    s.append( str );
    str = ' \0 ';
    QTextOStream( &str ) << degree(kinechain->list_plug[21].pval) + 12.73 << " # " ;
    s.append( str );
    str = ' \0 ';

    // Enviar el caracter que indica el final de los datos
    QTextOStream( &str ) << " @ " ;
    s.append( str );
    str = ' \0 ';
    
    // Escribimos al servidor
    QTextStream os(socket);
    os << s << "\n";
    s = ' \0 ';
    
    // Verificamos si existe el socket y las restricciones e iniciamos o no el timer
    if ( haySocket == 1 && connect_active == TRUE )
    timer_socket->start(400, TRUE);
}
Example #22
0
Poly2Mod compose(const Poly2Mod& q,const Poly2Mod& p)
{ // compose polynomials
  // assume P(x) = P3x^3 + P2x^2 + P1x^1 +P0
  // Calculate P(Q(x)) = P3.(Q(x))^3 + P2.(Q(x))^2 ....   
    Poly2Mod C,Q,T; 
    big t; 
    term2 *xptr,*yptr;
    int i,j,ik,L,n=degree(Modulus);
    int k=isqrt(n+1,1);
    if (k*k<n+1) k++;

// step 1

    Poly2Mod *P=new Poly2Mod[k+1];
    P[0]=1;
    for (i=1;i<=k;i++) P[i]=(P[i-1]*p);

    big *x,*y;
    x=(big *)mr_alloc(k,sizeof(big));
    y=(big *)mr_alloc(k,sizeof(big));
    t=mirvar(0);

    T=1;
    for (i=0;i<k;i++)
    {
        ik=i*k;
        Q.clear();
        for (L=0;L<=n;L++)
        {
            zero(t);
            xptr=q.p.start;
            while (xptr!=NULL) 
            {
                if (xptr->n<=ik+k-1) break;
                xptr=xptr->next;
            }
            for (j=k-1;j>=0;j--)
            {
                x[j]=t;
                if (xptr!=NULL)
                {
                    if (ik+j==xptr->n) 
                    {
                        x[j]=getbig(xptr->an);
                        xptr=xptr->next;
                    }
                }                
                              // x[j]=q.coeff(i*k+j)
                y[j]=t;
                yptr=P[j].p.start;
                while (yptr!=NULL)
                {
                    if (yptr->n<=L)
                    {
                        if (yptr->n==L) y[j]=getbig(yptr->an);
                        break;
                    }
                    yptr=yptr->next;
                }
            }                // y[j]=P[j].coeff(L)

// Asymptotically slow, but fast in practise ...
            gf2m_dotprod(k,x,y,t);
            Q.addterm((GF2m)t,L);
        }
        C+=(Q*T);  
        if (i<k-1) T*=P[k]; 
    }
    mr_free(t);
    mr_free(y);
    mr_free(x);

    delete [] P;
    return C;
}
Example #23
0
int FreeModule::primary_degree(int i) const
{
    int result = degree_monoid()->degree_weights(degree(i),get_ring()->get_heft_vector());
    return result;
}
Example #24
0
int degree(const Poly2Mod& m)  {return degree(m.p);}
Example #25
0
 /**
  * Factor to convert from minutes to radians
  **********************************************************************/
 static inline Math::real arcminute() throw() { return degree() / 60; }
Example #26
0
void setmod(const Poly2& p) 
{ 
    int i,n,m;
    Poly2 h;
    term2 *ptr;
    Modulus=p;

    n=degree(p);
    if (n<KARAT_BREAK_EVEN) return;
    h=reverse(p);
    h=invmodxn(h,n);
    h=reverse(h);   // h=RECIP(f)
    m=degree(h);
    if (m<n-1) h=mulxn(h,n-1-m);


    if (GF!=NULL)
    { // kill last Modulus
        for (i=0;i<N+2;i++)
        { 
            mr_free(GF[i]);
            mr_free(GRF[i]);
            mr_free(Q[i]); 
        }
        for (i=0;i<2*(N+INC);i++)
        {
            mr_free(W[i]);
            mr_free(T[i]);
        }
        mr_free(GF);
        mr_free(GRF);
        mr_free(Q);
        mr_free(W);
        mr_free(T);;
    }

    N=n;
    m=N; INC=0;
    while (m!=0) { m/=2; INC++; }

    GF=(big *)mr_alloc(N+2,sizeof(big));
    GRF=(big *)mr_alloc(N+2,sizeof(big));
    Q=(big *)mr_alloc(N+2,sizeof(big));

    W=(big *)mr_alloc(2*(N+INC),sizeof(big));
    T=(big *)mr_alloc(2*(N+INC),sizeof(big));

    for (i=0;i<N+2;i++)
    {
        GF[i]=mirvar(0);
        GRF[i]=mirvar(0);
        Q[i]=mirvar(0);
    }
    for (i=0;i<2*(N+INC);i++) 
    {
        W[i]=mirvar(0);
        T[i]=mirvar(0);
    }

    ptr=p.start;
    while (ptr!=NULL)
    {
        copy(getbig(ptr->an),GF[ptr->n]);
        ptr=ptr->next;
    }
    ptr=h.start;
    while (ptr!=NULL)
    {
        copy(getbig(ptr->an),GRF[ptr->n]);
        ptr=ptr->next;
    }
}
Example #27
0
int main(int argc, char** argv)
{
	size_t size=1<<5;
	if(argc>1) size=1<<atoi(argv[1]);
	size_t ne=size*size/8 + 1;

	boost::mt19937 rng;
	if(argc>2){
		rng.seed(atoi(argv[2]));
	}

	typedef bald_t G;
	bald_t g;
	boost::generate_random_graph(g, size, ne, rng);
	size_t e=boost::num_edges(g);
	size_t n=boost::num_vertices(g);
	std::cout << "generated " << e << " edges, " << n << " vertices\n";

	BOOST_AUTO(EE, boost::edges(g));
	for(;EE.first!=EE.second; ++EE.first){
		auto s=boost::source(*EE.first, g);
		auto t=boost::target(*EE.first, g);
		if(!boost::edge(t, s, g).second){
			boost::add_edge(t, s, g);
		}
	}

	// boost::add_edge(0,1,g);
	e=boost::num_edges(g);

	std::cout << "symmetric " << e << " edges\n";

	unsigned i=0;
	BOOST_AUTO(E, boost::edges(g));
	for(;E.first!=E.second; ++E.first){
		++i;

		std::cout << boost::source(*E.first, g) << " -- " <<
			boost::target(*E.first, g) << "\n";

		if(i==5) break;

	}

	std::deque<unsigned long > iso;
	BOOST_AUTO(V, boost::vertices(g));
	for(;V.first!=V.second; ++V.first){
			if(boost::out_degree(*V.first, g)){

			}else{
				iso.push_back(*V.first);
			}
	}

#ifdef REMOVE_ISOLATED
	// no longer necessary.
	for(auto i: iso){
		boost::remove_vertex(i, g);
	}
#endif

	n = boost::num_vertices(g);

	V=boost::vertices(g);
	for(;V.first!=V.second; ++V.first){
		assert(*V.first<n);
//		assert(boost::out_degree(*V.first,g));
	}

	std::cout << "tagged " << iso.size() <<"\n";

	i = 0;
	// boost md does not like cliques.
	trace3("clique check", n, e, size);
	if((n*(n-1u)) == boost::num_edges(g)){ untested();
		exit(0);
	}else{
		itested();
	}

	std::vector<int> inverse_perm(n, 0);
	std::vector<int> supernode_sizes(n, 1);
	BOOST_AUTO(id, boost::get(boost::vertex_index, g));
	std::vector<int> degree(n, 0);
	std::vector<int> io(n, 0);
	std::vector<int> o(n, 0);

	G h(g);
	assert(boost::num_edges(g)==boost::num_edges(g));

//	assert(n + iso.size() == size);

	/*
	 * (Graph& g,
	 *  DegreeMap degree,
	 *  InversePermutationMap inverse_perm,
	 *  PermutationMap perm,
	 *  SuperNodeMap supernode_size,
	 *  int delta,
	 *  VertexIndexMap vertex_index_map)
	 */

	unsigned ub=-1;

	unsigned w =
#ifndef HAVE_MINDEGREE_FORK
		0;
	itested();
#endif
	boost::minimum_degree_ordering
		(g,
		 boost::make_iterator_property_map(&degree[0], id, degree[0]),
		 &io[0],
		 &o[0],
		 boost::make_iterator_property_map(&supernode_sizes[0], id, supernode_sizes[0]),
		 0,
		 id
#ifdef HAVE_MINDEGREE_FORK
		 , ub
#endif
		);
	typename treedec::graph_traits<G>::treedec_type t;
	g = h; // restore

	int status;
#ifdef TRY_INEFFICIENT_VARIANT
	treedec::ordering_to_treedec(g, o, t ); // can kill g!
   h=g; // restore

	status = treedec::check_treedec(g,t);
	std::cout << "bagsize " << treedec::get_bagsize(t) << " status " << status <<"\n";
	std::cout << "same as bagsize! " << w <<"\n";
	assert(w == treedec::get_bagsize(t)); /// checks if BMD works!
#endif

	treedec::draft::vec_ordering_to_tree(g, o, t );

	status=treedec::check_treedec(g, t);
	if (!status) std::cout << "treedec is valid!!\n";
	std::cout << "bagsize " << treedec::get_bagsize(t) << " status " << status <<"\n";
	std::cout << "boost_minDegree_ordering said " << w << "\n";
	assert(!status);

	if(w != treedec::get_bagsize(t)){
	}
	assert(w == treedec::get_bagsize(t));


}
Example #28
0
  Vector Bspline::basis(double x) const {
    if (basis_dimension_ == 0) {
      return Vector(0);
    }

    // Each basis function looks forward 'degree' knots to include x.
    Vector ans(basis_dimension(), 0.0);
    if (x < knots_[0] || x > knots_.back()) {
      return ans;
    }

    // To find the knot in the left endpoint of the knot span, we first find the
    Vector::const_iterator terminal_knot_position = std::upper_bound(
        knots_.begin(), knots_.end(), x);
    int terminal_knot = terminal_knot_position - knots_.begin();
    int knot_span_for_x = terminal_knot - 1;

    // Each row of the basis_function_table corresponds to one knot
    // span.  Row zero corresponds to [knots_[0], knots_[1]), row 1 to
    // [knots_[1], knots_[2]), etc.  The columns correspond to the
    // degree of the spline.  We first compute the zero-degree bases.
    // We can use the zero-degree bases to get the first degree bases,
    // etc.
    //
    // The zero-degree basis is 1 in exactly one position (the knot
    // span containing x).  The linear basis is nonzero in two
    // positions: knot span containing x and the the one prior to
    // that.  Each additional degree increases the number of nonzero
    // knot-spans by 1.
    //
    // Given the initial (zero-degree) basis, we can compute each
    // higher degree basis using the recurrence relation:
    //   basis[knot_span, degree](x) =
    //       L(x, knot, degree) * basis(knot, degree - 1)
    //      +R(x, knot, degree) * basis(knot + 1, degree - 1)
    // The left coefficient L is
    //
    //                        (x - knots_[knot])
    // L(x, knot, degree) =   ---------------------
    //                  knots_[knot + degree] - knots_[knot]
    //
    // if the denominator is zero (because of knot multiplicity) then
    // the value of L is arbitrary, so we set it to zero.
    //
    // and the right coefficient R is
    //     R(x, knot, degree) = 1 - L(x, knot + 1, degree).
    //
    // All this is explained in deBoor ("A Practical Guide to
    // Splines") chapter IX, and online at
    // www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-basis.html

    int number_of_knot_spans = number_of_knots() - 1;

    // The entries of basis_function_table, column d, are the spline
    // basis functions of degree d.
    ArbitraryOffsetMatrix basis_function_table(
        -degree(), number_of_knot_spans + order_,
        0, order_,
        0.0);

    basis_function_table(knot_span_for_x, 0) = 1.0;
    for (int d = 1; d <= degree(); ++d) {
      // For a given knot_span containing x, each spline basis of
      // degree d is nonzero over its knot span, and the next d spans.
      // Thus to find the set of nonzero bases containing x, we must
      // look _back_ d spaces.
      for (int lag = 0; lag <= d; ++lag) {
        int span = knot_span_for_x - lag;
        double left_coefficient = compute_coefficient(x, span, d);
        double right_coefficient =
            1 - compute_coefficient(x, span + 1, d);
        double left_basis = basis_function_table(span, d - 1);
        double right_basis =
            span < number_of_knot_spans ?
                   basis_function_table(span + 1, d - 1) : 0.0;
        basis_function_table(span, d) = left_coefficient * left_basis
            + right_coefficient * right_basis;
      }
    }
    if (number_of_knots() > 1) {
      for (int i = -degree(); i < number_of_knot_spans; ++i) {
        ans[i + degree()] = basis_function_table(i, degree());
      }
    }
    return(ans);
  }
Example #29
0
File: elch.hpp Project: Bardo91/pcl
template <typename PointT> void
pcl::registration::ELCH<PointT>::loopOptimizerAlgorithm (LOAGraph &g, double *weights)
{
  std::list<int> crossings, branches;
  crossings.push_back (static_cast<int> (loop_start_));
  crossings.push_back (static_cast<int> (loop_end_));
  weights[loop_start_] = 0;
  weights[loop_end_] = 1;

  int *p = new int[num_vertices (g)];
  int *p_min = new int[num_vertices (g)];
  double *d = new double[num_vertices (g)];
  double *d_min = new double[num_vertices (g)];
  double dist;
  bool do_swap = false;
  std::list<int>::iterator crossings_it, end_it, start_min, end_min;

  // process all junctions
  while (!crossings.empty ())
  {
    dist = -1;
    // find shortest crossing for all vertices on the loop
    for (crossings_it = crossings.begin (); crossings_it != crossings.end (); )
    {
      dijkstra_shortest_paths (g, *crossings_it, boost::predecessor_map (p).distance_map (d));
      end_it = crossings_it;
      end_it++;
      // find shortest crossing for one vertex
      for (; end_it != crossings.end (); end_it++)
      {
        if (*end_it != p[*end_it] && (dist < 0 || d[*end_it] < dist))
        {
          dist = d[*end_it];
          start_min = crossings_it;
          end_min = end_it;
          do_swap = true;
        }
      }
      if (do_swap)
      {
        std::swap (p, p_min);
        std::swap (d, d_min);
        do_swap = false;
      }
      // vertex starts a branch
      if (dist < 0)
      {
        branches.push_back (static_cast<int> (*crossings_it));
        crossings_it = crossings.erase (crossings_it);
      }
      else
        crossings_it++;
    }

    if (dist > -1)
    {
      remove_edge (*end_min, p_min[*end_min], g);
      for (int i = p_min[*end_min]; i != *start_min; i = p_min[i])
      {
        //even right with weights[*start_min] > weights[*end_min]! (math works)
        weights[i] = weights[*start_min] + (weights[*end_min] - weights[*start_min]) * d_min[i] / d_min[*end_min];
        remove_edge (i, p_min[i], g);
        if (degree (i, g) > 0)
        {
          crossings.push_back (i);
        }
      }

      if (degree (*start_min, g) == 0)
        crossings.erase (start_min);

      if (degree (*end_min, g) == 0)
        crossings.erase (end_min);
    }
  }

  delete[] p;
  delete[] p_min;
  delete[] d;
  delete[] d_min;

  boost::graph_traits<LOAGraph>::adjacency_iterator adjacent_it, adjacent_it_end;
  int s;

  // error propagation
  while (!branches.empty ())
  {
    s = branches.front ();
    branches.pop_front ();

    for (boost::tuples::tie (adjacent_it, adjacent_it_end) = adjacent_vertices (s, g); adjacent_it != adjacent_it_end; ++adjacent_it)
    {
      weights[*adjacent_it] = weights[s];
      if (degree (*adjacent_it, g) > 1)
        branches.push_back (static_cast<int> (*adjacent_it));
    }
    clear_vertex (s, g);
  }
}
Example #30
0
    int isFlat (qreal tolerance) const
    {
        int deg = degree();

        // Find the  perpendicular distance from each interior control point to
        // the line connecting points[0] and points[degree]
        qreal *distance = new qreal[deg + 1];

        // Derive the implicit equation for line connecting first and last control points
        qreal a = points[0].y() - points[deg].y();
        qreal b = points[deg].x() - points[0].x();
        qreal c = points[0].x() * points[deg].y() - points[deg].x() * points[0].y();

        qreal abSquared = (a * a) + (b * b);

        for (int i = 1; i < deg; i++) {
            // Compute distance from each of the points to that line
            distance[i] = a * points[i].x() + b * points[i].y() + c;
            if (distance[i] > 0.0) {
                distance[i] = (distance[i] * distance[i]) / abSquared;
            }
            if (distance[i] < 0.0) {
                distance[i] = -((distance[i] * distance[i]) / abSquared);
            }
        }


        // Find the largest distance
        qreal max_distance_above = 0.0;
        qreal max_distance_below = 0.0;
        for (int i = 1; i < deg; i++) {
            if (distance[i] < 0.0) {
                max_distance_below = qMin(max_distance_below, distance[i]);
            }
            if (distance[i] > 0.0) {
                max_distance_above = qMax(max_distance_above, distance[i]);
            }
        }
        delete [] distance;

        // Implicit equation for zero line
        qreal a1 = 0.0;
        qreal b1 = 1.0;
        qreal c1 = 0.0;

        // Implicit equation for "above" line
        qreal a2 = a;
        qreal b2 = b;
        qreal c2 = c + max_distance_above;

        qreal det = a1 * b2 - a2 * b1;
        qreal dInv = 1.0/det;

        qreal intercept_1 = (b1 * c2 - b2 * c1) * dInv;

        // Implicit equation for "below" line
        a2 = a;
        b2 = b;
        c2 = c + max_distance_below;

        det = a1 * b2 - a2 * b1;
        dInv = 1.0/det;

        qreal intercept_2 = (b1 * c2 - b2 * c1) * dInv;

        // Compute intercepts of bounding box
        qreal left_intercept = qMin(intercept_1, intercept_2);
        qreal right_intercept = qMax(intercept_1, intercept_2);

        qreal error = 0.5 * (right_intercept-left_intercept);

        return (error < tolerance);
    }