Ejemplo n.º 1
0
CRef<CSeq_entry> CSraRun::GetSpotEntry(spotid_t spot_id) const
{
    CRef<CSeq_entry> entry;
    
    CSraStringValue name(m_Name, spot_id);

    entry = new CSeq_entry();
    CBioseq_set& seqset = entry->SetSet();
    seqset.SetLevel(0);
    seqset.SetClass(seqset.eClass_other);

    CSraValueFor<SRASpotDesc> sdesc(m_SDesc, spot_id);
    TSeqPos trim_start = m_Trim && m_TrimStart?
        CSraValueFor<INSDC_coord_zero>(m_TrimStart, spot_id).Value(): 0;
    TSeqPos trim_end = sdesc->clip_qual_right;

    CSraValueFor<SRAReadDesc> rdesc(m_RDesc, spot_id);
    CSraStringValue read(m_Read, spot_id);
    CSraBytesValue qual(m_Qual, spot_id);
    int seq_count = 0;
    string id_start = GetAccession()+'.'+NStr::UIntToString(spot_id)+'.';
    for ( int r = 0; r < sdesc->num_reads; ++r ) {
        if ( rdesc[r].type != SRA_READ_TYPE_BIOLOGICAL ) {
            continue;
        }
        TSeqPos len = rdesc[r].seg.len;
        if ( len == 0 ) {
            continue;
        }
        TSeqPos start = rdesc[r].seg.start;
        TSeqPos end = start + len;
        if ( m_Trim ) {
            start = max(start, trim_start);
            end = min(end, trim_end);
            if ( start >= end ) {
                continue;
            }
            len = end - start;
        }

        CRef<CSeq_entry> seq_entry(new CSeq_entry);
        CBioseq& seq = seq_entry->SetSeq();
        
        CRef<CSeq_id> id(new CSeq_id);
        id->SetGeneral().SetDb("SRA");
        id->SetGeneral().SetTag().SetStr(id_start+NStr::UIntToString(r+1));
        seq.SetId().push_back(id);

        {{
            CRef<CSeqdesc> desc(new CSeqdesc);
            desc->SetTitle(name.Value());
            seq.SetDescr().Set().push_back(desc);
        }}
        {{
            CSeq_inst& inst = seq.SetInst();
            inst.SetRepr(inst.eRepr_raw);
            inst.SetMol(inst.eMol_na);
            inst.SetLength(len);
            inst.SetSeq_data().SetIupacna().Set()
                .assign(read.data()+start, len);
        }}
        {{
            CRef<CSeq_annot> annot(new CSeq_annot);
            CRef<CSeq_graph> graph(new CSeq_graph);
            annot->SetData().SetGraph().push_back(graph);
            graph->SetTitle("Phred Quality");
            graph->SetLoc().SetWhole(*id);
            graph->SetNumval(len);
            CByte_graph& bytes = graph->SetGraph().SetByte();
            bytes.SetAxis(0);
            CByte_graph::TValues& values = bytes.SetValues();
            values.reserve(len);
            int min = kMax_Int;
            int max = kMin_Int;
            for ( size_t i = 0; i < len; ++i ) {
                int v = qual[start+i];
                values.push_back(v);
                if ( v < min ) {
                    min = v;
                }
                if ( v > max ) {
                    max = v;
                }
            }
            bytes.SetMin(min);
            bytes.SetMax(max);

            seq.SetAnnot().push_back(annot);
        }}

        seqset.SetSeq_set().push_back(seq_entry);
        ++seq_count;
    }
    switch ( seq_count ) {
    case 0:
        entry.Reset();
        break;
    case 1:
        entry = seqset.GetSeq_set().front();
        break;
    }
    return entry;
}
Ejemplo n.º 2
0
void ExcitedStates::plotSpectrum(Profile const profile, double const width)
{
//qDebug() << "Plot spectrum called";
   unsigned const bins(200);
   double const maxEnergy(m_maxValues.first+3);
   double const delta(maxEnergy/bins);

   QVector<double> x(bins), y(bins);

   for (int xi = 0; xi < bins; ++xi) {
       x[xi] = xi*delta;
       y[xi] = 0.0;
   }

   switch (profile) {

      case Gaussian: {
         double g(0.02*width);
         double A(std::sqrt(4.0*std::log(2.0)/(g*M_PI)));
         double a(-4.0*std::log(2.0)/g);
         for (int mode = 0; mode < m_rawData.size(); ++mode) {
             double nu(m_rawData[mode].first);
             double I(m_rawData[mode].second);
             for (unsigned xi = 0; xi < bins; ++xi) {
                 y[xi] += I*A*std::exp(a*(x[xi]-nu)*(x[xi]-nu));
             }
         }
      } break;

      case Lorentzian: {
         double A(2.0/M_PI);
         double g(0.005*width);
         double g2(g*g);
         for (int mode = 0; mode < m_rawData.size(); ++mode) {
             double nu(m_rawData[mode].first);
             double I(m_rawData[mode].second);
             for (unsigned xi = 0; xi < bins; ++xi) {
                 y[xi] += I*A*g / (g2+(x[xi]-nu)*(x[xi]-nu));
             }
         }
      } break;

   }

   double maxIntensity(0.0);
   for (int xi = 0; xi < bins; ++xi) {
       if (y[xi] > maxIntensity) maxIntensity = y[xi];
   }

   for (int xi = 0; xi < bins; ++xi) {
       y[xi] /= maxIntensity;
   }

   QCPGraph* graph(m_spectrum->addGraph());
   graph->setData(x, y);
   graph->setPen(m_pen);
   graph->setAntialiased(true);
   graph->setSelectedPen(m_selectedPen);

   m_spectrum->xAxis->setRange(0, maxEnergy);
   m_spectrum->yAxis->setRange(0, 1.00);
   m_spectrum->yAxis->setAutoTickStep(false);
   m_spectrum->yAxis->setTickStep(0.2);
}
Ejemplo n.º 3
0
int main(int argc, char** argv) {
  // Initialize control plain using mpi
  graphlab::mpi_tools::init(argc, argv);
  graphlab::distributed_control dc;
  global_logger().set_log_level(LOG_INFO);

  // Parse command line options -----------------------------------------------
  graphlab::command_line_options 
    clopts("Single Source Shortest Path Algorithm.");
  std::string graph_dir;
  std::string format = "adj";
  std::string exec_type = "synchronous";
  size_t powerlaw = 0;
  std::vector<graphlab::vertex_id_type> sources;
  bool max_degree_source = false;
  clopts.attach_option("graph", graph_dir,
                       "The graph file.  If none is provided "
                       "then a toy graph will be created");
  clopts.add_positional("graph");
  clopts.attach_option("format", format,
                       "graph format");
  clopts.attach_option("source", sources,
                       "The source vertices");
  clopts.attach_option("max_degree_source", max_degree_source,
                       "Add the vertex with maximum degree as a source");

  clopts.add_positional("source");

  clopts.attach_option("directed", DIRECTED_SSSP,
                       "Treat edges as directed.");

  clopts.attach_option("engine", exec_type, 
                       "The engine type synchronous or asynchronous");
 
  
  clopts.attach_option("powerlaw", powerlaw,
                       "Generate a synthetic powerlaw out-degree graph. ");
  std::string saveprefix;
  clopts.attach_option("saveprefix", saveprefix,
                       "If set, will save the resultant pagerank to a "
                       "sequence of files with prefix saveprefix");

  if(!clopts.parse(argc, argv)) {
    dc.cout() << "Error in parsing command line arguments." << std::endl;
    return EXIT_FAILURE;
  }


  // Build the graph ----------------------------------------------------------
  graph_type graph(dc, clopts);
  if(powerlaw > 0) { // make a synthetic graph
    dc.cout() << "Loading synthetic Powerlaw graph." << std::endl;
    graph.load_synthetic_powerlaw(powerlaw, false, 2, 100000000);
  } else if (graph_dir.length() > 0) { // Load the graph from a file
    dc.cout() << "Loading graph in format: "<< format << std::endl;
    graph.load_format(graph_dir, format);
  } else {
    dc.cout() << "graph or powerlaw option must be specified" << std::endl;
    clopts.print_description();
    return EXIT_FAILURE;
  }
  // must call finalize before querying the graph
  graph.finalize();
  dc.cout() << "#vertices:  " << graph.num_vertices() << std::endl
            << "#edges:     " << graph.num_edges() << std::endl;



  if(sources.empty()) {
    if (max_degree_source == false) {
      dc.cout()
        << "No source vertex provided. Adding vertex 0 as source" 
        << std::endl;
      sources.push_back(0);
    }
  }

  if (max_degree_source) {
    max_deg_vertex_reducer v = graph.map_reduce_vertices<max_deg_vertex_reducer>(find_max_deg_vertex);
    dc.cout()
      << "No source vertex provided.  Using highest degree vertex " << v.vid << " as source."
      << std::endl;
    sources.push_back(v.vid);
  }



  // Running The Engine -------------------------------------------------------
  graphlab::omni_engine<sssp> engine(dc, graph, exec_type, clopts);


  
  // Signal all the vertices in the source set
  for(size_t i = 0; i < sources.size(); ++i) {
    engine.signal(sources[i], min_distance_type(0));
  }

  engine.start();
  const float runtime = engine.elapsed_seconds();
  dc.cout() << "Finished Running engine in " << runtime
            << " seconds." << std::endl;


  // Save the final graph -----------------------------------------------------
  if (saveprefix != "") {
    graph.save(saveprefix, shortest_path_writer(),
               false,    // do not gzip
               true,     // save vertices
               false);   // do not save edges
  }

  // Tear-down communication layer and quit -----------------------------------
  graphlab::mpi_tools::finalize();
  return EXIT_SUCCESS;
} // End of main
	bool exactProbability(const context::inputGraph& inputGraph, std::vector<mpfr_class>& probabilities, mpfr_class& result, std::string& error)
	{
		error = "";
		const std::size_t nVertices = boost::num_vertices(inputGraph);
		if(probabilities.size() == 1)
		{
			probabilities.insert(probabilities.begin(), nVertices - 1, probabilities.front());
		}
		if(nVertices > 36)
		{
			error = "Maximum allowable number of vertices is 36.";
			return false;
		}
		if(probabilities.size() != nVertices)
		{
			error = "Length of input probabilities was different from the number of vertices";
			return false;
		}
		std::vector<mpfr_class> complementaryProbabilities;
		for(std::vector<mpfr_class>::iterator i = probabilities.begin(); i != probabilities.end(); i++)
		{
			complementaryProbabilities.push_back(1 - *i);
		}
		const counterType maximumState = 1LL << nVertices;
	
		result = 0;
#ifdef USE_OPENMP
		#pragma omp parallel 
#endif
		{		
			mpfr_class privateResult = 0;

			std::vector<int> connectedComponents(nVertices);
			std::vector<int> vertexIndices(nVertices);
			typedef boost::adjacency_matrix<boost::undirectedS> graphType;
			graphType graph(nVertices, boost::no_property());
#ifdef USE_OPENMP
			#pragma omp for
#endif
			for(counterType state = 0; state < maximumState; state++)
			{
				//first the vertices
				int nVerticesSubgraph = 0;
				for(int vertexCounter = 0; vertexCounter < (int)nVertices; vertexCounter++)
				{
					if(state & (1LL << vertexCounter)) 
					{
						vertexIndices[vertexCounter] = nVerticesSubgraph++;
					}
				}
				graph.m_matrix.clear();
				graph.m_matrix.resize(nVerticesSubgraph * (nVerticesSubgraph+ 1) / 2);
				graph.m_vertex_set = graphType::VertexList(0, nVerticesSubgraph);
				
				graph.m_vertex_properties.clear();
				graph.m_vertex_properties.resize(nVerticesSubgraph);
				graph.m_num_edges = 0;

				//now the edges
				context::inputGraph::edge_iterator start, end;
				boost::tie(start, end) = boost::edges(inputGraph);
				while(start != end)
				{
					if((state & (1LL << start->m_source)) && (state & (1LL << start->m_target)))
					{
						boost::add_edge(vertexIndices[start->m_source], vertexIndices[start->m_target], graph);
					}
					start++;
				}
				int nComponents = boost::connected_components(graph, &(connectedComponents[0]));
				if(nComponents <= 1)
				{
					mpfr_class currentTerm = 1;
					for(int vertexCounter = 0; vertexCounter < (int)nVertices; vertexCounter++)
					{
						if(state & (1LL << vertexCounter)) currentTerm *= probabilities[vertexCounter];
						else currentTerm *= complementaryProbabilities[vertexCounter];
					}
					privateResult += currentTerm;
				}
			}
#ifdef USE_OPENMP
			#pragma omp critical
#endif
			{
				result += privateResult;
			}
		}
		return true;
	}
