Beispiel #1
0
GraphType* generate_example5_graph(GraphType::FGSeedsType& fg_nodes,
                                   unsigned int& node_rows,
                                   const int use_seed[], int lambda)
{
  /* capacity edges */
  const int NUM_NODES = 15;
  const int NUM_EDGES = 21;
  int edges_a[]   = {0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7, 8, 9, 9, 9, 10, 10, 11, 12};
  int edges_b[]   = {3, 4, 4, 4, 6, 6, 8, 8, 7, 9, 10, 8, 10, 10, 10, 12, 13, 11, 14, 14, 13};
  int edges_cap[] = {30, 4, 10, 40, 20, 4, 10, 30, 4, 6, 40, 10, 40, 10, 8, 20, 6, 10, 20, 30, 4};
  int bg_cap[] = {1, 10, 10, 3, 1, 1, 7, 7, 10, 5, 1, 5, 10, 5, 7};



  GraphType::SrcSeedList fg1, fg2;

  static const unsigned int fg_nodes1[] = { 3, 4 };
  create_seed_list(fg_nodes1, sizeof(fg_nodes1)/sizeof(fg_nodes1[0]), fg1);
  static const unsigned int fg_nodes2[] = { 10 };
  create_seed_list(fg_nodes2, sizeof(fg_nodes2)/sizeof(fg_nodes2[0]), fg2);

  fg_nodes.clear();

  if (use_seed[0] == -1 || use_seed[0] == 1)
    fg_nodes.push_back(fg1);
  if (use_seed[0] == -1 || use_seed[1] == 1)
    fg_nodes.push_back(fg2);

  GraphType* g = construct_graph(NUM_NODES, NUM_EDGES, bg_cap, edges_a, edges_b,
                                 edges_cap, fg_nodes, lambda);

  node_rows = 3;

  return g;
}
// -------------------------------------------------------------------------
int GraphDefinition::multi_dijkstra(
    edge_t *edges,
    size_t edge_count,
    std::vector<int> vertices,
    bool directed,
    bool has_reverse_cost,
    path_element_tt **path,
    size_t *path_count,
    char **err_msg,
    std::vector<PDVI> &ruleList) {
    construct_graph(edges, edge_count, has_reverse_cost, directed);
    if (ruleList.size() > 0) {
        m_ruleTable.clear();
        LongVector vecsource;
        for (const auto &rule : ruleList) {
            std::vector<long> temp_precedencelist;
            temp_precedencelist.clear();
            for (auto const &seq : rule.second) {
                temp_precedencelist.push_back(seq);
            }
            long dest_edge_id = rule.second[0];
            if (m_ruleTable.find(dest_edge_id) != m_ruleTable.end()) {
                m_ruleTable[dest_edge_id].push_back(Rule(rule.first,
                    temp_precedencelist));
            } else {
                std::vector<Rule> temprules;
                temprules.clear();
                temprules.push_back(Rule(rule.first, temp_precedencelist));
                m_ruleTable.insert(std::make_pair(dest_edge_id, temprules));
            }
        }
        m_bIsturnRestrictOn = true;
    }
    parent = new PARENT_PATH[edge_count + 1];
    m_dCost = new CostHolder[edge_count + 1];
    m_vecPath.clear();
    size_t i;
    size_t total_vertices = vertices.size();
    for (i = 0; i < total_vertices - 1; i++) {
        int ret = my_dijkstra(vertices[i], vertices[i + 1], edge_count,
                err_msg);
        if (ret < 0) {
            deleteall();
            return -1;
        }
    }

    *path = (path_element_tt *) malloc(sizeof(path_element_tt) *
    (m_vecPath.size() + 1));
    *path_count = static_cast<int>(m_vecPath.size());

    for (size_t  i = 0; i < *path_count; i++) {
        (*path)[i].vertex_id = m_vecPath[i].vertex_id;
        (*path)[i].edge_id = m_vecPath[i].edge_id;
        (*path)[i].cost = m_vecPath[i].cost;
    }
    deleteall();
    return 0;
}
Beispiel #3
0
void
closest_pairs2graph(double *place, int n, int num_pairs, vtx_data ** graph)
{
    /* build a graph with with edges between the 'num_pairs' closest pairs in the 1-D space: 'place' */
    PairStack pairs_stack;
    initStack(&pairs_stack, num_pairs);
    find_closest_pairs(place, n, num_pairs, &pairs_stack);
    construct_graph(n, &pairs_stack, graph);
    freeStack(&pairs_stack);
}
Beispiel #4
0
Datei: graph.c Projekt: lita/opto
void solve(int nitems, int *n1ind, int *n2ind) {
    // TODO: free graph on failure
    int ncolours = 2;
    bool success = false;
    while (!success) {
        // Is it a good idea to reconstruct the graph just to update
        // the number of possible colors? Maybe you can do a DFS to update
        // to update the value
        Graph graph = construct_graph(ncolours, nitems, n1ind, n2ind);
        success = start_solver(&graph);
        ncolours++;
    }
}
Beispiel #5
0
int main()
{
	int i, j;
	while(scanf("%d%d", &nbox, &dim) != EOF)
	{
		for(i = 0; i < nbox; i++)
			for(j = 0; j < dim; j++)
				scanf("%d", &box[i][j]);
		construct_graph();
		find_longest();
		output();
	}
	return 0;
}
// -------------------------------------------------------------------------
Pgr_trspHandler::Pgr_trspHandler(
        pgr_edge_t *edges,
        const size_t edge_count,
        const bool directed,
        const std::vector<Rule> &ruleList) :
    m_ruleTable() {

    initialize_restrictions(ruleList);

    m_min_id = renumber_edges(edges, edge_count);

    construct_graph(
            edges,
            edge_count,
            directed);

}
Beispiel #7
0
/*
 * The only public interface for this file.  Do the dirty work of constructing a
 * child list for the given object.  Construct the graph, do the toplogical
 * sort, and then return the array of strings to the caller.
 *
 * The 'allowrecursion' parameter controls behavior when cycles are found.  If
 * it is set, the the cycle is ignored and the results returned as if the cycle
 * did not exist.  If it is not set, then the routine will generate an error if
 * a cycle is found.
 */