Ejemplo n.º 5
0
void ParmetisPartitioner::build_graph (const MeshBase& mesh)
{
  // build the graph in distributed CSR format.  Note that
  // the edges in the graph will correspond to
  // face neighbors
  const dof_id_type n_active_local_elem  = mesh.n_active_local_elem();

  // If we have boundary elements in this mesh, we want to account for
  // the connectivity between them and interior elements.  We can find
  // interior elements from boundary elements, but we need to build up
  // a lookup map to do the reverse.

  typedef LIBMESH_BEST_UNORDERED_MAP<const Elem *, const Elem *>
    map_type;
  map_type interior_to_boundary_map;

  {
    MeshBase::const_element_iterator       elem_it  = mesh.active_elements_begin();
    const MeshBase::const_element_iterator elem_end = mesh.active_elements_end();

    for (; elem_it != elem_end; ++elem_it)
      {
        const Elem* elem = *elem_it;

        // If we don't have an interior_parent then there's nothing to look us
        // up.
        if ((elem->dim() >= LIBMESH_DIM) ||
            !elem->interior_parent())
          continue;

        // get all relevant interior elements
        std::set<const Elem*> neighbor_set;
        elem->find_interior_neighbors(neighbor_set);

        std::set<const Elem*>::iterator n_it = neighbor_set.begin();
        for (; n_it != neighbor_set.end(); ++n_it)
          {
            // FIXME - non-const versions of the Elem set methods
            // would be nice
            Elem* neighbor = const_cast<Elem*>(*n_it);

#if defined(LIBMESH_HAVE_UNORDERED_MAP) || defined(LIBMESH_HAVE_TR1_UNORDERED_MAP) || defined(LIBMESH_HAVE_HASH_MAP) || defined(LIBMESH_HAVE_EXT_HASH_MAP)
            interior_to_boundary_map.insert
              (std::make_pair(neighbor, elem));
#else
            interior_to_boundary_map.insert
              (interior_to_boundary_map.begin(),
               std::make_pair(neighbor, elem));
#endif
          }
      }
  }

#ifdef LIBMESH_ENABLE_AMR
  std::vector<const Elem*> neighbors_offspring;
#endif

  std::vector<std::vector<dof_id_type> > graph(n_active_local_elem);
  dof_id_type graph_size=0;

  const dof_id_type first_local_elem = _pmetis->vtxdist[mesh.processor_id()];

  MeshBase::const_element_iterator       elem_it  = mesh.active_local_elements_begin();
  const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end();

  for (; elem_it != elem_end; ++elem_it)
    {
      const Elem* elem = *elem_it;

      libmesh_assert (_global_index_by_pid_map.count(elem->id()));
      const dof_id_type global_index_by_pid =
        _global_index_by_pid_map[elem->id()];

      const dof_id_type local_index =
        global_index_by_pid - first_local_elem;
      libmesh_assert_less (local_index, n_active_local_elem);

      std::vector<dof_id_type> &graph_row = graph[local_index];

      // Loop over the element's neighbors.  An element
      // adjacency corresponds to a face neighbor
      for (unsigned int ms=0; ms<elem->n_neighbors(); ms++)
        {
          const Elem* neighbor = elem->neighbor(ms);

          if (neighbor != NULL)
            {
              // If the neighbor is active treat it
              // as a connection
              if (neighbor->active())
                {
                  libmesh_assert(_global_index_by_pid_map.count(neighbor->id()));
                  const dof_id_type neighbor_global_index_by_pid =
                    _global_index_by_pid_map[neighbor->id()];

                  graph_row.push_back(neighbor_global_index_by_pid);
                  graph_size++;
                }

#ifdef LIBMESH_ENABLE_AMR

              // Otherwise we need to find all of the
              // neighbor's children that are connected to
              // us and add them
              else
                {
                  // The side of the neighbor to which
                  // we are connected
                  const unsigned int ns =
                    neighbor->which_neighbor_am_i (elem);
                  libmesh_assert_less (ns, neighbor->n_neighbors());

                  // Get all the active children (& grandchildren, etc...)
                  // of the neighbor

                  // FIXME - this is the wrong thing, since we
                  // should be getting the active family tree on
                  // our side only.  But adding too many graph
                  // links may cause hanging nodes to tend to be
                  // on partition interiors, which would reduce
                  // communication overhead for constraint
                  // equations, so we'll leave it.

                  neighbor->active_family_tree (neighbors_offspring);

                  // Get all the neighbor's children that
                  // live on that side and are thus connected
                  // to us
                  for (unsigned int nc=0; nc<neighbors_offspring.size(); nc++)
                    {
                      const Elem* child =
                        neighbors_offspring[nc];

                      // This does not assume a level-1 mesh.
                      // Note that since children have sides numbered
                      // coincident with the parent then this is a sufficient test.
                      if (child->neighbor(ns) == elem)
                        {
                          libmesh_assert (child->active());
                          libmesh_assert (_global_index_by_pid_map.count(child->id()));
                          const dof_id_type child_global_index_by_pid =
                            _global_index_by_pid_map[child->id()];

                          graph_row.push_back(child_global_index_by_pid);
                          graph_size++;
                        }
                    }
                }

#endif /* ifdef LIBMESH_ENABLE_AMR */


            }
        }

      if ((elem->dim() < LIBMESH_DIM) &&
          elem->interior_parent())
        {
          // get all relevant interior elements
          std::set<const Elem*> neighbor_set;
          elem->find_interior_neighbors(neighbor_set);

          std::set<const Elem*>::iterator n_it = neighbor_set.begin();
          for (; n_it != neighbor_set.end(); ++n_it)
            {
              // FIXME - non-const versions of the Elem set methods
              // would be nice
              Elem* neighbor = const_cast<Elem*>(*n_it);

              const dof_id_type neighbor_global_index_by_pid =
                _global_index_by_pid_map[neighbor->id()];

              graph_row.push_back(neighbor_global_index_by_pid);
              graph_size++;
            }
        }

      // Check for any boundary neighbors
      typedef map_type::iterator map_it_type;
      std::pair<map_it_type, map_it_type>
        bounds = interior_to_boundary_map.equal_range(elem);

      for (map_it_type it = bounds.first; it != bounds.second; ++it)
        {
          const Elem* neighbor = it->second;

          const dof_id_type neighbor_global_index_by_pid =
            _global_index_by_pid_map[neighbor->id()];

          graph_row.push_back(neighbor_global_index_by_pid);
          graph_size++;
        }
    }

  // Reserve space in the adjacency array
  _pmetis->xadj.clear();
  _pmetis->xadj.reserve (n_active_local_elem + 1);
  _pmetis->adjncy.clear();
  _pmetis->adjncy.reserve (graph_size);

  for (std::size_t r=0; r<graph.size(); r++)
    {
      _pmetis->xadj.push_back(_pmetis->adjncy.size());
      std::vector<dof_id_type> graph_row; // build this emtpy
      graph_row.swap(graph[r]); // this will deallocate at the end of scope
      _pmetis->adjncy.insert(_pmetis->adjncy.end(),
                             graph_row.begin(),
                             graph_row.end());
    }

  // The end of the adjacency array for the last elem
  _pmetis->xadj.push_back(_pmetis->adjncy.size());

  libmesh_assert_equal_to (_pmetis->xadj.size(), n_active_local_elem+1);
  libmesh_assert_equal_to (_pmetis->adjncy.size(), graph_size);
}
Ejemplo n.º 6
0
static void redrawGraph(void){
	#ifdef ov7670
		graph(rdReg(0x7b),2,pickSel(0));
		graph(rdReg(0x7c),4,pickSel(1));
		graph(rdReg(0x7d),8,pickSel(2));
		graph(rdReg(0x7e),15,pickSel(3));
		graph(rdReg(0x7f),19,pickSel(4));
		graph(rdReg(0x80),23,pickSel(5));
		graph(rdReg(0x81),26,pickSel(6));
		graph(rdReg(0x82),30,pickSel(7));
		graph(rdReg(0x83),34,pickSel(8));
		graph(rdReg(0x84),38,pickSel(9));
		graph(rdReg(0x85),45,pickSel(10));
		graph(rdReg(0x86),53,pickSel(11));
		graph(rdReg(0x87),68,pickSel(12));
		graph(rdReg(0x88),83,pickSel(13));
		graph(rdReg(0x89),98,pickSel(14));
		graph(256-(rdReg(0x7A)*3/4),120,GREEN);
	#elif defined ov7740
		graph(rdReg(0x9C),2,pickSel(0));
		graph(rdReg(0x9D),4,pickSel(1));
		graph(rdReg(0x9E),8,pickSel(2));
		graph(rdReg(0x9F),15,pickSel(3));
		graph(rdReg(0xA0),19,pickSel(4));
		graph(rdReg(0xA1),23,pickSel(5));
		graph(rdReg(0xA2),26,pickSel(6));
		graph(rdReg(0xA3),30,pickSel(7));
		graph(rdReg(0xA4),34,pickSel(8));
		graph(rdReg(0xA5),38,pickSel(9));
		graph(rdReg(0xA6),45,pickSel(10));
		graph(rdReg(0xA7),53,pickSel(11));
		graph(rdReg(0xA8),68,pickSel(12));
		graph(rdReg(0xA9),83,pickSel(13));
		graph(rdReg(0xAA),98,pickSel(14));
		graph(256-(rdReg(0xA8)*3/4),120,GREEN);
	#endif
}
void ClassicalImageInpainting(typename itk::SmartPointer<TImage> originalImage, Mask* const mask,
                              const unsigned int patchHalfWidth)
{
  itk::ImageRegion<2> fullRegion = originalImage->GetLargestPossibleRegion();

  // Blur the image
  typedef TImage BlurredImageType; // Usually the blurred image is the same type as the original image.
  typename BlurredImageType::Pointer blurredImage = BlurredImageType::New();
  float blurVariance = 2.0f;
  MaskOperations::MaskedBlur(originalImage.GetPointer(), mask, blurVariance, blurredImage.GetPointer());

//  ITKHelpers::WriteRGBImage(blurredImage.GetPointer(), "BlurredImage.png");

  typedef ImagePatchPixelDescriptor<TImage> ImagePatchPixelDescriptorType;

  // Create the graph
  typedef boost::grid_graph<2> VertexListGraphType;
  boost::array<std::size_t, 2> graphSideLengths = { { fullRegion.GetSize()[0],
                                                      fullRegion.GetSize()[1] } };
  std::shared_ptr<VertexListGraphType> graph(new VertexListGraphType(graphSideLengths));
  typedef boost::graph_traits<VertexListGraphType>::vertex_descriptor VertexDescriptorType;
  typedef boost::graph_traits<VertexListGraphType>::vertex_iterator VertexIteratorType;

  // Queue
  typedef IndirectPriorityQueue<VertexListGraphType> BoundaryNodeQueueType;
  std::shared_ptr<BoundaryNodeQueueType> boundaryNodeQueue(new BoundaryNodeQueueType(*graph));

  // Create the descriptor map. This is where the data for each pixel is stored.
  typedef boost::vector_property_map<ImagePatchPixelDescriptorType,
      BoundaryNodeQueueType::IndexMapType> ImagePatchDescriptorMapType;
  std::shared_ptr<ImagePatchDescriptorMapType> imagePatchDescriptorMap(new
      ImagePatchDescriptorMapType(num_vertices(*graph), *(boundaryNodeQueue->GetIndexMap())));

  // Create the patch inpainter.
  typedef PatchInpainter<TImage> OriginalImageInpainterType;
  std::shared_ptr<OriginalImageInpainterType> originalImagePatchInpainter(new
      OriginalImageInpainterType(patchHalfWidth, originalImage, mask));
  // Show the inpainted image at each iteration
//  originalImagePatchInpainter.SetDebugImages(true);
//  originalImagePatchInpainter.SetImageName("RGB");

  // Create an inpainter for the blurred image.
  typedef PatchInpainter<BlurredImageType> BlurredImageInpainterType;
  std::shared_ptr<BlurredImageInpainterType> blurredImagePatchInpainter(new
     BlurredImageInpainterType(patchHalfWidth, blurredImage, mask));

  // Create a composite inpainter.
  std::shared_ptr<CompositePatchInpainter> inpainter(new CompositePatchInpainter);
  inpainter->AddInpainter(originalImagePatchInpainter);
  inpainter->AddInpainter(blurredImagePatchInpainter);

  // Create the priority function
  typedef PriorityCriminisi<BlurredImageType> PriorityType;
  std::shared_ptr<PriorityType> priorityFunction(new PriorityType(blurredImage, mask, patchHalfWidth));

  // Create the descriptor visitor
  typedef ImagePatchDescriptorVisitor<VertexListGraphType, TImage, ImagePatchDescriptorMapType>
      ImagePatchDescriptorVisitorType;
  std::shared_ptr<ImagePatchDescriptorVisitorType> imagePatchDescriptorVisitor(new
      ImagePatchDescriptorVisitorType(originalImage.GetPointer(), mask,
                                      imagePatchDescriptorMap, patchHalfWidth));

  typedef DefaultAcceptanceVisitor<VertexListGraphType> AcceptanceVisitorType;
  std::shared_ptr<AcceptanceVisitorType> acceptanceVisitor(new AcceptanceVisitorType);

  // Create the inpainting visitor
  typedef InpaintingVisitor<VertexListGraphType, BoundaryNodeQueueType,
                            ImagePatchDescriptorVisitorType, AcceptanceVisitorType, PriorityType>
                            InpaintingVisitorType;
  std::shared_ptr<InpaintingVisitorType> inpaintingVisitor(new InpaintingVisitorType(mask, boundaryNodeQueue,
                                          imagePatchDescriptorVisitor, acceptanceVisitor,
                                          priorityFunction, patchHalfWidth, "InpaintingVisitor"));
  inpaintingVisitor->SetAllowNewPatches(false);
//  inpaintingVisitor.SetDebugImages(true); // Write PatchesCopied images that show the source and target patch at each iteration

  InitializePriority(mask, boundaryNodeQueue.get(), priorityFunction.get());

  // Initialize the boundary node queue from the user provided mask image.
  InitializeFromMaskImage<InpaintingVisitorType, VertexDescriptorType>(mask, inpaintingVisitor.get());

  // Create the nearest neighbor finder
  typedef ImagePatchDifference<ImagePatchPixelDescriptorType,
      SumSquaredPixelDifference<typename TImage::PixelType> > PatchDifferenceType;

  // Create the best patch searcher
  typedef LinearSearchBestProperty<ImagePatchDescriptorMapType,
                                   PatchDifferenceType> BestSearchType;
  std::shared_ptr<BestSearchType> linearSearchBest(new BestSearchType(*imagePatchDescriptorMap));

  // By specifying the radius as the image size/8, we are searching up to 1/4 of the image each time
  typedef NeighborhoodSearch<VertexDescriptorType, ImagePatchDescriptorMapType> NeighborhoodSearchType;
  NeighborhoodSearchType neighborhoodSearch(fullRegion, fullRegion.GetSize()[0]/8, *imagePatchDescriptorMap);

  // Perform the inpainting
  InpaintingAlgorithmWithLocalSearch<VertexListGraphType, InpaintingVisitorType,
                      BoundaryNodeQueueType, NeighborhoodSearchType,
                      CompositePatchInpainter, BestSearchType>(graph, inpaintingVisitor, boundaryNodeQueue,
                      linearSearchBest, inpainter, neighborhoodSearch);

  /*template <typename TVertexListGraph, typename TInpaintingVisitor,
            typename TPriorityQueue, typename TSearchRegion,
            typename TPatchInpainter, typename TBestPatchFinder>
   InpaintingAlgorithmWithLocalSearch(TVertexListGraph& graph,
                                     TInpaintingVisitor visitor,
                                     TPriorityQueue* boundaryNodeQueue,
                                     TBestPatchFinder bestPatchFinder,
                                     TPatchInpainter* patchInpainter,
                                     TSearchRegion& searchRegion) */
}
Ejemplo n.º 8
0
void GraphSLAM::addDataSM(SE2 currentOdom, RobotLaser* laser){
  boost::mutex::scoped_lock lockg(graphMutex);

  //Add current vertex
  VertexSE2 *v = new VertexSE2;

  SE2 displacement = _lastOdom.inverse() * currentOdom;
  SE2 currEst = _lastVertex->estimate() * displacement;

  v->setEstimate(currEst);
  v->setId(++_runningVertexId + idRobot() * baseId());
  //Add covariance information
  //VertexEllipse *ellipse = new VertexEllipse;
  //Matrix3f cov = Matrix3f::Zero(); //last vertex has zero covariance
  //ellipse->setCovariance(cov);
  //v->setUserData(ellipse);
  v->addUserData(laser);

  std::cout << endl << 
    "Current vertex: " << v->id() << 
    " Estimate: "<< v->estimate().translation().x() << 
    " " << v->estimate().translation().y() << 
    " " << v->estimate().rotation().angle() << std::endl;

  _graph->addVertex(v);

  //Add current odometry edge
  EdgeSE2 *e = new EdgeSE2;
  e->setId(++_runningEdgeId + idRobot() * baseId());
  e->vertices()[0] = _lastVertex;
  e->vertices()[1] = v;
      

  OptimizableGraph::VertexSet vset;
  vset.insert(_lastVertex);
  int j = 1;
  int gap = 5;
  while (j <= gap){
    VertexSE2 *vj =  dynamic_cast<VertexSE2 *>(graph()->vertex(_lastVertex->id()-j));
    if (vj)
      vset.insert(vj);
    else
      break;
    j++;
  }

  SE2 transf;
  bool shouldIAdd = _closeMatcher.closeScanMatching(vset, _lastVertex, v,  &transf, maxScore);

  if (shouldIAdd){
    e->setMeasurement(transf);
    e->setInformation(_SMinf);
  }else{ //Trust the odometry
    e->setMeasurement(displacement);
    // Vector3d dis = displacement.toVector();
    // dis.x() = fabs(dis.x());
    // dis.y() = fabs(dis.y());
    // dis.z() = fabs(dis.z());
    // dis += Vector3d(1e-3,1e-3,1e-2);  
    // Matrix3d dis2 = dis*dis.transpose();
    // Matrix3d newcov = dis2.cwiseProduct(_odomK);
    // e->setInformation(newcov.inverse());

    e->setInformation(_odominf);
  }

  _graph->addEdge(e);

  _lastOdom = currentOdom;
  _lastVertex = v;
}
Ejemplo n.º 9
0
 static Node<Mutex*> & root()
 {
     return graph().root();
 }
Ejemplo n.º 10
0
int main(){
    int x,y,k=20;
    int c=0,gr=1;
    background();
    COORD centr;
    centr.X=40;
    centr.Y=15;
    coordinateAxis(centr);
    graph(centr,k,gr);
	function(gr);
	    while (c != 27){ //27-esc для завершення роботи
        c = _getch();
        switch (c){
    case '8':
        centr.Y--;
        background();
        coordinateAxis (centr);
        graph (centr,k,gr);
        function(gr);
        break;
    case '5':
        centr.Y++;
        background();
        coordinateAxis (centr);
        graph (centr,k,gr);
        function(gr);
        break;
    case '4':
        centr.X--;
        background();
        coordinateAxis (centr);
        graph (centr, k,gr);
        function(gr);
        break;
    case '6':
        centr.X++;
        background();
        coordinateAxis (centr);
        graph (centr, k,gr);
        function(gr);
        break;
    case '+':
        k--;
        if (k == 0)
            k = 1;
        background();
        coordinateAxis (centr);
        graph (centr, k,gr);
        function(gr);
        break;
    case '-':
        k++;
        if (k == 0)
            k = 1;
        background();
        coordinateAxis (centr);
        graph (centr, k,gr);
        function(gr);
        break;
    case 32: // перехід до другого графіку
        gr = (gr == 1) ? 2 : 1;
		background();
        coordinateAxis (centr);
        graph (centr, k,gr);
        function(gr);
        break;
    }
    }

}
void LidarInpaintingRGBTextureVerification(TImage* const originalImage, Mask* const mask,
                                           const unsigned int patchHalfWidth, const unsigned int numberOfKNN,
                                           float slightBlurVariance = 1.0f, unsigned int searchRadius = 1000)
{
  typedef TImage RGBDxDyImageType;

  itk::ImageRegion<2> fullRegion = originalImage->GetLargestPossibleRegion();

  // Extract the RGB image
  typedef itk::Image<itk::CovariantVector<float, 3>, 2> RGBImageType;
  std::vector<unsigned int> firstThreeChannels = {0,1,2};
  RGBImageType::Pointer rgbImage = RGBImageType::New();
  ITKHelpers::ExtractChannels(originalImage, firstThreeChannels, rgbImage.GetPointer());

  // Blur the image for gradient computation stability (Criminisi's data term)
  RGBImageType::Pointer blurredRGBImage = RGBImageType::New();
  float blurVariance = 2.0f;
  MaskOperations::MaskedBlur(rgbImage.GetPointer(), mask, blurVariance, blurredRGBImage.GetPointer());

  ITKHelpers::WriteRGBImage(blurredRGBImage.GetPointer(), "BlurredRGBImage.png");

  // Blur the image slightly so that the SSD comparisons are not so noisy
  typename TImage::Pointer slightlyBlurredRGBDxDyImage = TImage::New();

  MaskOperations::MaskedBlur(originalImage, mask, slightBlurVariance, slightlyBlurredRGBDxDyImage.GetPointer());

  ITKHelpers::WriteImage(slightlyBlurredRGBDxDyImage.GetPointer(), "SlightlyBlurredRGBDxDyImage.mha");

  // Create the graph
  typedef ImagePatchPixelDescriptor<TImage> ImagePatchPixelDescriptorType;

  typedef boost::grid_graph<2> VertexListGraphType;

  // We can't make this a signed type (size_t versus int) because we allow negative
  boost::array<std::size_t, 2> graphSideLengths = { { fullRegion.GetSize()[0],
                                                      fullRegion.GetSize()[1] } };
  VertexListGraphType graph(graphSideLengths);
  typedef boost::graph_traits<VertexListGraphType>::vertex_descriptor VertexDescriptorType;
  typedef boost::graph_traits<VertexListGraphType>::vertex_iterator VertexIteratorType;

  // Get the index map
  typedef boost::property_map<VertexListGraphType, boost::vertex_index_t>::const_type IndexMapType;
  IndexMapType indexMap(get(boost::vertex_index, graph));

  // Create the descriptor map. This is where the data for each pixel is stored.
  typedef boost::vector_property_map<ImagePatchPixelDescriptorType, IndexMapType> ImagePatchDescriptorMapType;
  ImagePatchDescriptorMapType imagePatchDescriptorMap(num_vertices(graph), indexMap);

  // Create the patch inpainter.
  typedef PatchInpainter<TImage> OriginalImageInpainterType;
  OriginalImageInpainterType originalImagePatchInpainter(patchHalfWidth, originalImage, mask);
  originalImagePatchInpainter.SetDebugImages(true);
  originalImagePatchInpainter.SetImageName("RGB");

  // Create an inpainter for the blurred image.
  typedef PatchInpainter<RGBImageType> BlurredImageInpainterType;
  BlurredImageInpainterType blurredRGBImagePatchInpainter(patchHalfWidth, blurredRGBImage, mask);

  // Create an inpainter for the slightly blurred image.
  typedef PatchInpainter<TImage> SlightlyBlurredRGBDxDyImageImageInpainterType;
  SlightlyBlurredRGBDxDyImageImageInpainterType slightlyBlurredRGBDxDyImageImagePatchInpainter(patchHalfWidth, slightlyBlurredRGBDxDyImage, mask);

  // Create a composite inpainter. (Note: the mask is inpainted in InpaintingVisitor::FinishVertex)
  CompositePatchInpainter inpainter;
  inpainter.AddInpainter(&originalImagePatchInpainter);
  inpainter.AddInpainter(&blurredRGBImagePatchInpainter);
  inpainter.AddInpainter(&slightlyBlurredRGBDxDyImageImagePatchInpainter);

  // Create the priority function
  typedef PriorityCriminisi<RGBImageType> PriorityType;
  PriorityType priorityFunction(blurredRGBImage, mask, patchHalfWidth);
//  priorityFunction.SetDebugLevel(1);

  // Queue
  typedef IndirectPriorityQueue<VertexListGraphType> BoundaryNodeQueueType;
  BoundaryNodeQueueType boundaryNodeQueue(graph);

  // Create the descriptor visitor (used for SSD comparisons).
  typedef ImagePatchDescriptorVisitor<VertexListGraphType, TImage, ImagePatchDescriptorMapType>
      ImagePatchDescriptorVisitorType;
//  ImagePatchDescriptorVisitorType imagePatchDescriptorVisitor(originalImage, mask,
//                                  imagePatchDescriptorMap, patchHalfWidth); // Use the non-blurred image for the SSD comparisons
  ImagePatchDescriptorVisitorType imagePatchDescriptorVisitor(slightlyBlurredRGBDxDyImage, mask,
                                  imagePatchDescriptorMap, patchHalfWidth); // Use the slightly blurred image for the SSD comparisons.

  typedef DefaultAcceptanceVisitor<VertexListGraphType> AcceptanceVisitorType;
  AcceptanceVisitorType acceptanceVisitor;

  // Create the inpainting visitor. (The mask is inpainted in FinishVertex)
  typedef InpaintingVisitor<VertexListGraphType, BoundaryNodeQueueType,
      ImagePatchDescriptorVisitorType, AcceptanceVisitorType, PriorityType, TImage>
      InpaintingVisitorType;
  InpaintingVisitorType inpaintingVisitor(mask, boundaryNodeQueue,
                                          imagePatchDescriptorVisitor, acceptanceVisitor,
                                          &priorityFunction, patchHalfWidth, "InpaintingVisitor", originalImage);
  inpaintingVisitor.SetDebugImages(true); // This produces PatchesCopied* images showing where patches were copied from/to at each iteration
//  inpaintingVisitor.SetAllowNewPatches(false);
  inpaintingVisitor.SetAllowNewPatches(true); // we can do this as long as we use one of the LinearSearchKNNProperty*Reuse (like LinearSearchKNNPropertyLimitLocalReuse) in the steps below

  InitializePriority(mask, boundaryNodeQueue, &priorityFunction);

  // Initialize the boundary node queue from the user provided mask image.
  InitializeFromMaskImage<InpaintingVisitorType, VertexDescriptorType>(mask, &inpaintingVisitor);
  std::cout << "PatchBasedInpaintingNonInteractive: There are " << boundaryNodeQueue.CountValidNodes()
            << " nodes in the boundaryNodeQueue" << std::endl;

#define DUseWeightedDifference

#ifdef DUseWeightedDifference
  // The absolute value of the depth derivative range is usually about [0,12], so to make
  // it comparable to to the color image channel range of [0,255], we multiply by 255/12 ~= 20.
//  float depthDerivativeWeight = 20.0f;

  // This should not be computed "by eye" by looking at the Dx and Dy channels of the PTX scan, because there are typically
  // huge depth discontinuties around the objects that are going to be inpainted. We'd have to look at the masked version of this
  // image to determine the min/max values of the unmasked pixels. They will be much smaller than the min/max values of the original
  // image, which will make the depth derivative weights much higher (~100 or so)

//  std::vector<typename TImage::PixelType> channelMins = ITKHelpers::ComputeMinOfAllChannels(originalImage);
//  std::vector<typename TImage::PixelType> channelMaxs = ITKHelpers::ComputeMaxOfAllChannels(originalImage);
  typename TImage::PixelType channelMins;
  ITKHelpers::ComputeMinOfAllChannels(originalImage, channelMins);

  typename TImage::PixelType channelMaxs;
  ITKHelpers::ComputeMaxOfAllChannels(originalImage, channelMaxs);

  float minX = fabs(channelMins[3]);
  float maxX = fabs(channelMaxs[3]);
  float maxValueX = std::max(minX, maxX);
  std::cout << "maxValueX = " << maxValueX << std::endl;
  float depthDerivativeWeightX = 255.0f / maxValueX;
  std::cout << "Computed depthDerivativeWeightX = " << depthDerivativeWeightX << std::endl;

  float minY = fabs(channelMins[4]);
  float maxY = fabs(channelMaxs[4]);
  float maxValueY = std::max(minY, maxY);
  std::cout << "maxValueY = " << maxValueY << std::endl;
  float depthDerivativeWeightY = 255.0f / maxValueY;
  std::cout << "Computed depthDerivativeWeightY = " << depthDerivativeWeightY << std::endl;

  // Full pixels
  std::vector<float> weights = {1.0f, 1.0f, 1.0f, depthDerivativeWeightX, depthDerivativeWeightY};
  typedef WeightedSumSquaredPixelDifference<typename TImage::PixelType> FullPixelDifferenceType;
  FullPixelDifferenceType fullPixelDifferenceFunctor(weights);

  typedef ImagePatchDifference<ImagePatchPixelDescriptorType,
      FullPixelDifferenceType > FullPatchDifferenceType;
  FullPatchDifferenceType fullPatchDifferenceFunctor(fullPixelDifferenceFunctor);

  // First 3 channels only pixels
  typedef RGBSSD<typename TImage::PixelType> RGBPixelDifferenceType;
  RGBPixelDifferenceType rgbPixelDifferenceFunctor;

  typedef ImagePatchDifference<ImagePatchPixelDescriptorType,
      RGBPixelDifferenceType > RGBPatchDifferenceType;
  RGBPatchDifferenceType rgbPatchDifferenceFunctor(rgbPixelDifferenceFunctor);
#else
  // Use an unweighted pixel difference
  typedef ImagePatchDifference<ImagePatchPixelDescriptorType,
      SumSquaredPixelDifference<typename TImage::PixelType> > PatchDifferenceType;

  PatchDifferenceType patchDifferenceFunctor;
#endif

//#define DAllowReuse // comment/uncomment this line to toggle allowing patches to be used as the source patch more than once

#ifdef DAllowReuse
  // Create the first (KNN) neighbor finder
  typedef LinearSearchKNNProperty<ImagePatchDescriptorMapType, PatchDifferenceType> KNNSearchType;
  KNNSearchType linearSearchKNN(imagePatchDescriptorMap, numberOfKNN, patchDifferenceFunctor);
#else
  // Full pixel search
  typedef LinearSearchKNNPropertyLimitLocalReuse<ImagePatchDescriptorMapType, FullPatchDifferenceType, RGBImageType> FullKNNSearchType;
  FullKNNSearchType fullSearchKNN(imagePatchDescriptorMap, mask, numberOfKNN,
                                  fullPatchDifferenceFunctor, inpaintingVisitor.GetSourcePixelMapImage(),
                                  rgbImage.GetPointer());
  fullSearchKNN.SetDebugImages(true);

  // RGB-only search
  typedef LinearSearchKNNPropertyLimitLocalReuse<ImagePatchDescriptorMapType, RGBPatchDifferenceType, RGBImageType> RGBKNNSearchType;
  RGBKNNSearchType rgbSearchKNN(imagePatchDescriptorMap, mask, numberOfKNN,
                                  rgbPatchDifferenceFunctor, inpaintingVisitor.GetSourcePixelMapImage(),
                                  rgbImage.GetPointer());
  rgbSearchKNN.SetDebugImages(true);

  // Combine
  typedef LinearSearchKNNPropertyCombine<FullKNNSearchType, RGBKNNSearchType> KNNSearchType;
  KNNSearchType linearSearchKNN(fullSearchKNN, rgbSearchKNN);
#endif

  // Setup the second (1-NN) neighbor finder
  typedef std::vector<VertexDescriptorType>::iterator VertexDescriptorVectorIteratorType;

  // This is templated on TImage because we need it to write out debug patches from this searcher (since we are not using an RGB image to compute the histograms)
//  typedef LinearSearchBestTexture<ImagePatchDescriptorMapType, RGBImageType,
//      VertexDescriptorVectorIteratorType, TImage> BestSearchType; // Use the histogram of the gradient magnitudes of a scalar represetnation of the image (e.g. magnitude image)
//  typedef LinearSearchBestLidarTextureDerivatives<ImagePatchDescriptorMapType, RGBImageType,
//      VertexDescriptorVectorIteratorType, TImage> BestSearchType; // Use the concatenated histograms of the absolute value of the derivatives of each channel
  typedef LinearSearchBestLidarRGBTextureGradient<ImagePatchDescriptorMapType, RGBDxDyImageType,
      VertexDescriptorVectorIteratorType, RGBImageType> BestSearchType; // Use the concatenated histograms of the gradient magnitudes of each channel. This RGBDxDyImageType must match the rgbDxDyImage provided below

//  BestSearchType linearSearchBest(imagePatchDescriptorMap, rgbDxDyImage.GetPointer(), mask); // use non-blurred for texture sorting
  Debug debug;
//  debug.SetDebugOutputs(true);
//  debug.SetDebugImages(true);
//  linearSearchBest.SetDebugOutputs(true);
//  linearSearchBest.SetDebugImages(true);

   // use slightly blurred for texture sorting
  BestSearchType linearSearchBest(imagePatchDescriptorMap, slightlyBlurredRGBDxDyImage.GetPointer(),
                                  mask, rgbImage.GetPointer(), debug);
  linearSearchBest.WritePatches = true;


  // Setup the two step neighbor finder
  TwoStepNearestNeighbor<KNNSearchType, BestSearchType>
      twoStepNearestNeighbor(linearSearchKNN, linearSearchBest);

  // #define DFullSearch // comment/uncomment this line to set the search region

#ifdef DFullSearch
  // Perform the inpainting (full search)
  InpaintingAlgorithm(graph, inpaintingVisitor, &boundaryNodeQueue,
                      twoStepNearestNeighbor, &inpainter);
#else
  NeighborhoodSearch<VertexDescriptorType, ImagePatchDescriptorMapType> neighborhoodSearch(originalImage->GetLargestPossibleRegion(),
                                                              searchRadius, imagePatchDescriptorMap);

  // Perform the inpainting (local search)
  InpaintingAlgorithmWithLocalSearch(graph, inpaintingVisitor, &boundaryNodeQueue,
                                     twoStepNearestNeighbor, &inpainter, neighborhoodSearch);
#endif

}
Ejemplo n.º 12
0
static PyObject* graph_embeds(PyObject* self, PyObject* args)
{

    // Making Graphs
    vertex u, v;
    unsigned temp;
    graph (g);
    int gem, countVerteicesProcessed = 0;
    // vertex i, j, u, v; unsigned temp;
    // Finish making graphs
    PyObject* obj;
    PyObject* seq;
    int i, len;
    PyObject* item;
    long arrayValue;
    int embedsBoolean;

    int numberOfVertices = 0;

    if (!PyArg_ParseTuple(args, "O", &obj)) {
        printf("Item is not a list\n");
        // return NULL;
        Py_RETURN_NONE;
    }
    seq = PySequence_Fast(obj, "expected a sequence");
    len = PySequence_Size(obj);
    arrayValue = -5;
    // printf("[\n");
    for (i = 0; i < len; i++) {
        item = PySequence_Fast_GET_ITEM(seq, i);



        if(i == 0) {
            // should add a check to make sure it is an integer!
            numberOfVertices = PyInt_AsLong(item);
            // printf("numberOfVertices: %d\n", numberOfVertices);
            // graph creation
            if ((**g = (char) numberOfVertices) > maxverts - 2) Py_RETURN_NONE;
            // if ((**g = (char) numberOfVertices) > maxverts - 2) return 2;
            // end graph creation
        } else if(i <= numberOfVertices && i > 0) {
            // should add a check to make sure it is a list!
            countVerteicesProcessed++;
            PyObject* obj_adjacency = item;
            PyObject* seq_adjacency;
            int j = 0, len_adjacency;
            PyObject* item_adjacency;
            seq_adjacency = PySequence_Fast(obj_adjacency, "expected a sequence");
            len_adjacency = PySequence_Size(obj_adjacency);

            // make sure object is a sequence and put the for loop inside the conditional
            item_adjacency = PySequence_Fast_GET_ITEM(seq_adjacency, j);
            int degreeOfVertex = PyInt_AsLong(item_adjacency);
            if(degreeOfVertex != len_adjacency - 1) {
                printf("degreeOfVertex %d and length %d not matching!\n", degreeOfVertex, len_adjacency);
            }
            int adjacent[degreeOfVertex];
            // graph creation
            if ((degree (g, i) = (char) degreeOfVertex) > maxdeg - 2) Py_RETURN_NONE;
            // if ((degree (g, i) = (char) degreeOfVertex) > maxdeg - 2) return 4;
            // end graph creation
            for (j = 1; j < len_adjacency; j++) {
                item_adjacency = PySequence_Fast_GET_ITEM(seq_adjacency, j);

                // delete this code!
                PyObject* objectsRepresentation = PyObject_Repr(item);
                const char* s = PyString_AsString(objectsRepresentation);
                // printf("%s\n", s);
                PyObject* objType = PyObject_Type(item);
                PyObject* objTypeString = PyObject_Repr(objType);
                const char* sType = PyString_AsString(objTypeString);
                // printf("%s\n", sType);
                // end delete


                // make sure every object is an int!
                adjacent[j-1] = PyInt_AsLong(item_adjacency);
                // printf("%da\n", adjacent[j-1]);
                // make sure first int is the degree and is the same as the length -1 of the array

                // graph creation
                g [i][j] = (char) PyInt_AsLong(item_adjacency);
                // end graph creation
            }

        } else {
            printf("There is something that should not be here!\n");
            PyObject* objectsRepresentation = PyObject_Repr(item);
            const char* s = PyString_AsString(objectsRepresentation);
            printf("%s\n", s);
            PyObject* objType = PyObject_Type(item);
            PyObject* objTypeString = PyObject_Repr(objType);
            const char* sType = PyString_AsString(objTypeString);
            printf("%s\n", sType);
        }


    }

    if(countVerteicesProcessed < numberOfVertices) Py_RETURN_NONE;

    vertex j;
    // vertex i, j, u, v; unsigned temp;
    for (i = 1; i <= **g; i++) for (j = 1; j <= degree(g, i); j++) {
            // if (g [i][j] > **g) return 6; //this checks that the label of each vertex in the respective adjacency lists
            if (g [i][j] > **g) Py_RETURN_NONE;
            // do not exceed the number of vertices in the graph as listed in the file.
            for (u = g [i][j], v = 1; (v <= degree(g, u)) && (g[u][v] != i); v ++); //this loops through all the vertices
            // adjacent to u and stops whenever it finds the vertex i, or it finishes the list
            // if (v > degree(g, u)) return 7; // if v is greater than the degree, it means vertex i was not found in the
            if (v > degree(g, u)) Py_RETURN_NONE;
            // adjacency list for u, meaning the graph is directed. It seems directed graphs are not acceptable!
        }



    // printf("loop is done!\n");

    char s = 'p';
    gem = gembed (g, s, 1);
    // printf("gembed is done!\n");
    /*  system ("date"); */
    switch (gem) {
    case 0:
        // printf ( "no ");
        // switch (s) {
        //     case 'p' : printf ("projective"); break;
        //     case 't' : printf ("toroidal"); break;
        //     case 's' : printf ("spindle"); break;
        //     default  : printf ("ERROR");
        //     }
        // puts (" embeddings");
        embedsBoolean = 0;
        break;
    case 2:
        // puts ( "graph is planar");
        embedsBoolean = 1;
        break;
    case 1:
    case 3:
        // puts ( "graph embeds");
        embedsBoolean = 1;
        break;
    default:
        puts ( "whoops -- unknown result from gembed()");
        Py_RETURN_NONE;
        break;
    }



    Py_DECREF(seq);
    // printf("]\n");
    // printf("Item is a list!\n");

    if(embedsBoolean) Py_RETURN_TRUE;
    else Py_RETURN_FALSE;

    Py_RETURN_NONE;
}
Ejemplo n.º 13
0
int main(int argc, char** argv) {
    // Initialize control plain using mpi
    graphlab::mpi_tools::init(argc, argv);
    graphlab::distributed_control dc;
    global_logger().set_log_level(LOG_FATAL);

    // Parse command line options -------------------------------------
    graphlab::command_line_options 
        clopts("Distributed Path Finding Algorithm.");
    std::string graph_dir;
    std::string format = "tsv";
    std::string exec_type = "synchronous";
    clopts.attach_option("graph", graph_dir,
            "The graph file.  If none is provided "
            "then a toy graph will be created");
    clopts.add_positional("graph");

    clopts.attach_option("engine", exec_type, 
            "The engine type synchronous or asynchronous");

    std::string saveprefix;
    clopts.attach_option("saveprefix", saveprefix,
            "If set, will save the resultant pagerank to a "
            "sequence of files with prefix saveprefix");
    
    size_t n_tree = 1;
    clopts.attach_option("num_tree", n_tree,
            "Number of trees.");
   
    size_t n_query = 0;
    clopts.attach_option("num_query", n_query,
            "Preset number of experiments.");
    
    bool stepy = false;
    clopts.attach_option("stepy", stepy,
            "Regular mode or stepy mode.");

    std::string input_file = "";
    clopts.attach_option("input_file", input_file,
            "Read from file or randomly generate (default).");

    if(!clopts.parse(argc, argv)) {
        dc.cout() << 
            "Error in parsing command line arguments." << std::endl;
        return EXIT_FAILURE;
    }

    // Build the graph ---------------------------------------------
    dc.cout() << "\n0 Loading graph..." << std::endl;
    graph_type graph(dc, clopts);
    dc.cout() << "\tLoading graph in format: "<< format << std::endl;
    graph.load_format(graph_dir, format);
    // must call finalize before querying the graph
    graph.finalize();
    dc.cout() << "\t#vertices:  " << graph.num_vertices() << 
        "\t#edges:     " << graph.num_edges() << std::endl;

    // start the handler here
#ifdef TIE_FULL
#ifdef TIE_HEUR
    size_t n_query_batch = 10000;
#else
    size_t n_query_batch = 1000;
#endif
#else
    //size_t n_query_batch = n_query * 2;
    size_t n_query_batch = 50000;
#endif
#ifdef BIDIRECTIONAL_SEARCH
    n_query_batch /= 2;
#endif
    query_handler qh(n_tree, stepy, n_query,
            &dc, &clopts, &graph, 
            input_file, exec_type, 
            saveprefix, graph_dir,
            n_query_batch);

#ifndef CALC_REAL
    qh.ds_query_batch();
#else
    qh.real_query_serial();
#endif

    // Tear-down communication layer and quit ----------------------
    graphlab::mpi_tools::finalize();
    return EXIT_SUCCESS;
} // End of main
Ejemplo n.º 14
0
//no except
void __cdecl _tmain(int argc, TCHAR *argv[]) noexcept
{
    if (argc != 2 && argc != 3)
    {
        printf("Usage Error: Incorrect number of arguments\n\n");
        _tprintf("Usage:\n\t%s <mode> <map_file_name>\n", argv[0]);
        return;
    }

    uint64 total_read = 0;
    uint64 total_write = 0;

    clock_t begin, end;

    std::chrono::high_resolution_clock::time_point bStart = std::chrono::high_resolution_clock::now();

    if (strcmp(argv[1], "r") == 0){
        printf("Starting 1st Inversion\n");

        char* outputFile;
        char* nodeHash;
        std::chrono::high_resolution_clock::time_point b1 = std::chrono::high_resolution_clock::now();
        {
            InvertAndRelabelNodes<uint64> graph(argv[2], BUFFERSIZE * _1_MB, true);
            graph.execute();

            outputFile = graph.output_files[0];
            nodeHash = graph.nodesHash;

            printf("Total IO: read - %.2f GB; write - %.2f GB\n", (float)graph.total_read / _1_GB, (float)graph.total_write / _1_GB);
            total_read += graph.total_read;
            total_write += graph.total_write;
        }
        std::chrono::high_resolution_clock::time_point e1 = std::chrono::high_resolution_clock::now();
        printf("Took %lld seconds\n", std::chrono::duration_cast<std::chrono::seconds>(e1 - b1).count());
        printf("Ending 1st Inversion\n");

        printf("\nStarting 2nd Inversion\n");

        std::chrono::high_resolution_clock::time_point b2 = std::chrono::high_resolution_clock::now();
        {
            InvertAndRelabelNodes<uint32> graph(outputFile, BUFFERSIZE * _1_MB, false);
            graph.nodesHash = nodeHash;
            graph.execute();
            printf("Total IO: read - %.2f GB; write - %.2f GB\n", (float)graph.total_read / _1_GB, (float)graph.total_write / _1_GB);
            total_read += graph.total_read;
            total_write += graph.total_write;
        }
        std::chrono::high_resolution_clock::time_point e2 = std::chrono::high_resolution_clock::now();
        printf("Took %lld seconds\n", std::chrono::duration_cast<std::chrono::seconds>(e2 - b2).count());
        printf("Ending 2nd Inversion\n");
    }
    else if (strcmp(argv[1], "c") == 0) {
        printf("\nStarting Top 10\n");
        std::chrono::high_resolution_clock::time_point b3 = std::chrono::high_resolution_clock::now();
        {
            TopN topN("PLD-out-relabeled.dat");
            topN.execute();
            printf("Total IO: read - %.2f GB; write - %.2f GB\n", (float)topN.total_read / _1_GB, (float)topN.total_write / _1_GB);
            total_read += topN.total_read;
            total_write += topN.total_write;
        }
        std::chrono::high_resolution_clock::time_point e3 = std::chrono::high_resolution_clock::now();
        printf("Took %lld seconds\n", std::chrono::duration_cast<std::chrono::seconds>(e3 - b3).count());
        printf("\Ending Top 10\n");
    }
Ejemplo n.º 15
0
int main()
{
  try {
    // Set the position the camera has to reach
    vpHomogeneousMatrix cdMo ;
    cdMo[1][3] = 1.2; // t_y should be different from zero to be non singular
    cdMo[2][3] = 0.5;

    // Set the initial camera position
    vpHomogeneousMatrix cMo;
    cMo[0][3] = 0.3;
    cMo[1][3] = cdMo[1][3];
    cMo[2][3] = 1.;
    vpRotationMatrix cdRo(0, atan2(cMo[0][3], cMo[1][3]), 0);
    cMo.insert(cdRo);

    vpSimulatorPioneerPan robot ;
    robot.setSamplingTime(0.04);
    vpHomogeneousMatrix wMc, wMo;

    // Get robot position world frame
    robot.getPosition(wMc);

    // Compute the position of the object in the world frame
    wMo = wMc * cMo;

    // Define the target
    vpPoint point(0,0,0); // Coordinates in the object frame
    point.track(cMo);

    vpServo task;
    task.setServo(vpServo::EYEINHAND_L_cVe_eJe);
    task.setInteractionMatrixType(vpServo::CURRENT, vpServo::PSEUDO_INVERSE);
    task.setLambda(0.2);

    vpVelocityTwistMatrix cVe;
    cVe = robot.get_cVe();
    task.set_cVe(cVe);

    vpMatrix eJe;
    robot.get_eJe(eJe);
    task.set_eJe(eJe);

    // Current and desired visual feature associated later to the x coordinate of the point
    vpFeaturePoint s_x, s_xd;

    // Create the current x visual feature
    vpFeatureBuilder::create(s_x, point);

    // Create the desired x* visual feature
    s_xd.buildFrom(0, 0, cdMo[2][3]);

    // Add the feature
    task.addFeature(s_x, s_xd, vpFeaturePoint::selectX());

    // Create the current and desired log(Z/Z*) visual feature
    vpFeatureDepth s_Z, s_Zd;
    // Initial depth of the target in front of the camera
    double Z = point.get_Z();
    // Desired depth Z* of the target.
    double Zd = cdMo[2][3];
    s_Z.buildFrom(s_x.get_x(), s_x.get_y(), Z, log(Z/Zd));
    s_Zd.buildFrom(0, 0, Zd, 0); // log(Z/Z*) = 0 that's why the last parameter is 0

    // Add the feature
    task.addFeature(s_Z, s_Zd);

#ifdef VISP_HAVE_DISPLAY
    // Create a window (800 by 500) at position (400, 10) with 3 graphics
    vpPlot graph(3, 800, 500, 400, 10, "Curves...");

    // Init the curve plotter
    graph.initGraph(0,3);
    graph.initGraph(1,2);
    graph.initGraph(2,1);
    graph.setTitle(0, "Velocities");
    graph.setTitle(1, "Error s-s*");
    graph.setTitle(2, "Depth");
    graph.setLegend(0, 0, "vx");
    graph.setLegend(0, 1, "wz");
    graph.setLegend(0, 2, "qdot_pan");
    graph.setLegend(1, 0, "x");
    graph.setLegend(1, 1, "log(Z/Z*)");
    graph.setLegend(2, 0, "Z");
#endif

    int iter = 0;
    for (; ;)
    {
      robot.getPosition(wMc) ;
      cMo = wMc.inverse() * wMo;

      point.track(cMo);

      // Update the current x feature
      vpFeatureBuilder::create(s_x, point);

      // Update log(Z/Z*) feature. Since the depth Z change, we need to update the intection matrix
      Z = point.get_Z() ;
      s_Z.buildFrom(s_x.get_x(), s_x.get_y(), Z, log(Z/Zd));

      robot.get_cVe(cVe);
      task.set_cVe(cVe);
      robot.get_eJe(eJe);
      task.set_eJe(eJe);

      // Compute the control law. Velocities are computed in the mobile robot reference frame
      vpColVector v = task.computeControlLaw();

      // Send the velocity to the robot
      robot.setVelocity(vpRobot::ARTICULAR_FRAME, v);

#ifdef VISP_HAVE_DISPLAY
      graph.plot(0, iter, v); // plot velocities applied to the robot
      graph.plot(1, iter, task.getError()); // plot error vector
      graph.plot(2, 0, iter, Z); // plot the depth
#endif
      iter ++;

      if (task.getError().sumSquare() < 0.0001) {
        std::cout << "Reached a small error. We stop the loop... " << std::endl;
        break;
      }
    }
#ifdef VISP_HAVE_DISPLAY
    const char *legend = "Click to quit...";
    vpDisplay::displayText(graph.I, (int)graph.I.getHeight()-60, (int)graph.I.getWidth()-150, legend, vpColor::red);
    vpDisplay::flush(graph.I);
    vpDisplay::getClick(graph.I);
#endif

    // Kill the servo task
    task.print();
    task.kill();
  }
  catch(vpException &e) {
    std::cout << "Catch an exception: " << e << std::endl;
  }
}
Ejemplo n.º 16
0
GraphAndValues Masseuse::LoadPoseGraphAndLCC(
    const string& pose_graph_file, bool read_lcc) {


  FILE *fp = (FILE *)fopen(pose_graph_file.c_str(), "rb");

  if (fp == NULL) {
    fprintf(stderr, "Could not open file %s\n",
            pose_graph_file.c_str());
  }


  if (fread(&origin, sizeof(Eigen::Vector6d), 1, fp) != 1) {
    throw invalid_argument("LoadPoseGraphAndLCC:  Cannot load the origin!");
  }

  //  std::cerr << "read origin: " << origin.transpose() << std::endl;

  unsigned numRelPoses = 0;
  unsigned numLCC = 0;

  if (fread(&numRelPoses, sizeof(unsigned), 1, fp) != 1) {
    printf("error! Cannot load num of relative poses.\n");
    throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
  }

  if(read_lcc){
    if (fread(&numLCC, sizeof(unsigned), 1, fp) != 1) {
      printf("error! Cannot load num of loop closure constraints.\n");
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
  }

  std::cerr << "Will load " << numRelPoses << " rel poses, "
            << numLCC << " loop closure constranits." << std::endl;

  relative_poses.clear();
  // save all rel poses
  for (unsigned i = 0; i != numRelPoses; i++) {
    RelPose rPos;
    if (fread(&rPos.ref_id, sizeof(unsigned), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
    if (fread(&rPos.live_id, sizeof(unsigned), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
    if (fread(&rPos.rel_pose, sizeof(Eigen::Vector6d), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }
    if (fread(&rPos.cov, sizeof(Eigen::Matrix6d), 1, fp) != 1) {
      throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
    }

    relative_poses.push_back(rPos);
  }

  if(read_lcc){
    loop_closure_constraints.clear();
    // save all lcc here
    for (unsigned i = 0; i != numLCC; i++) {
      RelPose rPos;
      if (fread(&rPos.ref_id, sizeof(unsigned), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }
      if (fread(&rPos.live_id, sizeof(unsigned), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }
      if (fread(&rPos.rel_pose, sizeof(Eigen::Vector6d), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }
      if (fread(&rPos.cov, sizeof(Eigen::Matrix6d), 1, fp) != 1) {
        throw invalid_argument("LoadPoseGraphAndLCC:  error loading file");
      }

      loop_closure_constraints.push_back(rPos);
    }
  }
  fclose(fp);

  std::cerr << "Finished loading Pose Graph from  " << pose_graph_file
            << std::endl;

  std::shared_ptr<Values> initial(new Values);
  std::shared_ptr<Graph> graph(new Graph);
  Pose3 prev_pose;

  unsigned numICPfailed = 0;
  for (size_t ii = 0; ii < relative_poses.size(); ++ii){
    RelPose curr_pose = relative_poses[ii];
    if(ii == 0){
      // first relative pose, initialize graph at origin
      unsigned id = curr_pose.ref_id;
      Rot3 R(origin[3], origin[4], origin[5]);
      Point3 t = origin.head<3>();
      Pose3 orig(R, t);
      (*initial)[id] = orig;
      prev_pose = orig;

      //            std::cerr << "inserting origin: Rot: " << orig.rotationMatrix().eulerAngles
      //                         (0,1,2).transpose() << " Trans: " << orig.translation().transpose() <<
      //                         " at index:  " << id <<
      //                         std::endl;
    }

    // Build the next vertex using the relative contstraint
    Rot3 R(curr_pose.rel_pose[3], curr_pose.rel_pose[4],
        curr_pose.rel_pose[5]);
    Point3 t = curr_pose.rel_pose.head<3>();
    Pose3 rel(R, t);

    Pose3 new_pose = prev_pose*rel;
    (*initial)[curr_pose.live_id] = new_pose;

    //    std::cerr << "inserting pose: Rot: " << new_pose.rotationMatrix().eulerAngles
    //                 (0,1,2).transpose() << " Trans: " << new_pose.translation().transpose() <<
    //                 " at index:  " << curr_pose.live_id <<
    //                 std::endl;

    prev_pose = new_pose;

    // Also insert a factor for the binary pose constraint
    unsigned id1 = curr_pose.ref_id;
    unsigned id2 = curr_pose.live_id;

    Matrix m = curr_pose.cov;
    if(m.sum() == 0 || m.determinant() <= 0 || std::isnan(m.determinant())
       /*|| m.determinant() > options.cov_det_thresh*/){
      //      std::cerr << "ICP failed for rel pose between " << id1 << " and " << id2 <<
      //                   "Setting fixed covaraince..." <<
      //                   std::endl;
      Eigen::Vector6d cov_vec;
      // TODO: Improve handling of cases where the frame-to-frame ICP failed
      cov_vec << 7e-8, 7e-8, 7e-8, 8e-11, 8e-11, 8e-11;
      m = cov_vec.asDiagonal();
      numICPfailed++;
    }

    //        std::cerr <<  "Adding binary constraint between id: " << id1 << " and " <<
    //                      id2 << std::endl << "with cov: \n" << m << std::endl;

    // Create a new factor between poses
    if(options.use_identity_covariance){
      m.setIdentity();
    }

    m = m * options.rel_covariance_mult;

    Factor factor(id1, id2, rel, m);
    graph->push_back(factor);

  }

  std::cerr << std::setprecision(3) << std::fixed <<"ICP failed " << numICPfailed << " times " <<
               "out of " << relative_poses.size() << " ( " << (double)numICPfailed/(double)relative_poses.size() * 100 <<
               "% )" << std::endl;


  if( read_lcc ){
    std::cerr << "Reading LLC." << std::endl;

    int discarded_lcc = 0;
    for(size_t ii = 0; ii < loop_closure_constraints.size(); ++ii){
      RelPose curr_lcc = loop_closure_constraints[ii];
      unsigned id1 = curr_lcc.ref_id;
      unsigned id2 = curr_lcc.live_id;

      Rot3 R(curr_lcc.rel_pose[3], curr_lcc.rel_pose[4],
          curr_lcc.rel_pose[5]);
      Point3 t = curr_lcc.rel_pose.head<3>();
      Pose3 lcc(R, t);

      Matrix m = curr_lcc.cov;

      if(m.sum() == 0 ||
         m.determinant() > options.cov_det_thresh ||
         m.determinant() <= 0 ||
         std::isnan(m.determinant()))
      {
        // ICP failed or something went wrong for this loop closure, ignoring
        // The determinant of the cov. matrix may also be larger than the
        // specified threshold.
        discarded_lcc++;
        continue;
      }

      // check if the lcc is between far away poses. If so, downweight it's
      // covariance.

      //      const Pose3* lcc_0 = dynamic_cast<const Pose3*>(&initial->at(id1));
      //      const Pose3* lcc_1 = dynamic_cast<const Pose3*>(&initial->at(id2));

      //      Pose3 lcc_diff = lcc_0->compose(lcc).inverse().compose(*lcc_1);
      //            std::cerr << "distance between poses for lcc: " << ii <<
      //                         " between poses " <<  id1 << " and " << id2 << ": "
      //                      << lcc_diff.translation().norm() << std::endl;
      //      Pose3 diff = (*lcc_0).inverse().compose(*lcc_1);
      //      std::cerr << "distance between poses for lcc: " << ii <<
      //                   " between poses " <<  id1 << " and " << id2 << ": "
      //                << lcc.translation().norm() << std::endl;

      // Create a new factor between poses
      if(options.use_identity_covariance){
        m.setIdentity();
      }

      Factor lcc_factor(id1, id2, lcc, m);
      lcc_factor.isLCC = true;

      graph->push_back(lcc_factor);
      curr_lcc.ext_id = graph->size()-1;


      //      std::cerr << std::scientific <<
      //                   "Adding lcc between id: " << id1 << " and " <<
      //                    id2 << std::endl << "with cov: \n" << lcc_factor.cov << std::endl;

      //m_addedLCC[keyFromId(id2)] = curr_lcc;

      /*

      // If we already have a constraint between poses i and j, only use the one
      // with the highest degree of certainty (lowest cov. determinant)
      if(m_addedLCC.count(keyFromId(id2)) == 0){
        // LCC has not been added yet, just add
        graph->push_back(factor);
        curr_lcc.m_nExtId = graph->size()-1;
        m_addedLCC[keyFromId(id2)] = curr_lcc;
      }else{
        // Check if the covariance of the new lcc for poses i and j
        // is smaller than what we are currently using
        EstPose old_lcc = m_addedLCC[keyFromId(id2)];
        if(old_lcc.m_Cov.determinant() > curr_lcc.m_Cov.determinant()){
          // new det is smaller, replace
          curr_lcc.m_nExtId = old_lcc.m_nExtId;
          graph->replace(old_lcc.m_nExtId, factor);
          m_addedLCC[keyFromId(id2)] = curr_lcc;
//          std::cerr << "determinant for new lcc between " << id1 << " and " <<
//                       id2 << " is: " << curr_lcc.m_Cov.determinant() << " < "
//                    << old_lcc.m_Cov.determinant() << std::endl;

        }else{
          // Determinant for new constraint is larger, skip it
          continue;
        }

      }
      */

    }

    //    //ZZZZZZZZZZZZZ Temp, add wrong LCC to test switchable constraints
    //    unsigned id1 = 480;
    //    unsigned id2 = 870;
    //    Pose3& T2 = initial->at(id2);

    //    Pose3& T1 = initial->at(id1);

    //    Pose3 T12 = T1.inverse() * T2;


    //    // Add random values to the translation
    //    T12.translation()[0] += 5;
    //    T12.translation()[1] -= 2;
    //    T12.translation()[3] += 7;

    //    // Rotate the pose by an arbitrary amount
    //    Sophus::SO3d rot(0.5, 0.7, 0.1);

    //    T12.rotationMatrix() *= rot.matrix();
    //    Factor wrong_lcc(id1, id2, T12, Eigen::Matrix6d::Identity());
    //    wrong_lcc.isLCC = true;
    //    // now add the wrong LCC to the graph
    //    graph->push_back(wrong_lcc);


    std::cerr << std::setprecision(3) << std::fixed <<"Did not use " << discarded_lcc << " LCC " <<
                 "out of " << numLCC << " ( " << (double)discarded_lcc/(double)numLCC * 100 <<
                 "% )" << std::endl;

  }

  return make_pair(graph, initial);
}
Ejemplo n.º 17
0
int main(int argc, char** argv) {
  // initialize guacamole
  gua::init(argc, argv);

  // setup scene
  gua::SceneGraph graph("main_scenegraph");

  gua::math::vec4 iron(0.560, 0.570, 0.580, 1);
  gua::math::vec4 silver(0.972, 0.960, 0.915, 1);
  gua::math::vec4 aluminium(0.913, 0.921, 0.925, 1);
  gua::math::vec4 gold(1.000, 0.766, 0.336, 1);
  gua::math::vec4 copper(0.955, 0.637, 0.538, 1);
  gua::math::vec4 chromium(0.550, 0.556, 0.554, 1);
  gua::math::vec4 nickel(0.660, 0.609, 0.526, 1);
  gua::math::vec4 titanium(0.542, 0.497, 0.449, 1);
  gua::math::vec4 cobalt(0.662, 0.655, 0.634, 1);
  gua::math::vec4 platinum(0.672, 0.637, 0.585, 1);

  auto pbrMat(gua::MaterialShaderDatabase::instance()
                  ->lookup("gua_default_material")
                  ->make_new_material());
  // pbrMat.set_uniform("Color", chromium);
  // pbrMat.set_uniform("Roughness", 0.2f);
  // pbrMat.set_uniform("Metalness", 1.0f);

  std::string directory("/opt/3d_models/Cerberus_by_Andrew_Maximov/Textures/");
  pbrMat->set_uniform("ColorMap", directory + "Cerberus_A.tga");
  pbrMat->set_uniform("MetalnessMap", directory + "Cerberus_M.tga");
  pbrMat->set_uniform("RoughnessMap", directory + "Cerberus_R.tga");
  pbrMat->set_uniform("NormalMap", directory + "Cerberus_N.negated_green.tga");

  gua::TriMeshLoader loader;

  auto transform = graph.add_node<gua::node::TransformNode>("/", "transform");
  auto cerberus(loader.create_geometry_from_file(
      "cerberus", "/opt/3d_models/Cerberus_by_Andrew_Maximov/Cerberus_LP.3ds",
      pbrMat, gua::TriMeshLoader::NORMALIZE_POSITION |
                  gua::TriMeshLoader::NORMALIZE_SCALE));
  graph.add_node("/transform", cerberus);
  cerberus->set_draw_bounding_box(true);
  cerberus->rotate(90, 0.f, 1.f, 0.f);
  cerberus->rotate(90, 0.f, 0.f, 1.f);

  auto pointLight = graph.add_node<gua::node::LightNode>("/", "pointLight");
  pointLight->data.set_type(gua::node::LightNode::Type::POINT);
  pointLight->data.color = gua::utils::Color3f(1.0f, 1.0f, 1.0f);
  pointLight->data.brightness = 150.0f;  // lm
  pointLight->scale(9.f);
  pointLight->translate(-2.f, 3.f, 5.f);

  auto screen = graph.add_node<gua::node::ScreenNode>("/", "screen");
  screen->data.set_size(gua::math::vec2(1.92f, 1.08f));
  screen->translate(0, 0, 1.0);

  // add mouse interaction
  gua::utils::Trackball trackball(0.01, 0.002, 0.2);

  // setup rendering pipeline and window
  // auto resolution = gua::math::vec2ui(1920, 1080);
  auto resolution = gua::math::vec2ui(2560, 1440);

  std::string skymaps_dir("/opt/guacamole/resources/skymaps/");

  for (auto const& file :
       {std::string(directory + "Cerberus_A.tga"),
        std::string(directory + "Cerberus_M.tga"),
        std::string(directory + "Cerberus_R.tga"),
        std::string(directory + "Cerberus_N.negated_green.tga"),
        std::string(skymaps_dir + "skymap.jpg")}) {
    gua::TextureDatabase::instance()->load(file);
  }

  auto tiledPipe(std::make_shared<gua::PipelineDescription>());
  tiledPipe->add_pass(std::make_shared<gua::TriMeshPassDescription>());
  tiledPipe->add_pass(std::make_shared<gua::LightVisibilityPassDescription>());
  tiledPipe->add_pass(std::make_shared<gua::ResolvePassDescription>());

  auto camera = graph.add_node<gua::node::CameraNode>("/screen", "cam");
  camera->translate(0, 0, 2.0);
  camera->config.set_resolution(resolution);
  camera->config.set_screen_path("/screen");
  camera->config.set_scene_graph_name("main_scenegraph");
  camera->config.set_output_window_name("main_window");
  camera->config.set_enable_stereo(false);
  camera->set_pipeline_description(tiledPipe);

  auto window = std::make_shared<gua::GlfwWindow>();
  gua::WindowDatabase::instance()->add("main_window", window);
  window->config.set_enable_vsync(false);
  window->config.set_size(resolution);
  window->config.set_resolution(resolution);
  window->config.set_stereo_mode(gua::StereoMode::MONO);
  window->on_resize.connect([&](gua::math::vec2ui const& new_size) {
    window->config.set_resolution(new_size);
    camera->config.set_resolution(new_size);
    screen->data.set_size(
        gua::math::vec2(0.001 * new_size.x, 0.001 * new_size.y));
  });
  window->on_move_cursor.connect(
      [&](gua::math::vec2 const& pos) { trackball.motion(pos.x, pos.y); });
  window->on_button_press.connect(
      std::bind(mouse_button, std::ref(trackball), std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3));
  window->open();

  gua::Renderer renderer;

  // application loop
  gua::events::MainLoop loop;
  gua::events::Ticker ticker(loop, 1.0 / 500.0);

  size_t ctr{};
  ticker.on_tick.connect([&]() {

    // apply trackball matrix to object
    gua::math::mat4 modelmatrix =
        scm::math::make_translation(gua::math::float_t(trackball.shiftx()),
                                    gua::math::float_t(trackball.shifty()),
                                    gua::math::float_t(trackball.distance())) *
        gua::math::mat4(trackball.rotation());

    transform->set_transform(modelmatrix);

    if (ctr++ % 150 == 0)
      gua::Logger::LOG_WARNING
          << "Frame time: " << 1000.f / window->get_rendering_fps()
          << " ms, fps: " << window->get_rendering_fps() << std::endl;

    window->process_events();
    if (window->should_close()) {
      renderer.stop();
      window->close();
      loop.stop();
    } else {
      renderer.queue_draw({&graph});
    }
  });

  loop.start();

  return 0;
}
Ejemplo n.º 18
0
// ------------------------------------------------------------
// MetisPartitioner implementation
void MetisPartitioner::_do_partition (MeshBase& mesh,
				      const unsigned int n_pieces)
{
  libmesh_assert (n_pieces > 0);
  libmesh_assert (mesh.is_serial());

  // Check for an easy return
  if (n_pieces == 1)
    {
      this->single_partition (mesh);
      return;
    }

// What to do if the Metis library IS NOT present
#ifndef LIBMESH_HAVE_METIS

  libmesh_here();
  libMesh::err << "ERROR: The library has been built without"    << std::endl
	        << "Metis support.  Using a space-filling curve"  << std::endl
	        << "partitioner instead!"                         << std::endl;

  SFCPartitioner sfcp;

  sfcp.partition (mesh, n_pieces);

// What to do if the Metis library IS present
#else

  START_LOG("partition()", "MetisPartitioner");

  const unsigned int n_active_elem = mesh.n_active_elem();

  // build the graph
  // std::vector<int> options(5);
  std::vector<int> vwgt(n_active_elem);
  std::vector<int> part(n_active_elem);

  int
    n = static_cast<int>(n_active_elem),  // number of "nodes" (elements)
                                          //   in the graph
//    wgtflag = 2,                          // weights on vertices only,
//                                          //   none on edges
//    numflag = 0,                          // C-style 0-based numbering
    nparts  = static_cast<int>(n_pieces), // number of subdomains to create
    edgecut = 0;                          // the numbers of edges cut by the
                                          //   resulting partition

  // Set the options
  // options[0] = 0; // use default options

  // Metis will only consider the active elements.
  // We need to map the active element ids into a
  // contiguous range.  Further, we want the unique range indexing to be
  // independednt of the element ordering, otherwise a circular dependency
  // can result in which the partitioning depends on the ordering which
  // depends on the partitioning...
  std::map<const Elem*, unsigned int> global_index_map;
  {
    std::vector<unsigned int> global_index;

    MeshBase::element_iterator       it  = mesh.active_elements_begin();
    const MeshBase::element_iterator end = mesh.active_elements_end();

    MeshCommunication().find_global_indices (MeshTools::bounding_box(mesh),
					     it, end, global_index);

    libmesh_assert (global_index.size() == n_active_elem);

    for (unsigned int cnt=0; it != end; ++it)
      {
	const Elem *elem = *it;
	libmesh_assert (!global_index_map.count(elem));

	global_index_map[elem]  = global_index[cnt++];
      }
    libmesh_assert (global_index_map.size() == n_active_elem);
  }


  // build the graph in CSR format.  Note that
  // the edges in the graph will correspond to
  // face neighbors
  std::vector<int> xadj, adjncy;
  {
    std::vector<const Elem*> neighbors_offspring;

    MeshBase::element_iterator       elem_it  = mesh.active_elements_begin();
    const MeshBase::element_iterator elem_end = mesh.active_elements_end();

    // This will be exact when there is no refinement and all the
    // elements are of the same type.
    unsigned int graph_size=0;
    std::vector<std::vector<unsigned int> > graph(n_active_elem);

    for (; elem_it != elem_end; ++elem_it)
      {
	const Elem* elem = *elem_it;

	libmesh_assert (global_index_map.count(elem));

	const unsigned int elem_global_index =
	  global_index_map[elem];

	libmesh_assert (elem_global_index < vwgt.size());
	libmesh_assert (elem_global_index < graph.size());

	// maybe there is a better weight?
	// The weight is used to define what a balanced graph is
        if(!_weights)
          vwgt[elem_global_index] = elem->n_nodes();
        else
          vwgt[elem_global_index] = static_cast<int>((*_weights)[elem->id()]);

	// Loop over the element's neighbors.  An element
	// adjacency corresponds to a face neighbor
	for (unsigned int ms=0; ms<elem->n_neighbors(); ms++)
	  {
	    const Elem* neighbor = elem->neighbor(ms);

	    if (neighbor != NULL)
	      {
		// If the neighbor is active treat it
		// as a connection
		if (neighbor->active())
		  {
		    libmesh_assert (global_index_map.count(neighbor));

		    const unsigned int neighbor_global_index =
		      global_index_map[neighbor];

		    graph[elem_global_index].push_back(neighbor_global_index);
		    graph_size++;
		  }

#ifdef LIBMESH_ENABLE_AMR

		// Otherwise we need to find all of the
		// neighbor's children that are connected to
		// us and add them
		else
		  {
		    // The side of the neighbor to which
		    // we are connected
		    const unsigned int ns =
		      neighbor->which_neighbor_am_i (elem);
                    libmesh_assert (ns < neighbor->n_neighbors());

		    // Get all the active children (& grandchildren, etc...)
		    // of the neighbor.
		    neighbor->active_family_tree (neighbors_offspring);

		    // Get all the neighbor's children that
		    // live on that side and are thus connected
		    // to us
		    for (unsigned int nc=0; nc<neighbors_offspring.size(); nc++)
		      {
			const Elem* child =
			  neighbors_offspring[nc];

			// This does not assume a level-1 mesh.
			// Note that since children have sides numbered
			// coincident with the parent then this is a sufficient test.
			if (child->neighbor(ns) == elem)
			  {
			    libmesh_assert (child->active());
			    libmesh_assert (global_index_map.count(child));

			    const unsigned int child_global_index =
			      global_index_map[child];

			    graph[elem_global_index].push_back(child_global_index);
			    graph_size++;
			  }
		      }
		  }

#endif /* ifdef LIBMESH_ENABLE_AMR */

	      }
	  }
      }

    // Convert the graph into the format Metis wants
    xadj.reserve(n_active_elem+1);
    adjncy.reserve(graph_size);

    for (unsigned int r=0; r<graph.size(); r++)
      {
	xadj.push_back(adjncy.size());
	std::vector<unsigned int> graph_row; // build this emtpy
	graph_row.swap(graph[r]); // this will deallocate at the end of scope
	adjncy.insert(adjncy.end(),
		      graph_row.begin(),
		      graph_row.end());
      }

    // The end of the adjacency array for the last elem
    xadj.push_back(adjncy.size());

    libmesh_assert (adjncy.size() == graph_size);
    libmesh_assert (xadj.size() == n_active_elem+1);
  } // done building the graph


  if (adjncy.empty())
    adjncy.push_back(0);

  int ncon = 1;

  // Select which type of partitioning to create

  // Use recursive if the number of partitions is less than or equal to 8
  if (n_pieces <= 8)
    Metis::METIS_PartGraphRecursive(&n, &ncon, &xadj[0], &adjncy[0], &vwgt[0], NULL,
				    NULL, &nparts, NULL, NULL, NULL,
				    &edgecut, &part[0]);

  // Otherwise  use kway
  else
    Metis::METIS_PartGraphKway(&n, &ncon, &xadj[0], &adjncy[0], &vwgt[0], NULL,
			       NULL, &nparts, NULL, NULL, NULL,
			       &edgecut, &part[0]);


  // Assign the returned processor ids.  The part array contains
  // the processor id for each active element, but in terms of
  // the contiguous indexing we defined above
  {
    MeshBase::element_iterator       it  = mesh.active_elements_begin();
    const MeshBase::element_iterator end = mesh.active_elements_end();

    for (; it!=end; ++it)
      {
	Elem* elem = *it;

	libmesh_assert (global_index_map.count(elem));

	const unsigned int elem_global_index =
	  global_index_map[elem];

	libmesh_assert (elem_global_index < part.size());
	const unsigned int elem_procid =  static_cast<short int>(part[elem_global_index]);

        elem->processor_id() = elem_procid;
      }
  }

  STOP_LOG("partition()", "MetisPartitioner");
#endif
}
Ejemplo n.º 19
0
int main() {
	mt19937 rng;
	uniform_int_distribution<int> size_dist(0, 40);
	
	for(int t = 0; t < 10000; ++t) {
		int n = size_dist(rng);
		
		uniform_int_distribution<int> edgecount_dist(0, 5 * n);
		int edgecount = edgecount_dist(rng);
		if(n < 2) edgecount = 0;
		uniform_int_distribution<int> weight_dist(0, 12);
		
		vector<pair<double, pair<int, int> > > edges;
		for(int i = 0; i < edgecount; ++i) {
			uniform_int_distribution<int> vertex_dist(0, n - 1);
			int v1 = vertex_dist(rng);
			int v2 = v1;
			while(v1 == v2) v2 = vertex_dist(rng);
			
			edges.push_back(pair<double, pair<int, int> >(
				weight_dist(rng),
				pair<int, int>(v1, v2)
			));
		}
		
		vector<vector<int> > graph(n);
		for(int i = 0; i < edgecount; ++i) {
			int v1 = edges[i].second.first;
			int v2 = edges[i].second.second;
			graph[v1].push_back(v2);
			graph[v2].push_back(v1);
		}
		
		pair<vector<vector<int> >, double> p = kruskal(n, edges);
		
		if(!sameComponents(graph, p.first)) fail();
		
		for(int v = 0; v < n; ++v) {
			failIfNotTreeComponent(p.first, v);
		}
		
		double weight = 0.0;
		for(int x = 0; x < n; ++x) {
			for(int i = 0; i < p.first[x].size(); ++i) {
				int y = p.first[x][i];
				
				double best = 1.0 / 0.0;
				for(int ei = 0; ei < edges.size(); ++ei) {
					if(
						(edges[ei].second.first == x && edges[ei].second.second == y) ||
						(edges[ei].second.first == y && edges[ei].second.second == x)
					) {
						best = min(best, edges[ei].first);
					}
				}
				weight += best;
			}
		}
		
		if(weight != 2.0 * p.second) fail();
	}
	
	return 0;
}
Ejemplo n.º 20
0
int main(int argc, char** argv) {

  //auto resolution = gua::math::vec2ui(800, 600);
  auto resolution = gua::math::vec2ui(3840, 2160);

  // initialize guacamole
  int argc_d = 0;
  char** argv_d = {};
  gua::init(argc_d, argv_d);

  // setup scene
  gua::SceneGraph graph("main_scenegraph");

  auto desc(std::make_shared<gua::MaterialShaderDescription>());
  desc->load_from_file("data/materials/SimpleMaterial.gmd");

  auto shader(std::make_shared<gua::MaterialShader>("simple_mat", desc));
  gua::MaterialShaderDatabase::instance()->add(shader);

  auto mat(shader->make_new_material());

  gua::TriMeshLoader trimeshloader;

  auto teapot_geode(
      trimeshloader.create_geometry_from_file("teapot_geode",
                                              "data/objects/teapot.obj",
                                              mat,
                                              gua::TriMeshLoader::DEFAULTS));
  auto plate_geode(
      trimeshloader.create_geometry_from_file("plate_geode",
                                              "data/objects/plate.obj",
                                              mat,
                                              gua::TriMeshLoader::DEFAULTS));

  auto head = graph.add_node<gua::node::TransformNode>("/", "head");
  head->translate(0.0, 0.0, 8.0);

  auto teapot = graph.add_node<gua::node::TransformNode>("/", "teapot");
  teapot->scale(2.0f);
  auto plate = graph.add_node<gua::node::TransformNode>("/", "plate");

  graph.add_node("/teapot", teapot_geode);
  graph.add_node("/plate", plate_geode);

  const float aspect = resolution.x * 1.0f / resolution.y;

  auto pipe = std::make_shared<gua::PipelineDescription>();

  pipe->add_pass(std::make_shared<gua::TriMeshPassDescription>());
  pipe->add_pass(std::make_shared<gua::TexturedQuadPassDescription>());
  //pipe->add_pass(std::make_shared<gua::BBoxPassDescription>());
  pipe->add_pass(std::make_shared<gua::LightVisibilityPassDescription>());
  pipe->add_pass(std::make_shared<gua::ResolvePassDescription>());
  //pipe->add_pass(std::make_shared<gua::SSAAPassDescription>());
  //pipe->add_pass(std::make_shared<gua::DebugViewPassDescription>());

  auto camera_tl =
      graph.add_node<gua::node::CameraNode>("/head", "camera_tl");
  camera_tl->config.set_output_window_name("window_tl");
  camera_tl->config.set_screen_path("/head/camera_tl/screen_tl");
  camera_tl->config.set_scene_graph_name("main_scenegraph");
  camera_tl->config.set_resolution(resolution);
  camera_tl->config.set_view_id(1);
  camera_tl->set_pipeline_description(pipe);

  auto screen_tl = graph.add_node<gua::node::ScreenNode>("/head/camera_tl", "screen_tl");
  screen_tl->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_tl->translate(-0.8, 0.45, -2.5);

  auto camera_tr =
      graph.add_node<gua::node::CameraNode>("/head", "camera_tr");
  camera_tr->config.set_output_window_name("window_tr");
  camera_tr->config.set_screen_path("/head/camera_tr/screen_tr");
  camera_tr->config.set_scene_graph_name("main_scenegraph");
  camera_tr->config.set_resolution(resolution);
  camera_tr->config.set_view_id(2);
  camera_tr->set_pipeline_description(pipe);

  auto screen_tr = graph.add_node<gua::node::ScreenNode>("/head/camera_tr", "screen_tr");
  screen_tr->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_tr->translate( 0.8f, 0.45, -2.5f);

  auto camera_bl =
      graph.add_node<gua::node::CameraNode>("/head", "camera_bl");
  camera_bl->config.set_output_window_name("window_bl");
  camera_bl->config.set_screen_path("/head/camera_bl/screen_bl");
  camera_bl->config.set_scene_graph_name("main_scenegraph");
  camera_bl->config.set_resolution(resolution);
  //camera_bl->config.set_view_id(2);
  camera_bl->set_pipeline_description(pipe);

  auto screen_bl = graph.add_node<gua::node::ScreenNode>("/head/camera_bl", "screen_bl");
  screen_bl->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_bl->translate(-0.8, -0.45, -2.5f);

  auto camera_br =
      graph.add_node<gua::node::CameraNode>("/head", "camera_br");
  camera_br->config.set_output_window_name("window_br");
  camera_br->config.set_screen_path("/head/camera_br/screen_br");
  camera_br->config.set_scene_graph_name("main_scenegraph");
  camera_br->config.set_resolution(resolution);
  camera_br->set_pipeline_description(pipe);

  auto screen_br = graph.add_node<gua::node::ScreenNode>("/head/camera_br", "screen_br");
  screen_br->data.set_size(gua::math::vec2(1.6, 0.9));
  screen_br->translate( 0.8, -0.45, -2.5f);

  auto pointlight = graph.add_node<gua::node::LightNode>("/", "pointlight");
  pointlight->data.set_type(gua::node::LightNode::Type::POINT);
  pointlight->scale(30.0f);
  pointlight->rotate(-90, 1, 0, 0);
  pointlight->translate(1.0, 18.0, 1.0);

  pointlight->data.set_falloff(0.1f);
  pointlight->data.set_color({
    1.0f, 1.0f, 1.0f
  });
  pointlight->data.set_enable_specular_shading(true);
  pointlight->data.set_enable_diffuse_shading(true);

  auto add_window =
      [](std::string const & window_name,
         std::string const & display,
         std::shared_ptr<gua::node::CameraNode> const & cam_node) {
    auto window = std::make_shared<gua::Window>();
    window->config.set_display_name(display);
    window->join_swap_group(1);
    window->bind_swap_barrier(1);
    gua::WindowDatabase::instance()->add(window_name, window);
    set_window_default(window, cam_node->config.get_resolution());
    cam_node->config.set_output_window_name(window_name);
  };

  add_window("window_tl", ":0.0", camera_tl);

  gua::Renderer renderer;

  // application loop
  gua::events::MainLoop loop;

  gua::events::Ticker ticker(loop, 1.0 / 500.0);

  //gua::Timer frame_timer;
  //frame_timer.start();

  float time_value = 0;

  // application loop
  std::size_t cnt = 0;
  //while (true) {
    //std::this_thread::sleep_for(std::chrono::milliseconds(10));
  ticker.on_tick.connect([&]() {

    teapot_geode->rotate(0.3, 0, 1, 0);

    ++cnt;

    if (cnt == 10) {
      //add_window("window_tr", ":0.0", camera_tr);
      add_window("window_tr", ":0.1", camera_tr);
    }
    if (cnt == 20) {
      //add_window("window_bl", ":0.0", camera_bl);
      add_window("window_bl", ":0.2", camera_bl);
    }
    if (cnt == 30) {
      //add_window("window_br", ":0.0", camera_br);
      add_window("window_br", ":0.3", camera_br);
    }

    // GLFW only allows event processing from main thread
    if (gua::WindowDatabase::instance()->lookup("window_tl")) {
      gua::WindowDatabase::instance()->lookup("window_tl")->process_events();
    }

    if (gua::WindowDatabase::instance()->lookup("window_tr")) {
      gua::WindowDatabase::instance()->lookup("window_tr")->process_events();
    }

    if (gua::WindowDatabase::instance()->lookup("window_bl")) {
      gua::WindowDatabase::instance()->lookup("window_bl")->process_events();
    }

    if (gua::WindowDatabase::instance()->lookup("window_br")) {
      gua::WindowDatabase::instance()->lookup("window_br")->process_events();
    }

    plate->translate(-plate->get_bounding_box().center());
    plate->rotate(0.04f, 0, 1, 0);
    plate->translate(plate->get_bounding_box().center());

    renderer.queue_draw({
      &graph
    });
  });
  //}
  loop.start();
  renderer.stop();

  return 0;
}
Ejemplo n.º 21
0
 GiGraphics* graph() const { return CALL_VIEW2(graph(), NULL); }
void run(context_t& ctx, bool directed) {
    bool is_master = ctx.dc.procid() == 0;
    timer_start(is_master);

#ifdef GRANULA
    granula::operation powergraphJob("PowerGraph", "Id.Unique", "Job", "Id.Unique");
    granula::operation loadGraph("PowerGraph", "Id.Unique", "LoadGraph", "Id.Unique");
    if(is_master) {
        cout<<powergraphJob.getOperationInfo("StartTime", powergraphJob.getEpoch())<<endl;
        cout<<loadGraph.getOperationInfo("StartTime", loadGraph.getEpoch())<<endl;
    }
#endif

    // process parmaeters
    global_directed = directed;

    // load graph
    timer_next("load graph");
    graph_type graph(ctx.dc);
    load_graph(graph, ctx);
    graph.finalize();

#ifdef GRANULA
    if(is_master) {
        cout<<loadGraph.getOperationInfo("EndTime", loadGraph.getEpoch())<<endl;
    }
#endif

    // start engine
    timer_next("initialize engine");
    graphlab::omni_engine<triangle_count> engine(ctx.dc, graph, "synchronous", ctx.clopts);
    engine.signal_all();

#ifdef GRANULA
    granula::operation processGraph("PowerGraph", "Id.Unique", "ProcessGraph", "Id.Unique");
    if(is_master) {
        cout<<processGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl;
    }
#endif

    // run algorithm
    timer_next("run algorithm");
    engine.start();

#ifdef GRANULA
    if(is_master) {
        cout<<processGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl;
    }
#endif

#ifdef GRANULA
    granula::operation offloadGraph("PowerGraph", "Id.Unique", "OffloadGraph", "Id.Unique");
    if(is_master) {
        cout<<offloadGraph.getOperationInfo("StartTime", offloadGraph.getEpoch())<<endl;
    }
#endif

    // print output
    if (ctx.output_enabled) {
        timer_next("print output");
        vector<pair<graphlab::vertex_id_type, vertex_data_type> > data;
        collect_vertex_data(graph, data, is_master);

        for (size_t i = 0; i < data.size(); i++) {
            (*ctx.output_stream) << data[i].first << " " << data[i].second.clustering_coef << endl;
        }
    }

    timer_end();

#ifdef GRANULA
    if(is_master) {
        cout<<offloadGraph.getOperationInfo("EndTime", offloadGraph.getEpoch())<<endl;
        cout<<powergraphJob.getOperationInfo("EndTime", powergraphJob.getEpoch())<<endl;
    }
#endif

}
Ejemplo n.º 23
0
/*public*/
bool
ConnectedInteriorTester::isInteriorsConnected()
{

	// node the edges, in case holes touch the shell
	std::vector<Edge*> splitEdges;
	geomGraph.computeSplitEdges(&splitEdges);

	// form the edges into rings
	PlanarGraph graph(operation::overlay::OverlayNodeFactory::instance());

	graph.addEdges(splitEdges);
	setInteriorEdgesInResult(graph);
	graph.linkResultDirectedEdges();

	std::vector<EdgeRing*> edgeRings;
	buildEdgeRings(graph.getEdgeEnds(), edgeRings);

#if GEOS_DEBUG
	cerr << "buildEdgeRings constructed " << edgeRings.size() << " edgeRings." << endl;
#endif

	/*
	 * Mark all the edges for the edgeRings corresponding to the shells
	 * of the input polygons. 
	 * 
	 * Only ONE ring gets marked for each shell - if there are others
	 * which remain unmarked this indicates a disconnected interior.
	 */
	visitShellInteriors(geomGraph.getGeometry(), graph);

#if GEOS_DEBUG
	cerr << "after visitShellInteriors edgeRings are " << edgeRings.size() << " edgeRings." << endl;
#endif

	/*
	 * If there are any unvisited shell edges
	 * (i.e. a ring which is not a hole and which has the interior
	 * of the parent area on the RHS)
	 * this means that one or more holes must have split the interior of the
	 * polygon into at least two pieces.  The polygon is thus invalid.
	 */
	bool res=!hasUnvisitedShellEdge(&edgeRings);

#if GEOS_DEBUG
	cerr << "releasing " << edgeRings.size() << " edgeRings." << endl;
#endif
	// Release memory allocated by buildEdgeRings
	for(size_t i=0, n=edgeRings.size(); i<n; ++i)
	{
		EdgeRing* er = edgeRings[i];
#if GEOS_DEBUG
		cerr<<*er<<endl;
#endif
		assert(er);
		delete er;
#if GEOS_DEBUG
	cerr << "releasing edgeRing at " << er << endl;
#endif
	}
	edgeRings.clear();

	// Release memory allocated by MaximalEdgeRings
	// There should be no more references to this object
	// how to check this ? boost::shared_ptr<> comes to mind.
	//
	for (size_t i=0, n=maximalEdgeRings.size(); i<n; i++)
	{
		delete maximalEdgeRings[i];
	}
	maximalEdgeRings.clear();

	return res;
}
Ejemplo n.º 24
0
void HeaderSorter::do_process()
{
	DependencyGraph::vertex_iterator i, i_end;
	std::tie(i, i_end) = graph().vertices();
	std::for_each(i, i_end, std::bind(&HeaderSorter::processFile, this, std::placeholders::_1));
}
Ejemplo n.º 25
0
/*
  Configure node_t myself and set up the local sockets (listen only)
*/
static bool setup_myself(void) {
	config_t *cfg;
	subnet_t *subnet;
	char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
	char *fname = NULL;
	char *address = NULL;
	char *proxy = NULL;
	char *space;
	char *envp[5] = {NULL};
	struct addrinfo *ai, *aip, hint = {0};
	bool choice;
	int i, err;
	int replaywin_int;

	myself = new_node();
	myself->connection = new_connection();

	myself->hostname = xstrdup("MYSELF");
	myself->connection->hostname = xstrdup("MYSELF");

	myself->connection->options = 0;
	myself->connection->protocol_version = PROT_CURRENT;

	if(!(name = get_name())) {
		logger(LOG_ERR, "Name for tinc daemon required!");
		return false;
	}

	myself->name = name;
	myself->connection->name = xstrdup(name);
	xasprintf(&fname, "%s/hosts/%s", confbase, name);
	read_config_options(config_tree, name);
	read_config_file(config_tree, fname);
	free(fname);

	if(!read_rsa_private_key())
		return false;

	if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
		myport = xstrdup("655");

	if(!atoi(myport)) {
		struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
		sockaddr_t sa;
		if(!ai || !ai->ai_addr)
			return false;
		free(myport);
		memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
		sockaddr2str(&sa, NULL, &myport);
	}

	get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
	if(proxy) {
		if((space = strchr(proxy, ' ')))
			*space++ = 0;

		if(!strcasecmp(proxy, "none")) {
			proxytype = PROXY_NONE;
		} else if(!strcasecmp(proxy, "socks4")) {
			proxytype = PROXY_SOCKS4;
		} else if(!strcasecmp(proxy, "socks4a")) {
			proxytype = PROXY_SOCKS4A;
		} else if(!strcasecmp(proxy, "socks5")) {
			proxytype = PROXY_SOCKS5;
		} else if(!strcasecmp(proxy, "http")) {
			proxytype = PROXY_HTTP;
		} else if(!strcasecmp(proxy, "exec")) {
			proxytype = PROXY_EXEC;
		} else {
			logger(LOG_ERR, "Unknown proxy type %s!", proxy);
			return false;
		}

		switch(proxytype) {
			case PROXY_NONE:
			default:
				break;

			case PROXY_EXEC:
				if(!space || !*space) {
					logger(LOG_ERR, "Argument expected for proxy type exec!");
					return false;
				}
				proxyhost =  xstrdup(space);
				break;

			case PROXY_SOCKS4:
			case PROXY_SOCKS4A:
			case PROXY_SOCKS5:
			case PROXY_HTTP:
				proxyhost = space;
				if(space && (space = strchr(space, ' ')))
					*space++ = 0, proxyport = space;
				if(space && (space = strchr(space, ' ')))
					*space++ = 0, proxyuser = space;
				if(space && (space = strchr(space, ' ')))
					*space++ = 0, proxypass = space;
				if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
					logger(LOG_ERR, "Host and port argument expected for proxy!");
					return false;
				}
				proxyhost = xstrdup(proxyhost);
				proxyport = xstrdup(proxyport);
				if(proxyuser && *proxyuser)
					proxyuser = xstrdup(proxyuser);
				if(proxypass && *proxypass)
					proxypass = xstrdup(proxypass);
				break;
		}

		free(proxy);
	}

	/* Read in all the subnets specified in the host configuration file */

	cfg = lookup_config(config_tree, "Subnet");

	while(cfg) {
		if(!get_config_subnet(cfg, &subnet))
			return false;

		subnet_add(myself, subnet);

		cfg = lookup_config_next(config_tree, cfg);
	}

	/* Check some options */

	if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
		myself->options |= OPTION_INDIRECT;

	if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
		myself->options |= OPTION_TCPONLY;

	if(myself->options & OPTION_TCPONLY)
		myself->options |= OPTION_INDIRECT;

	get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
	get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
	get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
	get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
	strictsubnets |= tunnelserver;

	if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
		if(!strcasecmp(mode, "router"))
			routing_mode = RMODE_ROUTER;
		else if(!strcasecmp(mode, "switch"))
			routing_mode = RMODE_SWITCH;
		else if(!strcasecmp(mode, "hub"))
			routing_mode = RMODE_HUB;
		else {
			logger(LOG_ERR, "Invalid routing mode!");
			return false;
		}
		free(mode);
	}

	if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
		if(!strcasecmp(mode, "off"))
			forwarding_mode = FMODE_OFF;
		else if(!strcasecmp(mode, "internal"))
			forwarding_mode = FMODE_INTERNAL;
		else if(!strcasecmp(mode, "kernel"))
			forwarding_mode = FMODE_KERNEL;
		else {
			logger(LOG_ERR, "Invalid forwarding mode!");
			return false;
		}
		free(mode);
	}

	choice = true;
	get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
	if(choice)
		myself->options |= OPTION_PMTU_DISCOVERY;

	choice = true;
	get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
	if(choice)
		myself->options |= OPTION_CLAMP_MSS;

	get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
	get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
	if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
		if(!strcasecmp(mode, "no"))
			broadcast_mode = BMODE_NONE;
		else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
			broadcast_mode = BMODE_MST;
		else if(!strcasecmp(mode, "direct"))
			broadcast_mode = BMODE_DIRECT;
		else {
			logger(LOG_ERR, "Invalid broadcast mode!");
			return false;
		}
		free(mode);
	}

#if !defined(SOL_IP) || !defined(IP_TOS)
	if(priorityinheritance)
		logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
#endif

	if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
		macexpire = 600;

	if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
		if(maxtimeout <= 0) {
			logger(LOG_ERR, "Bogus maximum timeout!");
			return false;
		}
	} else
		maxtimeout = 900;

	if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
		if(udp_rcvbuf <= 0) {
			logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
			return false;
		}
	}

	if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
		if(udp_sndbuf <= 0) {
			logger(LOG_ERR, "UDPSndBuf cannot be negative!");
			return false;
		}
	}

	if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
		if(replaywin_int < 0) {
			logger(LOG_ERR, "ReplayWindow cannot be negative!");
			return false;
		}
		replaywin = (unsigned)replaywin_int;
	}

	if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
		if(!strcasecmp(afname, "IPv4"))
			addressfamily = AF_INET;
		else if(!strcasecmp(afname, "IPv6"))
			addressfamily = AF_INET6;
		else if(!strcasecmp(afname, "any"))
			addressfamily = AF_UNSPEC;
		else {
			logger(LOG_ERR, "Invalid address family!");
			return false;
		}
		free(afname);
	}

	get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);

	/* Generate packet encryption key */

	if(get_config_string
	   (lookup_config(config_tree, "Cipher"), &cipher)) {
		if(!strcasecmp(cipher, "none")) {
			myself->incipher = NULL;
		} else {
			myself->incipher = EVP_get_cipherbyname(cipher);

			if(!myself->incipher) {
				logger(LOG_ERR, "Unrecognized cipher type!");
				return false;
			}
		}
	} else
		myself->incipher = EVP_bf_cbc();

	if(myself->incipher)
		myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
	else
		myself->inkeylength = 1;

	myself->connection->outcipher = EVP_bf_ofb();

	if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
		keylifetime = 3600;

	keyexpires = now + keylifetime;
	
	/* Check if we want to use message authentication codes... */

	if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
		if(!strcasecmp(digest, "none")) {
			myself->indigest = NULL;
		} else {
			myself->indigest = EVP_get_digestbyname(digest);

			if(!myself->indigest) {
				logger(LOG_ERR, "Unrecognized digest type!");
				return false;
			}
		}
	} else
		myself->indigest = EVP_sha1();

	myself->connection->outdigest = EVP_sha1();

	if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
		if(myself->indigest) {
			if(myself->inmaclength > myself->indigest->md_size) {
				logger(LOG_ERR, "MAC length exceeds size of digest!");
				return false;
			} else if(myself->inmaclength < 0) {
				logger(LOG_ERR, "Bogus MAC length!");
				return false;
			}
		}
	} else
		myself->inmaclength = 4;

	myself->connection->outmaclength = 0;

	/* Compression */

	if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
		if(myself->incompression < 0 || myself->incompression > 11) {
			logger(LOG_ERR, "Bogus compression level!");
			return false;
		}
	} else
		myself->incompression = 0;

	myself->connection->outcompression = 0;

	/* Done */

	myself->nexthop = myself;
	myself->via = myself;
	myself->status.reachable = true;
	node_add(myself);

	graph();

	if(strictsubnets)
		load_all_subnets();

	/* Open device */

	devops = os_devops;

	if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
		if(!strcasecmp(type, "dummy"))
			devops = dummy_devops;
		else if(!strcasecmp(type, "raw_socket"))
			devops = raw_socket_devops;
		else if(!strcasecmp(type, "multicast"))
			devops = multicast_devops;