int
get_dependents(libzfs_handle_t *hdl, boolean_t allowrecursion,
    const char *dataset, char ***result, size_t *count)
{
	zfs_graph_t *zgp;
	zfs_vertex_t *zvp;

	if ((zgp = construct_graph(hdl, dataset)) == NULL)
		return (-1);

	if ((*result = zfs_alloc(hdl,
	    zgp->zg_nvertex * sizeof (char *))) == NULL) {
		zfs_graph_destroy(zgp);
		return (-1);
	}

	if ((zvp = zfs_graph_lookup(hdl, zgp, dataset, 0)) == NULL) {
		free(*result);
		zfs_graph_destroy(zgp);
		return (-1);
	}

	*count = 0;
	if (topo_sort(hdl, allowrecursion, *result, count, zvp) != 0) {
		free(*result);
		zfs_graph_destroy(zgp);
		return (-1);
	}

	/*
	 * Get rid of the last entry, which is our starting vertex and not
	 * strictly a dependent.
	 */
	assert(*count > 0);
	free((*result)[*count - 1]);
	(*count)--;

	zfs_graph_destroy(zgp);

	return (0);
}
Beispiel #8
0
GraphType* generate_example4_graph(GraphType::FGSeedsType& fg_nodes,
                                   unsigned int& node_rows,
                                   const int use_seed[], int lambda)
{
  const int NUM_NODES = 64;
  int bg_cap[] = {3, 7, 7, 3, 1, 10, 5, 1, 5, 10, 7, 5, 10, 5, 5, 7, 1, 10, 1, 7, 7, 3, 10, 1, 1, 10, 5, 5, 5, 7, 10, 1, 3, 10, 5, 10, 7, 3, 3, 7, 5, 1, 5, 5, 10, 3, 1, 5, 1, 1, 1, 3, 7, 1, 7, 1, 3, 3, 7, 1, 10, 10, 1, 5};

  /* capacity edges */
  const int NUM_EDGES = 115;
  int edges_a[]   = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9, 10, 10, 11, 11, 12, 12, 12, 14, 14, 15, 16, 17, 17, 17, 17, 18, 19, 19, 19, 20, 20, 21, 21, 21, 22, 22, 22, 24, 24, 25, 25, 26, 26, 26, 27, 27, 28, 28, 29, 29, 29, 30, 31, 31, 32, 33, 33, 33, 34, 34, 35, 35, 35, 36, 37, 37, 37, 38, 38, 38, 38, 39, 40, 40, 41, 42, 42, 42, 43, 43, 44, 44, 44, 45, 45, 46, 46, 46, 47, 48, 49, 49, 49, 50, 51, 51, 51, 52, 52, 52, 53, 53, 53, 54, 59, 60, 61};
  int edges_b[]   = {1, 8, 8, 9, 10, 10, 11, 11, 12, 13, 6, 13, 14, 14, 14, 9, 17, 18, 18, 19, 12, 20, 13, 20, 21, 21, 23, 23, 17, 18, 24, 25, 26, 26, 26, 27, 28, 21, 29, 22, 29, 30, 23, 30, 31, 32, 33, 26, 34, 27, 34, 35, 35, 36, 29, 36, 30, 36, 38, 38, 38, 39, 33, 34, 40, 41, 42, 43, 36, 43, 44, 37, 38, 44, 45, 39, 45, 46, 47, 47, 41, 49, 49, 43, 49, 51, 44, 51, 51, 52, 53, 46, 53, 47, 54, 55, 55, 56, 56, 57, 58, 59, 52, 59, 60, 53, 60, 61, 54, 61, 62, 63, 60, 61, 62};
  int edges_cap[] = {10, 4, 8, 8, 4, 10, 40, 40, 8, 6, 4, 40, 10, 40, 20, 30, 8, 30, 40, 4, 8, 10, 6, 4, 40, 40, 40, 8, 40, 6, 40, 4, 6, 4, 8, 6, 10, 4, 30, 10, 40, 30, 8, 4, 8, 40, 30, 20, 10, 10, 10, 10, 40, 8, 6, 10, 6, 40, 40, 40, 4, 10, 40, 40, 10, 4, 4, 20, 30, 10, 4, 20, 40, 8, 8, 6, 4, 4, 10, 6, 10, 40, 20, 6, 40, 40, 20, 40, 30, 6, 30, 30, 10, 8, 8, 20, 4, 8, 8, 30, 10, 4, 4, 8, 10, 8, 10, 6, 6, 40, 8, 8, 20, 40, 10};

  GraphType::SrcSeedList fg1, fg2, fg3;

  static const unsigned int fg_nodes1[] = { 10, 11 };
  create_seed_list(fg_nodes1, sizeof(fg_nodes1)/sizeof(fg_nodes1[0]), fg1);
  static const unsigned int fg_nodes2[] = { 42 };
  create_seed_list(fg_nodes2, sizeof(fg_nodes2)/sizeof(fg_nodes2[0]), fg2);
  static const unsigned int fg_nodes3[] = { 29, 37, 38 };
  create_seed_list(fg_nodes3, sizeof(fg_nodes3)/sizeof(fg_nodes3[0]), fg3);

  fg_nodes.clear();

  if (use_seed[0] == -1 || use_seed[0] == 1)
    fg_nodes.push_back(fg1);
  if (use_seed[0] == -1 || use_seed[1] == 1)
    fg_nodes.push_back(fg2);
  if (use_seed[0] == -1 || use_seed[2] == 1)
    fg_nodes.push_back(fg3);

  GraphType* g = construct_graph(NUM_NODES, NUM_EDGES, bg_cap, edges_a, edges_b,
                                 edges_cap, fg_nodes, lambda);

  node_rows = 8;

  return g;
}
Beispiel #9
0
// -------------------------------------------------------------------------
int GraphDefinition::multi_dijkstra(
    edge_t *edges,
    unsigned int edge_count,
    std::vector<int> vertices,
    bool directed,
    bool has_reverse_cost, 
    path_element_t **path,
    int *path_count,
    char **err_msg,
    std::vector<PDVI> &ruleList)
{
    construct_graph(edges, edge_count, has_reverse_cost, directed);
    if(ruleList.size() > 0)
    {
    m_ruleTable.clear();
    int total_rule = ruleList.size();
    int i;
    LongVector vecsource;
    // int kk;
    for(i = 0; i < total_rule; i++)
    {
        Rule rule;
        rule.cost = ruleList[i].first;
        int j;
        int seq_cnt = ruleList[i].second.size();
        for(j = 1; j < seq_cnt; j++)
        {
            rule.precedencelist.push_back(ruleList[i].second[j]);
        }
        int dest_edge_id = ruleList[i].second[0];
        if(m_ruleTable.find(dest_edge_id) != m_ruleTable.end())
        {
            m_ruleTable[dest_edge_id].push_back(rule);
        }
        else
        {
            std::vector<Rule> temprules;
            temprules.clear();
            temprules.push_back(rule);
            m_ruleTable.insert(std::make_pair(dest_edge_id, temprules));
        }
    }
    
    m_bIsturnRestrictOn = true;
    }
    parent = new PARENT_PATH[edge_count + 1];
    m_dCost = new CostHolder[edge_count + 1];
    m_vecPath.clear();
    int i;
    int total_vertices = vertices.size();
    for(i = 0; i < total_vertices - 1; i++)
    {
    int ret = my_dijkstra(vertices[i], vertices[i + 1], edge_count, err_msg);
    if(ret < 0)
    {
        deleteall();
        return -1;
    }
    }

    *path = (path_element_t *) malloc(sizeof(path_element_t) * (m_vecPath.size() + 1));
    *path_count = m_vecPath.size();

    for(i = 0; i < *path_count; i++)
    {
    (*path)[i].vertex_id = m_vecPath[i].vertex_id;
    (*path)[i].edge_id = m_vecPath[i].edge_id;
    (*path)[i].cost = m_vecPath[i].cost;
    }
    deleteall();
    return 0;
}
// MAIN =======================================================================>
int main(int argc, char** argv) {
  std::cout << "This program creates and denoises a synthetic " << std::endl
            << "image using loopy belief propagation inside " << std::endl
            << "the graphlab framework." << std::endl;

  // set the global logger
  global_logger().set_log_level(LOG_WARNING);
  global_logger().set_log_to_console(true);


  double bound = 1E-4;
  double damping = 0.1;
  size_t colors = 5;
  size_t rows = 200;
  size_t cols = 200;
  double sigma = 2;
  double lambda = 2;
  std::string smoothing = "laplace";
  std::string orig_fn = "source_img.pgm";
  std::string noisy_fn = "noisy_img.pgm";
  std::string pred_fn = "pred_img.pgm";
  std::string pred_type = "map";




  // Parse command line arguments --------------------------------------------->
  graphlab::command_line_options clopts("Loopy BP image denoising");
  clopts.attach_option("bound",
                       &bound, bound,
                       "Residual termination bound");
  clopts.attach_option("damping",
                       &damping, damping,
                       "The amount of message damping (higher = more damping)");
  clopts.attach_option("colors",
                       &colors, colors,
                       "The number of colors in the noisy image");
  clopts.attach_option("rows",
                       &rows, rows,
                       "The number of rows in the noisy image");
  clopts.attach_option("cols",
                       &cols, cols,
                       "The number of columns in the noisy image");
  clopts.attach_option("sigma",
                       &sigma, sigma,
                       "Standard deviation of noise.");
  clopts.attach_option("lambda",
                       &lambda, lambda,
                       "Smoothness parameter (larger => smoother).");
  clopts.attach_option("smoothing",
                       &smoothing, smoothing,
                       "Options are {square, laplace}");
  clopts.attach_option("orig",
                       &orig_fn, orig_fn,
                       "Original image file name.");
  clopts.attach_option("noisy",
                       &noisy_fn, noisy_fn,
                       "Noisy image file name.");
  clopts.attach_option("pred",
                       &pred_fn, pred_fn,
                       "Predicted image file name.");
  clopts.attach_option("pred_type",
                       &pred_type, pred_type,
                       "Predicted image type {map, exp}");
  

  clopts.set_scheduler_type("splash(splash_size=100)");
  clopts.set_scope_type("edge");
  

  bool success = clopts.parse(argc, argv);
  if(!success) {    
    return EXIT_FAILURE;
  }


  
  std::cout << "ncpus:          " << clopts.get_ncpus() << std::endl
            << "bound:          " << bound << std::endl
            << "damping:        " << damping << std::endl
            << "colors:         " << colors << std::endl
            << "rows:           " << rows << std::endl
            << "cols:           " << cols << std::endl
            << "sigma:          " << sigma << std::endl
            << "lambda:         " << lambda << std::endl
            << "smoothing:      " << smoothing << std::endl
            << "engine:         " << clopts.get_engine_type() << std::endl
            << "scope:          " << clopts.get_scope_type() << std::endl
            << "scheduler:      " << clopts.get_scheduler_type() << std::endl
            << "orig_fn:        " << orig_fn << std::endl
            << "noisy_fn:       " << noisy_fn << std::endl
            << "pred_fn:        " << pred_fn << std::endl
            << "pred_type:      " << pred_type << std::endl;

  
  

  // Create synthetic images -------------------------------------------------->
  // Creating image for denoising
  std::cout << "Creating a synthetic image. " << std::endl;
  image img(rows, cols);
  img.paint_sunset(colors);
  std::cout << "Saving image. " << std::endl;
  img.save(orig_fn.c_str());
  std::cout << "Corrupting Image. " << std::endl;
  img.corrupt(sigma);
  std::cout << "Saving corrupted image. " << std::endl;
  img.save(noisy_fn.c_str());


 
  
  
  // Create the graph --------------------------------------------------------->
  gl_types::core core;
  // Set the engine options
  core.set_engine_options(clopts);
  
  std::cout << "Constructing pairwise Markov Random Field. " << std::endl;
  construct_graph(img, colors, sigma, core.graph());

  
  // Setup global shared variables -------------------------------------------->
  // Initialize the edge agreement factor 
  std::cout << "Initializing shared edge agreement factor. " << std::endl;

  // dummy variables 0 and 1 and num_rings by num_rings
  graphlab::binary_factor edge_potential(0, colors, 0, colors);
  // Set the smoothing type
  if(smoothing == "square") {
    edge_potential.set_as_agreement(lambda);
  } else if (smoothing == "laplace") {
    edge_potential.set_as_laplace(lambda);
  } else {
    std::cout << "Invalid smoothing stype!" << std::endl;
    return EXIT_FAILURE;
  }
  std::cout << edge_potential << std::endl;
  
  EDGE_FACTOR.set(edge_potential);
  BOUND.set(bound);
  DAMPING.set(damping);
  


  // Running the engine ------------------------------------------------------->
  core.sched_options().add_option("update_function",bp_update);

  std::cout << "Running the engine. " << std::endl;

  
  // Add the bp update to all vertices
  core.add_task_to_all(bp_update, 100.0);
  // Starte the engine
  double runtime = core.start();
  
  size_t update_count = core.last_update_count();
  std::cout << "Finished Running engine in " << runtime 
            << " seconds." << std::endl
            << "Total updates: " << update_count << std::endl
            << "Efficiency: " << (double(update_count) / runtime)
            << " updates per second "
            << std::endl;  


  // Saving the output -------------------------------------------------------->
  /*std::cout << "Rendering the cleaned image. " << std::endl;
  if(pred_type == "map") {
    for(size_t v = 0; v < core.graph().num_vertices(); ++v) {
      const vertex_data& vdata = core.graph().vertex_data(v);
      img.pixel(v) = vdata.belief.max_asg();    
    }
  } else if(pred_type == "exp") {
    for(size_t v = 0; v < core.graph().num_vertices(); ++v) {
      const vertex_data& vdata = core.graph().vertex_data(v);
      img.pixel(v) = vdata.belief.expectation();
    }
  } else {
    std::cout << "Invalid prediction type! : " << pred_type
              << std::endl;
    return EXIT_FAILURE;
  }
  std::cout << "Saving cleaned image. " << std::endl;
  img.save(pred_fn.c_str());
 */
  std::cout << "Done!" << std::endl;
  return EXIT_SUCCESS;
} // End of main
Beispiel #11
0
Path build_held_karp_path(const Point *points, const unsigned int points_count)
{
	Graph *graph = NULL;

	Path res;
	// encode subset of original verticies as bits in first index: i-th bit == 1 => point i is in subset.
	float C[MAX_COMBINATIONS_COUNT][MAX_HELD_KARP_POINTS];
	short best_points[MAX_COMBINATIONS_COUNT][MAX_HELD_KARP_POINTS];
	unsigned int set_size = 0;

	if (points_count <= 1)	{
		res.points[0] = 0;
		return res;
	}
	graph = construct_graph(points, points_count);

	C[1][0] = 0;

	for (set_size = 1; set_size < points_count; ++set_size) {
		unsigned int shifted_subset = 0;
		for (shifted_subset = 1; shifted_subset < (1 << (points_count - 1)); ++shifted_subset) {
			int end_point_index = 0;
			const int subset = (shifted_subset << 1) | 1;
			if (one_bits_count(shifted_subset) !=  set_size) {
				continue;
			}
			C[subset][0] = FLT_MAX;
			for (end_point_index = 1; end_point_index < points_count; ++end_point_index) {
				if (is_bit_set(subset, end_point_index)) {
					const int subset_without_endpoint = subset & (~(1 << end_point_index));
					int i = 0;
					C[subset][end_point_index] = FLT_MAX;
					for (i = 0; i < points_count; ++i) {
						if (is_bit_set(subset, i) && i != end_point_index) {
							const float curr_cost = C[subset_without_endpoint][i] + graph->distances[i][end_point_index];
							if (C[subset][end_point_index] > curr_cost) {
								C[subset][end_point_index] = curr_cost;
								best_points[subset][end_point_index] = i;
							}
						}
					}
				}
			}
		}
	}
	{
		// select last edge for making a loop
		const int all_subset = (0xFFFFFFFF >> (32 - points_count));
		
		int i = 0;
		C[all_subset][0] = FLT_MAX;
		best_points[all_subset][0] = -1;

		for (i = 1; i < points_count; ++i) {
			const float curr_cost = C[all_subset][i] + graph->distances[i][0];
			if (C[all_subset][0] > curr_cost) {
				C[all_subset][0] = curr_cost;
				best_points[all_subset][0] = i;
			}
		}
	}

	{
		// traverse back best points matrix to restore full path
		int current_subset = (0xFFFFFFFF >> (32 - points_count));
		int curr_traverse_point = 0;
		int path_point = 0;

		res.points[path_point] = best_points[current_subset][0];
		curr_traverse_point = res.points[path_point];
		
		for (path_point = 1; path_point < points_count; ++path_point) {
			res.points[path_point] = best_points[current_subset][curr_traverse_point];

			current_subset = current_subset & (~(1 << curr_traverse_point));
			curr_traverse_point = res.points[path_point];
		}
	}
	
	destroy_graph(graph);
	res.size = points_count;
	return res;
}
Beispiel #12
0
int BiDirAStar:: bidir_astar(edge_astar_t *edges, size_t edge_count, int maxNode, int start_vertex, int end_vertex,
				path_element_t **path, size_t *path_count, char **err_msg)
{
	max_node_id = maxNode;
	max_edge_id = -1;
	
	// Allocate memory for local storage like cost and parent holder
	initall(maxNode);

	// construct the graph from the edge list, i.e. populate node and edge data structures
	construct_graph(edges, edge_count, maxNode);
	
	m_lStartNodeId = start_vertex;
	m_lEndNodeId = end_vertex;

	// int nodeCount = m_vecNodeVector.size();
	
	MinHeap fque(maxNode + 2);
	MinHeap rque(maxNode + 2);
	//std::priority_queue<PDI, std::vector<PDI>, std::greater<PDI> > fque;
	//std::priority_queue<PDI, std::vector<PDI>, std::greater<PDI> > rque;
	
	m_vecPath.clear();

	// Initialize the forward search
	m_pFParent[start_vertex].par_Node = -1;
	m_pFParent[start_vertex].par_Edge = -1;
	m_pFCost[start_vertex] = 0.0;
	fque.push(std::make_pair(0.0, start_vertex));

	// Initialize the reverse search
	m_pRParent[end_vertex].par_Node = -1;
	m_pRParent[end_vertex].par_Edge = -1;
	m_pRCost[end_vertex] = 0.0;
	rque.push(std::make_pair(0.0, end_vertex));

	// int new_node;
	int cur_node;
	// int dir;
/*
	The main loop. The algorithm is as follows:
	1. IF the sum of the current minimum of both heap is greater than so far found path, we cannot get any better, so break the loop.
	2. IF the reverse heap minimum is lower than the forward heap minimum, explore from reverse direction.
	3. ELSE explore from the forward directtion.
*/

	while(!fque.empty() && !rque.empty())
	{
		PDI fTop = fque.top();
		PDI rTop = rque.top();
		if(m_pFCost[fTop.second] + m_pRCost[rTop.second] > m_MinCost) //We are done, there is no path with lower cost
			break;

		if(rTop.first < fTop.first) // Explore from reverse queue
		{
			if(rTop.first > m_MinCost)
				break;
			cur_node = rTop.second;
			int dir = -1;
			rque.pop();
			explore(cur_node, m_pRCost[rTop.second], dir, rque);
		}
		else                        // Explore from forward queue
		{
			if(fTop.first > m_MinCost)
				break;
			cur_node = fTop.second;
			int dir = 1;
			fque.pop();
			explore(cur_node, m_pFCost[fTop.second], dir, fque);
		}
	}

/*
	Path reconstruction part. m_MidNode is the joining point where two searches meet to make a shortest path. It is updated in explore.
	If it contains -1, then no path is found. Other wise we have a shortest path and that is reconstructed in the m_vecPath.
*/

	if(m_MidNode == -1)
	{
		*err_msg = (char *)"Path Not Found";
		deleteall();
		return -1;
	}
	else
	{
		// reconstruct path from forward search
		fconstruct_path(m_MidNode);
		// reconstruct path from backward search
		rconstruct_path(m_MidNode);

		// insert the last row in the path trace (having edge_id = -1 and cost = 0.0)
		path_element_t pelement;
		pelement.vertex_id = end_vertex;
		pelement.edge_id = -1;
		pelement.cost = 0.0;
		m_vecPath.push_back(pelement);

		// Transfer data path to path_element_t format and allocate memory and populate the pointer
		*path = (path_element_t *) malloc(sizeof(path_element_t) * (m_vecPath.size() + 1));
		*path_count = m_vecPath.size();

		for(size_t i = 0; i < *path_count; i++)
		{
			(*path)[i].vertex_id = m_vecPath[i].vertex_id;
			(*path)[i].edge_id = m_vecPath[i].edge_id;
			(*path)[i].cost = m_vecPath[i].cost;
		}
		
	}
	deleteall();
	return 0;
}
double kruskal(struct Graph *graph, int source_vertex, int target_vertex) {
	PRINT_TEXT("_________________________________________________");
	PRINT_TEXT("...STARTING KRUSKAL...");
	clock_t start = clock();
	double cpu_time;
	int **adjacency_matrix = allocate_2D_matrix(MAX_VERTICES, MAX_VERTICES);
	int i, count = 0;

	struct Edge_Heap *heap = create_edge_heap();
	struct Node *node, *node2;
	for (i = 0; i < graph->totalVertices; i++) {
		node = graph->list[i].next;
		while (node) {
			/*Used to avoid the duplicate addition of edges in the heap*/
			if (adjacency_matrix[i][node->vertex] == 0) {
				adjacency_matrix[i][node->vertex] = 1;
				adjacency_matrix[node->vertex][i] = -1;
				insert_edge_heap(heap, i, node->vertex, node->weight);
				count++;
			}
			node = node->next;
		}
	}
	int size = heap->curr_size;
	heapsort(heap);
//	PRINT_TEXT("HEAP INSERTIONS DONE");
//	PRINT_TEXT_VALUE("TOTAL:", count);

	struct Graph *new_graph = construct_graph();
	struct Set_Arrays *set_data = make_set();
	count = 0;
	i = heap->curr_size - 1;
	while (i >= 0) {
		struct Edge *edge = &heap->A[i--];
//	while (is_edge_heap_empty(heap) != TRUE) {
//		struct Edge *edge = get_max(heap);
//		printf("Considering: %d %d %d\n", edge->vertex1, edge->vertex2,
//				edge->weight);
//		PRINT_VALUES(set_data->dad[edge->vertex1], set_data->dad[edge->vertex2])
		if (union_by_rank(set_data, edge->vertex1, edge->vertex2)) {
			count++;
			link_creation_with_weight(new_graph, edge->vertex1, edge->vertex2,
					edge->weight);
			link_creation_with_weight(new_graph, edge->vertex2, edge->vertex1,
					edge->weight);
//			PRINT_TEXT("ADDED");
		}
//		for (i = 0; i < MAX_VERTICES; i++) {
//			PRINT_VALUE(set_data->dad[i])
//		}

	}

//	PRINT_TEXT_VALUE("TOTAL EDGES ADDED:", count);
	/*Not including max capacity finding using BFS in calculation*/
	cpu_time = ((double) (clock() - start)) / CLOCKS_PER_SEC;

//	printGraph(new_graph);
	print_max_capacity_path_krukskal(new_graph, source_vertex, target_vertex);

	printf("KRUSKAL DONE, TIME TAKEN: %f\n", cpu_time);
	PRINT_TEXT("_________________________________________________");

	for (i = 0; i < MAX_VERTICES; i++)
		free(adjacency_matrix[i]);
	free(adjacency_matrix);

	return cpu_time;
}
Beispiel #14
0
int BiDirDijkstra:: bidir_dijkstra(edge_t *edges, unsigned int edge_count, int maxNode, int start_vertex, int end_vertex,
				path_element_t **path, int *path_count, char **err_msg)
{
	max_node_id = maxNode;
	max_edge_id = -1;
	init();
	construct_graph(edges, edge_count, maxNode);
	

	int nodeCount = m_vecNodeVector.size();
		
	std::priority_queue<PDI, std::vector<PDI>, std::greater<PDI> > fque;
	std::priority_queue<PDI, std::vector<PDI>, std::greater<PDI> > rque;
	
	m_vecPath.clear();

	int i;
	initall(maxNode);

	m_pFParent[start_vertex].par_Node = -1;
	m_pFParent[start_vertex].par_Edge = -1;
	m_pFCost[start_vertex] = 0.0;
	fque.push(std::make_pair(0.0, start_vertex));

	m_pRParent[end_vertex].par_Node = -1;
	m_pRParent[end_vertex].par_Edge = -1;
	m_pRCost[end_vertex] = 0.0;
	rque.push(std::make_pair(0.0, end_vertex));


	int new_node;
	int cur_node;
	int dir;

	while(!fque.empty() && !rque.empty())
	{
		PDI fTop = fque.top();
		PDI rTop = rque.top();
		if(fTop.first + rTop.first > m_MinCost) //We are done, there is no path with lower cost
			break;

		if(rTop.first < fTop.first) // Explore from reverse queue
		{
			cur_node = rTop.second;
			int dir = -1;
			rque.pop();
			explore(cur_node, rTop.first, dir, rque);
		}
		else                        // Explore from forward queue
		{
			cur_node = fTop.second;
			int dir = 1;
			fque.pop();
			explore(cur_node, fTop.first, dir, fque);
		}
	}

	if(m_MidNode == -1)
	{
		*err_msg = (char *)"Path Not Found";
		deleteall();
		return -1;
	}
	else
	{
		fconstruct_path(m_MidNode);
		rconstruct_path(m_MidNode);
		path_element_t pelement;
		pelement.vertex_id = end_vertex;
		pelement.edge_id = -1;
		pelement.cost = 0.0;
		m_vecPath.push_back(pelement);

		*path = (path_element_t *) malloc(sizeof(path_element_t) * (m_vecPath.size() + 1));
		*path_count = m_vecPath.size();

		for(i = 0; i < *path_count; i++)
		{
			(*path)[i].vertex_id = m_vecPath[i].vertex_id;
			(*path)[i].edge_id = m_vecPath[i].edge_id;
			(*path)[i].cost = m_vecPath[i].cost;
		}
		
	}
	deleteall();
	return 0;
}
Beispiel #15
0
// -------------------------------------------------------------------------
int GraphDefinition::my_dijkstra(edge_t *edges, unsigned int edge_count, int start_edge_id, double start_part, int end_edge_id, double end_part, bool directed, bool has_reverse_cost,
                path_element_t **path, int *path_count, char **err_msg, std::vector<PDVI> &ruleList)
{
    if(!m_bIsGraphConstructed)
    {
        init();
        construct_graph(edges, edge_count, has_reverse_cost, directed);
        m_bIsGraphConstructed = true;
    }
    GraphEdgeInfo* start_edge_info = m_vecEdgeVector[m_mapEdgeId2Index[start_edge_id]];
    edge_t start_edge;
    int start_vertex, end_vertex;
    m_dStartpart = start_part;
    m_dEndPart = end_part;
    m_lStartEdgeId = start_edge_id;
    m_lEndEdgeId = end_edge_id;

    if(start_part == 0.0)
    {
        start_vertex = start_edge_info->m_lStartNode;
    }
    else if(start_part == 1.0)
    {
        start_vertex = start_edge_info->m_lEndNode;
    }
    else
    {
        isStartVirtual = true;
        m_lStartEdgeId = start_edge_id;
        start_vertex = max_node_id + 1;
        max_node_id++;
        start_edge.id = max_edge_id + 1;
        max_edge_id++;
        start_edge.source = start_vertex;
        start_edge.reverse_cost = -1.0;
        if(start_edge_info->m_dCost >= 0.0)
        {
            start_edge.target = start_edge_info->m_lEndNode;
            start_edge.cost = (1.0 - start_part) * start_edge_info->m_dCost;
            addEdge(start_edge);
            edge_count++;
        }
        if(start_edge_info->m_dReverseCost >= 0.0)
        {
            start_edge.id = max_edge_id + 1;
            max_edge_id++;
            start_edge.target = start_edge_info->m_lStartNode;
            start_edge.cost = start_part * start_edge_info->m_dReverseCost;
            addEdge(start_edge);
            edge_count++;
        }
    }

    GraphEdgeInfo* end_edge_info = m_vecEdgeVector[m_mapEdgeId2Index[end_edge_id]];
    edge_t end_edge;
    
    if(end_part == 0.0)
    {
        end_vertex = end_edge_info->m_lStartNode;
    }
    else if(end_part == 1.0)
    {
        end_vertex = end_edge_info->m_lEndNode;
    }
    else
    {
        isEndVirtual = true;
        m_lEndEdgeId = end_edge_id;
        end_vertex = max_node_id + 1;
        max_node_id++;
        end_edge.id = max_edge_id + 1;
        max_edge_id++;
        end_edge.target = end_vertex;
        end_edge.reverse_cost = -1.0;
        if(end_edge_info->m_dCost >= 0.0)
        {
            end_edge.source = end_edge_info->m_lStartNode;
            end_edge.cost = end_part * end_edge_info->m_dCost;
            addEdge(end_edge);
            edge_count++;
        }
        if(end_edge_info->m_dReverseCost >= 0.0)
        {
            end_edge.source = end_edge_info->m_lEndNode;
            end_edge.id = max_edge_id + 1;
            end_edge.cost = (1.0 - end_part) * end_edge_info->m_dReverseCost;
            addEdge(end_edge);
            edge_count++;
        }
    }

    return(my_dijkstra(edges, edge_count, start_vertex, end_vertex, directed, has_reverse_cost, path, path_count, err_msg, ruleList));
}
Beispiel #16
0
// -------------------------------------------------------------------------
int GraphDefinition:: my_dijkstra(edge_t *edges, unsigned int edge_count, int start_vertex, int end_vertex, bool directed, bool has_reverse_cost,
                path_element_t **path, int *path_count, char **err_msg)
{
    if(!m_bIsGraphConstructed)
    {
        init();
        construct_graph(edges, edge_count, has_reverse_cost, directed);
        m_bIsGraphConstructed = true;
    }
    
    std::priority_queue<PDP, std::vector<PDP>, std::greater<PDP> > que;
    parent = new PARENT_PATH[edge_count + 1];
    m_dCost = new CostHolder[edge_count + 1];
    m_vecPath.clear();

    unsigned int i;
    for(i = 0; i <= edge_count; i++)
    {
        m_dCost[i].startCost = 1e15;
        m_dCost[i].endCost = 1e15;
    }
    
    if(m_mapNodeId2Edge.find(start_vertex) == m_mapNodeId2Edge.end())
    {
        *err_msg = (char *)"Source Not Found";
        deleteall();
        return -1;
    }

    if(m_mapNodeId2Edge.find(end_vertex) == m_mapNodeId2Edge.end())
    {
        *err_msg = (char *)"Destination Not Found";
        deleteall();
        return -1;
    }

    LongVector vecsource = m_mapNodeId2Edge[start_vertex];
    GraphEdgeInfo* cur_edge = NULL;

    for(i = 0; i < vecsource.size(); i++)
    {
        cur_edge = m_vecEdgeVector[vecsource[i]];
        if(cur_edge->m_lStartNode == start_vertex)
        {
            if(cur_edge->m_dCost >= 0.0)
            {
                m_dCost[cur_edge->m_lEdgeIndex].endCost= cur_edge->m_dCost;
                parent[cur_edge->m_lEdgeIndex].v_pos[0] = -1;
                parent[cur_edge->m_lEdgeIndex].ed_ind[0] = -1;
                que.push(std::make_pair(cur_edge->m_dCost, std::make_pair(cur_edge->m_lEdgeIndex, true)));
            }
        }
        else
        {
            if(cur_edge->m_dReverseCost >= 0.0)
            {
                m_dCost[cur_edge->m_lEdgeIndex].startCost = cur_edge->m_dReverseCost;
                parent[cur_edge->m_lEdgeIndex].v_pos[1] = -1;
                parent[cur_edge->m_lEdgeIndex].ed_ind[1] = -1;
                que.push(std::make_pair(cur_edge->m_dReverseCost, std::make_pair(cur_edge->m_lEdgeIndex, false)));
            }
        }
    }
    //parent[start_vertex].v_id = -1;
    //parent[start_vertex].ed_id = -1;
    //m_dCost[start_vertex] = 0.0;

    // int new_node;
    int cur_node = -1;

    while(!que.empty())
    {
        PDP cur_pos = que.top();
        que.pop();
        int cured_index = cur_pos.second.first;
        cur_edge = m_vecEdgeVector[cured_index];
        //GraphEdgeInfo* new_edge;

        if(cur_pos.second.second)      // explore edges connected to end node
        {
            cur_node = cur_edge->m_lEndNode;
            if(cur_edge->m_dCost < 0.0)
                continue;
            if(cur_node == end_vertex)
                break;
            explore(cur_node, *cur_edge, true, cur_edge->m_vecEndConnedtedEdge, que);
        }
        else        // explore edges connected to start node
        {
            cur_node = cur_edge->m_lStartNode;
            if(cur_edge->m_dReverseCost < 0.0)
                continue;
            if(cur_node == end_vertex)
                break;
            explore(cur_node, *cur_edge, false, cur_edge->m_vecStartConnectedEdge, que);
        }
    }
    if(cur_node != end_vertex)
    {
        if(m_lStartEdgeId == m_lEndEdgeId)
        {
            if(get_single_cost(1000.0, path, path_count))
            {
                return 0;
            }
        }
        *err_msg = (char *)"Path Not Found";
        deleteall();
        return -1;
    }
    else
    {
        double total_cost;
        if(cur_node == cur_edge->m_lStartNode)
        {
            total_cost = m_dCost[cur_edge->m_lEdgeIndex].startCost;
            construct_path(cur_edge->m_lEdgeIndex, 1);
        }
        else
        {
            total_cost = m_dCost[cur_edge->m_lEdgeIndex].endCost;
            construct_path(cur_edge->m_lEdgeIndex, 0);
        }
        path_element_t pelement;
        pelement.vertex_id = end_vertex;
        pelement.edge_id = -1;
        pelement.cost = 0.0;
        m_vecPath.push_back(pelement);

        if(m_lStartEdgeId == m_lEndEdgeId)
        {
            if(get_single_cost(total_cost, path, path_count))
            {
                return 0;
            }
        }
        
        *path = (path_element_t *) malloc(sizeof(path_element_t) * (m_vecPath.size() + 1));
        *path_count = m_vecPath.size();

        for(int i = 0; i < *path_count; i++)
        {
            (*path)[i].vertex_id = m_vecPath[i].vertex_id;
            (*path)[i].edge_id = m_vecPath[i].edge_id;
            (*path)[i].cost = m_vecPath[i].cost;
        }
        if(isStartVirtual)
        {
            (*path)[0].vertex_id = -1;
            (*path)[0].edge_id = m_lStartEdgeId;
        }
        if(isEndVirtual)
        {
            *path_count = *path_count - 1;
            (*path)[*path_count - 1].edge_id = m_lEndEdgeId;
        }
    }
    deleteall();
    return 0;
}
Beispiel #17
0
int main(int argc, char *argv[]){
  int listen_socket;
  int connection_socket;
  int av = 1;
  int thread_index = 0;
  int port = HTTP_PORT;
  struct sockaddr_in local_addr;
  struct sockaddr_in client_addr;
  struct arguments ar = {0,0,0,0};
  if(argc > 1){
    parse_arguments(argc,argv,&ar);
    
    if(ar.p == 1) port = &ar.port;      // use port provided from cli
  }
  if(ar.f == 0){
    ar.file_directory=get_current_dir_name();
    ar.file_directory[strlen(ar.file_directory)]='/';
  }
  construct_graph(ar.file_directory);
  
  pthread_t *threads = (pthread_t *)malloc(sizeof(pthread_t)*MAX_CONNECTIONS);
  int *thread_return = (int *)malloc(sizeof(int)*MAX_CONNECTIONS);

  int client_addr_len = sizeof(client_addr);
  if(ar.v==1) printf("%s \n","setting up socket...");
  if((listen_socket = socket(PF_INET,SOCK_STREAM,0)) == -1){
    perror("Unable te create listen socket");
    exit(0);
  }
  if(ar.v==1) printf("%s \n","setting socket options...");
  if(setsockopt(listen_socket,SOL_SOCKET,
		SO_REUSEADDR,
		&av,sizeof(av)) == -1){
    perror("Settings socket option");
    exit(0);
  }
  local_addr.sin_family = AF_INET;
  if(ar.p == 1) local_addr.sin_port = (int)htons(atoi(ar.port));
  else local_addr.sin_port = htons(HTTP_PORT);
  local_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  if(ar.v==1) printf("%s \n","binding socket to interface...");
  if(bind(listen_socket,(struct sockaddr*) &local_addr,
	  sizeof(local_addr)) == -1){
    perror("Unable to bind, root?");
    exit(0);
  }
  if(listen(listen_socket,5) == -1){
    perror("Unable to set socket backlog");
    exit(0);
  }
  while((connection_socket = accept(listen_socket,
				    (struct sockaddr*)&client_addr,
				    &client_addr_len)) != -1){
    if(thread_index == MAX_CONNECTIONS){
      perror("Max connections limit is reached, wont accespt any more connections");
    }else{
    thread_return[thread_index++] = pthread_create (&threads[thread_index-1],
						    NULL,process_http_request,&connection_socket);
    }
  }
  if(connection_socket == -1){
    perror("Unable to connect socket request");
  }
  free(threads);
  free(thread_return);
  return 0;
}