#ifdef ENABLE_UML
		else if(!strcasecmp(type, "uml"))
			devops = uml_devops;
#endif
#ifdef ENABLE_VDE
		else if(!strcasecmp(type, "vde"))
			devops = vde_devops;
#endif
	}

	if(!devops.setup())
		return false;

	/* Run tinc-up script to further initialize the tap interface */
	xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
	xasprintf(&envp[1], "DEVICE=%s", device ? : "");
	xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
	xasprintf(&envp[3], "NAME=%s", myself->name);

	execute_script("tinc-up", envp);

	for(i = 0; i < 4; i++)
		free(envp[i]);

	/* Run subnet-up scripts for our own subnets */

	subnet_update(myself, NULL, true);

	/* Open sockets */

	if(!do_detach && getenv("LISTEN_FDS")) {
		sockaddr_t sa;
		socklen_t salen;

		listen_sockets = atoi(getenv("LISTEN_FDS"));
#ifdef HAVE_UNSETENV
		unsetenv("LISTEN_FDS");
#endif

		if(listen_sockets > MAXSOCKETS) {
			logger(LOG_ERR, "Too many listening sockets");
			return false;
		}

		for(i = 0; i < listen_sockets; i++) {
			salen = sizeof sa;
			if(getsockname(i + 3, &sa.sa, &salen) < 0) {
				logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
				return false;
			}

			listen_socket[i].tcp = i + 3;

#ifdef FD_CLOEXEC
		        fcntl(i + 3, F_SETFD, FD_CLOEXEC);
#endif

			listen_socket[i].udp = setup_vpn_in_socket(&sa);
			if(listen_socket[i].udp < 0)
				return false;

			ifdebug(CONNECTIONS) {
				hostname = sockaddr2hostname(&sa);
				logger(LOG_NOTICE, "Listening on %s", hostname);
				free(hostname);
			}

			memcpy(&listen_socket[i].sa, &sa, salen);
		}
	} else {
Ejemplo n.º 26
0
void mexFunction( const int nlhs, mxArray *plhs[], const int nrhs, const mxArray *prhs[]) {
	/* Check for proper number of arguments. */
	if (nrhs != 1) {
		mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidNumInputs",
			"One input required.");
	} else if (nlhs > 1) {
		mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidNumOutputs",
			"At most one output is allowed.");
	}

	const mxArray *numberOfNodesArray = mxGetProperty(prhs[0], 0, "numberOfNodes");
	if (!mxIsNumeric(numberOfNodesArray) || mxGetNumberOfElements(numberOfNodesArray) != 1) {
		mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidNumberOfNodes", "Number of nodes is not numeric scalar.");
	}
	const int numberOfNodes = mxGetScalar(numberOfNodesArray);
	if (numberOfNodes < 1) {
		mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:emptyGraph",
			"Graph is empty.");
	}

	const mxArray *pAdjacencyMatrix = mxGetProperty(prhs[0], 0, "pAdjacencyMatrix");
	if (!mxIsLogical(pAdjacencyMatrix) || mxGetN(pAdjacencyMatrix) != numberOfNodes || mxGetM(pAdjacencyMatrix) != numberOfNodes) {
		mexErrMsgIdAndTxt("MATLAB:Graph:IsConnected:invalidAdjacencyMatrix", "Adjacency matrix is not logical square matrix");
	}
	const bool *adjacencyMatrix = mxGetLogicals(pAdjacencyMatrix);

	const mxArray *pIsDirectedArray = mxGetProperty(prhs[0], 0, "pIsDirected");
	if (!mxIsLogicalScalar(pIsDirectedArray)) {
		mexErrMsgIdAndTxt( "MATLAB:Graph:IsConnected:invalidIsDirected", "Direction is not logical scalar");
	}
	const bool isDirected = mxIsLogicalScalarTrue(pIsDirectedArray);

	bool *reachable = new bool[numberOfNodes];


	if (mxIsSparse(pAdjacencyMatrix)) {
		// Sparse adjacency matrix
		std::vector<std::vector<mwIndex> > graph(numberOfNodes), rgraph(numberOfNodes);
		const mwIndex* row = mxGetIr(pAdjacencyMatrix);
		const mwIndex* col = mxGetJc(pAdjacencyMatrix);
		const size_t nz = col[mxGetN(pAdjacencyMatrix)];
		mwIndex c = 0;
		for(size_t i = 0; i<nz; ++i) {
			while(col[c+1]<=i) ++c;
			if(adjacencyMatrix[i]) {
				graph[row[i]].push_back(c);
				rgraph[c].push_back(row[i]);
			}
		}
		memset(reachable, false, numberOfNodes * sizeof(bool));
		reachable[0] = true;
		int nReachable = 1;
		std::queue<int> nodeQueue;
		nodeQueue.push(0);

		while(!nodeQueue.empty() && nReachable < numberOfNodes) {
			const int i = nodeQueue.front(); nodeQueue.pop();
			std::vector<mwIndex>::const_iterator it = graph[i].begin();

			for (; it != graph[i].end(); ++it) {
				if(!reachable[*it]) {
					reachable[*it] = true;
					nReachable++;
					nodeQueue.push(*it);
				}
			}
		}
		if (!isDirected || nReachable != numberOfNodes) {
			plhs[0] = mxCreateLogicalScalar(nReachable == numberOfNodes);
		} else {
			memset(reachable, false, numberOfNodes * sizeof(bool));
			reachable[0] = true;
			int nReachable2 = 1;
			nodeQueue = std::queue<int>(); // Clear queue
			nodeQueue.push(0);
			while(!nodeQueue.empty() && nReachable2 < numberOfNodes) {
				const int i = nodeQueue.front(); nodeQueue.pop();
				std::vector<mwIndex>::const_iterator it = rgraph[i].begin();
				for (; it != rgraph[i].end(); ++it) {
					if(!reachable[*it]) {
						mexPrintf("Reachable 2 is %lu\n", *it);
						reachable[*it] = true;
						nReachable2++;
						nodeQueue.push(*it);
					}
				}
			}
			plhs[0] = mxCreateLogicalScalar(nReachable2 == numberOfNodes);
		}
	} else {
		// Full adjacency matrix
		memset(reachable, false, numberOfNodes * sizeof(bool));
		reachable[0] = true;
		int nReachable = 1;
		std::queue<int> nodeQueue;
		nodeQueue.push(0);

		while(!nodeQueue.empty() && nReachable < numberOfNodes) {
			const int i = nodeQueue.front(); nodeQueue.pop();
			for (int j=0; j<numberOfNodes; ++j) {
				if(adjacencyMatrix[i*numberOfNodes+j] && !reachable[j]) {
					reachable[j] = true;
					nReachable++;
					nodeQueue.push(j);
				}
			}
		}
		if (!isDirected || nReachable != numberOfNodes) {
			plhs[0] = mxCreateLogicalScalar(nReachable == numberOfNodes);
		} else {
			memset(reachable, false, numberOfNodes * sizeof(bool));
			reachable[0] = true;
			int nReachable2 = 1;
			nodeQueue = std::queue<int>(); // Clear queue
			nodeQueue.push(0);
			while(!nodeQueue.empty() && nReachable2 < numberOfNodes) {
				const int i = nodeQueue.front(); nodeQueue.pop();
				for (int j=0; j<numberOfNodes; ++j) {
					if(adjacencyMatrix[j*numberOfNodes+i] && !reachable[j]) {
						reachable[j] = true;
						nReachable2++;
						nodeQueue.push(j);
					}
				}
			}
			plhs[0] = mxCreateLogicalScalar(nReachable2 == numberOfNodes);
		}
	}

	delete [] reachable;
}
Ejemplo n.º 27
0
void ExcitedStates::initMoPlot()
{
   m_moPlot   = new QCustomPlot(); 
   m_moPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
   m_moPlot->axisRect()->setRangeDrag(m_moPlot->yAxis->orientation());
   m_moPlot->axisRect()->setRangeZoom(m_moPlot->yAxis->orientation());
   m_moPlot->xAxis->setSelectableParts(QCPAxis::spNone);
   
   QFrame* frame(m_configurator.moFrame);
   QVBoxLayout* layout(new QVBoxLayout());
   frame->setLayout(layout);
   layout->addWidget(m_moPlot);

   //layout->addWidget(new QLabel("This is a test"));
   //layout->setStretch(0,1);
   //layout->setStretch(1,0);

   QVector<double>  ticks;
   QVector<QString> labels;

   ticks << 0.75 << 2.50;
   labels << "Alpha" << "Beta";

   m_moPlot->xAxis->setAutoTicks(false);
   m_moPlot->xAxis->setAutoTickLabels(false);
   m_moPlot->xAxis->setTickVector(ticks);
   m_moPlot->xAxis->setTickVectorLabels(labels);
   m_moPlot->xAxis->setSubTickCount(0);
   m_moPlot->xAxis->setRange(0,3.25);

   Data::OrbitalSymmetries const& orbitals(m_excitedStates.data().orbitalSymmetries());

   unsigned nOrbs(orbitals.nOrbitals());
   unsigned nAlpha(orbitals.nAlpha());
   unsigned nBeta(orbitals.nBeta());
   QVector<double>  xAlpha(nOrbs), yAlpha(nOrbs), xBeta(nOrbs), yBeta(nOrbs); 
   QVector<double> a(1), b(1), y(1);
   QCPGraph* graph(0);

   unsigned i(0), g(0);

   Data::Spin spin(Data::Alpha);

   while (i < nOrbs) {
       y[0] = orbitals.energy(spin, i);

       g = 1; // degeneracy
       while (i+g < nOrbs && 
              std::abs(y[0]-orbitals.energy(spin, i+g)) < 0.001) { ++g; }

       for (unsigned k = i; k < i+g; ++k) {
           a[0]  = 0.75 - 0.25*(g-1) + (k-i)*0.50;
           graph = m_moPlot->addGraph();
           graph->setData(a, y);
           graph->setName(QString::number(k));
           graph->setScatterStyle(k<nAlpha ? QCPScatterStyle::ssOccupied 
                                           : QCPScatterStyle::ssVirtual);
           connect(graph, SIGNAL(selectionChanged(bool)), this, SLOT(moSelectionChanged(bool)));
       }

       i += g;
   }

   i    = 0;
   spin = Data::Beta;

   while (i < nOrbs) {
       y[0] = orbitals.energy(spin, i);

       g = 1; // degeneracy
       while (i+g < nOrbs && 
              std::abs(y[0]-orbitals.energy(spin, i+g)) < 0.001) { ++g; }

       for (unsigned k = i; k < i+g; ++k) {
           a[0]  = 2.50 - 0.25*(g-1) + (k-i)*0.50;
           graph = m_moPlot->addGraph();
           graph->setData(a, y);
           graph->setName(QString::number(k+nOrbs));
           graph->setScatterStyle(k<nBeta ? QCPScatterStyle::ssOccupied 
                                           : QCPScatterStyle::ssVirtual);
           connect(graph, SIGNAL(selectionChanged(bool)), this, SLOT(moSelectionChanged(bool)));
       }

       i += g;
   }

   m_moPlot->yAxis->setLabel("Energy/Hartree");
   m_moPlot->yAxis->setNumberPrecision(3);
   // Set the scale
   double yMin(-1.0), yMax(0.5);
   // Show 5 occupied and virtual orbitals to start with
   unsigned index, nShow(5);
   
   if (nBeta > nAlpha) {
      // Use the beta energies instead
      index = nBeta < nShow ? 0 : nBeta-nShow;
      yMin  = orbitals.energy(Data::Beta, index);
      index = nOrbs > nBeta+nShow ? nBeta+nShow : nOrbs;
      yMax  = orbitals.energy(Data::Beta, index);
   }else {
      index = nAlpha < nShow ? 0 : nAlpha-nShow;
      yMin  = orbitals.energy(Data::Alpha, index);
      index = nOrbs > nAlpha+nShow ? nAlpha+nShow : nOrbs;
      yMax  = orbitals.energy(Data::Alpha, index);
   }

   yMax = std::min(yMax, 0.5*std::abs(yMin));
   m_moPlot->yAxis->setRange(1.05*yMin,1.05*yMax);

   // add the orbital label
   m_label = new QCPItemText(m_moPlot);
   m_moPlot->addItem(m_label);
   m_label->position->setType(QCPItemPosition::ptViewportRatio); 
   m_label->setPositionAlignment(Qt::AlignTop|Qt::AlignRight);
   m_label->position->setCoords(0, 0); 
   m_label->setText("Orbital");
   m_label->setFont(QFont(font().family(), 10));
}
Ejemplo n.º 28
0
void renderGraph(QPainter & paint, const QRect & rect, ORGraphData & gData, XSqlQuery * query, const QMap<QString, QColor> & _colorMap) {
    int dpi = paint.device()->logicalDpiX();

    QFont fnt;

    tGraph graph(rect);
    fnt = gData.font;
    fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
    graph.setFont(fnt);
    if(gData.title.string.length() > 0) {
        graph.setTitle(gData.title.string);
        if(gData.title.font_defined) {
            fnt = gData.title.font;
            fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
            graph.setTitleFont(&fnt);
        }
    }

    QString lbl_clmn = gData.dataaxis.column;
    if(lbl_clmn.length() > 0 && gData.dataaxis.font_defined) {
        fnt = gData.dataaxis.font;
        fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
        graph.setDataFont(&fnt);
    }
    if(gData.dataaxis.title.string.length() > 0) {
        graph.setDataLabel(gData.dataaxis.title.string);
        if(gData.dataaxis.title.font_defined) {
            fnt = gData.dataaxis.title.font;
            fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
            graph.setDataLabelFont(&fnt);
        }
    }

    graph.setAutoMinMax(gData.valueaxis.autominmax);
    graph.setMinValue(gData.valueaxis.min);
    graph.setMaxValue(gData.valueaxis.max);
    if(gData.valueaxis.font_defined) {
        fnt = gData.valueaxis.font;
        fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
        graph.setValueFont(&fnt);
    }
    if(gData.valueaxis.title.string.length() > 0) {
        graph.setValueLabel(gData.valueaxis.title.string);
        if(gData.valueaxis.title.font_defined) {
            fnt = gData.valueaxis.title.font;
            fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
            graph.setValueLabelFont(&fnt);
        }
    }

    // setup the sets/series
    int snum = 0;
    ORSeriesData * sd = 0;
    for(snum = 0; snum < gData.series.count(); snum++) {
        sd = gData.series.at(snum);
        if(sd) {
            graph.setSetColor(snum, _colorMap[sd->color]);
            graph.setSetStyle(snum, sd->style);
        }
    }

    // populate the data
    if(query->first()) {
        do {
            if(lbl_clmn.length() > 0) {
                graph.setReferenceLabel(query->at(), query->value(lbl_clmn).toString());
            }
            for(snum = 0; snum < gData.series.count(); snum++) {
                sd = gData.series.at(snum);
                if(sd) {
                    graph.setSetValue(query->at(), snum, query->value(sd->column).toDouble());
                }
            }
        } while(query->next());
    }

    // draw the graph
    graph.draw(paint);
}
Ejemplo n.º 29
0
    template <typename ImageInfoLessThan> LessThanOnVertexImageInfo<ImageInfoLessThan>

    sortBy(ImageInfoLessThan imageInfoLessThan)
    {
        return LessThanOnVertexImageInfo<ImageInfoLessThan>(graph(), imageInfoLessThan);
    }
Ejemplo n.º 30
0
void start(graphlab::command_line_options& clopts,
           std::string & graph_dir,
           std::string & format,
           std::string & exec_type,
           std::string & saveprefix) {
    local_graph_type l_graph;
    std::vector<vertex_record> lvid2record_ref;
    std::vector<replica_record> replicas_lvid2record_ref;
    //typedef graphlab::hopscotch_map<graphlab::vertex_id_type, graphlab::lvid_type> hopscotch_map_type;
    //hopscotch_map_type vid2lvid_ref;
    //hopscotch_map_type replicas_vid2lvid_ref;

    unsigned int iter = 0;
    int iteration_number = 0;
    int surviving_server_count;
    bool replacement_server = atoi(getenv("REPLACEMENT")) != 0;
    int replacement_server_count = atoi(getenv("REPLACEMENT_COUNT"));
    bool ground_truth = atoi(getenv("GROUND_TRUTH")) != 0;
    bool proactive_replication = atoi(getenv("PROACTIVE_REPLICATION")) != 0;
    graphlab::reactive_zorro<pagerank>* rs;

    std::unordered_map<std::string, int> current_ip_to_id_map; // map from ip of process to its id for currently alive processes
    std::unordered_map<std::string, int> previous_ip_to_id_map; // map from ip of process to its id for previously alove processes
    std::vector<int> id_to_previous_id; // map from previous id of a process to its current ip, -1 if a process was not replaced

    while (1) {


        try {
            if (iter > 0) {
                // TODO: Sleep here if required to ensure that the count of surviving servers is accurate.
                // Consider all survivors and any replacement servers (if available) for the next execution.
                surviving_server_count = rs->stop_watching_zoookeeper(); // we can increase the surviving server count if replacements available
                std::cout << "Zorro: Surviving server count: " << surviving_server_count << std::endl;
                std::cout << "Zorro: Replacement server count: " << replacement_server_count << std::endl;
                setenv("ZK_NUMNODES", std::to_string(surviving_server_count + replacement_server_count).c_str(), 1);
            }


            // Initialize from ZooKeeper
            graphlab::dc_init_param initparam;
            graphlab::init_param_from_zookeeper(initparam);
            graphlab::distributed_control dc(initparam);

            // Initialize without ZooKeeper
            //graphlab::distributed_control dc;

            if (iter > 0) {
                rs->stop(); // end previous reactive_server session
                delete rs;
            }

            // Initialize the graph
            graph_type graph(dc, clopts);
            std::cout << "Zorro: Graph initialized." << std::endl;

            // Initialize synchronous engine
            graphlab::omni_engine<pagerank> engine(dc, graph, exec_type, clopts);
            auto sync_engine_ptr = static_cast<graphlab::synchronous_engine<pagerank> * >(engine.get_engine_ptr());

            // Set local_graph and lvid2record map in synchronous engine.
            // These are required to trasnfer surviving vertex values to replacement servers.
            if (!replacement_server) {
                sync_engine_ptr->set_l_graph_backup(&l_graph);
                sync_engine_ptr->set_lvid2record_backup(&lvid2record_ref);
                if (proactive_replication) {
                    sync_engine_ptr->set_replicas_lvid2record_backup(&replicas_lvid2record_ref);
                }
            }

            std::cout << "Zorro: Constructing id maps" << std::endl;
            // Waitless Zorro maps previous process ids to new process ids
            std::vector<std::string>& machines = initparam.machines;
            for (int i = 0; i < machines.size(); ++i) {
                std::cout << machines[i] << std::endl;
                size_t pos = machines[i].find(":");
                current_ip_to_id_map[machines[i].substr(0, pos)] = i;
            }


            if (iter == 0) {
                id_to_previous_id.resize(dc.numprocs());
                // TODO: Figure out the most efficient method to copy unordered_maps
                previous_ip_to_id_map.insert(current_ip_to_id_map.begin(), current_ip_to_id_map.end());
            }
            std::cout << "Zorro: Constructing id to id map" << std::endl;

            // Map previous proc ids to new proc ids
            for (auto element : previous_ip_to_id_map) {
                if (current_ip_to_id_map.find(element.first) != current_ip_to_id_map.end()) {
                    id_to_previous_id[element.second] = current_ip_to_id_map[element.first];
                } else {
                    id_to_previous_id[element.second] = -1;
                }
            }

            for (size_t i = 0; i < id_to_previous_id.size(); ++i) {
                std::cout << "Previous id: " << i << " now has an id: " << id_to_previous_id[i] << std::endl;
            }

            std::cout << "Zorro: Initializing reactive server" << std::endl;
            rs = new graphlab::reactive_zorro<pagerank>();
            rs->init(&dc, &engine, iteration_number);
            rs->wait_for_join();

            std::vector< std::pair<size_t, bool> > server_list =
                extract_and_set_iteration(sync_engine_ptr, rs->get_received_servers());
            sync_engine_ptr->set_server_list(server_list);
            std::cout << "Zorro: All processes have joined: " << server_list.size() << std::endl;
            sync_engine_ptr->resize_received_state_container(dc.numprocs());
            dc.barrier();

            graphlab::thread_group tgroup;
            // Broadcast surviving state if not a replacement server
            if(iter > 0 && !replacement_server) {
                std::cout << "Zorro: Rebuilding state by requesting vertex data." << std::endl;
                if (proactive_replication) {
                    sync_engine_ptr->broadcast_surviving_state_replicas(tgroup, surviving_server_count, id_to_previous_id);
                } else {
                    sync_engine_ptr->broadcast_surviving_state(tgroup, surviving_server_count, id_to_previous_id);
                }
            }

            // Load the graph
            graph.load_format(graph_dir, format);
            // must call finalize before querying the graph
            graph.finalize();

            std::cout << "#vertices: " << graph.num_vertices() << " #edges:" << graph.num_edges() << std::endl;

            // Initialize the vertex data
            sync_engine_ptr->resize(); // Separately called to enable parallel graph loading with recovery
            graph.transform_vertices(init_vertex);

            tgroup.join();
            std::vector<vid_vdata_vector_type> received_state;
            received_state = sync_engine_ptr->get_received_state();
            std::cout << "Zorro: Receive surviving state thread joined. Now merging." << std::endl;

            // Merge received state into primary graph state
            graphlab::thread_group tgroup_merge;
            for (size_t i = 0; i < received_state.size(); ++i) {
                tgroup_merge.launch(boost::bind(&merge_values, boost::ref(received_state[i]), boost::ref(graph)));
            }
            tgroup_merge.join();

            engine.signal_all();

            try {
                engine.start();
                rs->stop();

                const double runtime = engine.elapsed_seconds();
                std::cout << "Zorro: Completed Running engine in " << runtime << " seconds." << std::endl;

                if (ground_truth) {
                    write_results("/home/lamport/output_ground", graph); // write ground truth
                } else {
                    write_results("/home/lamport/output", graph); // write result with failures
                }

                // Save the final graph
                if (saveprefix != "") {
                    std::cout << "SAVING FILE" << std::endl;
                    graph.save(saveprefix, pagerank_writer(),
                               false,    // do not gzip
                               true,     // save vertices
                               false);   // do not save edges
                }
                return;
            } catch(graphlab::failure_exception e) {
                l_graph = std::move(graph.get_local_graph());
                //vid2lvid_ref = std::move(graph.get_vid2lvid());
                lvid2record_ref = std::move(graph.get_lvid2record());

                if (proactive_replication) {
                    //replicas_vid2lvid_ref = std::move(graph.get_replicas_vid2lvid());
                    replicas_lvid2record_ref = std::move(graph.get_replicas_lvid2record());
                }
                iteration_number = sync_engine_ptr->iteration();

                // TODO: Figure out the most efficient method to copy unordered_maps
                previous_ip_to_id_map.clear();
                previous_ip_to_id_map.insert(current_ip_to_id_map.begin(), current_ip_to_id_map.end());
                current_ip_to_id_map.clear();
                throw e;
            }
        } catch(graphlab::failure_exception) {
            std::cout << "Zorro: Failed Running engine at iteration: " << iter << ". Recovering..." << std::endl;
            ++iter;
            continue;
        }
    }
}